Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(sales): sales rules on a unified enforcementRule table, with enforcement gates (#1382)
Naveen Kashyape59a9e26e210
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex b609e34cc6..49ed07ac6d 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1123,6 +1123,26 @@ canvas hosting Radix popovers/selects.**Applies to:** `packages/form/src/components/InputOTP.tsx`, `packages/form/src/ValidatedForm.tsx`, any auto-submitting form field.+## A blanket symbol rename re-homes family-neutral code into one family++**Context:** Renaming the "Item Rules" feature to "Sales Rules" was done with a repo-wide `ItemRule` → `SalesRule` string sweep. It also caught `ItemRuleFilter` / `toItemRuleFilter` in `packages/utils` — a shared item-scoping matcher where "Item" meant *the item being filtered*, not the feature. The result was `toSalesRuleFilter`, imported by the **storage** evaluator, with a docstring still reading "Normalize a raw `storageRule` row". Nothing failed: types, tests, and lint were all green, because a wrong name is not a type error.++**Problem:** A string-match rename cannot distinguish "the feature named X" from "the noun X used as a domain word". Shared code is exactly where the two collide, and the damage is invisible to every automated gate — it only shows up when the next reader trusts the name.++**Rule:** Before a blanket rename, list the symbols that will match and check each one's *consumers*, not just its definition: a symbol used by more than one feature is shared and must get a family-neutral name (`ItemFilter`, not `SalesRuleFilter`), not the new feature's name. After the sweep, grep the renamed symbols inside the OTHER feature's directories — a hit there is the tell. Docstrings and comments are part of the rename: a comment that contradicts its symbol's new name is proof the rename was mechanical.++**Applies to:** `packages/utils/src/rules.ts`, `packages/utils/src/rule-filters.ts`, `packages/ee/src/rules/**`, any repo-wide identifier rename.++## `git add` aborts the whole invocation on one unmatched pathspec++**Context:** Committing a spec that had been moved with `git mv`, the staging command listed both the old and new paths. The old path no longer existed, so `git add` exited with `fatal: pathspec … did not match any files` and staged **nothing** — but the following `git commit` still ran and produced a commit containing only the already-staged deletion. The spec was removed from the branch without its replacement, and it was pushed before anyone noticed.++**Problem:** `git add` is all-or-nothing across its arguments, and a `fatal:` from it does not stop a `&&`-free command sequence. The failure message scrolls past in a multi-command block, and `git commit` happily commits whatever the index already held — which after a `git mv` is exactly the destructive half of the change.++**Rule:** Never list a path that a previous step may have moved or deleted. Build the staging list from `git status --porcelain` output rather than typing paths, and **verify the index before committing** — `git status --porcelain | grep -vc "^[MARD]"` must be 0, or diff `git diff --cached --name-only` against the intended file list. Treat a commit whose file count differs from the intended change as a failed commit, not a done one.++**Applies to:** any commit flow following a `git mv`, `/check-and-commit`, scripted staging.+## Dating a synthetic-entity journal with company_today() drops it out of the "as of" report window**Context:** Intercompany elimination journals post to a synthetic "elimination entity" company (no user membership, no location). `generateEliminationEntries` dated them `company_today(elimination_entity)`. Because the elimination entity has no location, `company_today` fell back to UTC — and on an evening-Pacific boundary UTC had already rolled to the next day. The eliminations posted on Aug 18 while the invoices they eliminate posted Aug 17. The consolidated balance sheet ("Aug 2026 to date", cutoff = today = Aug 17) then showed Inter-Company Payables/Receivables = 100 (un-eliminated), while the account drill-down ("all time") correctly netted to 0 — a confusing split where the row and its own drill-down disagree.@@ -1772,3 +1792,13 @@ full-screen ERP route.**Rule:** One `step.run` per tenant, wrapped in `try/catch` that records `{ error }` and continues; return the per-tenant outcomes so the run output says who failed. Classify terminal failures (a refused OAuth grant is `AccountingAuthError`) and return them from the step instead of throwing — retries cannot fix them and only delay the next tenant. Pair the per-tenant step with a `maxDuration` on the serve route: a step's ceiling is that function's ceiling.**Applies to:** `packages/jobs/src/inngest/functions/**` — every cron with a per-company loop (`accounting-*-sweep`, `accounting-reconciliation`, `accounting-consolidation`, `scheduled/mrp.ts`); use `runIsolatedCompanyStep` (`integrations/accounting-auth-failure.ts`) for the accounting ones.++## A merged-away table breaks every existing backup unless the rename map and schema manifest move with it++**Context:** The sales-rules PR (#1382) merged `storageRule` / `storageRuleItemAssignment` / `storageRuleWorkCenterAssignment` into the shared `enforcementRule*` tables and dropped the old ones. The branch shipped with no `TABLE_RENAMES` entries and a stale `packages/jobs/manifests/schema.json` still listing the dropped tables.++**Problem:** A restore that meets an unmapped missing table refuses by design (`applyTableRenames` → `assertBackupImportable`), so every customer backup taken before the merge would stop restoring the moment it shipped. The pre-commit `db:check:backups` gate that catches this only runs against a migrated LOCAL database — on a worktree with no dev stack the hook skips with a warning, which is exactly the state a reviewer or merge-fixer is in.++**Rule:** A migration that renames or drops any tenant-scoped table needs, in the same commit: (1) a `TABLE_RENAMES` entry (`packages/jobs/src/backups/renames.ts` — new name, or `null` if the feature died), (2) a default (or nullability) on any NEW NOT-NULL column of the rename target so old backup rows can load, and (3) a regenerated `manifests/schema.json`, which requires running `pnpm db:migrate` + `pnpm db:check:backups` against a live local DB. If the DB isn't running, say so — a skipped hook is not a passed check.++**Applies to:** `packages/database/supabase/migrations/**` table renames/drops, `packages/jobs/src/backups/renames.ts`, `packages/jobs/manifests/schema.json`, `.claude/rules/workflow-database-migration.md` step 3b.diff --git a/.ai/plans/2026-08-11-item-rules.md b/.ai/plans/2026-08-11-item-rules.mdnew file mode 100644index 0000000000..f19ab0e815--- /dev/null+++ b/.ai/plans/2026-08-11-item-rules.md@@ -0,0 +1,606 @@+# Item Rules — implementation plan++**Spec:** .ai/specs/implemented/2026-08-11-item-rules.md+**Research:** (in-session; baked into spec §"Existing infrastructure")+**Branch:** cambridge-bom-feature-gap-audit (NO commits — user grants commit separately)++## Progress+- [x] Task 1: Resolve pre-existing generated-type modifications (diffs were regeneration noise; restored, then regenerated cleanly)+- [x] Task 2: Migration — itemRule / itemRuleAssignment / itemRuleAcknowledgment (20260810214426_item-rules-sales.sql; applied; types regenerated; @carbon/database typecheck green)+- [x] Task 3: Engine extensions in @carbon/utils (+ unit tests)+- [x] Task 4: Evaluator package packages/ee/src/item-rules (+ tests + exports)+- [x] Task 5: ERP module item-rules — models + service + barrel+- [x] Task 6: Value-options loaders (customerTypes, customerStatuses, countries)+- [x] Task 7: UI — ItemRuleForm + ItemRulesTable (parameterize shared builder components)+- [x] Task 8: Routes, path helpers, react-query key, Items sidebar+- [x] Task 9: Assignment routes + per-item drawer section+- [x] Task 10: Enforcement — quote line create/edit actions+- [x] Task 11: Enforcement — sales-order line create/edit actions+- [x] Task 12: Wire line forms through useStorageRuleViolations + ViolationModal+- [x] Task 13: Notifications (event + settings group + notify handler + triggers) — NOTE deviation: added migration 20260810221652_item-rule-notification-group.sql (companySettings."itemRuleNotificationGroup" text[]) because the plan omitted storage for the setting; applied locally+- [x] Task 14: Acknowledgment persistence in enforcement actions+- [x] Task 15: Docs — fix packages/utils/AGENTS.md, add module AGENTS.md (utils fix done earlier; modules/item-rules/AGENTS.md created)+- [x] Task 16: Final verification sweep — 6/6 package typechecks, utils 76 tests, ee 40 tests, lint green (NO commit of implementation)++## Dependencies+- Task 2 needs Task 1. Tasks 5–14 need Task 2 (generated types). Task 3 is independent of Task 2 (can run in parallel).+- Task 4 needs Task 3 (+ Task 2 types for its service queries).+- Task 7 needs Tasks 3, 5, 6. Task 8 needs 5, 7. Task 9 needs 5, 8.+- Tasks 10–11 need Task 4; Task 12 needs 10–11. Tasks 13–14 need 10–11.+- Task 15 independent (after 4). Task 16 last.++## Global constraints (every task)+- pnpm only. Never edit `packages/database/src/types.ts`, `swagger-docs-schema.ts`, or `functions/lib/types.ts` by hand.+- No commits, no pushes, no new git refs. No DB data writes (schema migration apply is the one sanctioned DB operation, Task 2).+- Never touch: configurator rules (`x+/part+/$itemId.rule*.tsx`, `configurationRule*`), storage-rules behavior (parameterize shared components additively — default behavior unchanged), MES app.+- Naming discipline: every new identifier uses the `itemRule` / `item-rules` prefix; no bare `rule` names.++---++## Task 1: Resolve pre-existing generated-type modifications++**Depends on:** none+**Files:**+- Inspect (do not edit): `packages/database/src/types.ts`, `packages/database/src/swagger-docs-schema.ts`, `packages/database/supabase/functions/lib/types.ts`++**Steps:**+1. `git diff --stat packages/database/src/types.ts packages/database/src/swagger-docs-schema.ts packages/database/supabase/functions/lib/types.ts` and skim `git diff packages/database/src/types.ts | head -100`.+2. These are generated files modified in the working tree before this run. If the diff is regeneration noise/drift (formatting, tables from already-applied local migrations), restore pristine state: `git checkout -- packages/database/src/types.ts packages/database/src/swagger-docs-schema.ts packages/database/supabase/functions/lib/types.ts`.+3. If the diff contains schema content that does NOT correspond to any migration on this branch (unknown tables/columns), STOP and report — do not restore, do not proceed to Task 2.++**Verify:**+```bash+git status --porcelain packages/database/+# Expected: no output (clean) — or STOP-and-report was taken+```++**Out of scope:** any other modified file.++## Task 2: Migration — itemRule / itemRuleAssignment / itemRuleAcknowledgment++**Depends on:** Task 1+**Files:**+- Create: `packages/database/supabase/migrations/<timestamp>_item-rules-sales.sql` (via `pnpm db:migrate:new item-rules-sales`)+- Copy from (precedent): `packages/database/supabase/migrations/20260507120000_item-rules.sql` (RLS shape), `20260609143732_document-template.sql` (house PK/audit template)++**Steps:**+1. `pnpm db:migrate:new item-rules-sales` (never hand-pick the timestamp; HHMMSS must not be `000000`).+2. Write exactly this SQL into the created file:++```sql+-- Item rules: predicate rules evaluated when items are added to sales+-- documents (quote / sales order lines). Distinct from storageRule (warehouse+-- surfaces) and configurationRule (product configurator).+CREATE TYPE "itemRuleSurface" AS ENUM ('quoteLine', 'salesOrderLine');++CREATE TABLE "itemRule" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "message" TEXT NOT NULL,+ "severity" TEXT NOT NULL CHECK ("severity" IN ('error', 'warn')),+ "conditionAst" JSONB NOT NULL,+ "surfaces" "itemRuleSurface"[] NOT NULL DEFAULT ARRAY['quoteLine', 'salesOrderLine']::"itemRuleSurface"[],+ "filteredItemTypes" TEXT[] NOT NULL DEFAULT '{}',+ "filteredItemGroupIds" TEXT[] NOT NULL DEFAULT '{}',+ "filteredItemMatchAll" BOOLEAN NOT NULL DEFAULT FALSE,+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "customFields" JSONB,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "itemRule_surfaces_nonempty" CHECK (array_length("surfaces", 1) >= 1)+);++ALTER TABLE "itemRule" ADD CONSTRAINT "itemRule_companyId_name_key" UNIQUE ("companyId", "name");+CREATE INDEX "itemRule_companyId_idx" ON "itemRule" ("companyId");+CREATE INDEX "itemRule_createdBy_idx" ON "itemRule" ("createdBy");+CREATE INDEX "itemRule_companyId_active_partial_idx" ON "itemRule" ("companyId") WHERE "active" = TRUE;++ALTER TABLE "public"."itemRule" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."itemRule"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);+CREATE POLICY "INSERT" ON "public"."itemRule"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);+CREATE POLICY "UPDATE" ON "public"."itemRule"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);+CREATE POLICY "DELETE" ON "public"."itemRule"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++CREATE TABLE "itemRuleAssignment" (+ "itemId" TEXT NOT NULL REFERENCES "item"("id") ON DELETE CASCADE,+ "ruleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "itemRuleAssignment_pkey" PRIMARY KEY ("itemId", "ruleId"),+ CONSTRAINT "itemRuleAssignment_rule_fkey" FOREIGN KEY ("ruleId", "companyId") REFERENCES "itemRule"("id", "companyId") ON DELETE CASCADE+);++CREATE INDEX "itemRuleAssignment_itemId_idx" ON "itemRuleAssignment" ("itemId");+CREATE INDEX "itemRuleAssignment_ruleId_idx" ON "itemRuleAssignment" ("ruleId");+CREATE INDEX "itemRuleAssignment_companyId_idx" ON "itemRuleAssignment" ("companyId");+CREATE INDEX "itemRuleAssignment_createdBy_idx" ON "itemRuleAssignment" ("createdBy");++ALTER TABLE "public"."itemRuleAssignment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."itemRuleAssignment"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);+CREATE POLICY "INSERT" ON "public"."itemRuleAssignment"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])+);+CREATE POLICY "UPDATE" ON "public"."itemRuleAssignment"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])+);+CREATE POLICY "DELETE" ON "public"."itemRuleAssignment"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])+);++-- Persisted override evidence: one row per acknowledged warn violation (and+-- blocked error attempt), keyed to the document the user was editing.+CREATE TABLE "itemRuleAcknowledgment" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "ruleId" TEXT,+ "documentType" TEXT NOT NULL CHECK ("documentType" IN ('quote', 'salesOrder')),+ "documentId" TEXT NOT NULL,+ "documentLineId" TEXT,+ "itemId" TEXT,+ "severity" TEXT NOT NULL CHECK ("severity" IN ('error', 'warn')),+ "outcome" TEXT NOT NULL CHECK ("outcome" IN ('blocked', 'acknowledged')),+ "message" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX "itemRuleAcknowledgment_companyId_idx" ON "itemRuleAcknowledgment" ("companyId");+CREATE INDEX "itemRuleAcknowledgment_ruleId_idx" ON "itemRuleAcknowledgment" ("ruleId");+CREATE INDEX "itemRuleAcknowledgment_document_idx" ON "itemRuleAcknowledgment" ("documentType", "documentId");+CREATE INDEX "itemRuleAcknowledgment_createdBy_idx" ON "itemRuleAcknowledgment" ("createdBy");++ALTER TABLE "public"."itemRuleAcknowledgment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."itemRuleAcknowledgment"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);+-- Append-only: INSERT permitted to anyone who can create sales lines (the+-- acknowledgment is written by the sales action); no UPDATE/DELETE policies.+CREATE POLICY "INSERT" ON "public"."itemRuleAcknowledgment"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[])+);++INSERT INTO "customFieldTable" ("table", "name", "module")+VALUES ('itemRule', 'Item Rule', 'Items')+ON CONFLICT DO NOTHING;+```++3. Apply locally: `pnpm db:migrate` (this regenerates types + swagger). This is the sanctioned schema-apply step; it writes no data.+4. If the regenerated `packages/database/src/types.ts` diff contains changes UNRELATED to the three new tables/enum, STOP and report (local DB drift) — do not proceed.++**Verify:**+```bash+grep -c "itemRuleAcknowledgment\|itemRuleAssignment\|itemRule:" packages/database/src/types.ts+# Expected: >= 3 (all three tables present in generated types)+pnpm exec turbo run typecheck --filter=@carbon/database+# Expected: exit 0+```++**Out of scope:** touching the `transactionSurface` enum, `storageRule*` tables, or any existing table.++## Task 3: Engine extensions in @carbon/utils++**Depends on:** none (parallel with Task 2)+**Files:**+- Modify: `packages/utils/src/storage-rules.ts`+- Modify: `packages/utils/src/field-registry.ts`+- Modify/Create test: locate existing engine tests via `ls packages/utils/src/*.test.ts`; add cases to the storage-rules test file (or create `packages/utils/src/item-rules.test.ts` beside it using the same vitest imports)++**Steps:**+1. `storage-rules.ts`:+ - Add `"customer"` to `ROOT_KEYS` (line ~161) and `customer?: Record<string, unknown> & { customFields?: Record<string, unknown>; location?: Record<string, unknown> }` to `RuleContext`.+ - Add after `TRANSACTION_SURFACES`:+ ```ts+ export const ITEM_RULE_SURFACES = ["quoteLine", "salesOrderLine"] as const;+ export type ItemRuleSurface = (typeof ITEM_RULE_SURFACES)[number];+ export type RuleSurface = TransactionSurface | ItemRuleSurface;+ ```+ - Widen ONLY these signatures from `TransactionSurface` to `RuleSurface`: `CompiledRule.surfaces`, `StorageRuleRow.surfaces` stays as-is; instead add:+ ```ts+ export type ItemRuleRow = {+ id: string;+ severity: Severity;+ message: string;+ conditionAst: ConditionAst;+ surfaces?: ItemRuleSurface[];+ updatedAt?: string | null;+ active?: boolean;+ };+ export const compileItemRuleWithCache = (row: ItemRuleRow): CompiledRule =>+ compileWithCache({+ ...row,+ targetType: "item",+ surfaces: (row.surfaces && row.surfaces.length > 0+ ? row.surfaces+ : [...ITEM_RULE_SURFACES]) as unknown as TransactionSurface[]+ });+ ```+ and change `evaluateRules`'s `surface` param type to `RuleSurface` plus `CompiledRule.surfaces` to `readonly RuleSurface[]` (compile paths unchanged — `.includes()` is type-safe with the union). If widening `CompiledRule.surfaces` breaks existing ee/module typechecks, prefer `readonly string[]` narrowing at the two comparison sites and record the deviation in the run record.+ - Add:+ ```ts+ export const ITEM_RULE_SURFACE_CONTEXT_AVAILABILITY: Record<ItemRuleSurface, readonly FieldContext[]> = {+ quoteLine: ["item", "customer", "transaction"],+ salesOrderLine: ["item", "customer", "transaction"]+ };+ export const isFieldAvailableOnItemRuleSurfaces = (def: FieldDef, surfaces: readonly ItemRuleSurface[]): boolean =>+ surfaces.length === 0 ||+ surfaces.every((s) => ITEM_RULE_SURFACE_CONTEXT_AVAILABILITY[s]?.includes(def.context));+ export const getFieldsForItemRuleSurfaces = (surfaces: readonly ItemRuleSurface[]): FieldDef[] =>+ getFieldsForItemRules().filter((f) => isFieldAvailableOnItemRuleSurfaces(f, surfaces));+ ```+ (`getFieldsForItemRules` comes from field-registry, next step.)+2. `field-registry.ts`:+ - Add `"customer"` to the `FieldContext` union; add `"customerTypes" | "customerStatuses" | "countries"` to `ValueOptionsLoader`.+ - Add a SEPARATE registry (do NOT add to `FIELD_REGISTRY` — storage builder must not see these):+ ```ts+ export const ITEM_RULE_FIELD_REGISTRY: FieldDef[] = [+ fields.database({ table: "customer", column: "customerTypeId", nullable: true, label: "Customer type", type: "id", operators: ID_OPS, context: "customer", targetType: "item", ctxKey: "customer", valueOptionsLoader: "customerTypes" }),+ fields.database({ table: "customer", column: "customerStatusId", nullable: true, label: "Customer status", type: "id", operators: ID_OPS, context: "customer", targetType: "item", ctxKey: "customer", valueOptionsLoader: "customerStatuses" }),+ fields.synthetic({ path: "customer.location.countryCode", derivedFrom: "Ship-to country (alpha-2) resolved from the document's customer location address.", nullable: true, label: "Customer country", type: "id", operators: ID_OPS, context: "customer", valueOptionsLoader: "countries", targetType: "item" })+ ];+ export const getFieldsForItemRules = (): FieldDef[] => [+ ...FIELD_REGISTRY.filter((f) => f.context === "item" || f.targetType === "shared"),+ ...ITEM_RULE_FIELD_REGISTRY+ ];+ ```+ Note: `customer.customTypeId` path must come out as `customer.customerTypeId` — the `fields.database` helper prefixes with `ctxKey ?? table`; `ctxKey: "customer"` and `table: "customer"` are equivalent here, keep `ctxKey` for clarity.+ - Extend `getFieldDef` to also check `ITEM_RULE_FIELD_REGISTRY` and synthesize `customer.customFields.*` exactly like `item.customFields.*` (context `"customer"`, label = suffix, description "Custom field on the customer record.").+3. Tests (vitest): add cases asserting (a) `buildResolver("customer.location.countryCode")` resolves from a ctx with `customer.location.countryCode = "IR"`; (b) `compileItemRuleWithCache` + `evaluateRules` fire a violation for `{kind:"all", conditions:[{field:"item.type",op:"eq",value:"Part"},{field:"customer.location.countryCode",op:"in",value:["IR","KP"]}]}` with matching ctx on surface `"quoteLine"`, and produce a `"Customer country is required"`-style required-field violation when `customer.location` is absent; (c) `getFieldsForItemRuleSurfaces(["quoteLine"])` includes the three customer fields and excludes `storageUnit.*` / `workCenter.*` fields; (d) `getFieldDef("customer.customFields.foo")` returns a def with context `"customer"`.++**Verify:**+```bash+pnpm --filter @carbon/utils test+# Expected: all tests pass incl. new item-rules cases+pnpm exec turbo run typecheck --filter=@carbon/utils+# Expected: exit 0+```++**Out of scope:** changing operator semantics, storage `SURFACE_CONTEXT_AVAILABILITY`, `SURFACES_BY_TARGET_TYPE`, or any existing FIELD_REGISTRY entry.++## Task 4: Evaluator package packages/ee/src/item-rules++**Depends on:** Tasks 2, 3+**Files:**+- Create: `packages/ee/src/item-rules/context.ts`, `server.ts`, `service.ts`, `index.ts`, `context.test.ts`+- Modify: `packages/ee/package.json` — add exports `"./item-rules": "./src/item-rules/index.ts"` and `"./item-rules.server": "./src/item-rules/server.ts"` beside the storage-rules entries (lines 9–10)+- Copy from (precedent): `packages/ee/src/storage-rules/{context,server,service,index}.ts` + `context.test.ts`++**Steps:**+1. `context.ts` — pure assembly, mirroring storage version:+ ```ts+ export type ItemRuleLineInput = { lineId: string; itemId?: string | null; quantity: number };+ export type CustomerCtxInput = {+ id: string;+ customerTypeId?: string | null;+ customerStatusId?: string | null;+ customFields?: Record<string, unknown>;+ location?: { countryCode?: string | null } | null;+ };+ export const buildItemRuleLineContext = (args: {+ line: ItemRuleLineInput;+ surface: ItemRuleSurface;+ userId: string;+ item?: Record<string, unknown> & { customFields?: Record<string, unknown> };+ customer?: CustomerCtxInput;+ }): RuleContext+ ```+ Returns `{ item: line.itemId ? (args.item ?? { id: line.itemId }) : undefined, customer: args.customer ? { id, customerTypeId, customerStatusId, customFields, location: args.customer.location ?? undefined } : undefined, transaction: { kind: surface, quantity: line.quantity, userId } }`. IMPORTANT: when the customer has no resolvable location, set `location: undefined` (NOT `{}`) so `customer.location.countryCode` resolves undefined → required-field semantics fire.+2. `service.ts` — cross-app queries with `SupabaseClient<Database>` first arg:+ - `getActiveItemRulesForItems(client, companyId, itemIds: string[])` → loads (a) all active `itemRule` rows for the company, (b) `itemRuleAssignment` rows for `itemIds`. Returns `{ rules: ItemRuleRowDb[], assignmentsByItemId: Map<string, Set<string>> }` where a rule applies to an item iff it has an explicit assignment OR (`itemRuleAppliesToItem(item, toItemRuleFilter(rule))` — filter matching happens in server.ts where item rows exist).+ - `getItemRuleAssignmentsForItem(client, { itemId, companyId })` — merged explicit + broadcast list for the drawer, mirroring `getRuleAssignmentsForTarget` (`packages/ee/src/storage-rules/service.ts:205`).+ - `getItemRulesList(client, companyId)`, `assignItemRule(client, { itemId, ruleId, companyId, createdBy })`, `unassignItemRule(client, { itemId, ruleId, companyId })`.+3. `server.ts`:+ - `isItemRulesEnabledForCompany(client, companyId): Promise<boolean>` — copy `isStorageRulesEnabledForCompany` (`storage-rules/server.ts:45`) switching the feature key to `"ITEM_RULES"` (key already exists in `packages/ee/src/plan.ts:12`).+ - Re-export `isBlocked` and `dedupeViolations` from `../storage-rules/server` (do not duplicate).+ - `evaluateItemRuleLines(args: { client: SupabaseClient<Database>; companyId: string; userId: string; surface: ItemRuleSurface; lines: ItemRuleLineInput[]; customerId: string | null; customerLocationId: string | null }): Promise<{ violations: Violation[]; ruleNames: Record<string, string> }>`:+ a. Plan gate: return empty when `!(await isItemRulesEnabledForCompany(...))`.+ b. Load customer row (`customer` select `id, customerTypeId, customerStatusId, customFields` by id+companyId) and, when `customerLocationId` set, `customerLocation` select `id, address(countryCode)`; build `CustomerCtxInput` with `location: countryCode ? { countryCode } : undefined`.+ c. Batch-load items for `lines[].itemId`: select `id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, customFields, itemCost(itemPostingGroupId)`; flatten `itemPostingGroupId` via `itemPostingGroupIdFromEmbed` (import from `../storage-rules/context`).+ d. Load rules via `getActiveItemRulesForItems`; per line: applicable rules = explicit assignments ∪ broadcasts passing `itemRuleAppliesToItem`; compile with `compileItemRuleWithCache`; `evaluateRules(compiled, ctx, surface)`.+ e. `dedupeViolations` across lines; build `ruleNames` map (ruleId → rule.name).+4. `index.ts` — `export * from "./service"` + re-export the context types (client-safe only; server.ts NOT exported here).+5. `context.test.ts` — mirror the storage anti-drift test: assert the ctx built for each `ItemRuleSurface` populates exactly the contexts named in `ITEM_RULE_SURFACE_CONTEXT_AVAILABILITY` (item, customer, transaction), and that missing location yields `customer.location === undefined`.++**Verify:**+```bash+pnpm --filter @carbon/ee test+# Expected: pass, incl. item-rules context tests+pnpm exec turbo run typecheck --filter=@carbon/ee+# Expected: exit 0+```++**Out of scope:** modifying storage-rules server/service beyond adding exports; touching plan.ts (key exists).++## Task 5: ERP module item-rules — models + service + barrel++**Depends on:** Task 2+**Files:**+- Create: `apps/erp/app/modules/item-rules/item-rules.models.ts`, `item-rules.service.ts`, `index.ts`+- Copy from (precedent): `apps/erp/app/modules/storage-rules/storage-rules.models.ts`, `storage-rules.service.ts`, `index.ts`++**Steps:**+1. `item-rules.models.ts` — clone the storage validator with these changes: drop `targetType` and `appliesToAll`; `surfaces: zfd.repeatableOfType(z.enum(ITEM_RULE_SURFACES)).refine(arr => arr.length >= 1, { message: "Pick at least one surface" })`; superRefine keeps ONLY the field-availability check, using `isFieldAvailableOnItemRuleSurfaces` (no targetType check needed). Export `itemRuleValidator`, `itemRuleAssignmentValidator = z.object({ itemId: z.string().min(1), ruleId: z.string().min(1) })`, `itemRuleSeverities = ["error","warn"] as const`.+2. `item-rules.service.ts` — mirror storage service exactly (`getStorageRules:52` → `getItemRules` filtering `itemRule` table; `getItemRule`, `upsertItemRule` (insert vs update branch on `createdBy`, cast `conditionAst` to `Json`), `deleteItemRule`, `getItemRuleAssignmentCounts` (single assignment table)).+3. `index.ts` barrel: `export * from "./item-rules.models"; export * from "./item-rules.service";` plus re-export from `@carbon/ee/item-rules`: `getActiveItemRulesForItems, getItemRuleAssignmentsForItem, getItemRulesList, assignItemRule, unassignItemRule`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0 (module compiles; not yet routed)+```++**Out of scope:** UI components (Task 7), routes (Task 8).++## Task 6: Value-options loaders++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/modules/storage-rules/ui/useValueOptions.ts` — add `customerTypes`, `customerStatuses`, `countries` loader branches+- Inspect for existing API routes: `apps/erp/app/routes/api+/sales.customer-types.ts` (exists — precedent for clientLoader caching); check for a customer-statuses api route and the countries api route (`path.to.api.countries` exists, used by `~/components/Form/Country.tsx`)++**Steps:**+1. Read `useValueOptions.ts` to learn the loader-branch shape (each `ValueOptionsLoader` maps to a fetch/store returning `{label, value}[]`).+2. Add three branches: `customerTypes` (fetch `path.to.api.customerTypes` if it exists — grep `customer-types` in `path.ts`; options `{label: name, value: id}`), `customerStatuses` (same pattern; if no api route exists, create `apps/erp/app/routes/api+/sales.customer-statuses.ts` copying `sales.customer-types.ts` with `getCustomerStatuses` from `~/modules/sales`), `countries` (fetch `path.to.api.countries`; options `{label: name, value: alpha2}` — value MUST be alpha2, matching `~/components/Form/Country.tsx:31-34`).+3. If `useValueOptions.ts` is structured as a switch over loader names, keep additions additive; do not alter existing branches.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** the `ValueCombobox` component internals.++## Task 7: UI — ItemRuleForm + ItemRulesTable++**Depends on:** Tasks 3, 5, 6+**Files:**+- Create: `apps/erp/app/modules/item-rules/ui/ItemRuleForm.tsx`, `ItemRulesTable.tsx`, `ui/index.ts`+- Modify (additive parameterization only): `apps/erp/app/modules/storage-rules/ui/RuleBuilder.tsx`, `SurfacesField.tsx` (and `ConditionRow.tsx`/`FieldCombobox.tsx` only if they hardcode targetType field lookups)+- Copy from (precedent): `apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx`, `StorageRulesTable.tsx`++**Steps:**+1. Read `RuleBuilder.tsx` + `SurfacesField.tsx`. Where they derive the field list / surface list from `targetType`, add OPTIONAL props: `fields?: FieldDef[]` (RuleBuilder — when provided, use instead of the targetType lookup) and `surfaceOptions?: { value: string; label: string; }[]` (SurfacesField). Defaults preserve current storage behavior exactly.+2. `ItemRuleForm.tsx` — clone StorageRuleForm: ModalDrawer + ValidatedForm with `validator={itemRuleValidator}`, action `path.to.itemRule(id)` / `path.to.newItemRule`; fields: Input name + Boolean active, TextArea description, SeveritySelect (reuse from `~/modules/storage-rules/ui` — export it from that module's ui index if not already), `ItemFilterSelector` (reuse), `SurfacesField` with `surfaceOptions=[{value:"quoteLine",label:"Quote line"},{value:"salesOrderLine",label:"Sales order line"}]`, `RuleBuilder` with `fields={getFieldsForItemRuleSurfaces(liveSurfaces)}`, `MessageWithTokens` (reuse), `CustomFormFields table="itemRule"`.+3. `ItemRulesTable.tsx` — clone StorageRulesTable with columns Name / Severity / Surfaces / Status / Items (assignment count); permission checks use `parts`; row menu edit/delete via `path.to.itemRule(id)` / `path.to.deleteItemRule(id)`.+4. If a shared component turns out to be too storage-coupled for a small optional-prop change (e.g. deep targetType branching), fork it into `modules/item-rules/ui/` with the minimal copy and note the fork in the run record — do NOT restructure the storage component.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+pnpm run lint+# Expected: exit 0 (or only pre-existing warnings)+```++**Out of scope:** StorageRuleForm behavior/визual changes; the `StorageRulesGroups` card layout (item rules use the table layout).++## Task 8: Routes, path helpers, react-query key, Items sidebar++**Depends on:** Tasks 5, 7+**Files:**+- Create: `apps/erp/app/routes/x+/items+/item-rules.tsx` (list), `item-rules.new.tsx`, `item-rules.$id.tsx`, `item-rules.$id.delete.tsx`+- Modify: `apps/erp/app/utils/path.ts` — add `itemRules: `${x}/items/item-rules``, `newItemRule`, `itemRule(id)`, `deleteItemRule(id)`, `itemRuleAssign(itemId)`, `itemRuleUnassign(itemId, ruleId)` in alphabetical position near the other `itemR*` helpers+- Modify: `apps/erp/app/utils/react-query.ts` — add `itemRulesQuery` cloning `storageRulesQuery` (line 188)+- Modify: `apps/erp/app/modules/items/ui/useItemsSubmodules.tsx` — add an "Item Rules" entry (`name: t\`Item Rules\``, `to: path.to.itemRules`) in the appropriate group+- Copy from (precedent): `apps/erp/app/routes/x+/inventory+/storage-rules.tsx`, `storage-rules.new.tsx`, `storage-rules.$id.tsx`, `storage-rules.$id.delete.tsx`++**Steps:**+1. Clone each storage-rules route file, swapping: module imports → `~/modules/item-rules`, permissions `inventory` → `parts`, plan gate `requirePlan({ feature: "ITEM_RULES", ... })` in new/`$id`/delete actions (copy the exact `requirePlan` usage from the storage new route), paths → item-rule helpers, list component → `ItemRulesTable`, and the upgrade overlay via `usePlanGate` with feature `ITEM_RULES`.+2. Breadcrumb `handle.breadcrumb: msg\`Item Rules\`` matching neighboring items routes.+3. Keep `clientAction` cache invalidation using `itemRulesQuery(getCompanyId()).queryKey` in mutating routes, mirroring storage routes.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+grep -n "itemRules" apps/erp/app/utils/path.ts+# Expected: the six new helpers+```++**Out of scope:** renaming or touching `$itemId.rule.tsx` (configurator).++## Task 9: Assignment routes + per-item drawer section++**Depends on:** Tasks 5, 8+**Files:**+- Create: `apps/erp/app/routes/x+/items+/item-rules.assign.$itemId.tsx`, `item-rules.unassign.$itemId.$ruleId.tsx`+- Modify: the per-item Rules drawer usage — read `apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx` and its mount in `apps/erp/app/routes/x+/part+/$itemId.inventory.tsx`+- Copy from (precedent): `apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx`, `rules.unassign.$itemId.$ruleId.tsx` (storage-rule item assignment routes)++**Steps:**+1. Clone the two storage assignment routes → item-rule equivalents calling `assignItemRule` / `unassignItemRule`, permission `update: "parts"`, plan gate `ITEM_RULES`.+2. Parameterize `RuleAssignmentsList` with optional props (`title?`, data-loader results + assign/unassign action paths passed in) OR render a second instance: in `$itemId.inventory.tsx`, load `getItemRuleAssignmentsForItem` alongside the existing storage call and render an "Item rules" section beneath the storage one in the same drawer. Choose the smaller diff; keep storage behavior identical.+3. If the drawer is mounted in multiple item-type routes (`tool+`, `material+`, `consumable+` `$itemId.inventory.tsx`), apply the same change ONLY to `part+` in this task and note the others as follow-up in the run record (parts are the sales-relevant type).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** the other item-type inventory routes (recorded follow-up).++## Task 10: Enforcement — quote line create/edit++**Depends on:** Task 4+**Files:**+- Modify: `apps/erp/app/routes/x+/quote+/$quoteId.new.tsx` — after validation, before `upsertQuoteLine` (~line 64)+- Modify: `apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx` — same evaluation in its update action+- Copy from (precedent): `apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx:34-111` (acknowledged → evaluate → dedupe → isBlocked → return violations)++**Steps:**+1. In each action, after `validator(...)` success: read `const acknowledged = formData.get("acknowledged") === "true"`.+2. Load the quote header (already loaded or via `getQuote`) for `customerId` + `customerLocationId`.+3. `const serviceRole = getCarbonServiceRole();` then:+ ```ts+ const { violations, ruleNames } = await evaluateItemRuleLines({+ client: serviceRole, companyId, userId, surface: "quoteLine",+ lines: [{ lineId: id ?? "new", itemId: validation.data.itemId ?? null, quantity: validation.data.quantity ?? 1 }],+ customerId: quote.customerId, customerLocationId: quote.customerLocationId ?? null+ });+ const deduped = dedupeViolations(violations);+ if (isBlocked(deduped, acknowledged)) {+ return { error: null, data: null, violations: deduped, ruleNames };+ }+ ```+ Import from `@carbon/ee/item-rules.server`. Match the exact return shape the shipment post route uses so `useStorageRuleViolations` picks it up.+4. Escape hatch: if the quote line validator has no single `quantity` field (quotes may have quantity arrays), use `1` as the transaction quantity and note it — quantity rules are out of scope for quotes v1.+5. Do not alter the success path (redirect/method resolution) otherwise.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** configurator flow branches in the quote action; pricing logic.++## Task 11: Enforcement — sales-order line create/edit++**Depends on:** Task 4+**Files:**+- Modify: `apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx` (before `upsertSalesOrderLine`, ~line 65)+- Modify: `apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx` (update action)+- Copy from (precedent): same as Task 10++**Steps:** identical wiring with `surface: "salesOrderLine"`, header from `getSalesOrder` route data (`customerId`, `customerLocationId`), `quantity: validation.data.saleQuantity ?? validation.data.quantity ?? 1` (read the SO line validator to pick the real field; if neither exists, use 1 and note).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** shipment/invoice-related SO actions.++## Task 12: Wire line forms through the violation hook++**Depends on:** Tasks 10, 11+**Files:**+- Modify: `apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx`+- Modify: `apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx`+- Copy from (precedent): `apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx` (or `ShipmentPostModal.tsx`) — how a caller swaps `fetcher.submit` for `rules.submit` and renders `<rules.ViolationModal/>`++**Steps:**+1. Read the precedent to copy the exact hook usage: `const rules = useStorageRuleViolations({ action: <the form's action path> })` from `@carbon/ee/storage-rules`.+2. In each form: route the ValidatedForm submission through the hook's fetcher (`fetcher={rules.fetcher}` if the hook exposes it, else follow the precedent's mechanism exactly) and render `<rules.ViolationModal />` inside the component tree.+3. The acknowledge re-submit appends `acknowledged=true` automatically (hook behavior) — no form changes needed for that.+4. Escape hatch: if `ValidatedForm` + the hook's fetcher don't compose (hook expects manual `submit(formData)`), follow the precedent's onSubmit interception pattern; if neither fits within a small diff, STOP and report with the structural mismatch.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** the inline supersession notice in `~/components/Form/Item.tssx` (stays), ConfiguratorModal.++## Task 13: Notifications++**Depends on:** Tasks 10, 11+**Files:**+- Modify: `packages/notifications/src/index.ts` — add `ItemRuleViolation` to `NotificationEvent` (line ~7), map it in `getNotificationTopic` (choose an existing suitable topic or add `ItemRules` topic + display entry), add email heading/CTA entries in `getNotificationEmailHeading`/`getNotificationEmailCtaLabel`+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — recipient resolution branch for the new event: recipients = company setting `itemRuleNotificationGroup`; default destinations InApp (+Email)+- Modify: `apps/erp/app/modules/settings/settings.models.ts` — add `itemRuleNotificationGroup: z.array(z.string()).optional()` beside `suggestionNotificationGroup` (line ~267); grep `suggestionNotificationGroup` across `apps/erp` to find the settings UI + save action and add the matching field/select there+- Modify: the four enforcement actions (Tasks 10–11) — after the outcome is known, fire-and-forget:+ ```ts+ await trigger("notify", { event: NotificationEvent.ItemRuleViolation, companyId, ... payload: { ruleIds, documentType, documentId, itemIds, outcome: blocked ? "blocked" : "acknowledged", actorId: userId } });+ ```+ matching the exact `trigger("notify", …)` call shape used elsewhere (grep `trigger("notify"` in `apps/erp` for the canonical invocation and payload keys). Fire ONLY when `deduped.length > 0` AND (blocked OR acknowledged-proceed) — never on clean submissions.++**Steps:** as above; read each precedent site before editing; keep the notify handler branch minimal (resolve group members → deliver via existing machinery).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp --filter=@carbon/jobs+# Expected: exit 0+pnpm --filter @carbon/notifications typecheck 2>/dev/null || pnpm exec turbo run typecheck --filter=@carbon/notifications+# Expected: exit 0+```++**Out of scope:** Slack destination config, digest inclusion, recurring-notification logic.++## Task 14: Acknowledgment persistence++**Depends on:** Tasks 10, 11+**Files:**+- Modify: the four enforcement actions — when violations exist and the action PROCEEDS (acknowledged warns), and when it BLOCKS, insert `itemRuleAcknowledgment` rows (one per deduped violation) via the service-role client:+ ```ts+ await serviceRole.from("itemRuleAcknowledgment").insert(deduped.map(v => ({+ companyId, ruleId: v.ruleId, documentType: "quote" /* or "salesOrder" */,+ documentId: quoteId, documentLineId: lineId ?? null, itemId: itemId ?? null,+ severity: v.severity, outcome: blocked ? "blocked" : "acknowledged",+ message: v.message, createdBy: userId+ })));+ ```+ Insert failures must not break the action — log and continue (wrap in try/catch or check error without returning).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/erp+# Expected: exit 0+```++**Out of scope:** an acknowledgments viewing UI (future).++## Task 15: Docs++**Depends on:** Task 4 (naming settled)+**Files:**+- Modify: `packages/utils/AGENTS.md` — replace the "Ask First" line "Modifying `storage-rules.ts` — affects Supabase storage bucket policies and file access patterns." with "Modifying `storage-rules.ts` / `field-registry.ts` — the rule-evaluation engine shared by storage rules and item rules; changes affect rule evaluation across ERP and MES." and the Key Modules row "`storage-rules` | Supabase storage bucket access policies" with "`storage-rules` | Rule engine: condition AST compiler/evaluator for storage + item rules"; fix the `field-registry` row to "Field registry for the rule builder/evaluator".+- Create: `apps/erp/app/modules/item-rules/AGENTS.md` — short module guide following a sibling (`modules/storage-rules` has none; use the AGENTS.md template from `.claude/skills/create-agents-md` conventions: purpose, key tables, service functions, safety notes incl. "reuses the shared engine in @carbon/utils; never fork the modal").++**Verify:**+```bash+grep -c "storage bucket" packages/utils/AGENTS.md+# Expected: 0+```++**Out of scope:** `.claude/rules/*` updates (uncommitted work must not be documented there per keep-sources-in-sync).++## Task 16: Final verification sweep++**Depends on:** all+**Steps:**+1. `pnpm exec turbo run typecheck --filter=@carbon/utils --filter=@carbon/ee --filter=@carbon/database --filter=@carbon/erp --filter=@carbon/jobs`+2. `pnpm --filter @carbon/utils test && pnpm --filter @carbon/ee test`+3. `pnpm run lint`+4. Update `.ai/runs/2026-08-11-item-rules.md` phase log + outcome. DO NOT COMMIT — report working-tree summary (`git status --porcelain | head -40`) to the user.++**Verify:** all commands exit 0; report includes file list.diff --git a/.ai/plans/2026-08-15-merge-rule-tables.md b/.ai/plans/2026-08-15-merge-rule-tables.mdindex ef16eb8eb9..88918f9e22 100644--- a/.ai/plans/2026-08-15-merge-rule-tables.md+++ b/.ai/plans/2026-08-15-merge-rule-tables.md@@ -1,7 +1,7 @@# Implementation plan — Sales Rules on a unified `enforcementRule` table- Date: 2026-08-15-- Spec: `.ai/specs/2026-08-11-item-rules.md`+- Spec: `.ai/specs/implemented/2026-08-11-item-rules.md`- Scope of this plan: the **data model and code layer** — create the unified rule table, move the shipped Storage Rules onto it, and build the sales family on top. The sales enforcement gates, notifications, and acknowledgment evidence are specified in the spec's Phase 1–3 and planned separately.## Starting pointdiff --git a/.ai/research/2026-08-11-item-rules.md b/.ai/research/2026-08-11-item-rules.mdindex 0a8459f2dc..9e554e089a 100644--- a/.ai/research/2026-08-11-item-rules.md+++ b/.ai/research/2026-08-11-item-rules.md@@ -46,4 +46,4 @@ Separate `itemRule` table + Items-module home (clean `parts_*` permissions, ownTwo stale-doc findings for whoever touches the engine: `packages/utils/AGENTS.md` described `storage-rules.ts` as "Supabase storage bucket access policies" (it is the rule engine), and older references to a `db:build` script are dead.-**Spec:** `.ai/specs/2026-08-11-item-rules.md`+**Spec:** `.ai/specs/implemented/2026-08-11-item-rules.md`diff --git a/.ai/runs/2026-08-11-item-rules.md b/.ai/runs/2026-08-11-item-rules.mdnew file mode 100644index 0000000000..de6e35e925--- /dev/null+++ b/.ai/runs/2026-08-11-item-rules.md@@ -0,0 +1,31 @@+# Feature run: Item Rules (Phases 1–2)++- Date: 2026-08-11+- Mode: fully-autonomous+- Request: "implement this fully" — the Item Rules feature (Phases 1–2) from the finalized PRD at ~/Downloads/carbon_item_rules_prd.html+- Phase plan: research [skip — completed in-session via two Explore agents (storage-rules architecture map + customer/sales-flow map); findings baked into the PRD] · spec [run — convert finalized PRD to canonical .ai/specs artifact; zero open questions remain] · plan [run] · execute [run — commits DEFERRED per standing user instruction (never commit without explicit ask); verified changes left in working tree] · test [skip — standing user instruction: no browser unless asked; verify via typecheck + unit tests] · self-review [run]++## Decisions+- Autonomy mode: fully-autonomous — "implement this fully" + session operating autonomously. (2026-08-11)+- Spec gate (🛑 open questions): auto-passed — PRD explicitly resolved all seven design questions (§3.6 decided conventions + §3.7); nothing open. (2026-08-11)+- Branch: build on current branch `cambridge-bom-feature-gap-audit` (Conductor workspace; renaming/creating refs without asking is disallowed; no commits will be made anyway). (2026-08-11)+- Commits: deferred entirely — user memory requires explicit "commit" green light; /execute verification gates still run per task. (2026-08-11)+- Pre-existing working-tree modifications to generated DB type files (packages/database/src/types.ts, swagger-docs-schema.ts, functions/lib/types.ts) noted at run start — investigate before applying migration; never hand-edit. (2026-08-11)++## Follow-on refactor: "Option A" rules code unification (2026-08-11)+- Decision: keep storageRule/itemRule tables separate (RLS simplicity, self-hosted unattended migrations, schema-divergence pressure); unify the CODE layer under `rules` naming. Table merge (Option B/B′) deliberately deferred until a real cross-family requirement appears — analysis recorded in conversation + spec unaffected.+- Scope: packages/utils storage-rules.ts → rules.ts (symbols unchanged); packages/ee/src/{storage-rules,item-rules} → src/rules/{storage,item} with shared modal+hook at rules/ root; exports ./rules + ./rules.server replace ./storage-rules(.server) + ./item-rules(.server), no aliases; StorageRuleViolationModal→RuleViolationModal, useStorageRuleViolations→useRuleViolations; full import sweep (ERP+MES+packages); AGENTS.md sync. Tables/RLS/plan keys/admin modules untouched.+- COMPLETE + verified: 31 import sites swept (ERP 27, MES 4); zero residual old-path/name greps; typechecks green (utils, ee, erp, mes); tests 76+40 pass; lint clean; renames via git mv. Collision (isBlocked/dedupeViolations dual re-export) resolved with explicit named re-exports in rules/server.ts. Docs synced (utils/ee/item-rules AGENTS.md + 2 .claude/rules files). Spec updated to new paths, pushed to PR #1368 as b1c750457.++## Phase log+- research: skipped (see Phase plan) — evidence lives in the PRD (storage-rules engine map, customer/location model, line-add flows)+- spec: .ai/specs/implemented/2026-08-11-item-rules.md (converted from PRD)++## Outcome+- All 16 plan tasks complete. Verification sweep green: typecheck 6/6 packages (@carbon/utils, @carbon/ee, @carbon/database, erp, @carbon/jobs, @carbon/notifications), @carbon/utils 76 tests, @carbon/ee 40 tests, lint clean (32 tasks, only pre-existing warnings).+- Implementation left UNCOMMITTED in the working tree per standing instruction; user reviews and green-lights the commit.+- Two migrations created + applied locally: 20260810214426_item-rules-sales.sql (planned) and 20260810221652_item-rule-notification-group.sql (Task 13 deviation — companySettings.itemRuleNotificationGroup was missing from the plan; additive, flagged).+- Notable deviations (all recorded in agent reports + plan notes): RuleSurface union widening in the engine; ITEM_RULE_FIELD_REGISTRY kept separate from FIELD_REGISTRY; ItemRuleAssignmentsList forked (storage component too coupled); quote transaction quantity = 1 (quantity-break arrays); compound notify documentId ("<type>:<id>:<outcome>") because the notify payload's documentType is a narrower enum; modal-mode onClose moved to onSuccess in both line forms (hook contract).+- Docs PR: https://github.com/crbnos/carbon/pull/1368 (research + spec, updated with data model / API / UI change summary + SQL snippets).+- CodeRabbit review (13 findings) triaged and resolved: 8 spec fixes (canonical evaluator name/signature, existing ITEM_RULES key, blocked-outcome prose, item-only guard, selection contract, assignment tenancy note, customer-context completeness), 2 documented design decisions (evidence atomicity best-effort; per-outcome notification scope, dedup key as follow-up), 2 pre-addressed (surface separation, name uniqueness), 1 implementation improvement: acknowledged-path evidence in the two create actions now inserts AFTER the line write with documentLineId = created line id (blocked path unchanged, null). Validated: erp typecheck exit 0, biome clean. Spec fixes pushed as 9de8a652e.+- Follow-ups recorded: item-rules card on tool/material/consumable inventory routes (part+ only in v1); SurfaceChips not parameterized (plain badges for item surfaces); no item-rule condition-value label resolver wired into evaluateItemRuleLines' message interpolation (labels resolve in builder + storage loaders, raw values in violation messages).diff --git a/.ai/specs/2026-08-11-item-rules.md b/.ai/specs/implemented/2026-08-11-item-rules.mdsimilarity index 98%rename from .ai/specs/2026-08-11-item-rules.mdrename to .ai/specs/implemented/2026-08-11-item-rules.mdindex 87970c26c3..a62019ca64 100644--- a/.ai/specs/2026-08-11-item-rules.md+++ b/.ai/specs/implemented/2026-08-11-item-rules.md@@ -1,6 +1,6 @@# Sales Rules — commercial & compliance checks on sales documents-- Status: **Ready to implement** (all design questions resolved)+- Status: **Implemented** on `naveen/item-rules` (sales-invoice surface added 2026-08-26: `salesInvoiceLine` enum value + CHECK widening, line gates on the two invoice write routes, terminal gate in `$invoiceId.post.tsx` before the `Pending` write, MCP backstop for `invoicing_upsertSalesInvoiceLine`, per-source-order ship-to resolution pinned by `packages/ee/src/rules/sales/invoice-shipto.test.ts`)- Date: 2026-08-11- Research: `.ai/research/2026-08-11-item-rules.md`, `.ai/research/2026-08-12-item-rules-enforcement-surface.md`- Scope: Phase 1 (data model + engine extensions + admin UI + sales-line enforcement) · Phase 2 (notifications + acknowledgment evidence) · Phase 3 (enforcement completeness — terminal gates through invoice post, unbypassable hard errors)diff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.mdindex b28b5106b4..7dabbd1a0d 100644--- a/.claude/rules/billing-system.md+++ b/.claude/rules/billing-system.md@@ -82,7 +82,7 @@ several `invoice.*` events are forwarded to GTM.## Plan gating (`packages/ee/src/plan.ts` + `plan.server.ts`)`FEATURE_PLANS` (`plan.ts`) is the source of truth — both client and server read it:-`API_KEYS, WEBHOOKS, INTEGRATIONS, ITEM_RULES, AUDIT_LOG, EMAIL_NOTIFICATIONS, STORAGE_RULES,+`API_KEYS, WEBHOOKS, INTEGRATIONS, SALES_RULES, AUDIT_LOG, EMAIL_NOTIFICATIONS, STORAGE_RULES,CUSTOMER_PORTALS` → each `[Plan.Business, Plan.Partner]`. `INTEGRATION_WHITELIST`(`email`) bypasses the `INTEGRATIONS` gate.diff --git a/.claude/rules/coding-conventions.md b/.claude/rules/coding-conventions.mdindex bc24a4ee20..1cfb74f843 100644--- a/.claude/rules/coding-conventions.md+++ b/.claude/rules/coding-conventions.md@@ -67,11 +67,20 @@ modules/{module}/(`~/modules/sales`), not deep files.**Folder names are kebab-case.** Multi-word directories use hyphens, not-camelCase — `modules/storage-rules`, `packages/ee/src/storage-rules` (not-`storageRules`). This applies to all directories (modules, package subdirs,-`ui/` groupings). React components inside still use PascalCase filenames-(`StorageRuleForm.tsx`); the `{module}.*.ts` service/model file prefixes mirror-their folder name.+camelCase — `packages/ee/src/paperless-parts`, `packages/ee/src/rules` (not+`paperlessParts`). This applies to modules and package subdirs. The `ui/`+feature groupings inside a module are the exception: they are PascalCase and+match the feature (`ui/StorageRules/`, `ui/SalesRules/`, `ui/WarehouseTransfers/`),+as are the React component filenames inside them (`StorageRuleForm.tsx`). The+`{module}.*.ts` service/model file prefixes mirror their folder name.++**A feature is not automatically a module.** A module is a business domain, and+it owns exactly one `{module}.models.ts` / `{module}.service.ts` pair. Sub-features+live *inside* their domain module as a `ui/{Feature}/` folder plus functions in+that one service/models file — e.g. storage rules live in `~/modules/inventory`+and sales rules in `~/modules/sales`, not in standalone `modules/storage-rules` /+`modules/sales-rules` directories. Create a new module only for a genuinely new+domain.MES is lighter: services live under `apps/mes/app/services/`, components under`apps/mes/app/components/`.diff --git a/.claude/rules/conventions-forms.md b/.claude/rules/conventions-forms.mdindex 804835fe28..2d94991008 100644--- a/.claude/rules/conventions-forms.md+++ b/.claude/rules/conventions-forms.md@@ -20,8 +20,9 @@ Real reference examples (current code):`payment-terms.$paymentTermId.tsx` (edit).- `apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx` +`apps/erp/app/routes/x+/resources+/work-centers.new.tsx`.-- `apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx` (uses `.superRefine`,- `zfd.checkbox`, `zfd.repeatableOfType`).+- `apps/erp/app/modules/inventory/ui/StorageRules/StorageRuleForm.tsx` (uses+ `.superRefine`, `zfd.checkbox`, `zfd.repeatableOfType`; its validator lives in+ the module's one `inventory.models.ts`).## File Locationsdiff --git a/.claude/rules/database-migration-patterns.md b/.claude/rules/database-migration-patterns.mdindex 4596e761df..6d7ed87e5f 100644--- a/.claude/rules/database-migration-patterns.md+++ b/.claude/rules/database-migration-patterns.md@@ -153,7 +153,7 @@ inside a transaction block with other statements that use the value).## Gotchas- Read the **newest** migration touching a table/function — renames (`shelf`→`storageUnit`,- `customRule`→`storageRule`) and revised RPCs are common.+ `customRule`→`storageRule`→`enforcementRule`) and revised RPCs are common.- Schema-qualify (`"public"."t"`) on RLS statements; cast helper results `::text[]`.- After adding a migration, regenerate types (`pnpm db:types`) or typecheck breaks with`SelectQueryError` / "excessively deep" errors.diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex cab0e8d5b9..ac7024348d 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -128,7 +128,7 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal- **`stockTransfer*`** — intra-location moves (separate from warehouse transfers).- **`pickMethod`** — default storage unit for picking an item at a location (`defaultStorageUnitId`).- **`itemPlanning`** / **`itemReplenishment`** — reorder/planning params and replenishment strategy.-- **`storageRule`** + assignment tables — renamed from `customRule`/`itemRule` (`20260603130000`).+- **`enforcementRule`** + assignment tables — ONE table for storage and sales rules, discriminated by `family` (`20260817143022`/`20260817143512`). Storage-family reads must filter `family = 'storage'`. Lineage: `itemRule` → `customRule` → `storageRule` → merged into `enforcementRule`.`get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)` — the centralread. Newest definition is `20260713235406_item-ledger-snapshot.sql` (snapshot + delta via@@ -148,7 +148,7 @@ Relevant enums: `itemLedgerType`, `itemLedgerDocumentType` (includes `Scrap`,## Gotchas- **Migrations are timestamp-ordered; tables get renamed.** `shelf`→`storageUnit`/`shelfId`→`storageUnitId`,- `customRule`→`storageRule`. Grep the NEWEST migration for the real name; never trust an older one or the+ `customRule`→`storageRule`→`enforcementRule` (merged with `salesRule`). Grep the NEWEST migration for the real name; never trust an older one or theold cache. The `shelf`→`storageUnit` rename was split across paired migrations`20260417000100` (rename, M2) + `..000300` (recreate dependents, M4) — they must apply together.- **Short-closed PO lines don't count as incoming supply.** `get_inventory_quantities`,diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex bab1f9b062..3fd343ec9f 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -441,7 +441,7 @@ the model context or the MCP dispatch.- To block a tool from MCP, add its `<module>_<func>` name to`MCP_BLOCKED_TOOL_NAMES` and regenerate metadata.- **A `{module}.service.ts` must not import a `*.server` module** (`@carbon/auth/users.server`,- `@carbon/ee/storage-rules.server`, an app `*.server.ts`, …) — even via `await import(...)`.+ `@carbon/ee/rules.server`, an app `*.server.ts`, …) — even via `await import(...)`.The module barrel (`~/modules/{module}`) re-exports the service, and client componentsvalue-import that barrel for validators/enums, so the service is in the **client** bundle;React Router's `react-router:dot-server` plugin then fails the build with *"Server-onlydiff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.mdindex dcc8d8b421..749a10e207 100644--- a/.claude/rules/shipments-receipts-ui-patterns.md+++ b/.claude/rules/shipments-receipts-ui-patterns.md@@ -66,7 +66,7 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship- **Status** (`ShipmentStatus.tsx`, `ReceiptStatus.tsx`): `Draft`(gray) `Pending`(orange)`Posted`(green) `Voided`(red). Shipment additionally shows `Invoiced`(blue) when `invoiced` and not voided.- **Modals**: `ReceiptPostModal` (validates lines on mount — batch lines need a batch number,- serials reconciled across indices `0..receivedQuantity`; uses `useStorageRuleViolations`),+ serials reconciled across indices `0..receivedQuantity`; uses `useRuleViolations`),`ShipmentVoidModal` / `ReceiptVoidModal` (destructive `Alert` + bulleted consequences, submitvia `fetcher.Form` to the void route). Shipment posting is gated by `ShipmentPostModal.tsx`.**Both post modals are source-aware for return flows**, and must stay in step with@@ -79,7 +79,7 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship## Posting flow (`$id.post.tsx` → edge fn)-The route action: evaluates storage/item rules (`@carbon/ee/storage-rules.server`) over the+The route action: evaluates storage/sales rules (`@carbon/ee/rules.server`) over therelevant surfaces, optimistically sets `status: "Pending"`, then`serviceRole.functions.invoke("post-shipment" | "post-receipt", { body: { type: "post", id, userId, companyId } })`.On error it reverts status to `Draft`. May then auto-print and (sales shipment) generate a packingdiff --git a/apps/erp/app/components/Form/Country.tsx b/apps/erp/app/components/Form/Country.tsxindex 988e5bb137..925b0f5112 100644--- a/apps/erp/app/components/Form/Country.tsx+++ b/apps/erp/app/components/Form/Country.tsx@@ -1,6 +1,7 @@import type { ComboboxProps } from "@carbon/form";import { useMount } from "@carbon/react";import { useLingui } from "@lingui/react/macro";+import { useMemo } from "react";import { useFetcher } from "react-router";import { Combobox } from "~/components/Form";import type { getCountries } from "~/modules/shared";@@ -19,19 +20,19 @@ Country.displayName = "Country";export default Country;-export const useCountries = () => {+export const useCountries = (enabled = true) => {const countryFetcher = useFetcher<Awaited<ReturnType<typeof getCountries>>>();useMount(() => {- countryFetcher.load(path.to.api.countries);+ if (enabled) countryFetcher.load(path.to.api.countries);});- const countries = countryFetcher.data?.data ?? [];-- const options = countries.map((c) => ({- value: c.alpha2,- label: c.name- }));+ const options = useMemo(() => {+ return (countryFetcher.data?.data ?? []).map((c) => ({+ value: c.alpha2,+ label: c.name+ }));+ }, [countryFetcher.data?.data]);return options;};diff --git a/apps/erp/app/components/Form/CustomerStatus.tsx b/apps/erp/app/components/Form/CustomerStatus.tsxindex 37d08891fd..cc07fce98c 100644--- a/apps/erp/app/components/Form/CustomerStatus.tsx+++ b/apps/erp/app/components/Form/CustomerStatus.tsx@@ -67,7 +67,7 @@ CustomerStatus.displayName = "CustomerStatus";export default CustomerStatus;-export const useCustomerStatuses = () => {+export const useCustomerStatuses = (enabled = true) => {const customerStatusFetcher =useFetcher<Awaited<ReturnType<typeof getCustomerStatusesList>>>();@@ -78,7 +78,7 @@ export const useCustomerStatuses = () => {const hasCustomerData = sharedCustomerData?.customerStatuses;useMount(() => {- if (!hasCustomerData)+ if (enabled && !hasCustomerData)customerStatusFetcher.load(path.to.api.customerStatuses);});diff --git a/apps/erp/app/components/Form/CustomerType.tsx b/apps/erp/app/components/Form/CustomerType.tsxindex 76b8c0ac4e..81b62de44e 100644--- a/apps/erp/app/components/Form/CustomerType.tsx+++ b/apps/erp/app/components/Form/CustomerType.tsx@@ -64,12 +64,12 @@ CustomerType.displayName = "CustomerType";export default CustomerType;-export const useCustomerTypes = () => {+export const useCustomerTypes = (enabled = true) => {const customerTypeFetcher =useFetcher<Awaited<ReturnType<typeof getCustomerTypesList>>>();useMount(() => {- customerTypeFetcher.load(path.to.api.customerTypes);+ if (enabled) customerTypeFetcher.load(path.to.api.customerTypes);});const options = useMemo(() => {diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 3f1ab64462..aed955e6e4 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -317,6 +317,23 @@ function GenericNotification({{...props}/>);+ case NotificationEvent.SalesRuleViolation: {+ // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"+ const [docType, docId] = id.split(":");+ return (+ <Notification+ icon={<LuShieldAlert />}+ to={+ docType === "salesInvoice"+ ? path.to.salesInvoiceDetails(docId ?? "")+ : docType === "salesOrder"+ ? path.to.salesOrderDetails(docId ?? "")+ : path.to.quoteDetails(docId ?? "")+ }+ {...props}+ />+ );+ }case NotificationEvent.IntegrationSync:// id is the provider id ("rillet", "xero", ...) — link to that// integration's settings page, where the Sync Activity tab lives.diff --git a/apps/erp/app/components/RulesUpgradeOverlay.tsx b/apps/erp/app/components/RulesUpgradeOverlay.tsxnew file mode 100644index 0000000000..372fa7a0bd--- /dev/null+++ b/apps/erp/app/components/RulesUpgradeOverlay.tsx@@ -0,0 +1,51 @@+// Plan-gate overlay shell shared by the two rule families (Inventory → Storage+// Rules, Sales → Sales Rules). The families differ only in their preview table,+// their mock fixtures, and their copy — the overlay chrome is identical, so it+// lives here once. A third family gets the overlay for free.++import type { ReactNode } from "react";+import { LuShieldCheck } from "react-icons/lu";+import {+ UpgradeOverlay,+ UpgradeOverlayActions,+ UpgradeOverlayCard,+ UpgradeOverlayContent,+ UpgradeOverlayDescription,+ UpgradeOverlayIcon,+ UpgradeOverlayPreview,+ UpgradeOverlayTitle,+ UpgradeOverlayUpgradeButton+} from "~/components/UpgradeOverlay";++type RulesUpgradeOverlayProps = {+ /** Blurred table rendered behind the upgrade card. */+ preview: ReactNode;+ /** Feature name — already wrapped in `<Trans>` by the caller. */+ title: ReactNode;+ /** One-sentence pitch — already wrapped in `<Trans>` by the caller. */+ description: ReactNode;+};++export default function RulesUpgradeOverlay({+ preview,+ title,+ description+}: RulesUpgradeOverlayProps) {+ return (+ <UpgradeOverlay>+ <UpgradeOverlayPreview>{preview}</UpgradeOverlayPreview>+ <UpgradeOverlayCard>+ <UpgradeOverlayIcon>+ <LuShieldCheck className="size-6 text-muted-foreground" />+ </UpgradeOverlayIcon>+ <UpgradeOverlayContent>+ <UpgradeOverlayTitle>{title}</UpgradeOverlayTitle>+ <UpgradeOverlayDescription>{description}</UpgradeOverlayDescription>+ </UpgradeOverlayContent>+ <UpgradeOverlayActions>+ <UpgradeOverlayUpgradeButton />+ </UpgradeOverlayActions>+ </UpgradeOverlayCard>+ </UpgradeOverlay>+ );+}diff --git a/apps/erp/app/modules/agent/kb/docs/reference/sales-rules.md b/apps/erp/app/modules/agent/kb/docs/reference/sales-rules.mdnew file mode 100644index 0000000000..f80e8d23d4--- /dev/null+++ b/apps/erp/app/modules/agent/kb/docs/reference/sales-rules.md@@ -0,0 +1,127 @@+# Sales rules++> Predicate guards on sales documents: block a restricted item with an error, or warn and let the user acknowledge and continue.++A **sales rule** is a guard that runs when an item is put on a sales document. It checks the line against a+condition you define and, if the condition fails, either **blocks** the write or **warns** and lets the user+acknowledge and continue. Rules fire on **quote lines**, **sales order lines**, and **sales+invoice lines**.++For example, to keep an export-controlled part away from a restricted destination: scope the rule to the+item's group, fire on all three surfaces, and require `customer.location.countryCode` `notIn` your restricted+list. Severity **error**, message `` `{item.id}` cannot ship to this destination``. Add that item to a quote+for a customer in a listed country and the line is stopped with exactly that message.++Sales rules are a **compliance** layer, not a hint. They re-run at every commitment point — finalizing a+quote, converting it to an order, confirming the order, posting the shipment, posting the invoice — so a line+that slipped in through a conversion, an import, or the API is still caught before it matters. A blocked+document writes nothing.++## What a rule checks++Each rule holds a small **condition tree**, a match kind over one or more field/operator/value rows:++- **Match kind**: `all` (every condition must hold), `any` (at least one), or `none` (none may hold).+- **Field**: chosen from a fixed registry: item facts (`item.type`, `item.replenishmentSystem`,+ `item.itemTrackingType`, item custom fields), customer facts (`customer.customerTypeId`,+ `customer.customerStatusId`, customer custom fields), the document's ship-to country+ (`customer.location.countryCode`), and the line's `transaction.quantity`.+- **Operator**: `eq`, `neq`, `in`, `notIn`, `isSet`, `isNotSet`, `gt`, `lt`.++The **message** shown on a violation supports tokens like `` `{item.id}` `` and+`` `{customer.location.countryCode}` ``, so the text can name the offending line. The rule "passes" when its+conditions hold; a violation fires when they don't.++Aside from the `isSet` / `isNotSet` checks, a condition pointing at a field that has **no value** fails as a+*"…is required"* violation. A country rule on an order with no ship-to location fails closed as *"Customer+location is required"* rather than waving the line through. The same applies to a standalone invoice line+with no source order: it has no ship-to, and the bill-to address is never substituted for it.++## Where rules fire++A rule lists the **surfaces** (sales-document line types) it applies to: `quoteLine`, `salesOrderLine`, and+`salesInvoiceLine`. Two kinds of checkpoint run them:++- **Line checks** as a line is created or edited on a quote, sales order, or sales invoice.+- **Document gates** at each commitment point: finalizing a quote, converting a quote to an order (or an RFQ to a quote),+ confirming a sales order, posting its shipment, and posting a sales invoice. The gate re-reads **every**+ line on the document, so it also catches staleness — a rule authored after the line was written, or a+ ship-to that changed.++The ship-to that country rules evaluate is where the goods actually go: a drop shipment+overrides the order header's address, and an invoice line converted from a sales order resolves its+destination through that order.++On the customer-facing digital quote page, `error` violations refuse acceptance with a neutral message and+your internal rule text never reaches the customer. `warn` violations are logged for the seller and the+acceptance proceeds — there is no employee present to acknowledge them.++## Block or warn++| Severity | Behavior |+| --- | --- |+| `error` | Blocks the line or document until the condition is satisfied. Cannot be acknowledged past. |+| `warn` | Surfaces the message but lets the user **acknowledge and continue**. |++Both outcomes leave a trail: a blocked write and an acknowledged warning are each recorded as evidence+(rule, document, line, item, who, when), and the people in the **sales rule notification group**+(Settings → Sales) are notified by email.++## Scope and assignment++A rule reaches the lines it applies to in one of two ways:++- **By filter**: scope to **item types** and/or **item groups**, combined with OR or AND. An empty filter+ matches **every** item.+- **By assignment**: pin a rule to a specific item from the **Sales rules** card on that item's Inventory+ page.++Unlike `docs/reference/storage-rules`, sales rules always target items — there is no+work-center target.++## Rule fields++ - **Name**: A unique name for the rule.+ - **Severity**: `error` (block) or `warn` (acknowledge and continue).+ - **Conditions**: The match kind plus the field / operator / value rows.+ - **Message**: Shown on a violation; supports `{token}` interpolation.+ - **Surfaces**: Which sales-document lines the rule fires on.+ - **Item filters**: Item types and/or groups to scope a rule (empty = all items).+ - **Active**: Whether the rule is currently evaluated.++## Where to manage them++Sales rules live in the **Sales** area, under **Sales Rules**. Create, edit, and toggle them there. To attach+an existing rule to a single item, use the **Sales rules** card on the item's Inventory page.++Sales rules are an **Enterprise** capability, gated to the **Business** plan. On other plans the screen shows+an upgrade prompt and no rules are evaluated.++## Related++ - Storage rules The sibling rule family: the same condition builder, applied to inventory transactions instead of sales+ documents.+ - Quotes The first surface: rules run as quote lines are written and again at finalize and convert.+ - Sales orders Rules gate order confirmation and the shipment that fulfills it.+ - Invoices The last checkpoint: an invoice raised with no upstream order is still checked at post.++## Troubleshooting++Sales-rule violations carry **custom, company-authored messages** — there is no fixed error string to match.+If a user pastes an unfamiliar error from saving a quote, sales order, or sales invoice line, or from+finalizing, converting, confirming, or posting one of those documents, and it reads like a business rule+("cannot ship to this destination", "customer status", a country or item named in the text), it is very+likely a sales rule firing.++How to resolve one:+1. Find the rule: **Sales → Sales Rules** — the rule's *Message* column will match the pasted text (token+ values like the item id filled in).+2. If the document is wrong, fix the data the rule checks: the customer's ship-to location, the customer+ type or status, the item on the line.+3. If the rule is wrong or too strict, edit its conditions, change its severity from `error` to `warn`, or+ toggle it off (*Active*).+4. A `warn`-severity violation isn't an error — the user can acknowledge the dialog and resubmit; it goes+ through. Acknowledgments are recorded and the sales rule notification group is emailed.++A violation ending in "…is required" means the rule checked a field that has no value on the line — most+often a missing ship-to location on the document. Supply the value rather than changing the rule.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/storage-rules.md b/apps/erp/app/modules/agent/kb/docs/reference/storage-rules.mdindex 990cef896a..387687790a 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/storage-rules.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/storage-rules.md@@ -85,7 +85,7 @@ A rule reaches the lines it applies to in one of two ways:- **Message**: Shown on a violation; supports `{token}` interpolation.- **Surfaces**: Which transactions the rule fires on.- **Target**: `item` or `workCenter`.- - **Item filters**: Item types and/or groups to scope an item rule (empty = all items).+ - **Item filters**: Item types and/or groups to scope a rule (empty = all items).- **Active**: Whether the rule is currently evaluated.## Where to manage them@@ -98,6 +98,8 @@ plans the screen shows an upgrade prompt and no rules are evaluated.## Related+ - Sales rules The sibling rule family: the same condition builder, applied to quote, sales order, and sales invoice+ lines.- Items The most common rule target: scope by item type or group, or assign per item.- Inventory Storage rules run on inventory transactions: receipts, shipments, transfers, picks.- Work centers The other target: guards on operation start/finish and material issue/receive.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex 750da1c01f..37431e5c8c 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -1390,6 +1390,22 @@"\"Failed to insert job\""]},+ {+ "slug": "docs/reference/sales-rules",+ "title": "Sales rules",+ "description": "Predicate guards on sales documents: block a restricted item with an error, or warn and let the user acknowledge and continue.",+ "keywords": ["sales", "rules", "docs", "reference"],+ "headings": [+ "What a rule checks",+ "Where rules fire",+ "Block or warn",+ "Scope and assignment",+ "Rule fields",+ "Where to manage them",+ "Related",+ "Troubleshooting"+ ]+ },{"slug": "docs/reference/scheduling","title": "Scheduling",diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.mdindex 74eb8afd26..bd3b2176c7 100644--- a/apps/erp/app/modules/inventory/AGENTS.md+++ b/apps/erp/app/modules/inventory/AGENTS.md@@ -79,6 +79,25 @@ import { getInventoryItems, insertManualInventoryAdjustment } from "~/modules/inimport { inventoryAdjustmentValidator, receiptValidator } from "~/modules/inventory";```+## Storage Rules (sub-area)++Configurable if-condition-then-error/warn rules evaluated on **warehouse/MES transaction surfaces** (the storage-legal subset of `enforcementRuleSurface`: receipt, shipment, stockTransfer, warehouseTransfer, inventoryAdjustment, place, pick, operationStart, operationFinish, materialIssue, materialReceive). Lives **inside** this module: validators in `inventory.models.ts`, UI in `ui/StorageRules/`; the admin CRUD is the family-parametrized implementation in `~/modules/shared` (see "Service functions" below). There is no `modules/storage-rules` directory — a rule feature is not its own domain.++Sibling feature to **sales rules** (`~/modules/sales`, sales-document surfaces). Both share the engine in `@carbon/utils` (`rules.ts` + `field-registry.ts` + the zod AST mirror in `rules-schema.ts`), the evaluator/violation UI in `@carbon/ee/rules(.server)`, AND the `enforcementRule` table — one table for both families, discriminated by `family`.++- **Rule** — `enforcementRule` row (`family = 'storage'`; the table is shared with sales rules, so every read/write here MUST filter `family = 'storage'`): `conditionAst` JSONB, `severity` (`error` blocks; `warn` blocks until acknowledged), `targetType` (`item` | `workCenter`, enum `enforcementRuleTargetType`), `surfaces`, `appliesToAll` (workCenter broadcast gate) and the `filteredItem*` columns (item scoping). Assignments are polymorphic across `enforcementRuleItemAssignment` / `enforcementRuleWorkCenterAssignment` — `targetType` picks the table. The item table is shared with the sales family: resolve pinned rules against a family-filtered fetch, never a PostgREST embed.+- **Evaluator** — `@carbon/ee/rules.server`: `evaluateLinesForSurface`, `isBlocked`, `dedupeViolations`, plan gate `isStorageRulesEnabledForCompany`. Its item load swallows query errors, which silently skips every broadcast rule — a known gap kept for behavior compatibility (see the comment at the call site). New evaluators must throw instead.+- **One modal** — posting actions return `{ violations, ruleNames }`; callers submit via `useRuleViolations` and render `RuleViolationModal`. Do not fork a second violation UI.++### Storage Rules safety++- The `ui/StorageRules/` components are the **shared** rule-builder surface — sales rules imports `RuleBuilder`, `SurfacesField`, `MessageWithTokens`, `SeveritySelect`, and `ItemFilterSelector` from here by deep path. Changes must stay backward-compatible; parameterize additively rather than rewriting.+- These components must NOT import a module barrel (`~/modules/inventory`, `~/modules/items`, or `~/modules/sales`) — deep file imports only. `inventory` already depends on `items`, and the sales module imports these components for its SalesRules UI, so a barrel import would create a cycle. `StorageRules` is deliberately **not** re-exported from `ui/index.ts` for the same reason.+- `getEnforcementRuleAssignmentCounts` (in `~/modules/shared`) spans BOTH assignment tables — a rule lives in exactly one, so the union of single-table counts is correct. Rule ids are globally unique, so counting by id needs no family predicate even though the item table is shared.+- Never widen the `enforcementRule_storage_surfaces` CHECK to admit sales-document surfaces — that CHECK is what replaced the old per-family enum typing.++Service functions: the admin CRUD is NOT in `inventory.service.ts` — both families share one parametrized implementation in `~/modules/shared` (`getEnforcementRules` / `getEnforcementRule` / `upsertEnforcementRule` / `deleteEnforcementRule` / `getEnforcementRuleAssignmentCounts`), called with `"storage"` as the family. Cross-app `getActiveRulesForTargets` / `getRuleAssignmentsForTarget` / `getStorageRulesList` / `assignStorageRule` / `unassignStorageRule` are imported from `@carbon/ee/rules` DIRECTLY at the call site — this module's barrel deliberately does not re-export them. Routes: `x+/inventory+/storage-rules*`, plus assignment routes under `x+/items+/rules.*` (item targets) and `x+/resources+/work-centers.rules.*` (work-center targets).+## Related Modules- **purchasing** — receipts consume PO lines; receipt posting updates `purchaseOrderLine.quantityReceived`diff --git a/apps/erp/app/modules/inventory/index.ts b/apps/erp/app/modules/inventory/index.tsindex 3c7b31fa7c..d05d92b5a7 100644--- a/apps/erp/app/modules/inventory/index.ts+++ b/apps/erp/app/modules/inventory/index.ts@@ -1,3 +1,6 @@+// Rule queries shared with MES are NOT re-exported here — import them from+// `@carbon/ee/rules` directly so the package boundary stays visible at the+// call site (this module owns only the ERP-side admin CRUD + validators).export * from "./inventory.models";export * from "./inventory.service";export * from "./types";diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 2648050a9b..414bc66015 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -1,3 +1,12 @@+import {+ conditionAstFormField,+ getFieldDef,+ isFieldAvailableOnSurfaces,+ RULE_SEVERITIES,+ SURFACES_BY_TARGET_TYPE,+ TARGET_TYPES,+ TRANSACTION_SURFACES+} from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";import { batchPropertyDataTypes } from "../items/items.models";@@ -639,3 +648,63 @@ export const pickQuantityValidator = z.object({quantity: zfd.numeric(z.number().min(0)),markShort: zfd.text(z.string().optional())});++// -----------------------------------------------------------------------------+// Storage Rules — predicate rules evaluated on warehouse/MES transaction+// surfaces (receipt, shipment, pick, place, …). Sibling feature to sales rules+// (`~/modules/sales`, sales-document surfaces); both share the engine and the+// AST schema in @carbon/utils.+// -----------------------------------------------------------------------------+export const storageRuleSeverities = RULE_SEVERITIES;++export const storageRuleValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ name: z.string().trim().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(storageRuleSeverities),+ targetType: z.enum(TARGET_TYPES),+ // Broadcast gate for workCenter rules. Item-target storage rules ignore+ // this and use the filteredItem* fields instead (empty = all items).+ appliesToAll: zfd.checkbox(),+ filteredItemTypes: zfd.repeatableOfType(z.string()).optional(),+ filteredItemGroupIds: zfd.repeatableOfType(z.string()).optional(),+ filteredItemMatchAll: zfd.checkbox(),+ active: zfd.checkbox(),+ surfaces: zfd+ .repeatableOfType(z.enum(TRANSACTION_SURFACES))+ .refine((arr) => arr.length >= 1, {+ message: "Pick at least one surface"+ }),+ conditionAst: conditionAstFormField+ })+ .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`+ });+ }+ }++ // Reject conditions on a registry field whose context the evaluator won't+ // populate for every selected surface (else it resolves undefined → false+ // "X is required"). Unknown paths are left to runtime presence handling.+ val.conditionAst.conditions.forEach((c, i) => {+ const def = getFieldDef(c.field);+ if (def && !isFieldAvailableOnSurfaces(def, val.surfaces)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["conditionAst", "conditions", i, "field"],+ message: `"${def.label}" isn't available on the selected surface(s)`+ });+ }+ });+ });diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsxindex e5a27548e3..7257422517 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx@@ -1,4 +1,4 @@-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import {DatePicker,Hidden,@@ -94,7 +94,7 @@ const InventoryStorageUnits = ({const permissions = usePermissions();const { t } = useLingui();const adjustmentModal = useDisclosure();- const ruleViolations = useStorageRuleViolations({+ const ruleViolations = useRuleViolations({action: path.to.inventoryItemAdjustment(pickMethod.itemId),onSuccess: adjustmentModal.onClose});diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsxindex ef5e06bb78..cbf45048db 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx@@ -1,5 +1,5 @@import { useCarbon } from "@carbon/auth";-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import {Alert,AlertDescription,@@ -169,7 +169,7 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {validateReceiptTracking();});- const ruleViolations = useStorageRuleViolations({+ const ruleViolations = useRuleViolations({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 3c7eed1781..6d50386e1d 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx@@ -1,5 +1,5 @@import { useCarbon } from "@carbon/auth";-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import {Alert,AlertDescription,@@ -239,7 +239,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {validateShipmentTracking();});- const ruleViolations = useStorageRuleViolations({+ const ruleViolations = useRuleViolations({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 44e40c81a1..f573828132 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx@@ -1,5 +1,5 @@import type { Result } from "@carbon/auth";-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import {Button,Copy,@@ -57,14 +57,14 @@ const StockTransferHeader = () => {const postModal = useDisclosure();const deleteModal = useDisclosure();const statusFetcher = useFetcher<Result>();- // Item rules fire on Release + Complete (the "go" transitions). Each gets+ // Storage 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 = useStorageRuleViolations({+ const releaseRules = useRuleViolations({action: path.to.stockTransferStatus(id)});const releaseFetcher = releaseRules.fetcher;- const completeRules = useStorageRuleViolations({+ const completeRules = useRuleViolations({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 94c385294d..af76178bb2 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx@@ -1,6 +1,6 @@import type { Result } from "@carbon/auth";import { useCarbon } from "@carbon/auth";-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import { getLogger } from "@carbon/logger";import {Badge,@@ -913,9 +913,9 @@ function WizardFooter({ locationId }: { locationId: string }) {const linesCount = useStockTransferWizardLinesCount();const totalQuantity = useStockTransferWizardTotalQuantity();- // Item Rule pre-flight on Create Transfer (auto-released → the stock-commit+ // Storage Rule pre-flight on Create Transfer (auto-released → the stock-commit// gate sits here). The modal surfaces violations before the transfer exists.- const createRules = useStorageRuleViolations<Result>({+ const createRules = useRuleViolations<Result>({action: path.to.newStockTransfer,onSuccess: () => clearStockTransferWizard()});diff --git a/apps/erp/app/modules/storage-rules/ui/ConditionRow.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/ConditionRow.tsxsimilarity index 96%rename from apps/erp/app/modules/storage-rules/ui/ConditionRow.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/ConditionRow.tsxindex bf6c242ef7..17eb34947e 100644--- a/apps/erp/app/modules/storage-rules/ui/ConditionRow.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/ConditionRow.tsx@@ -54,6 +54,11 @@ type ConditionRowProps = {* surfaces valid for the targetType when omitted.*/surfaces?: TransactionSurface[];+ /**+ * Explicit field pool forwarded to the field picker (sales rules). When+ * provided it replaces the targetType-derived registry lookup.+ */+ fields?: FieldDef[];};function ConditionRowImpl({@@ -64,7 +69,8 @@ function ConditionRowImpl({onRemove,optionsByLoader,targetType,- surfaces+ surfaces,+ fields}: ConditionRowProps) {const { t } = useLingui();@@ -143,6 +149,7 @@ function ConditionRowImpl({value={condition.field}targetType={targetType}surfaces={surfaces}+ fields={fields}onChange={(path) => {const nextDef = getFieldDef(path);const nextOps = nextDef ? availableOperators(nextDef) : [];diff --git a/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/FieldCombobox.tsxsimilarity index 94%rename from apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/FieldCombobox.tsxindex a8293531d8..b1e61847de 100644--- a/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/FieldCombobox.tsx@@ -32,7 +32,8 @@ import {LuCheck,LuChevronDown,LuInfo,- LuReceipt+ LuReceipt,+ LuUser} from "react-icons/lu";const CONTEXT: Record<@@ -52,11 +53,13 @@ const CONTEXT: Record<transaction: {label: "Transaction",icon: <LuReceipt className="h-3.5 w-3.5" />- }+ },+ customer: { label: "Customer", icon: <LuUser className="h-3.5 w-3.5" /> }};const CONTEXT_ORDER: FieldDef["context"][] = ["item",+ "customer","storage","workCenter","operation",@@ -75,6 +78,11 @@ type FieldComboboxProps = {* can't pick a field that won't resolve at runtime.*/surfaces?: TransactionSurface[];+ /**+ * Explicit field pool (sales rules). When provided it replaces the+ * targetType-derived registry lookup entirely.+ */+ fields?: FieldDef[];};export default function FieldCombobox({@@ -83,7 +91,8 @@ export default function FieldCombobox({placeholder,className,targetType,- surfaces+ surfaces,+ fields}: FieldComboboxProps) {const { t } = useLingui();const [open, setOpen] = useState(false);@@ -91,12 +100,14 @@ export default function FieldCombobox({const grouped = useMemo(() => {const map = new Map<FieldDef["context"], FieldDef[]>();for (const ctx of CONTEXT_ORDER) map.set(ctx, []);- const pool = targetType- ? getFieldsForTargetTypeAndSurfaces(targetType, surfaces ?? [])- : FIELD_REGISTRY;+ const pool =+ fields ??+ (targetType+ ? getFieldsForTargetTypeAndSurfaces(targetType, surfaces ?? [])+ : FIELD_REGISTRY);for (const f of pool) map.get(f.context)!.push(f);return map;- }, [targetType, surfaces]);+ }, [targetType, surfaces, fields]);const selected = useMemo(() => getFieldDef(value), [value]);const ctx = selected ? CONTEXT[selected.context] : undefined;diff --git a/apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/ItemFilterSelector.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/ItemFilterSelector.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/MessageWithTokens.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/MessageWithTokens.tsxsimilarity index 87%rename from apps/erp/app/modules/storage-rules/ui/MessageWithTokens.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/MessageWithTokens.tsxindex d77ee86e07..a9517d2155 100644--- a/apps/erp/app/modules/storage-rules/ui/MessageWithTokens.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/MessageWithTokens.tsx@@ -20,7 +20,7 @@ import {type FieldDef,getFieldDef,getFieldsForTargetType,- type TransactionSurface+ type RuleSurface} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { MouseEvent, ReactNode, TextareaHTMLAttributes } from "react";@@ -47,6 +47,11 @@ type MessageWithTokensProps = {* so e.g. workCenter rules don't list `item.replenishmentSystem`.*/targetType?: "item" | "workCenter";+ /**+ * Explicit field pool (sales rules). When provided it replaces the+ * targetType/registry lookup for the token dropdown entirely.+ */+ fields?: FieldDef[];};type TokenItem = { token: string; description: string };@@ -55,9 +60,10 @@ type TokenGroup = { heading: string; tokens: TokenItem[] };/*** Maps each surface to the ctx-block keys whose fields will be populated* at eval time. Used to filter the FIELD_REGISTRY into a relevant- * suggestion list.+ * suggestion list. Keyed by the full `RuleSurface` union so the sales-rule+ * form (sales-document surfaces) reuses this component unchanged.*/-const CTX_KEYS_BY_SURFACE: Record<TransactionSurface, FieldDef["context"][]> = {+const CTX_KEYS_BY_SURFACE: Record<RuleSurface, FieldDef["context"][]> = {receipt: ["storage", "transaction"],shipment: ["storage", "transaction"],stockTransfer: ["storage", "transaction"],@@ -68,11 +74,15 @@ const CTX_KEYS_BY_SURFACE: Record<TransactionSurface, FieldDef["context"][]> = {operationStart: ["workCenter", "operation", "transaction"],operationFinish: ["workCenter", "operation", "transaction"],materialIssue: ["workCenter", "operation", "transaction"],- materialReceive: ["workCenter", "operation", "transaction"]+ materialReceive: ["workCenter", "operation", "transaction"],+ quoteLine: ["customer", "transaction"],+ salesOrderLine: ["customer", "transaction"],+ salesInvoiceLine: ["customer", "transaction"]};const CONTEXT_LABELS: Record<FieldDef["context"], string> = {item: "Item",+ customer: "Customer",storage: "Storage unit",workCenter: "Work center",operation: "Operation",@@ -85,6 +95,7 @@ const CONTEXT_LABELS: Record<FieldDef["context"], string> = {// bucketed by context — `O(n)` once instead of `O(n)` per ctx per render.const FIELDS_BY_CTX: Record<FieldDef["context"], FieldDef[]> = {item: [],+ customer: [],storage: [],workCenter: [],operation: [],@@ -95,14 +106,20 @@ for (const f of FIELD_REGISTRY) FIELDS_BY_CTX[f.context].push(f);// Stable references for default values. `surfacesValue ?? []` would// allocate a fresh `[]` every render, busting the `groups` memo — and// re-running the per-condition token assembly even when nothing changed.-const EMPTY_SURFACES: TransactionSurface[] = [];-const ORDERED_CTX: FieldDef["context"][] = ["storage", "transaction"];+const EMPTY_SURFACES: RuleSurface[] = [];+// `customer` is only ever in `allowedCtx` for sales-rule surfaces, so storage+// rules render identically with it in the ordered list.+const ORDERED_CTX: FieldDef["context"][] = [+ "customer",+ "storage",+ "transaction"+];// Hoist the static icon node — re-rendering the parent doesn't need to// reallocate the icon element (rendering-hoist-jsx).const BRACES_ICON = <LuBraces />;-// Mirror of the runtime `TOKEN_RE` in packages/utils/src/storage-rules.ts so the+// Mirror of the runtime `TOKEN_RE` in packages/utils/src/rules.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.@@ -113,6 +130,9 @@ const TOKEN_RE =// generic dotted-path resolver. Treat any such token as known so the editor// stops painting valid custom-field references as errors.const CUSTOM_FIELD_PREFIX = "item.customFields.";+// Same for `customer.customFields.*` — only honored when an explicit sales-rule+// `fields` pool is provided, so storage-rule highlighting is unchanged.+const CUSTOMER_CUSTOM_FIELD_PREFIX = "customer.customFields.";// Only background + ring — text stays `text-transparent` (inherited from// the overlay) so the textarea's real glyphs show through cleanly. Adding a@@ -127,13 +147,13 @@ export default function MessageWithTokens({label,conditions,surfacesFieldName = "surfaces",- targetType+ targetType,+ fields}: MessageWithTokensProps) {const { t } = useLingui();const textareaRef = useRef<HTMLTextAreaElement | null>(null);const overlayRef = useRef<HTMLDivElement | null>(null);- const [surfacesValue] =- useControlField<TransactionSurface[]>(surfacesFieldName);+ const [surfacesValue] = useControlField<RuleSurface[]>(surfacesFieldName);const surfaces = surfacesValue ?? EMPTY_SURFACES;const { getInputProps, error, defaultValue } = useField(name);@@ -188,12 +208,14 @@ 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).+ // Field pool: an explicit `fields` prop wins (sales rules), then the+ // rule's targetType; falls back to full registry when neither is+ // provided (legacy usage).const scopedFieldsByCtx: Partial<Record<FieldDef["context"], FieldDef[]>> ={};- if (targetType) {- const pool = getFieldsForTargetType(targetType);+ const pool =+ fields ?? (targetType ? getFieldsForTargetType(targetType) : null);+ if (pool) {for (const f of pool) {const bucket = scopedFieldsByCtx[f.context];if (bucket) bucket.push(f);@@ -201,7 +223,7 @@ export default function MessageWithTokens({}}const fieldsForCtx = (ctx: FieldDef["context"]): FieldDef[] =>- targetType ? (scopedFieldsByCtx[ctx] ?? []) : FIELDS_BY_CTX[ctx];+ pool ? (scopedFieldsByCtx[ctx] ?? []) : FIELDS_BY_CTX[ctx];// 1. Per-condition tokens.conds.forEach((c, i) => {@@ -263,7 +285,7 @@ export default function MessageWithTokens({}return out;- }, [conditions, surfaces, targetType]);+ }, [conditions, surfaces, targetType, fields]);const knownTokens = useMemo(() => {const set = new Set<string>();@@ -286,7 +308,10 @@ export default function MessageWithTokens({if (idx > last) out.push(text.slice(last, idx));const inner = m[1] ?? "";const known =- knownTokens.has(inner) || inner.startsWith(CUSTOM_FIELD_PREFIX);+ knownTokens.has(inner) ||+ inner.startsWith(CUSTOM_FIELD_PREFIX) ||+ (fields !== undefined &&+ inner.startsWith(CUSTOMER_CUSTOM_FIELD_PREFIX));out.push(<markkey={key++}@@ -303,7 +328,7 @@ export default function MessageWithTokens({}if (last < text.length) out.push(text.slice(last));return out;- }, [text, knownTokens]);+ }, [text, knownTokens, fields]);// Identical typography between the overlay and the textarea — any drift// here desyncs the highlighted rectangles from the rendered glyphs.diff --git a/apps/erp/app/modules/storage-rules/ui/MultiValueCombobox.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/MultiValueCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/MultiValueCombobox.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/MultiValueCombobox.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/OperatorCombobox.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/OperatorCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/OperatorCombobox.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/OperatorCombobox.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/RuleAssignmentsList.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/RuleBuilder.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/RuleBuilder.tsxsimilarity index 81%rename from apps/erp/app/modules/storage-rules/ui/RuleBuilder.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/RuleBuilder.tsxindex dabd33f2af..06c19a3f12 100644--- a/apps/erp/app/modules/storage-rules/ui/RuleBuilder.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/RuleBuilder.tsx@@ -10,6 +10,7 @@ import {type Condition,type ConditionAst,FIELD_REGISTRY,+ type FieldDef,getFieldsForTargetTypeAndSurfaces,type MatchKind,type TargetType,@@ -32,6 +33,12 @@ type RuleBuilderProps = {* rule actually triggers — not every surface valid for the targetType.*/surfaces?: TransactionSurface[];+ /**+ * Explicit field pool (e.g. sales rules pass+ * `getFieldsForSalesRuleSurfaces(...)`). When provided it replaces the+ * targetType-derived registry lookup entirely.+ */+ fields?: FieldDef[];/*** Notifies the parent of every condition-list change so siblings (e.g.* `MessageWithTokens`) can offer per-condition tokens that resolve to@@ -42,11 +49,14 @@ type RuleBuilderProps = {const emptyConditionFor = (targetType: TargetType | undefined,- surfaces: TransactionSurface[] | undefined+ surfaces: TransactionSurface[] | undefined,+ fields: FieldDef[] | undefined): Condition => {- const pool = targetType- ? getFieldsForTargetTypeAndSurfaces(targetType, surfaces ?? [])- : FIELD_REGISTRY;+ const pool =+ fields ??+ (targetType+ ? getFieldsForTargetTypeAndSurfaces(targetType, surfaces ?? [])+ : FIELD_REGISTRY);return { field: pool[0]?.path ?? "", op: "eq", value: undefined };};@@ -55,6 +65,7 @@ export default function RuleBuilder({initial,targetType,surfaces,+ fields,onConditionsChange}: RuleBuilderProps) {const { t } = useLingui();@@ -86,9 +97,16 @@ export default function RuleBuilder({const [conditions, setConditions] = useState<Condition[]>(initial?.conditions?.length? initial.conditions- : [emptyConditionFor(targetType, surfaces)]+ : [emptyConditionFor(targetType, surfaces, fields)]+ );+ // Customer-context option lists exist only when the caller's field pool has+ // customer fields (i.e. the sales-rule builder); the default storage pools+ // never do, so their builders skip those fetches entirely.+ const includeCustomerFields = useMemo(+ () => (fields ?? []).some((f) => f.context === "customer"),+ [fields]);- const optionsByLoader = useValueOptions();+ const optionsByLoader = useValueOptions({ includeCustomerFields });// Keep parents in sync with the live condition list. `onConditionsChange`// identity isn't tracked — parents wrap in `useCallback` if they need it.@@ -113,8 +131,11 @@ export default function RuleBuilder({}, []);const handleAdd = useCallback(() => {- setConditions((prev) => [...prev, emptyConditionFor(targetType, surfaces)]);- }, [targetType, surfaces]);+ setConditions((prev) => [+ ...prev,+ emptyConditionFor(targetType, surfaces, fields)+ ]);+ }, [targetType, surfaces, fields]);const ast: ConditionAst = { kind, conditions };@@ -156,6 +177,7 @@ export default function RuleBuilder({optionsByLoader={optionsByLoader}targetType={targetType}surfaces={surfaces}+ fields={fields}/>))}</div>diff --git a/apps/erp/app/modules/storage-rules/ui/SeveritySelect.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/SeveritySelect.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/SeveritySelect.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/SeveritySelect.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRuleForm.tsxsimilarity index 98%rename from apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/StorageRuleForm.tsxindex 2cc396f306..4cc587f783 100644--- a/apps/erp/app/modules/storage-rules/ui/StorageRuleForm.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRuleForm.tsx@@ -30,7 +30,7 @@ import {} from "~/components/Form";import { usePermissions } from "~/hooks";import { path } from "~/utils/path";-import { storageRuleValidator } from "../storage-rules.models";+import { storageRuleValidator } from "../../inventory.models";import ItemFilterSelector from "./ItemFilterSelector";import MessageWithTokens from "./MessageWithTokens";import RuleBuilder from "./RuleBuilder";@@ -178,7 +178,7 @@ export default function StorageRuleForm({conditions={liveConditions}targetType={targetType}/>- <CustomFormFields table="storageRule" />+ <CustomFormFields table="enforcementRule" /></VStack></ModalDrawerBody><ModalDrawerFooter>diff --git a/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesGroups.tsxsimilarity index 98%rename from apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesGroups.tsxindex a387864a0a..7a788c060a 100644--- a/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesGroups.tsx@@ -56,8 +56,8 @@ type RuleListItem = {};// How a rule reaches its targets, for the badge + assignment display.-// Item rules use type/group filters (empty = all items); other targets use the-// appliesToAll broadcast flag.+// Item-target rules use type/group filters (empty = all items); other targets+// use the appliesToAll broadcast flag.function ruleReach(rule: RuleListItem): {broadcastLabel: string | null;showAssignments: boolean;diff --git a/apps/erp/app/modules/storage-rules/ui/StorageRulesTable.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesTable.tsxsimilarity index 98%rename from apps/erp/app/modules/storage-rules/ui/StorageRulesTable.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesTable.tsxindex e1fc6ab212..79f251e9b6 100644--- a/apps/erp/app/modules/storage-rules/ui/StorageRulesTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesTable.tsx@@ -43,7 +43,7 @@ const StorageRulesTable = memo(({ data, count }: StorageRulesTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const permissions = usePermissions();- const customColumns = useCustomColumns<StorageRuleRowView>("storageRule");+ const customColumns = useCustomColumns<StorageRuleRowView>("enforcementRule");const rows = useMemo(() => data, [data]);diff --git a/apps/erp/app/modules/storage-rules/ui/StorageRulesUpgradeOverlay.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesUpgradeOverlay.tsxsimilarity index 64%rename from apps/erp/app/modules/storage-rules/ui/StorageRulesUpgradeOverlay.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesUpgradeOverlay.tsxindex 5c7afe5718..3b979a3848 100644--- a/apps/erp/app/modules/storage-rules/ui/StorageRulesUpgradeOverlay.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/StorageRulesUpgradeOverlay.tsx@@ -1,16 +1,5 @@import { Trans } from "@lingui/react/macro";-import { LuShieldCheck } from "react-icons/lu";-import {- UpgradeOverlay,- UpgradeOverlayActions,- UpgradeOverlayCard,- UpgradeOverlayContent,- UpgradeOverlayDescription,- UpgradeOverlayIcon,- UpgradeOverlayPreview,- UpgradeOverlayTitle,- UpgradeOverlayUpgradeButton-} from "~/components/UpgradeOverlay";+import RulesUpgradeOverlay from "~/components/RulesUpgradeOverlay";import StorageRulesTable from "./StorageRulesTable";const mockRules = [@@ -74,29 +63,17 @@ const mockRules = [export default function StorageRulesUpgradeOverlay() {return (- <UpgradeOverlay>- <UpgradeOverlayPreview>+ <RulesUpgradeOverlay+ preview={<StorageRulesTable data={mockRules as never} count={mockRules.length} />- </UpgradeOverlayPreview>- <UpgradeOverlayCard>- <UpgradeOverlayIcon>- <LuShieldCheck className="size-6 text-muted-foreground" />- </UpgradeOverlayIcon>- <UpgradeOverlayContent>- <UpgradeOverlayTitle>- <Trans>Storage Rules</Trans>- </UpgradeOverlayTitle>- <UpgradeOverlayDescription>- <Trans>- Enforce per-item validation and guidelines across receipts,- shipments, transfers, and adjustments.- </Trans>- </UpgradeOverlayDescription>- </UpgradeOverlayContent>- <UpgradeOverlayActions>- <UpgradeOverlayUpgradeButton />- </UpgradeOverlayActions>- </UpgradeOverlayCard>- </UpgradeOverlay>+ }+ title={<Trans>Storage Rules</Trans>}+ description={+ <Trans>+ Enforce per-item validation and guidelines across receipts, shipments,+ transfers, and adjustments.+ </Trans>+ }+ />);}diff --git a/apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/SurfaceChips.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/SurfaceChips.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/SurfacesField.tsxsimilarity index 72%rename from apps/erp/app/modules/storage-rules/ui/SurfacesField.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/SurfacesField.tsxindex 795e0172e2..ea45334e8b 100644--- a/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageRules/SurfacesField.tsx@@ -82,16 +82,30 @@ const SURFACE_META: Record<}};-type SurfacesFieldProps = {+export type SurfaceOption<S extends string = string> = {+ value: S;+ label: string;+ description?: string;+ icon?: JSX.Element;+};++type SurfacesFieldProps<S extends string> = {name: string;label?: string;targetType?: "item" | "workCenter";+ /**+ * Custom surface catalog (e.g. sales-rule sales surfaces). When provided it+ * replaces the storage `TransactionSurface` catalog entirely and+ * `targetType` is ignored. Omit for storage rules — the default behavior+ * is unchanged.+ */+ surfaceOptions?: SurfaceOption<S>[];/*** 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;+ onSurfacesChange?: (next: S[]) => void;};/**@@ -101,15 +115,16 @@ type SurfacesFieldProps = {* Soft-guards against unchecking the last selected surface (zod `min(1)` is* the server-side backstop).*/-export default function SurfacesField({+export default function SurfacesField<S extends string = TransactionSurface>({name,label,targetType,+ surfaceOptions,onSurfacesChange-}: SurfacesFieldProps) {+}: SurfacesFieldProps<S>) {const { t } = useLingui();const { error, isOptional } = useField(name);- const [value, setValue] = useControlField<TransactionSurface[]>(name);+ const [value, setValue] = useControlField<S[]>(name);const selected = value ?? [];// Mirror selection up to the form. Identity of `onSurfacesChange` not@@ -119,23 +134,34 @@ export default function SurfacesField({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;+ let options: ChoiceSelectOption<S>[];+ if (surfaceOptions) {+ options = surfaceOptions.map((o) => ({+ value: o.value,+ title: o.label,+ description: o.description,+ icon: o.icon+ }));+ } else {+ 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) => ({+ // Default generic (S = TransactionSurface) makes this cast a no-op; it+ // only exists because TS can't see that the fallback branch implies the+ // default type parameter.+ options = visibleSurfaces.map((s) => ({value: s,title: SURFACE_META[s].title,description: SURFACE_META[s].description,icon: SURFACE_META[s].icon- })- );+ })) as unknown as ChoiceSelectOption<S>[];+ }- const handleChange = (next: TransactionSurface[]) => {+ const handleChange = (next: S[]) => {if (next.length === 0) return; // soft guard — keep at least onesetValue(next);};@@ -155,7 +181,7 @@ export default function SurfacesField({/>))}- <ChoiceSelect<TransactionSurface>+ <ChoiceSelect<S>multiplevalue={selected}onChange={handleChange}diff --git a/apps/erp/app/modules/storage-rules/ui/ValueCombobox.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/ValueCombobox.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/ValueCombobox.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/ValueCombobox.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/ValueInput.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/ValueInput.tsxsimilarity index 100%rename from apps/erp/app/modules/storage-rules/ui/ValueInput.tsxrename to apps/erp/app/modules/inventory/ui/StorageRules/ValueInput.tsxdiff --git a/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts b/apps/erp/app/modules/inventory/ui/StorageRules/useValueOptions.tssimilarity index 62%rename from apps/erp/app/modules/storage-rules/ui/useValueOptions.tsrename to apps/erp/app/modules/inventory/ui/StorageRules/useValueOptions.tsindex c019bd4a29..9940fe8fc1 100644--- a/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts+++ b/apps/erp/app/modules/inventory/ui/StorageRules/useValueOptions.ts@@ -1,5 +1,8 @@import type { ValueOptionsLoader } from "@carbon/utils";import { useMemo } from "react";+import { useCountries } from "~/components/Form/Country";+import { useCustomerStatuses } from "~/components/Form/CustomerStatus";+import { useCustomerTypes } from "~/components/Form/CustomerType";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useStorageTypes } from "~/components/Form/StorageTypes";@@ -28,10 +31,20 @@ const ITEM_TYPES_OPTIONS = enumOptions(inventoryItemTypes);const ITEM_TRACKING_TYPES_OPTIONS = enumOptions(itemTrackingTypes);const REPLENISHMENT_SYSTEMS_OPTIONS = enumOptions(itemReplenishmentSystems);-export function useValueOptions(): ValueOptionsByLoader {+export function useValueOptions(+ opts: { includeCustomerFields?: boolean } = {}+): ValueOptionsByLoader {+ const { includeCustomerFields = false } = opts;const locations = useLocations();const storageTypes = useStorageTypes();const itemPostingGroups = useItemPostingGroups();+ // Sales-rule loaders (customer-context fields). `countries` values are+ // alpha-2 codes, matching the persisted `customer.location.countryCode`.+ // Only fetched when the builder's field pool actually contains customer+ // fields — a storage-rule builder never shows them.+ const customerTypes = useCustomerTypes(includeCustomerFields);+ const customerStatuses = useCustomerStatuses(includeCustomerFields);+ const countries = useCountries(includeCustomerFields);return useMemo<ValueOptionsByLoader>(() => ({@@ -40,8 +53,18 @@ export function useValueOptions(): ValueOptionsByLoader {itemPostingGroups,itemTypes: ITEM_TYPES_OPTIONS,itemTrackingTypes: ITEM_TRACKING_TYPES_OPTIONS,- replenishmentSystems: REPLENISHMENT_SYSTEMS_OPTIONS+ replenishmentSystems: REPLENISHMENT_SYSTEMS_OPTIONS,+ customerTypes,+ customerStatuses,+ countries}),- [locations, storageTypes, itemPostingGroups]+ [+ locations,+ storageTypes,+ itemPostingGroups,+ customerTypes,+ customerStatuses,+ countries+ ]);}diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsxindex 0773c60b88..33e9dd2d09 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx@@ -1,5 +1,5 @@import { useCarbon } from "@carbon/auth";-import { useStorageRuleViolations } from "@carbon/ee/storage-rules";+import { useRuleViolations } from "@carbon/ee/rules";import { InputControlled, ValidatedForm } from "@carbon/form";import {Button,@@ -68,10 +68,10 @@ const WarehouseTransferForm = ({}: WarehouseTransferFormProps) => {const { company } = useUser();const permissions = usePermissions();- // Item rules eval at every "go" status transition (Confirm/Ship/Receive/+ // Storage 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 = useStorageRuleViolations<typeof statusAction>({+ const statusRules = useRuleViolations<typeof statusAction>({action: warehouseTransfer?.id? path.to.warehouseTransferStatus(warehouseTransfer.id): ""diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsxindex e5143297b7..d775d9c67a 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import {Button,Copy,@@ -34,6 +35,7 @@ import {LuTruck} from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";+import type { FetcherWithComponents } from "react-router";import { Link, useFetcher, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { usePanels } from "~/components/Layout/Panels";@@ -43,7 +45,6 @@ import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";import type { SalesInvoice, SalesInvoiceLine } from "~/modules/invoicing";import { isInvoicePayable } from "~/modules/invoicing";import { getPayInvoiceHref } from "~/modules/invoicing/ui/Payment/PaymentForm";-import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";import { useItems } from "~/stores";import { path } from "~/utils/path";import SalesInvoicePostModal from "./SalesInvoicePostModal";@@ -66,7 +67,17 @@ const SalesInvoiceHeader = () => {variant: "dropdown"});- const postFetcher = useFetcher<typeof action>();+ // Post submissions run through the violation hook's fetcher so a blocked+ // post opens the shared violation modal, with acknowledge-and-resubmit for+ // warns. The post modal closes itself on success.+ const postRules = useRuleViolations({+ action: path.to.salesInvoicePost(invoiceId ?? "")+ });+ const postFetcher = postRules.fetcher as FetcherWithComponents<{+ success?: boolean;+ message?: string;+ violations?: unknown[];+ }>;const { carbon } = useCarbon();const [linesNotAssociatedWithSO, setLinesNotAssociatedWithSO] = useState<@@ -457,6 +468,7 @@ const SalesInvoiceHeader = () => {defaultCc={routeData?.defaultCc ?? []}/>)}+ <postRules.ViolationModal />{voidModal.isOpen && (<SalesInvoiceVoidModal onClose={voidModal.onClose} />)}diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsxindex dfd488594d..a1cbc0bb11 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import { Combobox, ValidatedForm } from "@carbon/form";import {Alert,@@ -102,6 +103,19 @@ const SalesInvoiceLineForm = ({if (!invoiceId) throw new Error("invoiceId not found");+ // Sales-rule enforcement: submissions run through the violation hook's+ // fetcher so a blocked response opens <rules.ViolationModal /> with an+ // acknowledge-and-resubmit path for warns. Modal close happens on success+ // (not on submit) so violations can surface first.+ const rules = useRuleViolations({+ action: initialValues.id+ ? path.to.salesInvoiceLine(invoiceId, initialValues.id)+ : path.to.newSalesInvoiceLine(invoiceId),+ onSuccess: () => {+ if (type === "modal") onClose?.();+ }+ });+const [items] = useItems();const routeData = useRouteData<{salesInvoice: SalesInvoice;@@ -397,6 +411,7 @@ const SalesInvoiceLineForm = ({><ModalCardContent size="xxlarge"><ValidatedForm+ fetcher={rules.fetcher}defaultValues={initialValues}validator={salesInvoiceLineValidator}method="post"@@ -407,9 +422,6 @@ const SalesInvoiceLineForm = ({}className="w-full"isDisabled={isEditing && isLocked}- onSubmit={() => {- if (type === "modal") onClose?.();- }}><HStackclassName={cn(@@ -946,6 +958,7 @@ const SalesInvoiceLineForm = ({</ModalCardContent></ModalCard></ModalCardProvider>+ <rules.ViolationModal /></Tabs>);};diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsxindex cc142e0452..b2b086d114 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx@@ -38,7 +38,11 @@ import { salesInvoicePostValidator } from "../../invoicing.models";import StripeCustomerPanel from "./StripeCustomerPanel";type SalesInvoicePostModalProps = {- fetcher: FetcherWithComponents<{ success: boolean; message: string }>;+ fetcher: FetcherWithComponents<{+ success?: boolean;+ message?: string;+ violations?: unknown[];+ }>;isOpen: boolean;onClose: () => void;invoiceId: string;@@ -120,10 +124,15 @@ const SalesInvoicePostModal = ({if (fetcher.data?.success) {if (fetcher.data?.message) toast.success(fetcher.data.message);onClose();- } else if (fetcher.data?.success === false && fetcher.data?.message) {+ } else if (+ fetcher.data?.success === false &&+ fetcher.data?.message &&+ // Violations render in the shared ViolationModal; don't also toast them.+ (fetcher.data?.violations ?? []).length === 0+ ) {toast.error(fetcher.data.message);}- }, [fetcher.data?.success]);+ }, [fetcher.data]);const resolution = stripeCustomer.data ?? null;const isStale = loadedKeyRef.current !== requestKey;diff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.tsindex db9dea650b..4984a30c38 100644--- a/apps/erp/app/modules/production/production.mcp.server.ts+++ b/apps/erp/app/modules/production/production.mcp.server.ts@@ -1,10 +1,7 @@import { hasPermission } from "@carbon/auth";import { getUserClaims } from "@carbon/auth/users.server";import type { Database, Json } from "@carbon/database";-import {- evaluateLinesForSurface,- isBlocked-} from "@carbon/ee/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { getDatabaseClient } from "~/services/database.server";@@ -17,7 +14,7 @@ import {} from "./production.service";// MCP-exposed production writes that depend on server-only modules-// (`@carbon/auth/users.server`, `@carbon/ee/storage-rules.server`). These CANNOT+// (`@carbon/auth/users.server`, `@carbon/ee/rules.server`). These CANNOT// live in `production.service.ts`: that file is re-exported by the// `~/modules/production` barrel, which client components value-import, so it is// part of the client bundle and React Router's dot-server plugin rejects anydiff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 84b6a4a889..e3eee767db 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -9800,7 +9800,7 @@ export async function saveInspectionDocumentAtomic(// scripts/generate-mcp.ts as production_issueMaterial / _completeJob / _scheduleJob.// `issueMaterial`, `completeJob`, and `scheduleJob` moved to `production.mcp.server.ts`: they-// depend on server-only modules (`@carbon/ee/storage-rules.server`, `@carbon/auth/users.server`)+// depend on server-only modules (`@carbon/ee/rules.server`, `@carbon/auth/users.server`)// that cannot be referenced from this file, which is client-reachable via the module barrel./**diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.mdindex 22dbc6f02a..8cefff9820 100644--- a/apps/erp/app/modules/sales/AGENTS.md+++ b/apps/erp/app/modules/sales/AGENTS.md@@ -85,6 +85,37 @@ cd apps/erp && pnpm exec vitest run app/modules/salesimport { resolvePrice, applyPriceRules, getCustomer } from "~/modules/sales";```+## Sales Rules (sub-area)++Configurable if-condition-then-error/warn rules evaluated when an item is added to a **sales document** (quote line, sales order line, sales invoice line) — e.g. "if item type is X and the customer's ship-to country is Y → block". Lives **inside** this module: validators in `sales.models.ts`, UI in `ui/SalesRules/`; the admin CRUD is the family-parametrized implementation in `~/modules/shared` (see "Service functions" below). There is no `modules/sales-rules` directory — a rule feature is not its own domain.++Distinct from **storage rules** (`~/modules/inventory`, warehouse/MES surfaces) and **configurator rules** (`configurationRule`, `x+/part+/$itemId.rule*.tsx`) — storage and sales rules now share ONE table, `enforcementRule`, discriminated by `family` ('storage' | 'sales'); the configurator's `configurationRule` is unrelated. Every read/write in this module MUST filter `family = 'sales'`.++- **Rule** — `enforcementRule` row (`family = 'sales'`): `conditionAst` JSONB (`{kind: all|any|none, conditions:[{field,op,value}]}`), `severity` (`error` blocks; `warn` requires acknowledgment), `message` with `{token}` interpolation, `surfaces` (`enforcementRuleSurface` enum; the sales-legal subset `quoteLine` | `salesOrderLine` | `salesInvoiceLine` is enforced by the `enforcementRule_sales_surfaces` CHECK), item scoping via `filteredItemTypes`/`filteredItemGroupIds`/`filteredItemMatchAll` (empty = all items) or explicit `enforcementRuleItemAssignment` pins (shared with the storage family — always resolve pins against a family-filtered rule set, never a PostgREST embed).+- **Shared engine** — the AST compiler/evaluator lives in `@carbon/utils` (`rules.ts` + `field-registry.ts`, with the zod AST mirror in `rules-schema.ts`): `compileSalesRuleWithCache`, `evaluateRules`, `SALES_RULE_SURFACES`, `getFieldsForSalesRuleSurfaces`, `SALES_RULE_FIELD_REGISTRY` (customer type/status/country + synthesized `customer.customFields.*`). Countries are **alpha-2** codes.+- **Evaluator** — `@carbon/ee/rules.server` `evaluateSalesRuleLines` (service-role client; plan-gated on `SALES_RULES`). Missing ship-to → the engine's required-field semantics emit "Customer location is required" at the rule's severity.+- **Fail loud, never silently permissive.** A failed rule load, item load, or ship-to resolution THROWS. Each of those returns "nothing to enforce" if swallowed, which turns a compliance control off with no signal.+- **Drop-ship ship-to** — `resolveSalesOrderShipTo` returns the shipment's `customerLocationId`, never the header's, when `dropShipment` is set. If the drop-ship location is missing it returns null rather than falling back: the header is a DIFFERENT address, so a fallback would clear a country rule that should have blocked.+- **Invoice ship-to** — a sales invoice has NO customer ship-to (`invoiceCustomerLocationId` is the bill-to; the `locationId` columns are Carbon's own warehouses). An order-derived line (`salesInvoiceLine.salesOrderId`) resolves through `resolveSalesOrderShipTo`; a standalone line passes `customerLocationId: null` and fails closed via required-field semantics. NEVER substitute the bill-to — pinned by `packages/ee/src/rules/sales/invoice-shipto.test.ts`.+- **One modal** — enforcement actions return `{ violations, ruleNames }`; forms submit via `useRuleViolations` and render the shared `RuleViolationModal` (`@carbon/ee/rules`). Do not add a second violation UI.+- **Acknowledgment log** — `enforcementRuleAcknowledgment` (append-only): one row per deduped violation on blocked attempts and acknowledged overrides.++### Sales Rules safety++- MUST evaluate with the **service role** client in route actions AFTER `requirePermissions` — the check must see full truth regardless of the acting user's read permissions.+- MUST gate write routes with `requirePlan({ feature: "SALES_RULES" })` (key in `packages/ee/src/plan.ts`).+- The shared rule-builder components (`RuleBuilder`, `SurfacesField`, `MessageWithTokens`, `SeveritySelect`, `ItemFilterSelector`) live in `~/modules/inventory/ui/StorageRules/` and are imported by **deep path**. Keep any parameterization **additive** (defaults preserve storage behavior), and never import a module *barrel* from these components — keep the dependency a one-way deep import from `sales` into the inventory UI folder to avoid a barrel cycle. The shared zod AST schema lives in `@carbon/utils` for the same reason.+- Never widen the `enforcementRule_sales_surfaces` CHECK to admit storage surfaces — that CHECK is what replaced the old per-family enum typing.+- Never duplicate `isBlocked`/`dedupeViolations`/the violation modal — import from `@carbon/ee/rules(.server)`.++| Table | Purpose |+|---|---|+| `enforcementRule` (`family='sales'`) | Rule definitions (house PK `("id","companyId")`; RLS writes `sales_*` for sales-family rows) |+| `enforcementRuleItemAssignment` | Explicit per-item pins, PK `(itemId, ruleId)` — SHARED with storage rules |+| `enforcementRuleAcknowledgment` | Append-only override/block evidence (INSERT via `sales_create`) |++Service functions: the admin CRUD is NOT in `sales.service.ts` — both families share one parametrized implementation in `~/modules/shared` (`getEnforcementRules` / `getEnforcementRule` / `upsertEnforcementRule` / `deleteEnforcementRule` / `getEnforcementRuleAssignmentCounts`), called with `"sales"` as the family. Cross-app `getActiveSalesRulesForItems` / `getSalesRuleAssignmentsForItem` / `getSalesRulesList` / `assignSalesRule` / `unassignSalesRule` are imported from `@carbon/ee/rules` DIRECTLY at the call site — this module's barrel deliberately does not re-export them. Routes: `x+/sales+/sales-rules*` (list/new/edit/delete/assign/unassign), sidebar entry in `useSalesSubmodules`, per-item "Sales rules" card on `x+/part+/$itemId.inventory.tsx`. Enforcement: the quote, sales-order, and sales-invoice line create + edit actions, plus document gates (quote finalize/convert, RFQ convert, order confirm, shipment post, invoice post — the invoice-post gate runs in `x+/sales-invoice+/$invoiceId.post.tsx` BEFORE the optimistic `Pending` write). Every blocked or acknowledged outcome (line checks, gates, and the MCP backstops' blocks) is recorded through `recordSalesRuleOutcome` in `sales.server.ts` — one `enforcementRuleAcknowledgment` row per violation plus the `sales-rule-violation` notification; the RFQ-convert gate is the one exception (the table's documentType CHECK has no `salesRfq`; the minted quote re-records downstream).+## Related Modules- **production** — sales order lines create jobs for Make to Order itemsdiff --git a/apps/erp/app/modules/sales/index.ts b/apps/erp/app/modules/sales/index.tsindex f0ff82b5ab..c74857fd16 100644--- a/apps/erp/app/modules/sales/index.ts+++ b/apps/erp/app/modules/sales/index.ts@@ -1,3 +1,6 @@+// Rule queries shared with MES are NOT re-exported here — import them from+// `@carbon/ee/rules` directly so the package boundary stays visible at the+// call site (this module owns only the ERP-side admin CRUD + validators).export * from "./sales.models";export * from "./sales.service";export * from "./sales.utils";diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex 5a668fa51a..1f73ceb463 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -1,7 +1,12 @@import {bicMatchesCountry,+ conditionAstFormField,getBankFieldConfig,- isValidSwiftBic+ getFieldDef,+ isFieldAvailableOnSalesRuleSurfaces,+ isValidSwiftBic,+ RULE_SEVERITIES,+ SALES_RULE_SURFACES} from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";@@ -1089,6 +1094,49 @@ export function isQuoteLocked(status: string | null | undefined): boolean {return status !== null && status !== undefined && status !== "Draft";}+// -----------------------------------------------------------------------------+// Sales Rules — predicate rules evaluated when an item is added to a sales+// document (quote line / sales order line). Distinct from storage rules+// (`~/modules/inventory`, warehouse/MES surfaces) and the configurator's+// `configurationRule`. The AST schema and engine are shared via @carbon/utils.+// -----------------------------------------------------------------------------+export const salesRuleSeverities = RULE_SEVERITIES;++export const salesRuleValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ name: z.string().trim().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(salesRuleSeverities),+ // Sales rules are always item-target and broadcast via the filteredItem*+ // columns (empty = all items), so there is no targetType/appliesToAll.+ filteredItemTypes: zfd.repeatableOfType(z.string()).optional(),+ filteredItemGroupIds: zfd.repeatableOfType(z.string()).optional(),+ filteredItemMatchAll: zfd.checkbox(),+ active: zfd.checkbox(),+ surfaces: zfd+ .repeatableOfType(z.enum(SALES_RULE_SURFACES))+ .refine((arr) => arr.length >= 1, {+ message: "Pick at least one surface"+ }),+ conditionAst: conditionAstFormField+ })+ .superRefine((val, ctx) => {+ // Reject conditions on a registry field whose context the evaluator won't+ // populate for every selected surface (else it resolves undefined → false+ // "X is required"). Unknown paths are left to runtime presence handling.+ val.conditionAst.conditions.forEach((c, i) => {+ const def = getFieldDef(c.field);+ if (def && !isFieldAvailableOnSalesRuleSurfaces(def, val.surfaces)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["conditionAst", "conditions", i, "field"],+ message: `"${def.label}" isn't available on the selected surface(s)`+ });+ }+ });+ });// ─── Sales Return Orders (RMAs) ───export const salesReturnOrderStatusType = [diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.tsindex 682fdd794a..cd15299ce4 100644--- a/apps/erp/app/modules/sales/sales.server.ts+++ b/apps/erp/app/modules/sales/sales.server.ts@@ -1,7 +1,14 @@import type { Database } from "@carbon/database";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";+import type { Violation } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+import { getCompanySettings } from "~/modules/settings";import { getDatabaseClient } from "~/services/database.server";+const logger = getLogger("erp", "sales-server");+type BreakRow = { quantity: number; overridePrice: number; active: boolean };export async function duplicatePriceOverrides(@@ -218,3 +225,98 @@ export async function saveQuoteLineWithPrices(args: {}});}++// ---------------------------------------------------------------------------+// Sales-rule outcome evidence+// ---------------------------------------------------------------------------++/**+ * Persist sales-rule override/block evidence and notify the configured group.+ *+ * One `enforcementRuleAcknowledgment` row per deduped violation, plus one+ * `sales-rule-violation` notification. Both writes are best-effort: evidence+ * or notification failures are logged and must never break the submission+ * they describe. Callers pass the SERVICE-ROLE client — the acknowledgment+ * table's INSERT policy requires `sales_create`, but the documents these+ * gates protect (invoices, shipments) are legitimately posted by users+ * without it.+ *+ * Line actions pass `documentLineId`/`itemId` for the single line they wrote;+ * document gates leave them unset and each violation's own `lineId` (stamped+ * by the document evaluator) attributes the row instead.+ */+export async function recordSalesRuleOutcome(+ serviceRole: SupabaseClient<Database>,+ args: {+ companyId: string;+ userId: string;+ documentType: "quote" | "salesOrder" | "salesInvoice";+ documentId: string;+ outcome: "blocked" | "acknowledged";+ violations: Violation[];+ ruleNames: Record<string, string>;+ documentLineId?: string | null;+ itemId?: string | null;+ }+): Promise<void> {+ const {+ companyId,+ userId,+ documentType,+ documentId,+ outcome,+ violations,+ ruleNames+ } = args;+ if (violations.length === 0) return;++ const acknowledgmentInsert = await serviceRole+ .from("enforcementRuleAcknowledgment")+ .insert(+ violations.map((v) => ({+ companyId,+ ruleId: v.ruleId,+ ruleName: ruleNames[v.ruleId] ?? null,+ documentType,+ documentId,+ // A caller that evaluated a single line knows the real line id (or+ // that none exists yet) and passes the key — the evaluator's stamp is+ // a placeholder ("new") there. Document gates omit the key and the+ // per-violation stamp is the attribution.+ documentLineId:+ "documentLineId" in args+ ? (args.documentLineId ?? null)+ : (v.lineId ?? null),+ itemId: args.itemId ?? null,+ severity: v.severity,+ outcome,+ message: v.message,+ createdBy: userId+ }))+ );+ if (acknowledgmentInsert.error) {+ logger.error("Failed to record sales rule acknowledgments", {+ error: acknowledgmentInsert.error+ });+ }++ try {+ const companySettings = await getCompanySettings(serviceRole, companyId);+ if (companySettings.data?.salesRuleNotificationGroup?.length) {+ await trigger("notify", {+ companyId,+ documentId: `${documentType}:${documentId}:${outcome}`,+ event: NotificationEvent.SalesRuleViolation,+ recipient: {+ type: "group",+ groupIds: companySettings.data.salesRuleNotificationGroup+ },+ from: userId+ });+ }+ } catch (err) {+ logger.error("Failed to trigger sales rule violation notification", {+ error: err+ });+ }+}diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsxindex 4b0b744ef2..a5344cee94 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx@@ -1,5 +1,6 @@import { useCarbon } from "@carbon/auth";import { getQuoteDisplayId } from "@carbon/documents/utils";+import { useRuleViolations } from "@carbon/ee/rules";import { ValidatedForm } from "@carbon/form";import {Alert,@@ -19,7 +20,6 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useState } from "react";import { LuTriangleAlert } from "react-icons/lu";-import type { FetcherWithComponents } from "react-router";import { useParams } from "react-router";import {CustomerContact,@@ -44,14 +44,12 @@ type QuotationFinalizeModalProps = {onClose: () => void;quote?: Quotation;shipment: QuotationShipment | null;- fetcher: FetcherWithComponents<{}>;defaultCc?: string[];};const QuotationFinalizeModal = ({quote,onClose,- fetcher,shipment,defaultCc = []}: QuotationFinalizeModalProps) => {@@ -59,6 +57,16 @@ const QuotationFinalizeModal = ({const { quoteId } = useParams();if (!quoteId) throw new Error("quoteId not found");+ // Finalizing re-evaluates sales rules across every line (the terminal gate in+ // the action). Route the submission through the violations hook so a blocked+ // finalize opens the shared modal instead of silently doing nothing, and only+ // close this modal once the action actually succeeds.+ const ruleViolations = useRuleViolations({+ action: path.to.quoteFinalize(quoteId),+ onSuccess: onClose+ });+ const { fetcher } = ruleViolations;+const integrations = useIntegrations();const canEmail = integrations.has("email");const { carbon } = useCarbon();@@ -161,7 +169,6 @@ const QuotationFinalizeModal = ({method="post"validator={quoteFinalizeValidator}action={path.to.quoteFinalize(quoteId)}- onSubmit={onClose}defaultValues={{notification: notificationType as "Email" | "None",customerContact: quote?.customerContactId ?? undefined,@@ -247,6 +254,7 @@ const QuotationFinalizeModal = ({</ModalFooter></ValidatedForm></ModalContent>+ <ruleViolations.ViolationModal /></Modal>);};diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsxindex f62ef25b62..16240bd2cd 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx@@ -92,7 +92,6 @@ const QuoteHeader = () => {const deleteQuoteModal = useDisclosure();const [asRevision, setAsRevision] = useState(false);- const finalizeFetcher = useFetcher<{}>();const statusFetcher = useFetcher<{}>();const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({@@ -241,10 +240,8 @@ const QuoteHeader = () => {<ButtononClick={finalizeModal.onOpen}- isLoading={finalizeFetcher.state !== "idle"}isDisabled={routeData?.quote?.status !== "Draft" ||- finalizeFetcher.state !== "idle" ||!permissions.can("update", "sales") ||!eligibleLines?.length}@@ -339,7 +336,6 @@ const QuoteHeader = () => {quote={routeData?.quote}shipment={routeData?.shipment ?? null}onClose={finalizeModal.onClose}- fetcher={finalizeFetcher}// @ts-expect-error TS2339 - TODO: fix typedefaultCc={routeData?.defaultCc ?? []}/>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsxindex b76a867f22..af425103cf 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import { TextArea, ValidatedForm } from "@carbon/form";import {Badge,@@ -28,7 +29,7 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useState } from "react";import { BsThreeDotsVertical } from "react-icons/bs";import { LuTrash } from "react-icons/lu";-import { Link, useFetcher, useParams } from "react-router";+import { Link, useParams } from "react-router";import type { z } from "zod";import { MethodIcon, MethodItemTypeIcon } from "~/components";import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";@@ -81,7 +82,6 @@ const QuoteLineForm = ({onClose}: QuoteLineFormProps) => {const { t, i18n } = useLingui();- const fetcher = useFetcher<typeof action>();const permissions = usePermissions();const { company } = useUser();const { carbon } = useCarbon();@@ -90,6 +90,20 @@ const QuoteLineForm = ({if (!quoteId) throw new Error("quoteId not found");+ // Sales-rule enforcement: submissions run through the violation hook's+ // fetcher so a blocked response opens <rules.ViolationModal /> with an+ // acknowledge-and-resubmit path for warns. Modal close happens on success+ // (not on submit) so violations can surface first.+ const rules = useRuleViolations<typeof action>({+ action: initialValues.id+ ? path.to.quoteLine(quoteId, initialValues.id)+ : path.to.newQuoteLine(quoteId),+ onSuccess: () => {+ if (type === "modal") onClose?.();+ }+ });+ const fetcher = rules.fetcher;+const [items] = useItems();const routeData = useRouteData<{quote: Quotation;@@ -302,9 +316,6 @@ const QuoteLineForm = ({}className="w-full"isDisabled={isEditing && isLocked}- onSubmit={() => {- if (type === "modal") onClose?.();- }}><HStack className="w-full justify-between items-start"><ModalCardHeader>@@ -563,6 +574,7 @@ const QuoteLineForm = ({</ModalCardContent></ModalCard></ModalCardProvider>+ <rules.ViolationModal />{isEditing && deleteDisclosure.isOpen && (<DeleteQuoteLineline={initialValues as QuotationLine}diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsxindex ffeb96f214..07dcfce3bd 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import { SelectControlled, ValidatedForm } from "@carbon/form";import { getLogger } from "@carbon/logger";import {@@ -47,7 +48,7 @@ import {LuTruck,LuUpload} from "react-icons/lu";-import { useNavigation, useParams } from "react-router";+import { useParams } from "react-router";import type { z } from "zod";import { CustomerAvatar, DateTime } from "~/components";import { Enumerable } from "~/components/Enumerable";@@ -311,8 +312,15 @@ const QuoteToOrderDrawer = ({}};- const navigation = useNavigation();- const isSubmitting = navigation.state !== "idle";+ // Converting re-evaluates sales rules across every quote line (the terminal+ // gate in the action) before the edge function writes sales order lines.+ // Submitting through the violations hook — rather than a plain navigation —+ // is what lets a blocked convert surface the shared modal.+ const ruleViolations = useRuleViolations({+ action: path.to.convertQuoteToOrder(quote.id!),+ onSuccess: onClose+ });+ const isSubmitting = ruleViolations.fetcher.state !== "idle";const isNextButtonDisabled =step === 1 && Object.keys(selectedLines).length === 0;@@ -337,6 +345,7 @@ const QuoteToOrderDrawer = ({method="post"action={path.to.convertQuoteToOrder(quote.id!)}validator={salesConfirmValidator}+ fetcher={ruleViolations.fetcher}defaultValues={{notification: "None",customerContact: quote.customerContactId ?? undefined,@@ -382,6 +391,7 @@ const QuoteToOrderDrawer = ({</>)}</DrawerContent>+ <ruleViolations.ViolationModal /></Drawer>);};diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsxindex 545b1c8d00..078c6499c6 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx@@ -1,4 +1,5 @@import type { Database } from "@carbon/database";+import { useRuleViolations } from "@carbon/ee/rules";import { SelectControlled, ValidatedForm } from "@carbon/form";import {Button,@@ -59,7 +60,6 @@ import type { SalesInvoice } from "~/modules/invoicing/types";import SalesInvoiceStatus from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus";import type { Job } from "~/modules/production/types";import { SalesReturnOrderStatus } from "~/modules/sales/ui/SalesReturnOrders";-import type { action as confirmAction } from "~/routes/x+/sales-order+/$orderId.confirm";import type { action as statusAction } from "~/routes/x+/sales-order+/$orderId.status";import { useCustomers } from "~/stores/customers";import { path } from "~/utils/path";@@ -70,12 +70,10 @@ import SalesStatus from "./SalesStatus";import { useSalesOrder } from "./useSalesOrder";const SalesOrderConfirmModal = ({- fetcher,salesOrder,onClose,defaultCc = []}: {- fetcher: FetcherWithComponents<{ success: boolean; message: string }>;salesOrder?: SalesOrder;onClose: () => void;defaultCc?: string[];@@ -91,14 +89,27 @@ const SalesOrderConfirmModal = ({canEmail ? "Email" : "None");- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ // Confirming re-evaluates sales rules across every line (the terminal gate in+ // the action). Route the submission through the violations hook so a blocked+ // confirm opens the shared modal rather than only flashing a toast, and close+ // this modal only once the action actually succeeds.+ const ruleViolations = useRuleViolations({+ action: path.to.salesOrderConfirm(orderId),+ onSuccess: onClose+ });+ const fetcher = ruleViolations.fetcher as FetcherWithComponents<{+ success?: boolean;+ message?: string;+ violations?: unknown[];+ }>;+useEffect(() => {- if (fetcher.data?.success) {- onClose();- } else if (fetcher.data?.success === false && fetcher.data?.message) {+ // Violations render in the ViolationModal; don't also toast their message.+ if ((fetcher.data?.violations ?? []).length > 0) return;+ if (fetcher.data?.success === false && fetcher.data?.message) {toast.error(fetcher.data.message);}- }, [fetcher.data?.success]);+ }, [fetcher.data]);return (<Modal@@ -114,7 +125,6 @@ const SalesOrderConfirmModal = ({method="post"action={path.to.salesOrderConfirm(orderId)}validator={salesConfirmValidator}- onSubmit={onClose}defaultValues={{notification: notificationType,customerContact: salesOrder?.customerContactId ?? undefined,@@ -175,6 +185,7 @@ const SalesOrderConfirmModal = ({</ModalFooter></ValidatedForm></ModalContent>+ <ruleViolations.ViolationModal /></Modal>);};@@ -210,7 +221,6 @@ const SalesOrderHeader = () => {const isLocked = isSalesOrderLocked(routeData?.salesOrder?.status);const statusFetcher = useFetcher<typeof statusAction>();- const confirmFetcher = useFetcher<typeof confirmAction>();const { ship, invoice } = useSalesOrder();const linesRequireJobs = hasLinesRequiringJobs({@@ -403,10 +413,8 @@ const SalesOrderHeader = () => {? "primary": "secondary"}- isLoading={confirmFetcher.state !== "idle"}onClick={confirmDisclosure.onOpen}isDisabled={- confirmFetcher.state !== "idle" ||!["Draft", "Needs Approval"].includes(routeData?.salesOrder?.status ?? "") ||@@ -660,7 +668,6 @@ const SalesOrderHeader = () => {)}{confirmDisclosure.isOpen && (<SalesOrderConfirmModal- fetcher={confirmFetcher}salesOrder={routeData?.salesOrder}onClose={confirmDisclosure.onClose}defaultCc={routeData?.defaultCc ?? []}diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsxindex 7603d53c9d..e95b563de0 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import { Combobox, ValidatedForm } from "@carbon/form";import {@@ -105,6 +106,19 @@ const SalesOrderLineForm = ({if (!orderId) throw new Error("orderId not found");+ // Sales-rule enforcement: submissions run through the violation hook's+ // fetcher so a blocked response opens <rules.ViolationModal /> with an+ // acknowledge-and-resubmit path for warns. Modal close happens on success+ // (not on submit) so violations can surface first.+ const rules = useRuleViolations({+ action: initialValues.id+ ? path.to.salesOrderLine(orderId, initialValues.id)+ : path.to.newSalesOrderLine(orderId),+ onSuccess: () => {+ if (type === "modal") onClose?.();+ }+ });+const routeData = useRouteData<{salesOrder: SalesOrder;}>(path.to.salesOrder(orderId));@@ -433,6 +447,7 @@ const SalesOrderLineForm = ({><ModalCardContent size="xxlarge"><ValidatedForm+ fetcher={rules.fetcher}defaultValues={initialValues}validator={salesOrderLineValidator}method="post"@@ -443,9 +458,6 @@ const SalesOrderLineForm = ({}className="w-full"isDisabled={isEditing && isLocked}- onSubmit={() => {- if (type === "modal") onClose?.();- }}><HStackclassName={cn(@@ -1052,6 +1064,7 @@ const SalesOrderLineForm = ({</ModalCard></ModalCardProvider></Tabs>+ <rules.ViolationModal /></>);};diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsxindex c9eb6c8c36..523e7fc102 100644--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx@@ -1,4 +1,5 @@import { useCarbon } from "@carbon/auth";+import { useRuleViolations } from "@carbon/ee/rules";import { Select, Submit, ValidatedForm } from "@carbon/form";import {Alert,@@ -26,7 +27,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useState } from "react";+import { useState } from "react";import {LuCircleCheck,LuCircleX,@@ -414,17 +415,27 @@ function ConvertToQuoteModal({path.to.salesRfq(rfqId));- const fetcher = useFetcher<{ error: string | null }>();+ // Converting re-evaluates sales rules across the RFQ's mapped lines (the+ // terminal gate in the action) before the edge function mints quote lines.+ // Route the submission through the violations hook so a blocked convert+ // opens the shared modal instead of silently doing nothing.+ const ruleViolations = useRuleViolations({+ action: path.to.salesRfqConvert(rfqId),+ onSuccess: onClose+ });+ const fetcher = ruleViolations.fetcher as ReturnType<+ typeof useFetcher<{ error: string | null; violations?: unknown[] }>+ >;const isLoading = fetcher.state !== "idle";const linesWithoutItems = lines.filter((line) => !line.itemId);const requiresPartNumbers = linesWithoutItems.length > 0;const requiresCustomer = !routeData?.rfqSummary?.customerId;- useEffect(() => {- if (fetcher.state === "loading") {- onClose();- }- }, [fetcher.state, onClose]);+ // NOTE: do NOT close on `fetcher.state === "loading"`. A fetcher passes+ // through `loading` (revalidation) even when the action RETURNS data, so that+ // would unmount this modal — and the nested ViolationModal — the moment the+ // sales-rule gate returns violations. Closing is owned by the hook's+ // `onSuccess`, which fires only when the action actually succeeded.return (<Modal@@ -508,6 +519,7 @@ function ConvertToQuoteModal({</fetcher.Form></ModalFooter></ModalContent>+ <ruleViolations.ViolationModal /></Modal>);}diff --git a/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleAssignmentsList.tsx b/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleAssignmentsList.tsxnew file mode 100644index 0000000000..ab2c99b1e6--- /dev/null+++ b/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleAssignmentsList.tsx@@ -0,0 +1,369 @@+// Per-item "Sales rules" card — the sales-rule counterpart of+// `~/modules/inventory/ui/StorageRules/RuleAssignmentsList`. Forked (not parameterized)+// because that component hard-codes the STORAGE_RULES plan gate, the storage+// path constants, storage SurfaceChips, and targetType copy; a fork is the+// smaller diff and leaves storage behavior untouched.++import {+ Badge,+ Button,+ Card,+ CardContent,+ CardHeader,+ Combobox,+ HStack,+ IconButton,+ Status,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { SALES_RULE_SURFACES, type SalesRuleSurface } 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";++const SALES_RULE_SURFACE_LABELS: Record<SalesRuleSurface, string> = {+ quoteLine: "Quote line",+ salesOrderLine: "Sales order line",+ salesInvoiceLine: "Sales invoice line"+};++type AssignedSalesRule = {+ ruleId: string;+ salesRule: {+ id: string;+ name: string;+ severity: "error" | "warn";+ message: string;+ active: boolean;+ surfaces?: SalesRuleSurface[];+ };+ /**+ * `"__all__"` marks a broadcast rule (matched via the rule's item filters,+ * not an explicit assignment). UI shows the reach badge and suppresses+ * unassign — edit the rule's filters to remove it.+ */+ inheritedFromId?: string | null;+ inheritedFromName?: string | null;+};++type SalesRuleLibraryRule = {+ id: string;+ name: string;+ severity: "error" | "warn";+ active: boolean;+};++type SalesRuleAssignmentsListProps = {+ itemId: string;+ assignments: AssignedSalesRule[];+ library: SalesRuleLibraryRule[];+};++export default function SalesRuleAssignmentsList({+ itemId,+ assignments,+ library+}: SalesRuleAssignmentsListProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher();+ const { isGated } = usePlanGate({ feature: "SALES_RULES" });+ // Assignment mutations are gated on `update: "sales"` (the assign/unassign+ // routes), so the UI mirrors that single permission.+ const canUpdate = permissions.can("update", "sales");+ const description = t`Enforce checks on quote, sales order, and sales invoice lines for this item.`;++ 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.salesRuleAssign(itemId)+ });+ };++ 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>Sales 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 && canUpdate && (+ <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.newSalesRule}>+ <Trans>Add rule</Trans>+ </Link>+ </Button>+ </div>+ )}+ </div>+ );++ if (isGated) {+ return (+ <Card className="flex-grow">+ <CardHeader>{header}</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 sales rules</Trans>+ </UpgradeOverlayTitle>+ <UpgradeOverlayDescription>+ {description}+ </UpgradeOverlayDescription>+ </UpgradeOverlayContent>+ <UpgradeOverlayActions>+ <UpgradeOverlayUpgradeButton />+ </UpgradeOverlayActions>+ </div>+ </CardContent>+ </Card>+ );+ }++ const body = isEmpty ? (+ <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 checks on this item.+ </Trans>+ </p>+ </div>++ {canUpdate && (+ <HStack className="gap-2 flex-wrap justify-center pt-1">+ {availableOptions.length > 0 ? (+ <>+ <Combobox+ value=""+ options={availableOptions}+ onChange={handleAssign}+ placeholder={t`Add from library…`}+ />+ <Button+ asChild+ variant="secondary"+ size="sm"+ leftIcon={<LuPlus />}+ >+ <Link to={path.to.newSalesRule}>+ <Trans>Create new rule</Trans>+ </Link>+ </Button>+ </>+ ) : (+ <>+ <Button+ asChild+ variant="secondary"+ size="sm"+ leftIcon={<LuLibrary />}+ >+ <Link to={path.to.salesRules}>+ <Trans>Browse library</Trans>+ </Link>+ </Button>+ <Button asChild size="sm" leftIcon={<LuPlus />}>+ <Link to={path.to.newSalesRule}>+ <Trans>Create new rule</Trans>+ </Link>+ </Button>+ </>+ )}+ </HStack>+ )}+ </div>+ ) : (+ <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) => {+ const isBroadcast = a.inheritedFromId === "__all__";+ const surfaces =+ a.salesRule.surfaces && a.salesRule.surfaces.length > 0+ ? a.salesRule.surfaces+ : [...SALES_RULE_SURFACES];+ return (+ <Tr key={a.ruleId}>+ <Td className="whitespace-nowrap">+ <HStack className="gap-2 items-center flex-wrap">+ <Hyperlink to={path.to.salesRule(a.ruleId)}>+ <HStack className="gap-2 items-center">+ <LuShieldCheck className="text-muted-foreground shrink-0" />+ <span>{a.salesRule.name}</span>+ </HStack>+ </Hyperlink>+ {isBroadcast && (+ <Badge+ variant="outline"+ className="text-[10px] uppercase tracking-wide"+ >+ {a.inheritedFromName ?? <Trans>All items</Trans>}+ </Badge>+ )}+ </HStack>+ </Td>+ <Td>+ {a.salesRule.severity === "error" ? (+ <Badge variant="red">+ <Trans>Error</Trans>+ </Badge>+ ) : (+ <Badge variant="yellow">+ <Trans>Warning</Trans>+ </Badge>+ )}+ </Td>+ <Td>+ <div className="flex items-center gap-1">+ {surfaces.map((s) => (+ <Badge key={s} variant="secondary">+ {SALES_RULE_SURFACE_LABELS[s]}+ </Badge>+ ))}+ </div>+ </Td>+ <Td>+ {a.salesRule.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.salesRule.message}+ </p>+ </Td>+ <Td className="text-right">+ <Form+ method="post"+ action={path.to.salesRuleUnassign(itemId, a.ruleId)}+ >+ <IconButton+ type="submit"+ icon={<LuTrash />}+ aria-label={+ isBroadcast+ ? t`Edit the rule's item filters to remove it`+ : t`Unassign rule`+ }+ title={+ isBroadcast+ ? t`Edit the rule's item filters to remove it`+ : undefined+ }+ variant="ghost"+ size="sm"+ isDisabled={!canUpdate || isBroadcast}+ />+ </Form>+ </Td>+ </Tr>+ );+ })}+ </Tbody>+ </Table>+ );++ return (+ <Card className="flex-grow">+ <CardHeader>{header}</CardHeader>+ <CardContent>{body}</CardContent>+ </Card>+ );+}diff --git a/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleForm.tsx b/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleForm.tsxnew file mode 100644index 0000000000..38f6b1bd3b--- /dev/null+++ b/apps/erp/app/modules/sales/ui/SalesRules/SalesRuleForm.tsx@@ -0,0 +1,214 @@+// Create/edit drawer for Sales Rules. Mirrors+// `~/modules/inventory/ui/StorageRules/StorageRuleForm` minus targetType/appliesToAll —+// sales rules are always item-target and broadcast via the item filters.+// Reuses the shared storage-rules builder components, parameterized with the+// sales-rule surface catalog + field pool.++import { Boolean, ValidatedForm } from "@carbon/form";+import {+ Button,+ HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,+ VStack+} from "@carbon/react";+import {+ type Condition,+ type ConditionAst,+ getFieldsForSalesRuleSurfaces,+ SALES_RULE_SURFACES,+ type SalesRuleSurface+} from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useMemo, useState } from "react";+import { LuFileText, LuReceipt, LuShoppingCart } from "react-icons/lu";+import type { z } from "zod";+import {+ CustomFormFields,+ Hidden,+ Input,+ Submit,+ TextArea+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import ItemFilterSelector from "~/modules/inventory/ui/StorageRules/ItemFilterSelector";+import MessageWithTokens from "~/modules/inventory/ui/StorageRules/MessageWithTokens";+import RuleBuilder from "~/modules/inventory/ui/StorageRules/RuleBuilder";+import SeveritySelect from "~/modules/inventory/ui/StorageRules/SeveritySelect";+import SurfacesField from "~/modules/inventory/ui/StorageRules/SurfacesField";+import { path } from "~/utils/path";+import { salesRuleValidator } from "../../sales.models";++const SALES_RULE_SURFACE_OPTIONS: {+ value: SalesRuleSurface;+ label: string;+ description?: string;+ icon?: JSX.Element;+}[] = [+ {+ value: "quoteLine",+ label: "Quote line",+ description: "When an item is added to a quote",+ icon: <LuFileText />+ },+ {+ value: "salesOrderLine",+ label: "Sales order line",+ description: "When an item is added to a sales order",+ icon: <LuShoppingCart />+ },+ {+ value: "salesInvoiceLine",+ label: "Sales invoice line",+ description: "When an item is added to a sales invoice",+ icon: <LuReceipt />+ }+];++type SalesRuleFormInitial = Partial<z.infer<typeof salesRuleValidator>> & {+ conditionAst?: ConditionAst;+};++type SalesRuleFormProps = {+ initialValues: SalesRuleFormInitial;+ open?: boolean;+ onClose: () => void;+};++export default function SalesRuleForm({+ initialValues,+ open = true,+ onClose+}: SalesRuleFormProps) {+ const { t } = useLingui();+ const permissions = usePermissions();++ const isEditing = !!initialValues.id;+ const isDisabled = isEditing+ ? !permissions.can("update", "sales")+ : !permissions.can("create", "sales");++ const conditionAstInitial: ConditionAst = (initialValues.conditionAst as+ | ConditionAst+ | undefined) ?? {+ kind: "all",+ conditions: []+ };++ // Live mirror of the AST conditions, kept in sync via RuleBuilder's+ // callback. MessageWithTokens reads it to offer per-condition tokens.+ const [liveConditions, setLiveConditions] = useState<Condition[]>(+ conditionAstInitial.conditions+ );++ // Default new rules to all sales-rule surfaces. Editing keeps whatever was+ // saved.+ const defaultSurfaces = (initialValues.surfaces ?? [+ ...SALES_RULE_SURFACES+ ]) as SalesRuleSurface[];++ const [liveSurfaces, setLiveSurfaces] =+ useState<SalesRuleSurface[]>(defaultSurfaces);++ // Field pool the builder + token dropdown may reference, narrowed by the+ // rule's live surfaces (mirrors the save-time validator gate).+ const salesRuleFields = useMemo(+ () => getFieldsForSalesRuleSurfaces(liveSurfaces),+ [liveSurfaces]+ );++ const defaults = {+ id: initialValues.id ?? undefined,+ name: initialValues.name ?? "",+ description: initialValues.description ?? "",+ message: initialValues.message ?? "",+ severity: initialValues.severity ?? "error",+ filteredItemTypes: initialValues.filteredItemTypes ?? [],+ filteredItemGroupIds: initialValues.filteredItemGroupIds ?? [],+ filteredItemMatchAll: initialValues.filteredItemMatchAll ?? false,+ active: initialValues.active ?? true,+ surfaces: defaultSurfaces+ };++ return (+ <ModalDrawerProvider type="drawer">+ <ModalDrawer+ open={open}+ onOpenChange={(o) => {+ if (!o) onClose();+ }}+ >+ <ModalDrawerContent size="lg">+ <ValidatedForm+ validator={salesRuleValidator}+ method="post"+ action={+ isEditing+ ? path.to.salesRule(initialValues.id!)+ : path.to.newSalesRule+ }+ defaultValues={defaults}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing ? <Trans>Edit rule</Trans> : <Trans>New rule</Trans>}+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <VStack spacing={4}>+ <HStack className="w-full gap-x-4">+ <Input name="name" label={t`Name`} />++ <div className="shrink-0 pb-2">+ <Boolean variant="large" name="active" label={t`Active`} />+ </div>+ </HStack>+ <TextArea+ name="description"+ label={t`Description`}+ placeholder={t`Optional context for this rule`}+ />+ <SeveritySelect name="severity" />+ <ItemFilterSelector />+ <SurfacesField<SalesRuleSurface>+ name="surfaces"+ surfaceOptions={SALES_RULE_SURFACE_OPTIONS}+ onSurfacesChange={setLiveSurfaces}+ />+ <RuleBuilder+ name="conditionAst"+ initial={conditionAstInitial}+ onConditionsChange={setLiveConditions}+ fields={salesRuleFields}+ />+ <MessageWithTokens+ name="message"+ conditions={liveConditions}+ fields={salesRuleFields}+ />+ <CustomFormFields table="enforcementRule" />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>+ <Trans>Save</Trans>+ </Submit>+ <Button variant="solid" onClick={() => onClose()}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>+ );+}diff --git a/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesTable.tsx b/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesTable.tsxnew file mode 100644index 0000000000..e83479a9d9--- /dev/null+++ b/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesTable.tsx@@ -0,0 +1,173 @@+// List table for Sales → Sales Rules. Mirrors+// `~/modules/inventory/ui/StorageRules/StorageRulesTable` minus the targetType column;+// permission checks use `sales`.++import type { Json } from "@carbon/database";+import { Badge, MenuIcon, MenuItem, Status } from "@carbon/react";+import { SALES_RULE_SURFACES, type SalesRuleSurface } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import { LuPencil, LuShieldCheck, LuTrash } from "react-icons/lu";+import { useNavigate } from "react-router";+import { Hyperlink, New, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { usePermissions, useUrlParams } from "~/hooks";+import { useCustomColumns } from "~/hooks/useCustomColumns";+import { path } from "~/utils/path";++type SalesRuleRowView = {+ id: string;+ name: string;+ severity: "error" | "warn";+ active: boolean;+ description?: string | null;+ message: string;+ updatedAt?: string | null;+ customFields: Json;+ assignmentCount?: number;+ surfaces?: SalesRuleSurface[];+};++const SALES_RULE_SURFACE_LABELS: Record<SalesRuleSurface, string> = {+ quoteLine: "Quote line",+ salesOrderLine: "Sales order line",+ salesInvoiceLine: "Sales invoice line"+};++type SalesRulesTableProps = {+ data: SalesRuleRowView[];+ count: number;+};++const SalesRulesTable = memo(({ data, count }: SalesRulesTableProps) => {+ const { t } = useLingui();+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const permissions = usePermissions();+ const customColumns = useCustomColumns<SalesRuleRowView>("enforcementRule");++ const rows = useMemo(() => data, [data]);++ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {+ const defaults: ColumnDef<(typeof rows)[number]>[] = [+ {+ accessorKey: "name",+ header: t`Name`,+ cell: ({ row }) => (+ <Hyperlink+ to={`${path.to.salesRule(row.original.id)}?${params.toString()}`}+ >+ <Enumerable value={row.original.name} />+ </Hyperlink>+ ),+ meta: { icon: <LuShieldCheck /> }+ },+ {+ accessorKey: "severity",+ header: t`Severity`,+ cell: ({ row }) =>+ row.original.severity === "error" ? (+ <Badge variant="red">+ <Trans>Error</Trans>+ </Badge>+ ) : (+ <Badge variant="yellow">+ <Trans>Warn</Trans>+ </Badge>+ )+ },+ {+ accessorKey: "surfaces",+ header: t`Surfaces`,+ cell: ({ row }) => {+ const surfaces =+ row.original.surfaces && row.original.surfaces.length > 0+ ? row.original.surfaces+ : [...SALES_RULE_SURFACES];+ return (+ <div className="flex items-center gap-1">+ {surfaces.map((s) => (+ <Badge key={s} variant="secondary">+ {SALES_RULE_SURFACE_LABELS[s]}+ </Badge>+ ))}+ </div>+ );+ }+ },+ {+ accessorKey: "active",+ header: t`Status`,+ cell: ({ row }) =>+ row.original.active ? (+ <Status color="green">+ <Trans>Active</Trans>+ </Status>+ ) : (+ <Status color="gray">+ <Trans>Inactive</Trans>+ </Status>+ )+ },+ {+ accessorKey: "assignmentCount",+ header: t`Items`,+ cell: ({ row }) => (+ <span className="tabular-nums text-muted-foreground">+ {row.original.assignmentCount ?? 0}+ </span>+ )+ }+ ];+ return [...defaults, ...customColumns];+ }, [customColumns, params, t]);++ const renderContextMenu = useCallback(+ (row: (typeof rows)[number]) => (+ <>+ <MenuItem+ disabled={!permissions.can("update", "sales")}+ onClick={() => {+ navigate(`${path.to.salesRule(row.id)}?${params.toString()}`);+ }}+ >+ <MenuIcon icon={<LuPencil />} />+ <Trans>Edit Rule</Trans>+ </MenuItem>+ <MenuItem+ disabled={!permissions.can("delete", "sales")}+ destructive+ onClick={() => {+ navigate(`${path.to.deleteSalesRule(row.id)}?${params.toString()}`);+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ <Trans>Delete Rule</Trans>+ </MenuItem>+ </>+ ),+ [navigate, params, permissions]+ );++ return (+ <Table<(typeof rows)[number]>+ data={data}+ columns={columns}+ count={count}+ primaryAction={+ permissions.can("create", "sales") && (+ <New+ label={t`Rule`}+ to={`${path.to.newSalesRule}?${params.toString()}`}+ />+ )+ }+ renderContextMenu={renderContextMenu}+ title={t`Sales Rules`}+ />+ );+});++SalesRulesTable.displayName = "SalesRulesTable";+export default SalesRulesTable;diff --git a/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesUpgradeOverlay.tsx b/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesUpgradeOverlay.tsxnew file mode 100644index 0000000000..5f2a32585b--- /dev/null+++ b/apps/erp/app/modules/sales/ui/SalesRules/SalesRulesUpgradeOverlay.tsx@@ -0,0 +1,63 @@+// Plan-gate overlay for Sales → Sales Rules. Shares the overlay chrome with+// the storage family via `~/components/RulesUpgradeOverlay`; only the preview+// table, the mock fixtures, and the copy are family-specific.++import { Trans } from "@lingui/react/macro";+import RulesUpgradeOverlay from "~/components/RulesUpgradeOverlay";+import SalesRulesTable from "./SalesRulesTable";++const mockRules = [+ {+ id: "mock-1",+ name: "Block export-restricted destinations",+ severity: "error" as const,+ active: true,+ description: "Block quoting restricted parts to embargoed countries.",+ message: "This part cannot be sold to the selected destination.",+ updatedAt: "2026-05-04T10:00:00Z",+ customFields: {},+ assignmentCount: 18,+ surfaces: ["quoteLine", "salesOrderLine"] as const+ },+ {+ id: "mock-2",+ name: "Warn on inactive customer status",+ severity: "warn" as const,+ active: true,+ description: "Flag lines for customers whose status is not active.",+ message: "Customer status requires review before ordering.",+ updatedAt: "2026-04-29T14:22:00Z",+ customFields: {},+ assignmentCount: 6,+ surfaces: ["salesOrderLine"] as const+ },+ {+ id: "mock-3",+ name: "Distributor-only parts",+ severity: "error" as const,+ active: false,+ description: "Restrict select parts to distributor customer types.",+ message: "This part is only available to distributors.",+ updatedAt: "2026-04-21T09:15:00Z",+ customFields: {},+ assignmentCount: 3,+ surfaces: ["quoteLine"] as const+ }+];++export default function SalesRulesUpgradeOverlay() {+ return (+ <RulesUpgradeOverlay+ preview={+ <SalesRulesTable data={mockRules as never} count={mockRules.length} />+ }+ title={<Trans>Sales Rules</Trans>}+ description={+ <Trans>+ Enforce customer and item checks when items are added to quotes, sales+ orders, and sales invoices.+ </Trans>+ }+ />+ );+}diff --git a/apps/erp/app/modules/sales/ui/SalesRules/index.ts b/apps/erp/app/modules/sales/ui/SalesRules/index.tsnew file mode 100644index 0000000000..b9f778d3b0--- /dev/null+++ b/apps/erp/app/modules/sales/ui/SalesRules/index.ts@@ -0,0 +1,4 @@+export { default as SalesRuleAssignmentsList } from "./SalesRuleAssignmentsList";+export { default as SalesRuleForm } from "./SalesRuleForm";+export { default as SalesRulesTable } from "./SalesRulesTable";+export { default as SalesRulesUpgradeOverlay } from "./SalesRulesUpgradeOverlay";diff --git a/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx b/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsxindex 3e8d6a8ddd..d2f761bb45 100644--- a/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx+++ b/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx@@ -5,6 +5,7 @@ import {LuList,LuPercent,LuShapes,+ LuShieldCheck,LuSquareUser,LuStar,LuUndo2@@ -80,6 +81,12 @@ export default function useSalesSubmodules() {role: "employee",icon: <LuPercent />},+ {+ name: t`Sales Rules`,+ to: path.to.salesRules,+ role: "employee",+ icon: <LuShieldCheck />+ },{name: t`No Quote Reasons`,to: path.to.noQuoteReasons,diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 56133a1a99..17b1ca980d 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -346,6 +346,12 @@ export const rfqReadyValidator = z.object({.optional()});+export const salesRuleNotificationValidator = z.object({+ salesRuleNotificationGroup: z+ .array(z.string().min(1, { message: "Invalid selection" }))+ .optional()+});+export const suggestionNotificationValidator = z.object({suggestionNotificationGroup: z.array(z.string().min(1, { message: "Invalid selection" }))diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 55720643f1..3028c5b052 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1244,6 +1244,17 @@ export async function updateAccountsReceivableEmail(.eq("id", companyId);}+export async function updateSalesRuleNotificationSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ salesRuleNotificationGroup: string[]+) {+ return client+ .from("companySettings")+ .update(sanitize({ salesRuleNotificationGroup }))+ .eq("id", companyId);+}+export async function updateQuoteLineCategoryMarkups(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex abadb86dbf..8a8f63a144 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -1,10 +1,12 @@-import type { Database, Tables } from "@carbon/database";+import type { Database, Json, Tables } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { getContentType, getFileExtension } from "@carbon/files";import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";-import { getPurchaseOrderStatus } from "@carbon/utils";+import type { ConditionAst, Severity } from "@carbon/utils";+import { datetime, getPurchaseOrderStatus } from "@carbon/utils";import type {+ PostgrestResponse,PostgrestSingleResponse,SupabaseClient} from "@supabase/supabase-js";@@ -1403,3 +1405,203 @@ export function resolveSupplierPrice(: fallbackUnitPrice;return basePrice * exchangeRate;}++// -----------------------------------------------------------------------------+// Enforcement Rules (storage + sales families)+// -----------------------------------------------------------------------------+// Both rule families live in ONE `enforcementRule` table discriminated by+// `family`, so the admin CRUD is written once here rather than duplicated in+// `inventory.service.ts` and `sales.service.ts`. Callers pass their family+// explicitly — there is no per-family wrapper to keep in sync, and adding a+// third family costs nothing here.+//+// Cross-app queries (assignment loaders, evaluator fetches) live in+// `@carbon/ee/rules`; this file is the ERP-only admin surface, because it+// depends on ERP request-utils (GenericQueryFilters, sanitize).++export type EnforcementRuleFamily =+ Database["public"]["Enums"]["enforcementRuleFamily"];++export type EnforcementRuleRow =+ Database["public"]["Tables"]["enforcementRule"]["Row"];++/** Item-scoping columns shared by both families (empty arrays = every item). */+type RuleItemFilterFields = {+ filteredItemTypes?: string[];+ filteredItemGroupIds?: string[];+ filteredItemMatchAll?: boolean;+};++/**+ * Storage-family-only shape. The DB pins sales rows to `targetType: 'item'` /+ * `appliesToAll: false` via the `enforcementRule_sales_shape` CHECK, so these+ * stay optional here and simply go unset for sales.+ */+type RuleTargetFields = {+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"];+ appliesToAll?: boolean;+};++type RuleSurfaces = Database["public"]["Enums"]["enforcementRuleSurface"][];++export type EnforcementRuleInsert = RuleItemFilterFields &+ RuleTargetFields & {+ name: string;+ description?: string | null;+ message: string;+ severity: Severity;+ conditionAst: ConditionAst;+ surfaces: RuleSurfaces;+ active: boolean;+ createdBy: string;+ customFields?: Json;+ };++export type EnforcementRuleUpdate = RuleItemFilterFields &+ RuleTargetFields & {+ id: string;+ name: string;+ description?: string | null;+ message: string;+ severity: Severity;+ conditionAst: ConditionAst;+ surfaces: RuleSurfaces;+ active: boolean;+ updatedBy: string;+ customFields?: Json;+ };++export async function getEnforcementRules(+ client: SupabaseClient<Database>,+ family: EnforcementRuleFamily,+ companyId: string,+ args?: GenericQueryFilters & {+ search: string | null;+ targetType?:+ | Database["public"]["Enums"]["enforcementRuleTargetType"]+ | null;+ }+): Promise<PostgrestResponse<EnforcementRuleRow>> {+ let query = client+ .from("enforcementRule")+ .select("*", { count: "exact" })+ .eq("companyId", companyId)+ .eq("family", family);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }+ if (args?.targetType) {+ query = query.eq("targetType", args.targetType);+ }++ // The `family` argument is a union rather than a literal, which is enough to+ // drop PostgREST's inferred row type to `any`; state it once here so every+ // caller gets a real row instead of re-annotating at each call site.+ return setGenericQueryFilters(query, args ?? {}, [+ { column: "name", ascending: true }+ ]) as unknown as Promise<PostgrestResponse<EnforcementRuleRow>>;+}++export async function getEnforcementRule(+ client: SupabaseClient<Database>,+ family: EnforcementRuleFamily,+ id: string,+ companyId: string+): Promise<PostgrestSingleResponse<EnforcementRuleRow>> {+ return (+ client+ .from("enforcementRule")+ .select("*")+ .eq("id", id)+ .eq("family", family)+ // RLS scopes the user client already; the explicit predicate is+ // defense-in-depth for service-role callers (these functions are+ // MCP-exposed).+ .eq("companyId", companyId)+ // Same union-family `any` collapse as `getEnforcementRules` above.+ .single() as unknown as Promise<+ PostgrestSingleResponse<EnforcementRuleRow>+ >+ );+}++export async function upsertEnforcementRule(+ client: SupabaseClient<Database>,+ family: EnforcementRuleFamily,+ companyId: string,+ rule: EnforcementRuleInsert | EnforcementRuleUpdate+) {+ if ("createdBy" in rule) {+ return client+ .from("enforcementRule")+ .insert({+ ...rule,+ companyId,+ family,+ conditionAst: rule.conditionAst as unknown as Json+ })+ .select("id")+ .single();+ }+ return client+ .from("enforcementRule")+ .update({+ ...sanitize(rule),+ conditionAst: rule.conditionAst as unknown as Json,+ updatedAt: datetime.timestamp()+ })+ .eq("id", rule.id)+ .eq("family", family)+ .eq("companyId", companyId)+ .select("id")+ .single();+}++export async function deleteEnforcementRule(+ client: SupabaseClient<Database>,+ family: EnforcementRuleFamily,+ id: string,+ companyId: string+) {+ return client+ .from("enforcementRule")+ .delete()+ .eq("id", id)+ .eq("family", family)+ .eq("companyId", companyId);+}++/**+ * Pin counts per rule id. Rule ids are globally unique, so counting by id needs+ * no family predicate even though the item table is shared between families.+ * Work-center pins only exist for the storage family; passing sales ids simply+ * matches nothing there.+ */+export async function getEnforcementRuleAssignmentCounts(+ client: SupabaseClient<Database>,+ ruleIds: string[]+) {+ if (ruleIds.length === 0) return { data: {}, error: null };++ const tables = [+ "enforcementRuleItemAssignment",+ "enforcementRuleWorkCenterAssignment"+ ] as const;++ const results = await Promise.all(+ tables.map((table) =>+ client.from(table).select("ruleId").in("ruleId", ruleIds)+ )+ );++ const counts: Record<string, number> = {};+ 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/storage-rules/index.ts b/apps/erp/app/modules/storage-rules/index.tsdeleted file mode 100644index c260292031..0000000000--- a/apps/erp/app/modules/storage-rules/index.ts+++ /dev/null@@ -1,13 +0,0 @@-// ERP-side Storage Rules module. Re-exports cross-app queries from the-// `@carbon/ee/storage-rules` package alongside ERP-only admin CRUD + form-// validators.--export {- assignStorageRule,- getActiveRulesForTargets,- getRuleAssignmentsForTarget,- getStorageRulesList,- unassignStorageRule-} from "@carbon/ee/storage-rules";-export * from "./storage-rules.models";-export * from "./storage-rules.service";diff --git a/apps/erp/app/modules/storage-rules/storage-rules.models.ts b/apps/erp/app/modules/storage-rules/storage-rules.models.tsdeleted file mode 100644index 5f73a032d7..0000000000--- a/apps/erp/app/modules/storage-rules/storage-rules.models.ts+++ /dev/null@@ -1,125 +0,0 @@-import type { Operator } from "@carbon/utils";-import {- getFieldDef,- isFieldAvailableOnSurfaces,- SURFACES_BY_TARGET_TYPE,- TARGET_TYPES,- TRANSACTION_SURFACES-} from "@carbon/utils";-import { z } from "zod";-import { zfd } from "zod-form-data";--export const storageRuleSeverities = ["error", "warn"] as const;--/** The subset of the shared `Operator` union storage rules accept on the wire. */-export const storageRuleOperators = [- "eq",- "neq",- "in",- "notIn",- "isSet",- "isNotSet",- "gt",- "lt"-] as const satisfies readonly Operator[];--const storageRuleConditionValueSchema = z.union([- z.string(),- z.number(),- z.boolean(),- z.array(z.union([z.string(), z.number(), z.boolean()])),- z.null()-]);--const storageRuleConditionSchema = z.object({- field: z.string().min(1, { message: "Field is required" }),- op: z.enum(storageRuleOperators),- value: storageRuleConditionValueSchema.optional()-});--export const storageRuleMatchKinds = ["all", "any", "none"] as const;--export const storageRuleConditionAstSchema = z.object({- kind: z.enum(storageRuleMatchKinds),- conditions: z- .array(storageRuleConditionSchema)- .min(1, { message: "At least one condition is required" })-});--const storageRuleConditionAstFormField = z.preprocess((raw) => {- if (typeof raw !== "string") return raw;- try {- return JSON.parse(raw);- } catch {- return raw;- }-}, storageRuleConditionAstSchema);--export const storageRuleValidator = z- .object({- id: zfd.text(z.string().optional()),- name: z.string().trim().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(storageRuleSeverities),- targetType: z.enum(TARGET_TYPES),- // Broadcast gate for workCenter rules. Item rules ignore this and use the- // filteredItem* fields instead (empty = all items).- appliesToAll: zfd.checkbox(),- filteredItemTypes: zfd.repeatableOfType(z.string()).optional(),- filteredItemGroupIds: zfd.repeatableOfType(z.string()).optional(),- filteredItemMatchAll: zfd.checkbox(),- active: zfd.checkbox(),- surfaces: zfd- .repeatableOfType(z.enum(TRANSACTION_SURFACES))- .refine((arr) => arr.length >= 1, {- message: "Pick at least one surface"- }),- conditionAst: storageRuleConditionAstFormField- })- .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`- });- }- }-- // Reject conditions on a registry field whose context the evaluator won't- // populate for every selected surface (else it resolves undefined → false- // "X is required"). Unknown paths are left to runtime presence handling.- val.conditionAst.conditions.forEach((c, i) => {- const def = getFieldDef(c.field);- if (def && !isFieldAvailableOnSurfaces(def, val.surfaces)) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["conditionAst", "conditions", i, "field"],- message: `"${def.label}" isn't available on the selected surface(s)`- });- }- });- });--/**- * 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 storageRuleAssignmentValidator = (- targetType: "item" | "workCenter"-) => {- const idKey = targetType === "item" ? "itemId" : "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 storageRuleAcknowledgeValidator = zfd.checkbox();diff --git a/apps/erp/app/modules/storage-rules/storage-rules.service.ts b/apps/erp/app/modules/storage-rules/storage-rules.service.tsdeleted file mode 100644index d94e7309c4..0000000000--- a/apps/erp/app/modules/storage-rules/storage-rules.service.ts+++ /dev/null@@ -1,145 +0,0 @@-// ERP-only admin CRUD for the Inventory → Storage Rules page.-// Cross-app queries (assignment loaders, list fetch for tab data, polymorphic-// assign/unassign) live in `@carbon/ee/storage-rules`.--import type { Database, Json } from "@carbon/database";-import type {- ConditionAst,- Severity,- TargetType,- TransactionSurface-} from "@carbon/utils";-import { datetime } from "@carbon/utils";-import type { SupabaseClient } from "@supabase/supabase-js";-import type { GenericQueryFilters } from "~/utils/query";-import { setGenericQueryFilters } from "~/utils/query";-import { sanitize } from "~/utils/supabase";--type StorageRuleFilters = {- appliesToAll: boolean;- filteredItemTypes?: string[];- filteredItemGroupIds?: string[];- filteredItemMatchAll?: boolean;-};--type StorageRuleInsert = StorageRuleFilters & {- name: string;- description?: string | null;- message: string;- severity: Severity;- conditionAst: ConditionAst;- surfaces: TransactionSurface[];- targetType: TargetType;- active: boolean;- companyId: string;- createdBy: string;- customFields?: Json;-};--type StorageRuleUpdate = StorageRuleFilters & {- id: string;- name: string;- description?: string | null;- message: string;- severity: Severity;- conditionAst: ConditionAst;- surfaces: TransactionSurface[];- active: boolean;- updatedBy: string;- customFields?: Json;-};--export async function getStorageRules(- client: SupabaseClient<Database>,- companyId: string,- args?: GenericQueryFilters & {- search: string | null;- targetType?: TargetType | null;- }-) {- let query = client- .from("storageRule")- .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 getStorageRule(- client: SupabaseClient<Database>,- id: string-) {- return client.from("storageRule").select("*").eq("id", id).single();-}--export async function upsertStorageRule(- client: SupabaseClient<Database>,- rule: StorageRuleInsert | StorageRuleUpdate-) {- if ("createdBy" in rule) {- return client- .from("storageRule")- .insert({ ...rule, conditionAst: rule.conditionAst as unknown as Json })- .select("id")- .single();- }- return client- .from("storageRule")- .update({- ...sanitize(rule),- conditionAst: rule.conditionAst as unknown as Json,- updatedAt: datetime.timestamp()- })- .eq("id", rule.id)- .select("id")- .single();-}--export async function deleteStorageRule(- client: SupabaseClient<Database>,- id: string-) {- return client.from("storageRule").delete().eq("id", id);-}--export async function getRuleAssignmentCounts(- client: SupabaseClient<Database>,- ruleIds: string[]-) {- // Counts span both 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<- "storageRuleItemAssignment" | "storageRuleWorkCenterAssignment"- > = ["storageRuleItemAssignment", "storageRuleWorkCenterAssignment"];-- 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/workflows/ui/Builder/config/ClauseRow.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsxindex d3384c3d80..cd68ecb7ad 100644--- a/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx+++ b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx@@ -6,7 +6,7 @@ import { useLingui } from "@lingui/react/macro";import type React from "react";import { memo, useEffect, useMemo } from "react";import { LuX } from "react-icons/lu";-import OperatorCombobox from "~/modules/storage-rules/ui/OperatorCombobox";+import OperatorCombobox from "~/modules/inventory/ui/StorageRules/OperatorCombobox";import {propertyLabelKey,useWorkflowCatalog,diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex 68316b22d0..a372f255e8 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -60,6 +60,16 @@ function resolve(case NotificationEvent.SalesRfqAssignment:case NotificationEvent.SalesRfqReady:return path.to.salesRfq(documentId);+ case NotificationEvent.SalesRuleViolation: {+ // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"+ const [docType, docId] = documentId.split(":");+ if (!docId) return null;+ return docType === "salesInvoice"+ ? path.to.salesInvoice(docId)+ : docType === "salesOrder"+ ? path.to.salesOrder(docId)+ : path.to.quote(docId);+ }case NotificationEvent.MaintenanceDispatchAssignment:case NotificationEvent.MaintenanceDispatchCreated:return path.to.maintenanceDispatch(documentId);diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.tsindex ab21bde7b7..43fdc9a7a1 100644--- a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts@@ -26,6 +26,12 @@ export const MCP_BLOCKED_TOOL_NAMES: readonly string[] = [// before calling it). `production_scheduleJob` is the intended MCP entry point —// it re-applies that gate — so the raw trigger must not be reachable via MCP."production_triggerJobSchedule",+ // Bulk sales-order line insert. It has no in-app caller — it is reachable+ // only through this executor, which exposes every named export of+ // sales.service.ts. It writes lines without the sales-rule evaluation the+ // route action performs, and unlike `upsertSalesOrderLine` there is no+ // single-line path to gate.+ "sales_insertSalesOrderLines",// Unreachable by construction: these tables carry USER-scoped RLS// (`"createdBy"::uuid = auth.uid()`, migration 20260228000000_rls-refactor-3.sql),// but an API key authenticates by header rather than a Supabase JWT, sodiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex ff21ca5ace..1b49101fb4 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1572,+ "totalTools": 1577,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},@@ -205,7 +205,7 @@{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"eabbf12414ff","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"95e8492e812f","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"07d244c0f017","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},@@ -298,7 +298,7 @@{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"eabbf12414ff","injectAuth":"companyId","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"95e8492e812f","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},@@ -401,7 +401,7 @@{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"eabbf12414ff","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"95e8492e812f","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -780,13 +780,13 @@{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"eabbf12414ff","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"95e8492e812f","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"eabbf12414ff","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"e76f5b90d591","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"eabbf12414ff","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"95e8492e812f","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"d66b033b984d","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"95e8492e812f","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},@@ -1333,7 +1333,6 @@{"name":"sales_insertCustomerLocation","classification":"WRITE","paramCount":4,"schema":"c30fcaea26e0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertQuote","classification":"WRITE","paramCount":16,"schema":"a6c40455c9f1","response":"9e29b49e1dc8","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertSalesOrder","classification":"WRITE","paramCount":17,"schema":"b76b79d52d88","response":"dbfc22813350","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesOrderLines","classification":"WRITE","paramCount":1,"schema":"1262a5b246c0","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertSalesReturnOrder","classification":"WRITE","paramCount":12,"schema":"307356313ba5","response":"c32485518acd","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertSalesRFQ","classification":"WRITE","paramCount":13,"schema":"5a54a12e500f","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"6db20595d1b7","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},@@ -1408,7 +1407,7 @@{"name":"settings_getCompany","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8abc93835023","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCompanyIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a98b34db51d","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCompanyPlan","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"9e95c96c5750","injectAuth":"companyId","permission":"settings:view","paginates":false},+ {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d4be152e819f","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getConfig","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"aa1021ff34cf","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCurrentSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCustomField","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a533a796c094","injectAuth":"companyId","permission":"settings:view","paginates":false},@@ -1418,7 +1417,7 @@{"name":"settings_getDocumentSections","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getDocumentSectionsByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getDocumentTemplate","classification":"READ","paramCount":1,"schema":"aeac292b00cb","response":"99cae633d7cb","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentTemplateConfig","classification":"READ","paramCount":1,"schema":"aeac292b00cb","response":"cd13b17cccd0","injectAuth":"companyId","permission":"settings:view","paginates":false},+ {"name":"settings_getDocumentTemplateConfig","classification":"READ","paramCount":1,"schema":"aeac292b00cb","response":"3adb0f240f97","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getEmployeeCompanies","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a521b8a3bee8","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getIndustries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5dcce0f224dd","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getIntegration","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"099545249106","injectAuth":"companyId","permission":"settings:view","paginates":false},@@ -1477,6 +1476,7 @@{"name":"settings_updateRequireMfaSetting","classification":"WRITE","paramCount":1,"schema":"1a5429a80ff2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateRfqReadySetting","classification":"WRITE","paramCount":1,"schema":"8828dbf1724d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},+ {"name":"settings_updateSalesRuleNotificationSetting","classification":"WRITE","paramCount":1,"schema":"fcb0888da832","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateSequence","classification":"WRITE","paramCount":2,"schema":"c28f12fe484d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateShelfLifeSettings","classification":"WRITE","paramCount":4,"schema":"a6f593fa5702","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},{"name":"settings_updateShowCurrencyTrailingZerosSetting","classification":"WRITE","paramCount":1,"schema":"42d586011b23","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},@@ -1500,6 +1500,7 @@{"name":"shared_createApprovalRequest","classification":"WRITE","paramCount":1,"schema":"e6294fee6965","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_deleteApprovalRule","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_deleteCustomerPortal","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_deleteEnforcementRule","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa9ceafd871f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","paramCount":1,"schema":"1fbe3d41dab0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_generateEmbedding","classification":"WRITE","paramCount":1,"schema":"e3dce8d1afb8","response":"569f4d6b0385","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_getApprovalById","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4ed114babb27","injectAuth":"companyId","permission":"none","paginates":false},@@ -1514,6 +1515,9 @@{"name":"shared_getCountries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0e8a11b4e81c","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getCustomerPortal","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getCustomerPortals","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"fbffc4ca5fac","injectAuth":"companyId","permission":"none","paginates":true},+ {"name":"shared_getEnforcementRule","classification":"READ","paramCount":2,"schema":"fa9ceafd871f","response":"55286a46f24b","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","paramCount":1,"schema":"47af2b550d52","response":"ab5d5774b961","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRules","classification":"READ","paramCount":2,"schema":"fa46224dbc18","response":"a58a59f02a18","injectAuth":"companyId","permission":"none","paginates":true},{"name":"shared_getExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0f7860db4299","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getLatestApprovalRequestForDocument","classification":"READ","paramCount":2,"schema":"943dca4ef0da","response":"a46647e8d6f1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_getLowerTierApproverUserIds","classification":"READ","paramCount":2,"schema":"63a69fed1f5d","response":"681004346c78","injectAuth":"companyId","permission":"none","paginates":false},@@ -1537,6 +1541,7 @@{"name":"shared_updateModelThumbnail","classification":"WRITE","paramCount":2,"schema":"7d1e1e5f7144","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},{"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},{"name":"shared_upsertApprovalRule","classification":"WRITE","paramCount":1,"schema":"833ecfb8d78b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},+ {"name":"shared_upsertEnforcementRule","classification":"WRITE","paramCount":2,"schema":"ec92de61cff6","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_upsertModelUpload","classification":"WRITE","paramCount":1,"schema":"b024a13e3afd","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},{"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsxindex 21f1e46f78..7a11342529 100644--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx@@ -1,5 +1,9 @@import { assertIsPost, notFound } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ dedupeViolations,+ evaluateSalesRulesForSalesDocument+} from "@carbon/ee/rules.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";@@ -10,6 +14,7 @@ import {getSalesOrder,selectedLinesValidator} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import { getCompanySettings } from "~/modules/settings";import { generateAndAttachSalesOrderPdf } from "~/modules/shared/shared.server";import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";@@ -88,6 +93,67 @@ export async function action(args: ActionFunctionArgs) {purchaseOrderNumber = file.name.replace(/\.pdf$/i, "");}+ // Terminal gate on the customer-facing accept. This endpoint is+ // unauthenticated — the share link is the only credential — so it is+ // HARD-BLOCK-ONLY: there is no employee here, nobody who may legitimately+ // acknowledge a warning, and internal compliance text must never reach+ // the customer. Errors refuse with a neutral message; warnings are logged+ // for the seller and the order proceeds.+ const { violations: salesRuleViolations, ruleNames: salesRuleNames } =+ await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId: quote.data.companyId,+ userId: quote.data.createdBy,+ documentType: "quote",+ documentId: quote.data.id+ });+ // Only the lines the customer selected convert — a deselected line's+ // violations must not block the acceptance.+ const acceptedLineIds = new Set(+ Object.entries(selectedLines)+ .filter(([, line]) => (line.quantity ?? 0) > 0)+ .map(([lineId]) => lineId)+ );+ const dedupedSalesRuleViolations = dedupeViolations(+ salesRuleViolations+ ).filter((v) => !v.lineId || acceptedLineIds.has(v.lineId));+ const blockingViolations = dedupedSalesRuleViolations.filter(+ (v) => v.severity === "error"+ );++ if (blockingViolations.length > 0) {+ logger.error("Digital quote acceptance blocked by sales rules", {+ quoteId: quote.data.id,+ companyId: quote.data.companyId,+ violations: blockingViolations+ });+ // The customer is told to contact their rep — the rep needs the+ // signal: write the same evidence + notification every internal gate+ // writes, attributed to the quote's owner (there is no session user).+ await recordSalesRuleOutcome(serviceRole, {+ companyId: quote.data.companyId,+ userId: quote.data.createdBy,+ documentType: "quote",+ documentId: quote.data.id,+ outcome: "blocked",+ violations: blockingViolations,+ ruleNames: salesRuleNames+ });+ return {+ success: false,+ message:+ "This quote can no longer be accepted online. Please contact your sales representative."+ };+ }++ if (dedupedSalesRuleViolations.length > 0) {+ logger.warn("Digital quote accepted with sales rule warnings", {+ quoteId: quote.data.id,+ companyId: quote.data.companyId,+ violations: dedupedSalesRuleViolations+ });+ }+const [convert] = await Promise.all([convertQuoteToOrder(serviceRole, {id: quote.data.id,diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.tsindex 9bfe33faff..156db029e9 100644--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts@@ -68,6 +68,13 @@ vi.mock("~/modules/sales/sales.service", () => ({insertSalesOrder: spies.insertSalesOrder}));vi.mock("~/modules/settings/settings.service", () => ({}));+// The sales-rule gate imports `~/modules/sales/sales.server` and+// `@carbon/ee/rules.server` — both server-only graphs (glossary/lingui, env+// validation at import). Dispatch behavior under a gate block is not what+// these golden tests pin, so stub it as "no block".+vi.mock("./sales-rules-gate.server", () => ({+ checkSalesRulesForOperation: vi.fn(async () => null)+}));vi.mock("~/modules/shared/shared.service", () => ({}));vi.mock("~/modules/users/users.service", () => ({}));vi.mock("~/services/database.server", () => ({diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.tsindex 31a60b88a6..6fbab6d374 100644--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts@@ -12,6 +12,7 @@ import { ORPCError } from "@orpc/server";import { getDatabaseClient } from "~/services/database.server";import type { AuthedContext } from "./base.server";import { functionRegistry } from "./registry.server";+import { checkSalesRulesForOperation } from "./sales-rules-gate.server";export interface DispatchResult {data: unknown;@@ -330,6 +331,19 @@ export async function dispatchOperation(// else: optional param with nothing to fill — skip.}+ // Sales-rule gate — evaluates the RESOLVED payload for the gated sales+ // operations (line writes + finalize/convert transitions) and refuses on+ // error-severity violations, mirroring the route actions. Covers every+ // dispatch caller: HTTP v1, MCP, the in-app agent, and workflows.+ const salesRuleBlock = await checkSalesRulesForOperation(+ meta,+ context,+ functionArgs+ );+ if (salesRuleBlock) {+ throw new ORPCError("FORBIDDEN", { message: salesRuleBlock });+ }+let result = await (func as (...args: any[]) => any)(...functionArgs);// Supabase query builders are thenable but not yet executed.if (diff --git a/apps/erp/app/routes/api+/v1+/lib/sales-rules-gate.server.ts b/apps/erp/app/routes/api+/v1+/lib/sales-rules-gate.server.tsnew file mode 100644index 0000000000..b5d44f6fbe--- /dev/null+++ b/apps/erp/app/routes/api+/v1+/lib/sales-rules-gate.server.ts@@ -0,0 +1,370 @@+// Sales-rule gate for the operation dispatch path.+//+// The route actions that write sales-document lines (and the terminal+// finalize/convert transitions) evaluate sales rules before acting. The+// dispatch path calls the same service functions by name — HTTP v1, MCP+// call_tool, the in-app agent, and the workflow dispatcher all pass through+// `dispatchOperation` — so without this gate any of those callers could put a+// restricted item on a sales document, or finalize/convert one carrying+// error-severity violations, with no evaluation at all.+//+// The check lives HERE rather than inside the service functions deliberately:+// service files are re-exported from module barrels that client components+// import, so they must stay free of server-only imports. This module is+// server-only by construction.+//+// Only `error`-severity violations block. A `warn` needs a human to+// acknowledge it, and there is no human on this path — warns pass so an agent+// isn't wedged on a rule a person could have waved past. Blocks record the+// same acknowledgment evidence the human routes write; passed warns leave no+// row on purpose ("acknowledged" means a person waved them past, and none+// did).+//+// The gate reads the RESOLVED positional payload out of `functionArgs` — the+// exact object the service will receive, after `dispatchOperation`'s named /+// wrapped / flat shape resolution — so a nested request cannot skip+// evaluation and still reach the service.++import type { ManifestEntry } from "@carbon/api";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ dedupeViolations,+ evaluateSalesRuleLines,+ evaluateSalesRulesForSalesDocument,+ resolveSalesOrderShipTo,+ type SalesDocumentType+} from "@carbon/ee/rules.server";+import { breakQuantities } from "@carbon/utils";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";++type GateContext = { companyId: string; userId: string };++const LINE_WRITE_OPERATIONS: Record<+ string,+ {+ surface: "quoteLine" | "salesOrderLine" | "salesInvoiceLine";+ param: string;+ documentKey: string;+ documentType: "quote" | "salesOrder" | "salesInvoice";+ }+> = {+ sales_upsertQuoteLine: {+ surface: "quoteLine",+ param: "quotationLine",+ documentKey: "quoteId",+ documentType: "quote"+ },+ sales_upsertSalesOrderLine: {+ surface: "salesOrderLine",+ param: "salesOrderLine",+ documentKey: "salesOrderId",+ documentType: "salesOrder"+ },+ invoicing_upsertSalesInvoiceLine: {+ surface: "salesInvoiceLine",+ param: "salesInvoiceLine",+ documentKey: "invoiceId",+ documentType: "salesInvoice"+ }+};++/** The resolved positional value for `paramName`, as the service will receive it. */+function resolvedParam(+ meta: ManifestEntry,+ functionArgs: unknown[],+ paramName: string+): unknown {+ const index = meta.serviceParams.indexOf(paramName);+ return index >= 0 ? functionArgs[index] : undefined;+}++/**+ * Evaluate sales rules for a gated operation. Returns the block message when+ * error-severity violations fire, null when the operation may proceed.+ * Non-gated operations return null without touching the database.+ */+export async function checkSalesRulesForOperation(+ meta: ManifestEntry,+ context: GateContext,+ functionArgs: unknown[]+): Promise<string | null> {+ return (+ (await checkLineWrite(meta, context, functionArgs)) ??+ (await checkDocumentTransition(meta, context, functionArgs))+ );+}++async function checkLineWrite(+ meta: ManifestEntry,+ context: GateContext,+ functionArgs: unknown[]+): Promise<string | null> {+ const op = LINE_WRITE_OPERATIONS[meta.name];+ if (!op) return null;++ const resolved = resolvedParam(meta, functionArgs, op.param);+ if (!resolved || typeof resolved !== "object" || Array.isArray(resolved)) {+ return null;+ }+ const payload = resolved as Record<string, unknown>;++ const itemId = typeof payload.itemId === "string" ? payload.itemId : null;+ if (!itemId) return null;++ const documentId =+ typeof payload[op.documentKey] === "string"+ ? (payload[op.documentKey] as string)+ : null;+ if (!documentId) return null;++ const serviceRole = getCarbonServiceRole();+ const lineId = typeof payload.id === "string" ? payload.id : "new";++ const shipTo =+ op.surface === "salesOrderLine"+ ? await resolveSalesOrderShipTo(+ serviceRole,+ documentId,+ context.companyId+ )+ : op.surface === "salesInvoiceLine"+ ? await (async () => {+ // An invoice line converted from a sales order resolves its+ // ship-to through that order; a standalone line has none and+ // none may be invented (the bill-to is a different address), so+ // a null location lets a destination rule fail closed via the+ // engine's required-field semantics.+ if (lineId !== "new") {+ const existing = await serviceRole+ .from("salesInvoiceLine")+ .select("salesOrderId")+ .eq("id", lineId)+ .eq("companyId", context.companyId)+ .maybeSingle();+ if (existing.data?.salesOrderId) {+ return resolveSalesOrderShipTo(+ serviceRole,+ existing.data.salesOrderId,+ context.companyId+ );+ }+ }+ const { data } = await serviceRole+ .from("salesInvoice")+ .select("customerId")+ .eq("id", documentId)+ .eq("companyId", context.companyId)+ .maybeSingle();+ return {+ customerId: data?.customerId ?? null,+ customerLocationId: null+ };+ })()+ : await (async () => {+ const { data } = await serviceRole+ .from("quote")+ .select("customerId, customerLocationId")+ .eq("id", documentId)+ .eq("companyId", context.companyId)+ .maybeSingle();+ return {+ customerId: data?.customerId ?? null,+ customerLocationId: data?.customerLocationId ?? null+ };+ })();++ // A quote line carries a break array — evaluate every break (min-quantity+ // rules fire on the smallest, max-quantity on the largest); the other+ // surfaces carry one scalar quantity.+ const quantities =+ typeof payload.saleQuantity === "number"+ ? [payload.saleQuantity]+ : Array.isArray(payload.quantity)+ ? breakQuantities(payload.quantity as number[])+ : typeof payload.quantity === "number"+ ? [payload.quantity]+ : [1];++ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId: context.companyId,+ userId: context.userId,+ surface: op.surface,+ lines: quantities.map((quantity) => ({ lineId, itemId, quantity })),+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });++ const errors = dedupeViolations(violations).filter(+ (v) => v.severity === "error"+ );+ if (errors.length === 0) return null;++ await recordSalesRuleOutcome(serviceRole, {+ companyId: context.companyId,+ userId: context.userId,+ documentType: op.documentType,+ documentId,+ documentLineId: lineId === "new" ? null : lineId,+ itemId,+ outcome: "blocked",+ violations: errors,+ ruleNames+ });++ return `Blocked by sales rules: ${errors.map((v) => v.message).join("; ")}`;+}++// Statuses that do NOT advance a document past its human gates. Everything+// else — including enum values added later — is treated as advancing, so a new+// status fails closed into evaluation rather than slipping past it.+const NON_ADVANCING_QUOTE_STATUSES = new Set([+ "Draft",+ "Lost",+ "Cancelled",+ "Expired"+]);+const NON_ADVANCING_SALES_ORDER_STATUSES = new Set([+ "Draft",+ "Needs Approval",+ "Cancelled",+ "Closed"+]);++/**+ * Ops that can move a document's `status` past the confirm/finalize gates+ * without going through them: the direct status setters, the generic updates+ * (whose payload may carry `status`), and the deprecated upserts. The gate+ * evaluates only when the payload actually carries an ADVANCING status for an+ * EXISTING document (a create has no lines yet, so there is nothing to+ * evaluate).+ */+const STATUS_WRITE_OPERATIONS: Record<+ string,+ {+ documentType: "quote" | "salesOrder";+ param: string;+ nonAdvancing: Set<string>;+ }+> = {+ sales_updateQuote: {+ documentType: "quote",+ param: "input",+ nonAdvancing: NON_ADVANCING_QUOTE_STATUSES+ },+ sales_updateQuoteStatus: {+ documentType: "quote",+ param: "update",+ nonAdvancing: NON_ADVANCING_QUOTE_STATUSES+ },+ sales_upsertQuote: {+ documentType: "quote",+ param: "quote",+ nonAdvancing: NON_ADVANCING_QUOTE_STATUSES+ },+ sales_updateSalesOrder: {+ documentType: "salesOrder",+ param: "input",+ nonAdvancing: NON_ADVANCING_SALES_ORDER_STATUSES+ },+ sales_updateSalesOrderStatus: {+ documentType: "salesOrder",+ param: "update",+ nonAdvancing: NON_ADVANCING_SALES_ORDER_STATUSES+ },+ sales_upsertSalesOrder: {+ documentType: "salesOrder",+ param: "salesOrder",+ nonAdvancing: NON_ADVANCING_SALES_ORDER_STATUSES+ }+};++function statusTransitionTarget(+ meta: ManifestEntry,+ functionArgs: unknown[]+): { documentType: SalesDocumentType; documentId: string } | null {+ // `releaseSalesOrder` hardcodes its advancing status and takes a scalar id.+ if (meta.name === "sales_releaseSalesOrder") {+ const id = resolvedParam(meta, functionArgs, "salesOrderId");+ return typeof id === "string"+ ? { documentType: "salesOrder", documentId: id }+ : null;+ }++ const op = STATUS_WRITE_OPERATIONS[meta.name];+ if (!op) return null;+ const resolved = resolvedParam(meta, functionArgs, op.param);+ if (!resolved || typeof resolved !== "object" || Array.isArray(resolved)) {+ return null;+ }+ const payload = resolved as Record<string, unknown>;+ const documentId = typeof payload.id === "string" ? payload.id : null;+ const status = typeof payload.status === "string" ? payload.status : null;+ if (!documentId || !status || op.nonAdvancing.has(status)) return null;+ return { documentType: op.documentType, documentId };+}++async function checkDocumentTransition(+ meta: ManifestEntry,+ context: GateContext,+ functionArgs: unknown[]+): Promise<string | null> {+ let documentType: SalesDocumentType | null =+ meta.name === "sales_finalizeQuote" ||+ meta.name === "sales_convertQuoteToOrder"+ ? "quote"+ : meta.name === "sales_convertSalesRfqToQuote"+ ? "salesRfq"+ : null;++ // `finalizeQuote` addresses the quote by a scalar `quoteId` param; the two+ // convert functions take a `payload` object whose document id is `id`.+ const scalarId = resolvedParam(meta, functionArgs, "quoteId");+ const payload = resolvedParam(meta, functionArgs, "payload");+ let documentId =+ typeof scalarId === "string"+ ? scalarId+ : payload && typeof payload === "object" && !Array.isArray(payload)+ ? typeof (payload as Record<string, unknown>).id === "string"+ ? ((payload as Record<string, unknown>).id as string)+ : null+ : null;++ if (!documentType || !documentId) {+ const statusTarget = statusTransitionTarget(meta, functionArgs);+ if (!statusTarget) return null;+ documentType = statusTarget.documentType;+ documentId = statusTarget.documentId;+ }++ const serviceRole = getCarbonServiceRole();+ const { violations, ruleNames } = await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId: context.companyId,+ userId: context.userId,+ documentType,+ documentId+ });++ const errors = dedupeViolations(violations).filter(+ (v) => v.severity === "error"+ );+ if (errors.length === 0) return null;++ // Blocked evidence, same as the route gates. An RFQ has no evidence row+ // (the acknowledgment table's documentType CHECK covers quote / salesOrder /+ // salesInvoice only); its lines are re-gated at the quote stage.+ if (documentType === "quote" || documentType === "salesOrder") {+ await recordSalesRuleOutcome(serviceRole, {+ companyId: context.companyId,+ userId: context.userId,+ documentType,+ documentId,+ outcome: "blocked",+ violations: errors,+ ruleNames+ });+ }++ return `Blocked by sales rules: ${errors.map((v) => v.message).join("; ")}`;+}diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsxindex d6b56d6a7a..dbf9b6509f 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx@@ -1,7 +1,11 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";+import {+ getSalesRuleAssignmentsForItem,+ getSalesRulesList+} from "@carbon/ee/rules";+import { getStorageRulesDataForTarget } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -13,6 +17,7 @@ import {getTrackedEntityExpirations,InventoryDetails} from "~/modules/inventory";+import RuleAssignmentsList from "~/modules/inventory/ui/StorageRules/RuleAssignmentsList";import type { Consumable, UnitOfMeasureListItem } from "~/modules/items";import {getBomHasShelfLifeManagedInput,@@ -27,7 +32,7 @@ import {} from "~/modules/items";import { PickMethodForm } from "~/modules/items/ui/Item";import { getLocationsList } from "~/modules/resources";-import RuleAssignmentsList from "~/modules/storage-rules/ui/RuleAssignmentsList";+import { SalesRuleAssignmentsList } from "~/modules/sales/ui/SalesRules";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";import { useItems } from "~/stores/items";@@ -160,7 +165,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shelfLife,bomHasShelfLifeManagedInput,trackedEntityExpirations,- rulesData+ rulesData,+ salesRuleAssignments,+ salesRuleLibrary] = await Promise.all([getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),@@ -169,7 +176,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {targetType: "item",targetId: itemId,companyId- })+ }),+ getSalesRuleAssignmentsForItem(client, { itemId, companyId }),+ getSalesRulesList(client, companyId)]);return {@@ -182,7 +191,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemId,locationId,ruleAssignments: rulesData.assignments,- ruleLibrary: rulesData.library+ ruleLibrary: rulesData.library,+ salesRuleAssignments: salesRuleAssignments.data ?? [],+ salesRuleLibrary: salesRuleLibrary.data ?? []};}@@ -257,7 +268,9 @@ export default function ConsumableInventoryRoute() {trackedEntityExpirations,itemId,ruleAssignments,- ruleLibrary+ ruleLibrary,+ salesRuleAssignments,+ salesRuleLibrary} = useLoaderData<typeof loader>();const consumableData = useRouteData<{@@ -315,6 +328,11 @@ export default function ConsumableInventoryRoute() {assignments={ruleAssignments as never}library={ruleLibrary as never}/>+ <SalesRuleAssignmentsList+ itemId={itemId}+ assignments={salesRuleAssignments as never}+ library={salesRuleLibrary as never}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsxindex e18bbf9e23..f75660149c 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx@@ -5,7 +5,7 @@ import {dedupeViolations,evaluateLinesForSurface,isBlocked-} from "@carbon/ee/storage-rules.server";+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -38,7 +38,7 @@ export async function action({ request, params }: ActionFunctionArgs) {validation.data;const acknowledged = formData.get("acknowledged") === "true";- // Business rule evaluation. Item rules fire on the `inventoryAdjustment`+ // Business rule evaluation. Storage rules fire on the `inventoryAdjustment`// surface, and on `place` when the adjustment lands stock in a bin (positive// delta) or `pick` when it removes from a bin (negative delta) — so bin-level// rules tied to those surfaces also kick in for manual adjustments.@@ -70,7 +70,7 @@ export async function action({ request, params }: ActionFunctionArgs) {// Pick the bin surface from `adjustmentType` only. `quantity` is a// positive magnitude per `inventoryAdjustmentValidator` — sign-based// direction detection would misclassify `Negative Adjmt.` as `place`.- // Item rules own the `place`/`pick` surfaces. Scrap removes from a bin+ // Storage rules own the `place`/`pick` surfaces. Scrap removes from a bin// (pick); Unscrap restores to a bin (place).const isNegative =d.adjustmentType === "Negative Adjmt." || d.adjustmentType === "Scrap";diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsxindex b632bb59ff..6a7ac84994 100644--- a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx@@ -2,22 +2,19 @@ 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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData, useNavigate } from "react-router";import { ConfirmDelete } from "~/components/Modals";-import { deleteStorageRule, getStorageRule } from "~/modules/storage-rules";+import { deleteEnforcementRule, getEnforcementRule } from "~/modules/shared";import { getParams, path } from "~/utils/path";-import { getCompanyId, storageRulesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, { delete: "inventory" });+ const { client, companyId } = await requirePermissions(request, {+ delete: "inventory"+ });const { id } = params;if (!id) throw notFound("id required");- const rule = await getStorageRule(client, id);+ const rule = await getEnforcementRule(client, "storage", id, companyId);if (rule.error || !rule.data) {throw redirect(path.to.storageRules,@@ -44,7 +41,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id } = params;if (!id) throw new Error("id required");- const result = await deleteStorageRule(client, id);+ const result = await deleteEnforcementRule(client, "storage", id, companyId);if (result.error) {throw redirect(`${path.to.storageRules}?${getParams(request)}`,@@ -58,22 +55,14 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(- storageRulesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteStorageRuleRoute() {const { rule } = useLoaderData<typeof loader>();- const { id } = (rule as { id: string }) ?? { id: "" };+ const id = rule?.id ?? "";const navigate = useNavigate();return (<ConfirmDeleteaction={path.to.deleteStorageRule(id)}- name={(rule as { name?: string })?.name ?? "this rule"}+ name={rule?.name ?? "this rule"}text="Are you sure you want to delete this rule? Assignments will also be removed."onCancel={() => navigate(path.to.storageRules)}/>diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsxindex 5886379438..99c3d554c0 100644--- a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx@@ -2,28 +2,22 @@ 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 { validationError, 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 {- getStorageRule,- storageRuleValidator,- upsertStorageRule-} from "~/modules/storage-rules";-import StorageRuleForm from "~/modules/storage-rules/ui/StorageRuleForm";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData, useNavigate } from "react-router";+import { storageRuleValidator } from "~/modules/inventory";+import StorageRuleForm from "~/modules/inventory/ui/StorageRules/StorageRuleForm";+import { getEnforcementRule, upsertEnforcementRule } from "~/modules/shared";import { getParams, path } from "~/utils/path";-import { getCompanyId, storageRulesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, { view: "inventory" });+ const { client, companyId } = await requirePermissions(request, {+ view: "inventory"+ });const { id } = params;if (!id) throw notFound("id required");- const rule = await getStorageRule(client, id);+ const rule = await getEnforcementRule(client, "storage", id, companyId);if (rule.error || !rule.data) throw notFound("Rule not found");return { rule: rule.data };}@@ -47,9 +41,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const formData = await request.formData();const validation = await validator(storageRuleValidator).validate(formData);- if (validation.error) return validation.error;+ if (validation.error) return validationError(validation.error);- const update = await upsertStorageRule(client, {+ const update = await upsertEnforcementRule(client, "storage", companyId, {...validation.data,id,description: validation.data.description ?? null,@@ -57,23 +51,15 @@ export async function action({ request, params }: ActionFunctionArgs) {});if (update.error) {- return await flash(- request,- error(update.error, "Failed to update rule")- ).then(() => null);+ return data(+ {},+ await flash(request, error(update.error, "Failed to update rule"))+ );}throw redirect(`${path.to.storageRules}?${getParams(request)}`);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(- storageRulesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditStorageRuleRoute() {const { rule } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsxindex 175b75fcf4..0c7830c3dd 100644--- a/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx@@ -2,21 +2,14 @@ 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 { validationError, 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 {- storageRuleValidator,- upsertStorageRule-} from "~/modules/storage-rules";-import StorageRuleForm from "~/modules/storage-rules/ui/StorageRuleForm";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData, useNavigate } from "react-router";+import { storageRuleValidator } from "~/modules/inventory";+import StorageRuleForm from "~/modules/inventory/ui/StorageRules/StorageRuleForm";+import { upsertEnforcementRule } from "~/modules/shared";import { getParams, path } from "~/utils/path";-import { getCompanyId, storageRulesQuery } from "~/utils/react-query";const isTargetType = (value: string | null): value is TargetType =>value === "item" || value === "workCenter";@@ -44,33 +37,24 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const validation = await validator(storageRuleValidator).validate(formData);- if (validation.error) return validation.error;+ if (validation.error) return validationError(validation.error);- const insert = await upsertStorageRule(client, {+ const insert = await upsertEnforcementRule(client, "storage", companyId, {...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);+ return data(+ {},+ await flash(request, error(insert.error, "Failed to create rule"))+ );}throw redirect(`${path.to.storageRules}?${getParams(request)}`);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(- storageRulesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewStorageRuleRoute() {const { targetType } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.tsxindex ff052b619e..6ddcb3ce5f 100644--- a/apps/erp/app/routes/x+/inventory+/storage-rules.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.tsx@@ -5,12 +5,12 @@ 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 StorageRulesGroups from "~/modules/inventory/ui/StorageRules/StorageRulesGroups";+import StorageRulesUpgradeOverlay from "~/modules/inventory/ui/StorageRules/StorageRulesUpgradeOverlay";import {- getRuleAssignmentCounts,- getStorageRules-} from "~/modules/storage-rules";-import StorageRulesGroups from "~/modules/storage-rules/ui/StorageRulesGroups";-import StorageRulesUpgradeOverlay from "~/modules/storage-rules/ui/StorageRulesUpgradeOverlay";+ getEnforcementRuleAssignmentCounts,+ getEnforcementRules+} from "~/modules/shared";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -25,7 +25,7 @@ export async function loader({ request }: LoaderFunctionArgs) {role: "employee"});- const rules = await getStorageRules(client, companyId, {+ const rules = await getEnforcementRules(client, "storage", companyId, {search: null,limit: 1000,offset: 0,@@ -40,7 +40,7 @@ export async function loader({ request }: LoaderFunctionArgs) {}const ids = (rules.data ?? []).map((r) => r.id);- const counts = await getRuleAssignmentCounts(client, ids);+ const counts = await getEnforcementRuleAssignmentCounts(client, ids);const countsData = (counts.data ?? {}) as Record<string, number>;const rows = (rules.data ?? []).map((r) => ({diff --git a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsxindex c114d6d76a..1959683de3 100644--- a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx@@ -2,14 +2,10 @@ 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 { assignStorageRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { assignStorageRule } from "~/modules/storage-rules";import { path } from "~/utils/path";-import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -57,17 +53,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Rule assigned")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { itemId } = params;- if (itemId) {- window?.clientCache?.setQueryData(- storageRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,- null- );- }- return await serverAction();-}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 c194642544..7beb49cccd 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@@ -2,14 +2,10 @@ 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 { unassignStorageRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { unassignStorageRule } from "~/modules/storage-rules";import { path } from "~/utils/path";-import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -45,17 +41,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Rule unassigned")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { itemId } = params;- if (itemId) {- window?.clientCache?.setQueryData(- storageRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsxindex f152327b44..ec2703d0b2 100644--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx@@ -1,7 +1,11 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";+import {+ getSalesRuleAssignmentsForItem,+ getSalesRulesList+} from "@carbon/ee/rules";+import { getStorageRulesDataForTarget } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -13,6 +17,7 @@ import {getTrackedEntityExpirations,InventoryDetails} from "~/modules/inventory";+import RuleAssignmentsList from "~/modules/inventory/ui/StorageRules/RuleAssignmentsList";import type { Material, UnitOfMeasureListItem } from "~/modules/items";import {getBomHasShelfLifeManagedInput,@@ -27,7 +32,7 @@ import {} from "~/modules/items";import { PickMethodForm } from "~/modules/items/ui/Item";import { getLocationsList } from "~/modules/resources";-import RuleAssignmentsList from "~/modules/storage-rules/ui/RuleAssignmentsList";+import { SalesRuleAssignmentsList } from "~/modules/sales/ui/SalesRules";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";import { useItems } from "~/stores";@@ -157,7 +162,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shelfLife,bomHasShelfLifeManagedInput,trackedEntityExpirations,- rulesData+ rulesData,+ salesRuleAssignments,+ salesRuleLibrary] = await Promise.all([getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),@@ -166,7 +173,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {targetType: "item",targetId: itemId,companyId- })+ }),+ getSalesRuleAssignmentsForItem(client, { itemId, companyId }),+ getSalesRulesList(client, companyId)]);return {@@ -179,7 +188,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemId,locationId,ruleAssignments: rulesData.assignments,- ruleLibrary: rulesData.library+ ruleLibrary: rulesData.library,+ salesRuleAssignments: salesRuleAssignments.data ?? [],+ salesRuleLibrary: salesRuleLibrary.data ?? []};}@@ -254,7 +265,9 @@ export default function MaterialInventoryRoute() {trackedEntityExpirations,itemId,ruleAssignments,- ruleLibrary+ ruleLibrary,+ salesRuleAssignments,+ salesRuleLibrary} = useLoaderData<typeof loader>();const materialData = useRouteData<{@@ -312,6 +325,11 @@ export default function MaterialInventoryRoute() {assignments={ruleAssignments as never}library={ruleLibrary as never}/>+ <SalesRuleAssignmentsList+ itemId={itemId}+ assignments={salesRuleAssignments as never}+ library={salesRuleLibrary as never}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsxindex 96ccef150b..d3727202f8 100644--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx@@ -1,7 +1,11 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";+import {+ getSalesRuleAssignmentsForItem,+ getSalesRulesList+} from "@carbon/ee/rules";+import { getStorageRulesDataForTarget } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -13,6 +17,7 @@ import {getTrackedEntityExpirations,InventoryDetails} from "~/modules/inventory";+import RuleAssignmentsList from "~/modules/inventory/ui/StorageRules/RuleAssignmentsList";import type { PartSummary, UnitOfMeasureListItem } from "~/modules/items";import {getBomHasShelfLifeManagedInput,@@ -27,7 +32,7 @@ import {} from "~/modules/items";import { PickMethodForm } from "~/modules/items/ui/Item";import { getLocationsList } from "~/modules/resources";-import RuleAssignmentsList from "~/modules/storage-rules/ui/RuleAssignmentsList";+import { SalesRuleAssignmentsList } from "~/modules/sales/ui/SalesRules";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";import { useItems } from "~/stores";@@ -116,7 +121,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemStorageUnitQuantities,shelfLife,bomHasShelfLifeManagedInput,- rulesData+ rulesData,+ salesRuleAssignments,+ salesRuleLibrary] = await Promise.all([getItemQuantities(client, itemId, companyId, locationId),getItemStorageUnitQuantities(client, itemId, companyId, locationId),@@ -126,7 +133,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {targetType: "item",targetId: itemId,companyId- })+ }),+ getSalesRuleAssignmentsForItem(client, { itemId, companyId }),+ getSalesRulesList(client, companyId)]);if (quantities.error) {throw redirect(@@ -164,7 +173,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemId,locationId,ruleAssignments: rulesData.assignments,- ruleLibrary: rulesData.library+ ruleLibrary: rulesData.library,+ salesRuleAssignments: salesRuleAssignments.data ?? [],+ salesRuleLibrary: salesRuleLibrary.data ?? []};}@@ -239,7 +250,9 @@ export default function PartInventoryRoute() {trackedEntityExpirations,itemId,ruleAssignments,- ruleLibrary+ ruleLibrary,+ salesRuleAssignments,+ salesRuleLibrary} = useLoaderData<typeof loader>();const partData = useRouteData<{@@ -296,6 +309,11 @@ export default function PartInventoryRoute() {assignments={ruleAssignments as never}library={ruleLibrary as never}/>+ <SalesRuleAssignmentsList+ itemId={itemId}+ assignments={salesRuleAssignments as never}+ library={salesRuleLibrary as never}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex fd5ae535ed..1461e66447 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -2,9 +2,15 @@ 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,+ evaluateSalesRuleLines,+ isBlocked+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { JSONContent } from "@carbon/react";import { VStack } from "@carbon/react";+import { breakQuantities } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import { Fragment, Suspense, useMemo } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";@@ -44,7 +50,10 @@ import {quoteLineValidator,reconcileQuantityBreaks} from "~/modules/sales";-import { saveQuoteLineWithPrices } from "~/modules/sales/sales.server";+import {+ recordSalesRuleOutcome,+ saveQuoteLineWithPrices+} from "~/modules/sales/sales.server";import {OpportunityLineDocuments,OpportunityLineNotes@@ -191,6 +200,42 @@ export async function action({ request, params }: ActionFunctionArgs) {// transaction. Previously the line update committed on its own, and a// resolver failure left it saved with its new breaks unpriced.const serviceRole = getCarbonServiceRole();++ // Sales-rule enforcement: evaluate before the line is written. Blocked+ // submissions return violations for the form's violation modal;+ // acknowledged warns pass through on re-submit.+ const acknowledged = formData.get("acknowledged") === "true";+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "quoteLine",+ // Quote lines carry a quantity-break array rather than a single+ // transaction quantity. Evaluate the largest break — it is the one most+ // likely to trip a `gt` threshold, so it is the conservative choice.+ lines: breakQuantities(d.quantity).map((quantity) => ({+ lineId,+ itemId: d.itemId ?? null,+ quantity+ })),+ customerId: quote.data?.customerId ?? null,+ customerLocationId: quote.data?.customerLocationId ?? null+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }const existingPrices = await serviceRole.from("quoteLinePrice").select("quantity")@@ -291,6 +336,22 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Acknowledged proceed: record only after the write committed — evidence+ // (and its notification) must describe a change that actually landed.+ if (deduped.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: deduped,+ ruleNames+ });+ }+throw redirect(path.to.quoteLine(quoteId, lineId));}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsxindex 709411350c..f2e319f634 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx@@ -2,8 +2,14 @@ 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,+ evaluateSalesRulesForSalesDocument,+ isBlocked+} from "@carbon/ee/rules.server";import { validator } from "@carbon/form";import { getLogger } from "@carbon/logger";+import type { Violation } from "@carbon/utils";import { parseAcceptLanguage } from "intl-parse-accept-language";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -13,6 +19,7 @@ import {salesConfirmValidator,selectedLinesValidator} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import {generateAndAttachSalesOrderPdf,sendSalesOrderEmail@@ -73,6 +80,67 @@ export async function action(args: ActionFunctionArgs) {const cc = notificationValidation.data?.cc;const serviceRole = getCarbonServiceRole();++ // Terminal gate, in the route rather than inside the `convert` edge function:+ // the edge function writes salesOrderLine rows directly and cannot run the+ // evaluator (it is Deno, and the evaluator's plan gate pulls in the ERP+ // server runtime). Gating here covers this path without duplicating the+ // evaluator into a tree CI never typechecks or tests.+ const acknowledged = formData.get("acknowledged") === "true";+ let violations: Violation[];+ let ruleNames: Record<string, string>;+ try {+ const result = await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId+ });+ violations = result.violations;+ ruleNames = result.ruleNames;+ } catch (err) {+ // Fail closed but not as a raw 500 — the modal shows the message.+ return {+ violations: [+ {+ ruleId: "__evaluation-error__",+ severity: "error" as const,+ message:+ err instanceof Error ? err.message : "Sales rule evaluation failed"+ }+ ],+ ruleNames: {}+ };+ }+ // Only the SELECTED lines convert (quantity > 0) — a deselected line never+ // becomes a sales-order line, so its violations must not block the+ // conversion or leave "acknowledged" evidence for a line that never+ // converted. A violation without a lineId (shouldn't happen — the document+ // evaluator stamps every one) is kept, failing closed.+ const convertingLineIds = new Set(+ Object.entries(selectedLines)+ .filter(([, line]) => (line.quantity ?? 0) > 0)+ .map(([lineId]) => lineId)+ );+ const deduped = dedupeViolations(violations).filter(+ (v) => !v.lineId || convertingLineIds.has(v.lineId)+ );+ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {+ // Record the same evidence + notification the per-line checks write —+ // an override at a gate is the strongest kind and must leave a trail.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { violations: deduped, ruleNames };+ }+const convert = await convertQuoteToOrder(serviceRole, {id: quoteId,purchaseOrderNumber: poNumber ?? "",@@ -99,6 +167,21 @@ export async function action(args: ActionFunctionArgs) {const salesOrderId = convert.data?.convertedId!;+ // Acknowledged-override evidence only once the conversion has committed —+ // a trail for a conversion that then failed would be false, and a retry+ // would duplicate it.+ if (deduped.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ outcome: "acknowledged",+ violations: deduped,+ ruleNames+ });+ }+// Generate PDF and optionally send email — failures here should not block// the redirect to the new sales order.try {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsxindex a25c9bb663..734e12898a 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx@@ -1,11 +1,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 { QuoteEmail } from "@carbon/documents/email";import { getQuoteDisplayId } from "@carbon/documents/pdf";+import {+ dedupeViolations,+ evaluateSalesRulesForSalesDocument,+ isBlocked+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";-import { datetime } from "@carbon/utils";+import { datetime, type Violation } from "@carbon/utils";import { renderAsync } from "@react-email/components";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -17,6 +23,7 @@ import {getQuote,quoteFinalizeValidator} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import { getCompany, getCompanySettings } from "~/modules/settings";import { upsertExternalLink } from "~/modules/shared";import { getUser } from "~/modules/users/users.server";@@ -49,6 +56,55 @@ export async function action(args: ActionFunctionArgs) {);}+ // Terminal gate: re-evaluate every line before the quote leaves for the+ // customer. Lines can arrive here from paths the per-line check never saw+ // (RFQ conversion, duplication, integrations, the API), and a line that+ // passed earlier may violate a rule authored since or a ship-to that changed.+ // Runs before the external link + PDF so a blocked quote produces neither.+ const formData = await request.clone().formData();+ const acknowledged = formData.get("acknowledged") === "true";+ let violations: Violation[];+ let ruleNames: Record<string, string>;+ try {+ const result = await evaluateSalesRulesForSalesDocument({+ client,+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId+ });+ violations = result.violations;+ ruleNames = result.ruleNames;+ } catch (err) {+ // Fail closed but not as a raw 500 — the modal shows the message.+ return {+ violations: [+ {+ ruleId: "__evaluation-error__",+ severity: "error" as const,+ message:+ err instanceof Error ? err.message : "Sales rule evaluation failed"+ }+ ],+ ruleNames: {}+ };+ }+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {+ // The strongest overrides happen at gates like this one — record the+ // same evidence + notification the per-line checks write.+ await recordSalesRuleOutcome(getCarbonServiceRole(), {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { violations: deduped, ruleNames };+ }+const externalLink = await upsertExternalLink(client, {id: quote.data.externalLinkId ?? undefined, // TODOdocumentType: "Quote",@@ -129,6 +185,21 @@ export async function action(args: ActionFunctionArgs) {await flash(request, error(finalize.error, "Failed to finalize quote")));}++ // Acknowledged-override evidence only once the finalize has committed —+ // a trail for a transition that then failed would be false, and a retry+ // would duplicate it.+ if (deduped.length > 0) {+ await recordSalesRuleOutcome(getCarbonServiceRole(), {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ outcome: "acknowledged",+ violations: deduped,+ ruleNames+ });+ }} catch (err) {throw redirect(path.to.quote(quoteId),diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsxindex ce61b29d9b..58c7cc07f5 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx@@ -2,8 +2,14 @@ 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,+ evaluateSalesRuleLines,+ isBlocked+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { getLogger } from "@carbon/logger";+import { breakQuantities } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -16,6 +22,7 @@ import {upsertQuoteLine,upsertQuoteLineMethod} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import { setCustomFields } from "~/utils/form";import { requireUnlocked } from "~/utils/lockedGuard.server";import { path } from "~/utils/path";@@ -61,6 +68,46 @@ export async function action({ request, params }: ActionFunctionArgs) {}const serviceRole = getCarbonServiceRole();++ // Sales-rule enforcement: evaluate before the line is written. Blocked+ // submissions return violations for the form's violation modal;+ // acknowledged warns pass through on re-submit.+ const acknowledged = formData.get("acknowledged") === "true";+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "quoteLine",+ // Quote lines carry a quantity-break array rather than a single+ // transaction quantity. Evaluate every break — a min-quantity rule fires+ // on the smallest, a max-quantity rule on the largest; dedupe collapses+ // same-message repeats.+ lines: breakQuantities(d.quantity).map((quantity) => ({+ lineId: "new",+ itemId: d.itemId ?? null,+ quantity+ })),+ customerId: quote.data?.customerId ?? null,+ customerLocationId: quote.data?.customerLocationId ?? null+ });+ const deduped = dedupeViolations(violations);+ const blocked = deduped.length > 0 && isBlocked(deduped, acknowledged);+ if (blocked) {+ // No line exists on a blocked create, so documentLineId stays null.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ documentLineId: null,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }+const createQuotationLine = await upsertQuoteLine(serviceRole, {...d,companyId,@@ -84,6 +131,23 @@ export async function action({ request, params }: ActionFunctionArgs) {const quoteLineId = createQuotationLine.data.id;+ // Acknowledged proceed: persist override evidence now that the line exists+ // so documentLineId captures the created line (and the notification only+ // fires for a line that actually landed).+ if (deduped.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "quote",+ documentId: quoteId,+ documentLineId: quoteLineId,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: deduped,+ ruleNames+ });+ }+if (d.methodType === "Purchase to Order") {const quantities = d.quantity ?? [1];const priceResult = await resolvePurchaseToOrderPrices(diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsxindex d048763814..55eb631ccb 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx@@ -6,7 +6,7 @@ import {dedupeViolations,evaluateLinesForSurface,isBlocked-} from "@carbon/ee/storage-rules.server";+} from "@carbon/ee/rules.server";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";@@ -31,7 +31,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const formData = await request.formData();const acknowledged = formData.get("acknowledged") === "true";- // Item Rule evaluation across every line on this receipt before posting.+ // Storage Rule evaluation across every line on this receipt before posting.// Use service role so item / storageUnit reads are not blocked by RLS for// users who have `inventory.update` but not `parts.view` etc.const serviceRole = getCarbonServiceRole();@@ -94,7 +94,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}// Place pass — the bin side of the receipt. Same lines, same item target;- // item rules own the `place` surface. Transfers double-up via the+ // storage rules own the `place` surface. Transfers double-up via the// warehouseTransfer surface (dedupe collapses the overlap).const placeSurfaces: ("place" | "warehouseTransfer")[] = ["place"];if (receiptForSurface?.sourceDocument === "Inbound Transfer") {diff --git a/apps/erp/app/routes/x+/receipt+/lines.update.tsx b/apps/erp/app/routes/x+/receipt+/lines.update.tsxindex 1f0813614c..04a839bd8c 100644--- a/apps/erp/app/routes/x+/receipt+/lines.update.tsx+++ b/apps/erp/app/routes/x+/receipt+/lines.update.tsx@@ -22,7 +22,7 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: `Invalid field: ${field}` }, data: null };}- // Item Rule evaluation runs at post time only (`$receiptId.post.tsx`).+ // Storage Rule evaluation runs at post time only (`$receiptId.post.tsx`).// Per-line saves go straight through.const update = await client.from("receiptLine")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.tsxindex 2f155a0c43..dd9b92f391 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx@@ -1,9 +1,9 @@import { notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";+import { getStorageRulesDataForTarget } from "@carbon/ee/rules.server";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import RuleAssignmentsList from "~/modules/storage-rules/ui/RuleAssignmentsList";+import RuleAssignmentsList from "~/modules/inventory/ui/StorageRules/RuleAssignmentsList";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {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.tsxindex 0acf9b7ce9..b78b0b6b6b 100644--- 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.tsx@@ -2,14 +2,10 @@ 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 { assignStorageRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { assignStorageRule } from "~/modules/storage-rules";import { path } from "~/utils/path";-import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -57,18 +53,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Rule assigned")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { workCenterId } = params;- if (workCenterId) {- window?.clientCache?.setQueryData(- storageRuleAssignmentsQuery("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.tsxindex 1406cd6e2d..2f0989c2d9 100644--- 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.tsx@@ -2,14 +2,10 @@ 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 { unassignStorageRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { unassignStorageRule } from "~/modules/storage-rules";import { path } from "~/utils/path";-import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -46,18 +42,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Rule unassigned")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { workCenterId } = params;- if (workCenterId) {- window?.clientCache?.setQueryData(- storageRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())- .queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsxnew file mode 100644index 0000000000..7fef845cae--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx@@ -0,0 +1,70 @@+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, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData, useNavigate } from "react-router";+import { ConfirmDelete } from "~/components/Modals";+import { deleteEnforcementRule, getEnforcementRule } from "~/modules/shared";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ delete: "sales"+ });+ const { id } = params;+ if (!id) throw notFound("id required");+ const rule = await getEnforcementRule(client, "sales", id, companyId);+ if (rule.error || !rule.data) {+ throw redirect(+ path.to.salesRules,+ 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: "sales"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "SALES_RULES",+ redirectTo: path.to.salesRules+ });++ const { id } = params;+ if (!id) throw new Error("id required");++ const result = await deleteEnforcementRule(client, "sales", id, companyId);+ if (result.error) {+ throw redirect(+ `${path.to.salesRules}?${getParams(request)}`,+ await flash(request, error(result.error, "Failed to delete rule"))+ );+ }++ throw redirect(+ `${path.to.salesRules}?${getParams(request)}`,+ await flash(request, success("Rule deleted"))+ );+}++export default function DeleteSalesRuleRoute() {+ const { rule } = useLoaderData<typeof loader>();+ const id = rule?.id ?? "";+ const navigate = useNavigate();+ return (+ <ConfirmDelete+ action={path.to.deleteSalesRule(id)}+ name={rule?.name ?? "this rule"}+ text="Are you sure you want to delete this rule? Assignments will also be removed."+ onCancel={() => navigate(path.to.salesRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsxnew file mode 100644index 0000000000..301149c43b--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx@@ -0,0 +1,90 @@+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 { validationError, validator } from "@carbon/form";+import type { SalesRuleSurface } from "@carbon/utils";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData, useNavigate } from "react-router";+import type { z } from "zod";+import { type salesRuleSeverities, salesRuleValidator } from "~/modules/sales";+import { SalesRuleForm } from "~/modules/sales/ui/SalesRules";+import { getEnforcementRule, upsertEnforcementRule } from "~/modules/shared";+import { getParams, path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "sales"+ });+ const { id } = params;+ if (!id) throw notFound("id required");+ const rule = await getEnforcementRule(client, "sales", id, companyId);+ 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: "sales"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "SALES_RULES",+ redirectTo: path.to.salesRules+ });++ const { id } = params;+ if (!id) throw new Error("id required");++ const formData = await request.formData();+ const validation = await validator(salesRuleValidator).validate(formData);+ if (validation.error) return validationError(validation.error);++ const update = await upsertEnforcementRule(client, "sales", companyId, {+ ...validation.data,+ id,+ description: validation.data.description ?? null,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ {},+ await flash(request, error(update.error, "Failed to update rule"))+ );+ }++ throw redirect(`${path.to.salesRules}?${getParams(request)}`);+}++export default function EditSalesRuleRoute() {+ const { rule } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ return (+ <SalesRuleForm+ // Per-field mapping from the DB row; the three casts below are genuine+ // DB-boundary narrowings (severity/surfaces are CHECK-constrained TEXT/+ // shared-enum columns, conditionAst is Json).+ initialValues={{+ id: rule.id,+ name: rule.name,+ description: rule.description ?? undefined,+ message: rule.message,+ severity: rule.severity as (typeof salesRuleSeverities)[number],+ filteredItemTypes: rule.filteredItemTypes ?? undefined,+ filteredItemGroupIds: rule.filteredItemGroupIds ?? undefined,+ filteredItemMatchAll: rule.filteredItemMatchAll,+ active: rule.active,+ surfaces: rule.surfaces as SalesRuleSurface[],+ conditionAst: rule.conditionAst as unknown as z.infer<+ typeof salesRuleValidator+ >["conditionAst"]+ }}+ onClose={() => navigate(path.to.salesRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsxnew file mode 100644index 0000000000..3786fa0844--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx@@ -0,0 +1,54 @@+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 { assignSalesRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "sales"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "SALES_RULES",+ redirectTo: path.to.salesRules+ });++ const { itemId } = params;+ if (!itemId) throw new Error("itemId required");++ const formData = await request.formData();+ const ruleId = String(formData.get("ruleId") ?? "");+ if (!ruleId) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.salesRules,+ await flash(request, error(null, "Rule id required"))+ );+ }++ const result = await assignSalesRule(client, {+ itemId,+ ruleId,+ companyId,+ createdBy: userId+ });++ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.salesRules,+ await flash(request, error(result.error, "Failed to assign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.salesRules,+ await flash(request, success("Rule assigned"))+ );+}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.new.tsxnew file mode 100644index 0000000000..25cdeb9fe0--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx@@ -0,0 +1,63 @@+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 { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useNavigate } from "react-router";+import { salesRuleValidator } from "~/modules/sales";+import { SalesRuleForm } from "~/modules/sales/ui/SalesRules";+import { upsertEnforcementRule } from "~/modules/shared";+import { getParams, path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, { create: "sales" });+ return {};+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "sales"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "SALES_RULES",+ redirectTo: path.to.salesRules+ });++ const formData = await request.formData();+ const validation = await validator(salesRuleValidator).validate(formData);+ if (validation.error) return validationError(validation.error);++ const insert = await upsertEnforcementRule(client, "sales", companyId, {+ ...validation.data,+ description: validation.data.description ?? null,+ createdBy: userId+ });++ if (insert.error) {+ return data(+ {},+ await flash(request, error(insert.error, "Failed to create rule"))+ );+ }++ throw redirect(`${path.to.salesRules}?${getParams(request)}`);+}++export default function NewSalesRuleRoute() {+ 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 (+ <SalesRuleForm+ initialValues={{}}+ onClose={() => navigate(path.to.salesRules)}+ />+ );+}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.tsxnew file mode 100644index 0000000000..17b10ea066--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.tsx@@ -0,0 +1,70 @@+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 {+ SalesRulesTable,+ SalesRulesUpgradeOverlay+} from "~/modules/sales/ui/SalesRules";+import {+ getEnforcementRuleAssignmentCounts,+ getEnforcementRules+} from "~/modules/shared";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: msg`Sales Rules`,+ to: path.to.salesRules+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "sales",+ role: "employee"+ });++ const rules = await getEnforcementRules(client, "sales", companyId, {+ search: null,+ limit: 1000,+ offset: 0,+ sorts: []+ });++ if (rules.error) {+ throw redirect(+ path.to.salesOrders,+ await flash(request, error(rules.error, "Failed to load sales rules"))+ );+ }++ const ids = (rules.data ?? []).map((r) => r.id);+ const counts = await getEnforcementRuleAssignmentCounts(client, ids);++ const countsData = (counts.data ?? {}) as Record<string, number>;+ const rows = (rules.data ?? []).map((r) => ({+ ...r,+ assignmentCount: countsData[r.id] ?? 0+ }));++ return { rows, count: rules.count ?? rows.length };+}++export default function SalesRulesRoute() {+ const { rows, count } = useLoaderData<typeof loader>();+ const { isGated } = usePlanGate({ feature: "SALES_RULES" });++ if (isGated) {+ return <SalesRulesUpgradeOverlay />;+ }++ return (+ <>+ <SalesRulesTable data={rows as never} count={count} />+ <Outlet />+ </>+ );+}diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsxnew file mode 100644index 0000000000..4aa2707aad--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx@@ -0,0 +1,43 @@+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 { unassignSalesRule } from "@carbon/ee/rules";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ update: "sales"+ });++ await requirePlan({+ request,+ client,+ companyId,+ feature: "SALES_RULES",+ redirectTo: path.to.salesRules+ });++ const { itemId, ruleId } = params;+ if (!itemId || !ruleId) throw new Error("itemId and ruleId required");++ const result = await unassignSalesRule(client, {+ itemId,+ ruleId,+ companyId+ });+ if (result.error) {+ throw redirect(+ request.headers.get("Referer") ?? path.to.salesRules,+ await flash(request, error(result.error, "Failed to unassign rule"))+ );+ }++ throw redirect(+ request.headers.get("Referer") ?? path.to.salesRules,+ await flash(request, success("Rule unassigned"))+ );+}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsxindex 80d218d220..cffef6d786 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx@@ -1,6 +1,13 @@import { assertIsPost, error, notFound } 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,+ evaluateSalesRuleLines,+ isBlocked,+ resolveSalesOrderShipTo+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { JSONContent } from "@carbon/react";import { getItemReadableId } from "@carbon/utils";@@ -18,6 +25,7 @@ import {} from "~/modules/invoicing";import SalesInvoiceLineForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm";import { getOpportunityLineDocuments } from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import {OpportunityLineDocuments,OpportunityLineNotes@@ -73,7 +81,7 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked sales invoice. Reopen it first."});- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "invoicing"});@@ -97,6 +105,72 @@ export async function action({ request, params }: ActionFunctionArgs) {d.assetId = undefined;}+ // Sales-rule enforcement — only for lines that reference an item. A line+ // converted from a sales order resolves its ship-to through that order+ // (drop-ship included); a standalone line has no ship-to and none may be+ // invented — the bill-to is a different address, so a null location flows+ // into the engine's required-field semantics and a destination rule blocks+ // rather than passes.+ let acknowledgedViolations: ReturnType<typeof dedupeViolations> = [];+ let acknowledgedRuleNames: Record<string, string> = {};+ if (d.itemId) {+ const serviceRole = getCarbonServiceRole();+ const acknowledged = formData.get("acknowledged") === "true";++ const existingLine = await serviceRole+ .from("salesInvoiceLine")+ .select("salesOrderId")+ .eq("id", lineId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (existingLine.error) {+ // A failed read must not evaluate the wrong destination.+ throw new Error(+ `Sales rule evaluation could not load sales invoice line ${lineId}: ${existingLine.error.message}`+ );+ }++ const shipTo = existingLine.data?.salesOrderId+ ? await resolveSalesOrderShipTo(+ serviceRole,+ existingLine.data.salesOrderId,+ companyId+ )+ : {+ customerId: invoice.data?.customerId ?? null,+ customerLocationId: null+ };++ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "salesInvoiceLine",+ lines: [{ lineId, itemId: d.itemId, quantity: d.quantity ?? 1 }],+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0) {+ if (isBlocked(deduped, acknowledged)) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }+ acknowledgedViolations = deduped;+ acknowledgedRuleNames = ruleNames;+ }+ }+const updateSalesInvoiceLine = await upsertSalesInvoiceLine(client, {id: lineId,...d,@@ -117,6 +191,22 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Acknowledged proceed: record only after the write committed — evidence+ // (and its notification) must describe a change that actually landed.+ if (acknowledgedViolations.length > 0) {+ await recordSalesRuleOutcome(getCarbonServiceRole(), {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: acknowledgedViolations,+ ruleNames: acknowledgedRuleNames+ });+ }+throw redirect(path.to.salesInvoiceLine(invoiceId, lineId));}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsxindex db6a09c25c..e61a6cbd37 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx@@ -1,6 +1,12 @@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,+ evaluateSalesRuleLines,+ isBlocked+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";import type { ActionFunctionArgs } from "react-router";@@ -14,6 +20,7 @@ import {upsertSalesInvoiceLine} from "~/modules/invoicing";import SalesInvoiceLineForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import type { MethodItemType } from "~/modules/shared";import { setCustomFields } from "~/utils/form";import { requireUnlocked } from "~/utils/lockedGuard.server";@@ -69,6 +76,49 @@ export async function action({ request, params }: ActionFunctionArgs) {d.assetId = undefined;}+ // Sales-rule enforcement — only for lines that reference an item (Comment+ // and Fixed Asset lines carry no itemId). A manually created invoice line+ // is standalone: it has no source sales order, so there is no ship-to and+ // none may be invented — the bill-to is a different address. A null+ // location flows into the engine's required-field semantics, so a+ // destination rule blocks rather than passes.+ const serviceRole = getCarbonServiceRole();+ let acknowledgedViolations: ReturnType<typeof dedupeViolations> = [];+ let acknowledgedRuleNames: Record<string, string> = {};+ if (d.itemId) {+ const acknowledged = formData.get("acknowledged") === "true";+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "salesInvoiceLine",+ lines: [{ lineId: "new", itemId: d.itemId, quantity: d.quantity ?? 1 }],+ customerId: invoice.data?.customerId ?? null,+ customerLocationId: null+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0) {+ const blocked = isBlocked(deduped, acknowledged);+ if (blocked) {+ // No line exists on a blocked create, so documentLineId stays null.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ documentLineId: null,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }+ acknowledgedViolations = deduped;+ acknowledgedRuleNames = ruleNames;+ }+ }+const createSalesInvoiceLine = await upsertSalesInvoiceLine(client, {...d,companyId,@@ -89,6 +139,23 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Acknowledged proceed: persist override evidence now that the line exists+ // so documentLineId captures the created line (and the notification only+ // fires for a line that actually landed).+ if (acknowledgedViolations.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ documentLineId: createSalesInvoiceLine.data.id,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: acknowledgedViolations,+ ruleNames: acknowledgedRuleNames+ });+ }+throw redirect(path.to.salesInvoiceDetails(invoiceId));}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsxindex 6794db89d5..acaa95fa46 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx@@ -4,6 +4,11 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Json } from "@carbon/database";import { SalesInvoiceEmail } from "@carbon/documents/email";import { createMappingService } from "@carbon/ee/accounting";+import {+ dedupeViolations,+ evaluateSalesRulesForSalesDocument,+ isBlocked+} from "@carbon/ee/rules.server";import { validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";@@ -36,6 +41,7 @@ import {STRIPE_CONNECT_INTEGRATION} from "~/modules/invoicing/stripe-customer.server";import { getCustomerContact, updateCustomerContact } from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import { getCompany } from "~/modules/settings";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getUser } from "~/modules/users/users.server";@@ -503,8 +509,9 @@ export async function action(args: ActionFunctionArgs) {const serviceRole = getCarbonServiceRole();+ const formData = await request.formData();const validation = await validator(salesInvoicePostValidator).validate(- await request.formData()+ formData);if (validation.error) {@@ -514,6 +521,62 @@ export async function action(args: ActionFunctionArgs) {};}+ // Sales-rule terminal gate. Posting is the revenue checkpoint and the only+ // gate an invoice raised with no upstream document ever passes — lines can+ // arrive from the convert edge function, the API, or MCP without the+ // per-line check. Re-reads the whole document, so it also catches+ // staleness (a rule authored after the lines were written). Must run+ // BEFORE the optimistic `Pending` write below, or a blocked post strands+ // the invoice in `Pending`; running first also prevents the Stripe send+ // and the customer email.+ const acknowledged = formData.get("acknowledged") === "true";+ // An evaluator throw (failed rule/item/ship-to load) must fail closed but+ // not as a raw 500 — surface it like the Stripe preflight below.+ let salesRuleResult: Awaited<+ ReturnType<typeof evaluateSalesRulesForSalesDocument>+ >;+ try {+ salesRuleResult = await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId+ });+ } catch (err) {+ logger.error("Sales rule evaluation failed", { error: err, invoiceId });+ return {+ success: false,+ message: `Invoice not posted — ${+ err instanceof Error ? err.message : "sales rule evaluation failed"+ }`+ };+ }+ const { ruleNames: salesRuleNames } = salesRuleResult;+ const salesRuleViolations = dedupeViolations(salesRuleResult.violations);+ if (+ salesRuleViolations.length > 0 &&+ isBlocked(salesRuleViolations, acknowledged)+ ) {+ // Record the same evidence + notification the per-line checks write —+ // posting is the revenue checkpoint, the strongest override there is.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ outcome: "blocked",+ violations: salesRuleViolations,+ ruleNames: salesRuleNames+ });+ return {+ success: false,+ message: "Sales rules blocked posting this invoice",+ violations: salesRuleViolations,+ ruleNames: salesRuleNames+ };+ }+const {notification,customerContact,@@ -615,6 +678,21 @@ export async function action(args: ActionFunctionArgs) {};}+ // Acknowledged-override evidence only once the post has committed — a+ // trail (and notification) for a post that then failed would be false, and+ // a retry would duplicate it.+ if (salesRuleViolations.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesInvoice",+ documentId: invoiceId,+ outcome: "acknowledged",+ violations: salesRuleViolations,+ ruleNames: salesRuleNames+ });+ }+const salesInvoice = await getSalesInvoice(serviceRole, invoiceId);if (salesInvoice.error) {return {diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsxindex 1cfc159c98..a07165784a 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx@@ -2,6 +2,12 @@ import { assertIsPost, error, notFound } 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,+ evaluateSalesRuleLines,+ isBlocked,+ resolveSalesOrderShipTo+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { JSONContent } from "@carbon/react";import { Card, CardHeader, CardTitle } from "@carbon/react";@@ -33,6 +39,7 @@ import {salesOrderLineValidator,upsertSalesOrderLine} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import {OpportunityLineDocuments,OpportunityLineNotes@@ -103,7 +110,7 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked sales order. Reopen it first."});- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "sales"});@@ -131,6 +138,52 @@ export async function action({ request, params }: ActionFunctionArgs) {d.assetId = undefined;}+ // Sales-rule enforcement — only for lines that reference an item (Comment+ // and Fixed Asset lines carry no itemId). Blocked submissions return+ // violations for the form's violation modal; acknowledged warns pass+ // through on re-submit.+ let acknowledgedViolations: ReturnType<typeof dedupeViolations> = [];+ let acknowledgedRuleNames: Record<string, string> = {};+ if (d.itemId) {+ const acknowledged = formData.get("acknowledged") === "true";+ const serviceRole = getCarbonServiceRole();+ // Drop shipments deliver to the drop-ship location, not the header's —+ // evaluating the header alone would clear an order that ships elsewhere.+ const shipTo = await resolveSalesOrderShipTo(+ serviceRole,+ orderId,+ companyId+ );+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "salesOrderLine",+ lines: [{ lineId, itemId: d.itemId, quantity: d.saleQuantity ?? 1 }],+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0) {+ if (isBlocked(deduped, acknowledged)) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }+ acknowledgedViolations = deduped;+ acknowledgedRuleNames = ruleNames;+ }+ }+const updateSalesOrderLine = await upsertSalesOrderLine(client, {id: lineId,...d,@@ -148,6 +201,22 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Acknowledged proceed: record only after the write committed — evidence+ // (and its notification) must describe a change that actually landed.+ if (acknowledgedViolations.length > 0) {+ await recordSalesRuleOutcome(getCarbonServiceRole(), {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ documentLineId: lineId,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: acknowledgedViolations,+ ruleNames: acknowledgedRuleNames+ });+ }+throw redirect(path.to.salesOrderLine(orderId, lineId));}diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsxindex 52b3786e5b..7d984fad76 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx@@ -1,6 +1,11 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ dedupeViolations,+ evaluateSalesRulesForSalesDocument,+ isBlocked+} from "@carbon/ee/rules.server";import { validator } from "@carbon/form";import { trackWorkEvent } from "@carbon/lib/telemetry";import { datetime, getSalesOrderStatus } from "@carbon/utils";@@ -12,6 +17,7 @@ import {getSalesOrderLines,salesConfirmValidator} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import {generateAndAttachSalesOrderPdf,sendSalesOrderEmail@@ -57,6 +63,43 @@ export async function action(args: ActionFunctionArgs) {};}+ // Terminal gate: re-evaluate sales rules across EVERY line on the order,+ // with today's context. Per-line checks only cover lines added through the+ // line routes — conversions, duplication, integrations and the API all+ // write lines without them — and a line that passed weeks ago may violate+ // a rule authored since, or a ship-to that has changed. Runs before the PDF+ // so a blocked order doesn't generate one.+ const formData = await request.formData();+ const acknowledged = formData.get("acknowledged") === "true";++ const { violations, ruleNames } = await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {+ // Record the same evidence + notification the per-line checks write —+ // an override at a gate is the strongest kind and must leave a trail.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return {+ success: false,+ message: "Sales rule violations must be resolved before confirming",+ violations: deduped,+ ruleNames+ };+ }+const acceptLanguage = request.headers.get("accept-language");const locales = parseAcceptLanguage(acceptLanguage, {validate: Intl.DateTimeFormat.supportedLocalesOf@@ -87,7 +130,7 @@ export async function action(args: ActionFunctionArgs) {}const validation = await validator(salesConfirmValidator).validate(- await request.formData()+ formData);if (validation.error) {@@ -170,6 +213,21 @@ export async function action(args: ActionFunctionArgs) {};}+ // Acknowledged-override evidence is written only once the confirm has+ // actually committed — evidence (and its notification) for a transition+ // that then failed would be a false trail, and a retry would duplicate it.+ if (deduped.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ outcome: "acknowledged",+ violations: deduped,+ ruleNames+ });+ }+await runMRP(getCarbonServiceRole(), getDatabaseClient(), {type: "salesOrder",id: orderId,diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsxindex 24f7dcd54f..dbc8e0f031 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx@@ -2,6 +2,12 @@ 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,+ evaluateSalesRuleLines,+ isBlocked,+ resolveSalesOrderShipTo+} from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect, useParams } from "react-router";@@ -14,6 +20,7 @@ import {salesOrderLineValidator,upsertSalesOrderLine} from "~/modules/sales";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import { SalesOrderLineForm } from "~/modules/sales/ui/SalesOrder";import { setCustomFields } from "~/utils/form";import { requireUnlocked } from "~/utils/lockedGuard.server";@@ -79,6 +86,56 @@ export async function action({ request, params }: ActionFunctionArgs) {}}+ // Sales-rule enforcement — only for lines that reference an item (Comment+ // and Fixed Asset lines carry no itemId). Blocked submissions return+ // violations for the form's violation modal; acknowledged warns pass+ // through on re-submit.+ const serviceRole = getCarbonServiceRole();+ let acknowledgedViolations: ReturnType<typeof dedupeViolations> = [];+ let acknowledgedRuleNames: Record<string, string> = {};+ if (d.itemId) {+ const acknowledged = formData.get("acknowledged") === "true";+ // Drop shipments deliver to the drop-ship location, not the header's —+ // evaluating the header alone would clear an order that ships elsewhere.+ const shipTo = await resolveSalesOrderShipTo(+ serviceRole,+ orderId,+ companyId+ );+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "salesOrderLine",+ lines: [+ { lineId: "new", itemId: d.itemId, quantity: d.saleQuantity ?? 1 }+ ],+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ const deduped = dedupeViolations(violations);+ if (deduped.length > 0) {+ const blocked = isBlocked(deduped, acknowledged);+ if (blocked) {+ // No line exists on a blocked create, so documentLineId stays null.+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ documentLineId: null,+ itemId: d.itemId ?? null,+ outcome: "blocked",+ violations: deduped,+ ruleNames+ });+ return { error: null, data: null, violations: deduped, ruleNames };+ }+ acknowledgedViolations = deduped;+ acknowledgedRuleNames = ruleNames;+ }+ }+const createSalesOrderLine = await upsertSalesOrderLine(client, {...d,companyId,@@ -96,6 +153,23 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Acknowledged proceed: persist override evidence now that the line exists+ // so documentLineId captures the created line (and the notification only+ // fires for a line that actually landed).+ if (acknowledgedViolations.length > 0) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: orderId,+ documentLineId: createSalesOrderLine.data.id,+ itemId: d.itemId ?? null,+ outcome: "acknowledged",+ violations: acknowledgedViolations,+ ruleNames: acknowledgedRuleNames+ });+ }+throw redirect(path.to.salesOrderDetails(orderId));}diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsxindex 8a4dd440d3..8ee0ab4ee5 100644--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx@@ -2,6 +2,12 @@ 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,+ evaluateSalesRulesForSalesDocument,+ isBlocked+} from "@carbon/ee/rules.server";+import type { Violation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -22,6 +28,47 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!id) throw new Error("Could not find id");const serviceRole = getCarbonServiceRole();++ // Terminal gate before the `convert` edge function mints quote lines. Gating+ // here rather than inside the edge function keeps the evaluator in one place+ // (it is Deno and cannot import the ERP server runtime the plan gate needs).+ const acknowledged =+ (await request.formData()).get("acknowledged") === "true";+ let violations: Violation[];+ let ruleNames: Record<string, string>;+ try {+ const result = await evaluateSalesRulesForSalesDocument({+ client: serviceRole,+ companyId,+ userId,+ documentType: "salesRfq",+ documentId: id+ });+ violations = result.violations;+ ruleNames = result.ruleNames;+ } catch (err) {+ // Fail closed but not as a raw 500 — the modal shows the message.+ return {+ violations: [+ {+ ruleId: "__evaluation-error__",+ severity: "error" as const,+ message:+ err instanceof Error ? err.message : "Sales rule evaluation failed"+ }+ ],+ ruleNames: {}+ };+ }+ const deduped = dedupeViolations(violations);+ // No acknowledgment evidence here: the table's documentType CHECK covers+ // quote / salesOrder / salesInvoice only, and the minted quote's own line+ // checks and finalize/convert gates re-evaluate (and record) everything+ // downstream.+ if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {+ return { violations: deduped, ruleNames };+ }+const convert = await convertSalesRfqToQuote(serviceRole, {id,companyId,diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsxindex ee137dfb48..67d7d95a17 100644--- a/apps/erp/app/routes/x+/settings+/sales.tsx+++ b/apps/erp/app/routes/x+/settings+/sales.tsx@@ -43,12 +43,14 @@ import {getCompanySettings,quoteLineCategoryMarkupsSettingsValidator,rfqReadyValidator,+ salesRuleNotificationValidator,updateAccountsReceivableAddressSetting,updateAccountsReceivableBillingAddress,updateDefaultCustomerCc,updateDigitalQuoteSetting,updateQuoteLineCategoryMarkups,updateRfqReadySetting,+ updateSalesRuleNotificationSetting,updateShowCustomerReadableIdSetting} from "~/modules/settings";import type { Handle } from "~/utils/handle";@@ -165,6 +167,29 @@ export async function action({ request }: ActionFunctionArgs) {return { success: true, message: "RFQ setting updated" };+ case "salesRuleViolations":+ const salesRuleValidation = await validator(+ salesRuleNotificationValidator+ ).validate(formData);++ if (salesRuleValidation.error) {+ return { success: false, message: "Invalid form data" };+ }++ const salesRuleSettings = await updateSalesRuleNotificationSetting(+ client,+ companyId,+ salesRuleValidation.data.salesRuleNotificationGroup ?? []+ );++ if (salesRuleSettings.error)+ return { success: false, message: salesRuleSettings.error.message };++ return {+ success: true,+ message: "Sales rule notification settings updated"+ };+case "categoryMarkups":const categoryMarkupsValidation = await validator(quoteLineCategoryMarkupsSettingsValidator@@ -600,6 +625,55 @@ export default function SalesSettingsRoute() {</CardFooter></ValidatedForm></Card>+ <Card>+ <ValidatedForm+ method="post"+ validator={salesRuleNotificationValidator}+ defaultValues={{+ salesRuleNotificationGroup:+ companySettings.salesRuleNotificationGroup ?? []+ }}+ fetcher={fetcher}+ >+ <input type="hidden" name="intent" value="salesRuleViolations" />+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Trans>Sales Rule Violations</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Enable notifications when a sales rule violation is blocked or+ acknowledged on a quote, sales order, or sales invoice.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <div className="flex flex-col gap-2">+ <Label>+ <Trans>Notifications</Trans>+ </Label>+ <Users+ name="salesRuleNotificationGroup"+ label={t`Who should receive notifications when a sales rule violation is blocked or acknowledged?`}+ type="employee"+ />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={+ fetcher.state !== "idle" &&+ fetcher.formData?.get("intent") === "salesRuleViolations"+ }+ >+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card></VStack></ScrollArea>);diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex 02fa37cb0a..404357a411 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -5,8 +5,10 @@ import { flash } from "@carbon/auth/session.server";import {dedupeViolations,evaluateLinesForSurface,- isBlocked-} from "@carbon/ee/storage-rules.server";+ evaluateSalesRuleLines,+ isBlocked,+ resolveSalesOrderShipTo+} from "@carbon/ee/rules.server";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";@@ -17,6 +19,7 @@ import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { upsertDocument } from "~/modules/documents";+import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";import {getCompanyTimeZone,getLocationTimeZone@@ -40,12 +43,12 @@ export async function action({ request, params }: ActionFunctionArgs) {const formData = await request.formData();const acknowledged = formData.get("acknowledged") === "true";- // Item Rule evaluation across every line on this shipment before posting.+ // Storage Rule evaluation across every line on this shipment before posting.const serviceRole = getCarbonServiceRole();const { data: lines } = await serviceRole.from("shipmentLine").select(- "id, itemId, storageUnitId, shippedQuantity, locationId, shipmentId"+ "id, lineId, itemId, storageUnitId, shippedQuantity, locationId, shipmentId").eq("shipmentId", shipmentId).eq("companyId", companyId);@@ -56,8 +59,10 @@ export async function action({ request, params }: ActionFunctionArgs) {// fire here too.const { data: shipmentForSurface } = await serviceRole.from("shipment")- .select("sourceDocument, locationId")+ .select("sourceDocument, sourceDocumentId, locationId").eq("id", shipmentId)+ // Service-role read: companyId scope is not backstopped by RLS here.+ .eq("companyId", companyId).single();const surfaces: ("shipment" | "warehouseTransfer")[] = ["shipment"];if (shipmentForSurface?.sourceDocument === "Outbound Transfer") {@@ -88,7 +93,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}// Pick pass — the bin side of the shipment. Same lines, same item target;- // item rules own the `pick` surface. Transfers double-up via the+ // storage rules own the `pick` surface. Transfers double-up via the// warehouseTransfer surface (dedupe collapses the overlap).const pickSurfaces: ("pick" | "warehouseTransfer")[] = ["pick"];if (shipmentForSurface?.sourceDocument === "Outbound Transfer") {@@ -107,14 +112,78 @@ export async function action({ request, params }: ActionFunctionArgs) {Object.assign(allRuleNames, ruleNames);}+ // Sales rules on the originating sales order — the last physical checkpoint.+ // Sales rules have no `shipment` surface (their enum is sales-document only),+ // so this evaluates under `salesOrderLine` rather than inventing a surface.+ // Scope is THIS shipment's lines at their real shipped quantities — the+ // whole order would let an unshipped violating line block a partial+ // shipment of a clean one. The ship-to is the order's resolved destination+ // (drop-ship included).+ let salesRuleViolations: ReturnType<typeof dedupeViolations> = [];+ if (+ shipmentForSurface?.sourceDocument === "Sales Order" &&+ shipmentForSurface.sourceDocumentId+ ) {+ const shipTo = await resolveSalesOrderShipTo(+ serviceRole,+ shipmentForSurface.sourceDocumentId,+ companyId+ );+ const { violations, ruleNames } = await evaluateSalesRuleLines({+ client: serviceRole,+ companyId,+ userId,+ surface: "salesOrderLine",+ lines: (lines ?? [])+ .filter((l) => !!l.itemId && Number(l.shippedQuantity ?? 0) > 0)+ .map((l) => ({+ // Attribute to the source sales-order line when linked, so the+ // evidence row and deep link land on the order line.+ lineId: (l.lineId as string | null) ?? (l.id as string),+ itemId: l.itemId as string,+ quantity: Number(l.shippedQuantity)+ })),+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ salesRuleViolations = violations;+ allViolations.push(...violations);+ Object.assign(allRuleNames, ruleNames);+ }+const deduped = dedupeViolations(allViolations);- if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {- return {- error: null,- data: null,- violations: deduped,- ruleNames: allRuleNames- };+ // Evidence covers only the SALES violations (the acknowledgment table is+ // sales-family evidence, attributed to the source order); storage+ // violations on the same post carry no evidence, as on every other+ // storage surface. The outcome reflects the submission's overall fate —+ // a post blocked by any violation records its sales violations as+ // blocked too. Acknowledged evidence waits until the post has committed.+ const salesDeduped = dedupeViolations(salesRuleViolations);+ if (deduped.length > 0) {+ const blocked = isBlocked(deduped, acknowledged);+ if (+ blocked &&+ salesDeduped.length > 0 &&+ shipmentForSurface?.sourceDocumentId+ ) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: shipmentForSurface.sourceDocumentId,+ outcome: "blocked",+ violations: salesDeduped,+ ruleNames: allRuleNames+ });+ }+ if (blocked) {+ return {+ error: null,+ data: null,+ violations: deduped,+ ruleNames: allRuleNames+ };+ }}// Expired-batch policy check. Mirrors post-stock-transfer / issue edge@@ -364,6 +433,19 @@ export async function action({ request, params }: ActionFunctionArgs) {// See the receipt post route: below the catch still runs after a rollback,// so the flag is what makes this "the post stuck", not the position.if (!reverted) {+ // Acknowledged-override evidence only once the post has stuck — a trail+ // (and notification) for a post that was rolled back would be false.+ if (salesDeduped.length > 0 && shipmentForSurface?.sourceDocumentId) {+ await recordSalesRuleOutcome(serviceRole, {+ companyId,+ userId,+ documentType: "salesOrder",+ documentId: shipmentForSurface.sourceDocumentId,+ outcome: "acknowledged",+ violations: salesDeduped,+ ruleNames: allRuleNames+ });+ }trackWorkEvent("shipment_posted", {companyId,userId,diff --git a/apps/erp/app/routes/x+/shipment+/lines.update.tsx b/apps/erp/app/routes/x+/shipment+/lines.update.tsxindex f01f133c7e..80eb6dbc0b 100644--- a/apps/erp/app/routes/x+/shipment+/lines.update.tsx+++ b/apps/erp/app/routes/x+/shipment+/lines.update.tsx@@ -22,7 +22,7 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: `Invalid field: ${field}` }, data: null };}- // Item Rule evaluation runs at post time only (`$shipmentId.post.tsx`).+ // Storage Rule evaluation runs at post time only (`$shipmentId.post.tsx`).// Per-line saves go straight through.const update = await client.from("shipmentLine")diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsxindex e867609430..29a38bc1b4 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx@@ -2,10 +2,7 @@ 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 {- evaluateLinesForSurface,- isBlocked-} from "@carbon/ee/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -49,7 +46,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}}- // Item Rule evaluation at "go" transitions — Released is the user's+ // Storage Rule evaluation at "go" transitions — Released is the user's// commitment to the transfer plan; pre-flight here so violations surface// before any picking happens. Completed kept as a defense-in-depth gate.// Draft / In Progress excluded — Draft is editing, In Progress is auto-setdiff --git a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsxindex 38cc41add8..f8342655e7 100644--- a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx@@ -50,7 +50,7 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: `Invalid field: ${field}` }, data: null };}- // Item Rule evaluation runs at commit time (when the transfer is posted),+ // Storage Rule evaluation runs at commit time (when the transfer is posted),// not on per-line edits. Saves go straight through.const update = await client.from("stockTransferLine")diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsxindex 6e5fc4fd47..e7e92c56b6 100644--- a/apps/erp/app/routes/x+/stock-transfer+/new.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx@@ -2,10 +2,7 @@ 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/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";@@ -38,7 +35,7 @@ export async function action({ request }: ActionFunctionArgs) {const { locationId, lines } = validation.data;const acknowledged = formData.get("acknowledged") === "true";- // Item Rule pre-flight. Create-Transfer auto-releases (insert sets+ // Storage Rule pre-flight. Create-Transfer auto-releases (insert sets// status="Released"), so this is the gate where rules must fire before// any stock-moving is started. Evaluate against the destination side// (`toStorageUnitId`) — that's where stock will land.diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsxindex 708cd4d37d..1e262714e0 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx@@ -1,7 +1,11 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";+import {+ getSalesRuleAssignmentsForItem,+ getSalesRulesList+} from "@carbon/ee/rules";+import { getStorageRulesDataForTarget } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import { VStack } from "@carbon/react";import { pluckUnique } from "@carbon/utils";@@ -13,6 +17,7 @@ import {getTrackedEntityExpirations,InventoryDetails} from "~/modules/inventory";+import RuleAssignmentsList from "~/modules/inventory/ui/StorageRules/RuleAssignmentsList";import type { ToolSummary, UnitOfMeasureListItem } from "~/modules/items";import {getBomHasShelfLifeManagedInput,@@ -27,7 +32,7 @@ import {} from "~/modules/items";import { PickMethodForm } from "~/modules/items/ui/Item";import { getLocationsList } from "~/modules/resources";-import RuleAssignmentsList from "~/modules/storage-rules/ui/RuleAssignmentsList";+import { SalesRuleAssignmentsList } from "~/modules/sales/ui/SalesRules";import { getUserDefaults } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";import { useItems } from "~/stores/items";@@ -149,7 +154,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shelfLife,bomHasShelfLifeManagedInput,trackedEntityExpirations,- rulesData+ rulesData,+ salesRuleAssignments,+ salesRuleLibrary] = await Promise.all([getItemShelfLife(client, itemId),getBomHasShelfLifeManagedInput(client, itemId, companyId),@@ -158,7 +165,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {targetType: "item",targetId: itemId,companyId- })+ }),+ getSalesRuleAssignmentsForItem(client, { itemId, companyId }),+ getSalesRulesList(client, companyId)]);return {@@ -171,7 +180,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemId,locationId,ruleAssignments: rulesData.assignments,- ruleLibrary: rulesData.library+ ruleLibrary: rulesData.library,+ salesRuleAssignments: salesRuleAssignments.data ?? [],+ salesRuleLibrary: salesRuleLibrary.data ?? []};}@@ -246,7 +257,9 @@ export default function ToolInventoryRoute() {trackedEntityExpirations,itemId,ruleAssignments,- ruleLibrary+ ruleLibrary,+ salesRuleAssignments,+ salesRuleLibrary} = useLoaderData<typeof loader>();const toolData = useRouteData<{@@ -303,6 +316,11 @@ export default function ToolInventoryRoute() {assignments={ruleAssignments as never}library={ruleLibrary as never}/>+ <SalesRuleAssignmentsList+ itemId={itemId}+ assignments={salesRuleAssignments as never}+ library={salesRuleLibrary as never}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsxindex b5fbb4caeb..186d896621 100644--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx@@ -2,10 +2,7 @@ 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 {- evaluateLinesForSurface,- isBlocked-} from "@carbon/ee/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -36,7 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- // Item Rule evaluation at every "go" transition — the user is committing to+ // Storage Rule evaluation at every "go" transition — the user is committing to// the transfer plan. Pre-flight blocks early (before child shipment/receipt// are created). Cancel + Reopen are intentionally excluded — they're not// commits.diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 173d565b15..62de0b4253 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -860,6 +860,8 @@ export const path = {deleteSalesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}/delete`),deleteSalesRfqLine: (id: string, lineId: string) =>generatePath(`${x}/sales-rfq/${id}/${lineId}/delete`),+ deleteSalesRule: (id: string) =>+ generatePath(`${x}/sales/sales-rules/${id}/delete`),deleteSavedView: (id: string) =>generatePath(`${x}/shared/views/delete/${id}`),deleteScrapReason: (id: string) =>@@ -1657,6 +1659,7 @@ export const path = {generatePath(`${x}/sales-return-order/${id}/new`),newSalesRFQ: `${x}/sales-rfq/new`,newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),+ newSalesRule: `${x}/sales/sales-rules/new`,newScrapReason: `${x}/production/scrap-reasons/new`,newSerialNumberSequence: `${x}/settings/serial-numbers/new`,newService: `${x}/service/new`,@@ -2098,6 +2101,12 @@ export const path = {salesRfqRoot: `${x}/sales-rfq`,salesRfqStatus: (id: string) => generatePath(`${x}/sales-rfq/${id}/status`),salesRfqs: `${x}/sales/rfqs`,+ salesRule: (id: string) => generatePath(`${x}/sales/sales-rules/${id}`),+ salesRuleAssign: (itemId: string) =>+ generatePath(`${x}/sales/sales-rules/assign/${itemId}`),+ salesRules: `${x}/sales/sales-rules`,+ salesRuleUnassign: (itemId: string, ruleId: string) =>+ generatePath(`${x}/sales/sales-rules/unassign/${itemId}/${ruleId}`),salesSettings: `${x}/settings/sales`,saveInspectionDocument: (id: string) =>generatePath(`${x}/inspection-document/${id}/save`),diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex 02f89a9acf..1801c60d70 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -195,28 +195,6 @@ export const uomsQuery = (companyId: string | null) => ({staleTime: RefreshRate.Medium});-export const storageRulesQuery = (- companyId: string | null,- targetType?: "item" | "storageUnit" | "workCenter" | null-) => ({- queryKey: ["storageRules", targetType ?? "all", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const storageRuleAssignmentsQuery = (- targetType: "item" | "storageUnit" | "workCenter",- targetId: string,- companyId: string | null-) => ({- queryKey: [- "storageRuleAssignments",- targetType,- targetId,- companyId ?? "null"- ],- staleTime: RefreshRate.Low-});-export const webhookTablesQuery = () => ({queryKey: ["webhookTables"],staleTime: RefreshRate.Neverdiff --git a/apps/erp/test/mcp-upsert-job-material.test.ts b/apps/erp/test/mcp-upsert-job-material.test.tsindex d37dbc7c0b..ffab2b22c2 100644--- a/apps/erp/test/mcp-upsert-job-material.test.ts+++ b/apps/erp/test/mcp-upsert-job-material.test.ts@@ -39,7 +39,7 @@ vi.mock("@carbon/auth", () => ({companyId: string) => Boolean(permissions?.[`${module}_${action}`]?.includes(companyId))}));-vi.mock("@carbon/ee/storage-rules.server", () => ({+vi.mock("@carbon/ee/rules.server", () => ({evaluateLinesForSurface: vi.fn(),isBlocked: vi.fn()}));diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex 0e3d5929fb..422b0bad8f 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -2,10 +2,7 @@ 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/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import {diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsxindex 7703a48fd6..c977b7e643 100644--- a/apps/mes/app/routes/x+/issue.tsx+++ b/apps/mes/app/routes/x+/issue.tsx@@ -2,10 +2,7 @@ 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/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex be5935ca45..3a5d435a31 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -3,10 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { activeJobStatuses } from "@carbon/database";-import {- evaluateLinesForSurface,- isBlocked-} from "@carbon/ee/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";diff --git a/apps/mes/app/routes/x+/unconsume.tsx b/apps/mes/app/routes/x+/unconsume.tsxindex d471a530bb..118f9e6d18 100644--- a/apps/mes/app/routes/x+/unconsume.tsx+++ b/apps/mes/app/routes/x+/unconsume.tsx@@ -1,10 +1,7 @@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/storage-rules.server";+import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";diff --git a/docs/content/docs/reference/meta.json b/docs/content/docs/reference/meta.jsonindex b2bca99bc1..e8d4c81912 100644--- a/docs/content/docs/reference/meta.json+++ b/docs/content/docs/reference/meta.json@@ -21,6 +21,7 @@"quotes","pricing","sales-orders",+ "sales-rules","rmas","customer-portal","approvals",diff --git a/docs/content/docs/reference/sales-rules.mdx b/docs/content/docs/reference/sales-rules.mdxnew file mode 100644index 0000000000..a680690395--- /dev/null+++ b/docs/content/docs/reference/sales-rules.mdx@@ -0,0 +1,151 @@+---+title: Sales rules+plan: Business+description: "Predicate guards on sales documents: block a restricted item with an error, or warn and let the user acknowledge and continue."+---++A **sales rule** is a guard that runs when an item is put on a sales document. It checks the line against a+condition you define and, if the condition fails, either **blocks** the write or **warns** and lets the user+acknowledge and continue. Rules fire on **quote lines**, **<Term>sales order</Term> lines**, and **sales+invoice lines**.++For example, to keep an export-controlled part away from a restricted destination: scope the rule to the+item's group, fire on all three surfaces, and require `customer.location.countryCode` `notIn` your restricted+list. Severity **error**, message `` `{item.id}` cannot ship to this destination``. Add that item to a quote+for a customer in a listed country and the line is stopped with exactly that message.++<Callout type="note">+Sales rules are a **compliance** layer, not a hint. They re-run at every commitment point — finalizing a+quote, converting it to an order, confirming the order, posting the shipment, posting the invoice — so a line+that slipped in through a conversion, an import, or the API is still caught before it matters. A blocked+document writes nothing.+</Callout>++## What a rule checks++Each rule holds a small **condition tree**, a match kind over one or more field/operator/value rows:++- **Match kind**: `all` (every condition must hold), `any` (at least one), or `none` (none may hold).+- **Field**: chosen from a fixed registry: item facts (`item.type`, `item.replenishmentSystem`,+ `item.itemTrackingType`, item custom fields), customer facts (`customer.customerTypeId`,+ `customer.customerStatusId`, customer custom fields), the document's ship-to country+ (`customer.location.countryCode`), and the line's `transaction.quantity`.+- **Operator**: `eq`, `neq`, `in`, `notIn`, `isSet`, `isNotSet`, `gt`, `lt`.++The **message** shown on a violation supports tokens like `` `{item.id}` `` and+`` `{customer.location.countryCode}` ``, so the text can name the offending line. The rule "passes" when its+conditions hold; a violation fires when they don't.++<Callout type="info">+Aside from the `isSet` / `isNotSet` checks, a condition pointing at a field that has **no value** fails as a+*"…is required"* violation. A country rule on an order with no ship-to location fails closed as *"Customer+location is required"* rather than waving the line through. The same applies to a standalone invoice line+with no source order: it has no ship-to, and the bill-to address is never substituted for it.+</Callout>++## Where rules fire++A rule lists the **surfaces** (sales-document line types) it applies to: `quoteLine`, `salesOrderLine`, and+`salesInvoiceLine`. Two kinds of checkpoint run them:++- **Line checks** as a line is created or edited on a quote, sales order, or sales invoice.+- **Document gates** at each commitment point: finalizing a quote, converting a quote to an order (or an RFQ to a quote),+ confirming a sales order, posting its shipment, and posting a sales invoice. The gate re-reads **every**+ line on the document, so it also catches staleness — a rule authored after the line was written, or a+ ship-to that changed.++The ship-to that country rules evaluate is where the goods actually go: a <Term>drop shipment</Term>+overrides the order header's address, and an invoice line converted from a sales order resolves its+destination through that order.++<Callout type="info">+On the customer-facing digital quote page, `error` violations refuse acceptance with a neutral message and+your internal rule text never reaches the customer. `warn` violations are logged for the seller and the+acceptance proceeds — there is no employee present to acknowledge them.+</Callout>++## Block or warn++| Severity | Behavior |+| --- | --- |+| `error` | Blocks the line or document until the condition is satisfied. Cannot be acknowledged past. |+| `warn` | Surfaces the message but lets the user **acknowledge and continue**. |++Both outcomes leave a trail: a blocked write and an acknowledged warning are each recorded as evidence+(rule, document, line, item, who, when), and the people in the **sales rule notification group**+(Settings → Sales) are notified by email.++## Scope and assignment++A rule reaches the lines it applies to in one of two ways:++- **By filter**: scope to **item types** and/or **item groups**, combined with OR or AND. An empty filter+ matches **every** item.+- **By assignment**: pin a rule to a specific item from the **Sales rules** card on that item's Inventory+ page.++Unlike [storage rules](/docs/reference/storage-rules), sales rules always target items — there is no+work-center target.++## Rule fields++<FieldTable>+ <Field name="Name">A unique name for the rule.</Field>+ <Field name="Severity">`error` (block) or `warn` (acknowledge and continue).</Field>+ <Field name="Conditions">The match kind plus the field / operator / value rows.</Field>+ <Field name="Message">Shown on a violation; supports `{token}` interpolation.</Field>+ <Field name="Surfaces">Which sales-document lines the rule fires on.</Field>+ <Field name="Item filters">Item types and/or groups to scope a rule (empty = all items).</Field>+ <Field name="Active">Whether the rule is currently evaluated.</Field>+</FieldTable>++## Where to manage them++Sales rules live in the **Sales** area, under **Sales Rules**. Create, edit, and toggle them there. To attach+an existing rule to a single item, use the **Sales rules** card on the item's Inventory page.++<Callout type="warn">+Sales rules are an **Enterprise** capability, gated to the **Business** plan. On other plans the screen shows+an upgrade prompt and no rules are evaluated.+</Callout>++## Related++<Cards>+ <Card title="Storage rules" href="/docs/reference/storage-rules">+ The sibling rule family: the same condition builder, applied to inventory transactions instead of sales+ documents.+ </Card>+ <Card title="Quotes" href="/docs/reference/quotes">+ The first surface: rules run as quote lines are written and again at finalize and convert.+ </Card>+ <Card title="Sales orders" href="/docs/reference/sales-orders">+ Rules gate order confirmation and the shipment that fulfills it.+ </Card>+ <Card title="Invoices" href="/docs/reference/invoices">+ The last checkpoint: an invoice raised with no upstream order is still checked at post.+ </Card>+</Cards>++<AgentContext>+## Troubleshooting++Sales-rule violations carry **custom, company-authored messages** — there is no fixed error string to match.+If a user pastes an unfamiliar error from saving a quote, sales order, or sales invoice line, or from+finalizing, converting, confirming, or posting one of those documents, and it reads like a business rule+("cannot ship to this destination", "customer status", a country or item named in the text), it is very+likely a sales rule firing.++How to resolve one:+1. Find the rule: **Sales → Sales Rules** — the rule's *Message* column will match the pasted text (token+ values like the item id filled in).+2. If the document is wrong, fix the data the rule checks: the customer's ship-to location, the customer+ type or status, the item on the line.+3. If the rule is wrong or too strict, edit its conditions, change its severity from `error` to `warn`, or+ toggle it off (*Active*).+4. A `warn`-severity violation isn't an error — the user can acknowledge the dialog and resubmit; it goes+ through. Acknowledgments are recorded and the sales rule notification group is emailed.++A violation ending in "…is required" means the rule checked a field that has no value on the line — most+often a missing ship-to location on the document. Supply the value rather than changing the rule.+</AgentContext>diff --git a/docs/content/docs/reference/storage-rules.mdx b/docs/content/docs/reference/storage-rules.mdxindex 9581739eb6..3eaf7edd2c 100644--- a/docs/content/docs/reference/storage-rules.mdx+++ b/docs/content/docs/reference/storage-rules.mdx@@ -94,7 +94,7 @@ A rule reaches the lines it applies to in one of two ways:<Field name="Message">Shown on a violation; supports `{token}` interpolation.</Field><Field name="Surfaces">Which transactions the rule fires on.</Field><Field name="Target">`item` or `workCenter`.</Field>- <Field name="Item filters">Item types and/or groups to scope an item rule (empty = all items).</Field>+ <Field name="Item filters">Item types and/or groups to scope a rule (empty = all items).</Field><Field name="Active">Whether the rule is currently evaluated.</Field></FieldTable>@@ -111,6 +111,10 @@ plans the screen shows an upgrade prompt and no rules are evaluated.## Related<Cards>+ <Card title="Sales rules" href="/docs/reference/sales-rules">+ The sibling rule family: the same condition builder, applied to quote, sales order, and sales invoice+ lines.+ </Card><Card title="Items" href="/docs/reference/items">The most common rule target: scope by item type or group, or assign per item.</Card>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 29031e74a9..3aefd31d57 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -1551,267 +1551,6 @@ export default {tags: ["salesOrderShipment"]}},- "/storageRule": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRule.id"- },- {- $ref: "#/parameters/rowFilter.storageRule.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRule.name"- },- {- $ref: "#/parameters/rowFilter.storageRule.description"- },- {- $ref: "#/parameters/rowFilter.storageRule.message"- },- {- $ref: "#/parameters/rowFilter.storageRule.severity"- },- {- $ref: "#/parameters/rowFilter.storageRule.conditionAst"- },- {- $ref: "#/parameters/rowFilter.storageRule.surfaces"- },- {- $ref: "#/parameters/rowFilter.storageRule.active"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.customFields"- },- {- $ref: "#/parameters/rowFilter.storageRule.targetType"- },- {- $ref: "#/parameters/rowFilter.storageRule.appliesToAll"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemTypes"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemGroupIds"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemMatchAll"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/order"- },- {- $ref: "#/parameters/range"- },- {- $ref: "#/parameters/rangeUnit"- },- {- $ref: "#/parameters/offset"- },- {- $ref: "#/parameters/limit"- },- {- $ref: "#/parameters/preferCount"- }- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/storageRule"- },- type: "array"- }- },- "206": {- description: "Partial Content"- }- },- tags: ["storageRule"]- },- post: {- parameters: [- {- $ref: "#/parameters/body.storageRule"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/preferPost"- }- ],- responses: {- "201": {- description: "Created"- }- },- tags: ["storageRule"]- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRule.id"- },- {- $ref: "#/parameters/rowFilter.storageRule.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRule.name"- },- {- $ref: "#/parameters/rowFilter.storageRule.description"- },- {- $ref: "#/parameters/rowFilter.storageRule.message"- },- {- $ref: "#/parameters/rowFilter.storageRule.severity"- },- {- $ref: "#/parameters/rowFilter.storageRule.conditionAst"- },- {- $ref: "#/parameters/rowFilter.storageRule.surfaces"- },- {- $ref: "#/parameters/rowFilter.storageRule.active"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.customFields"- },- {- $ref: "#/parameters/rowFilter.storageRule.targetType"- },- {- $ref: "#/parameters/rowFilter.storageRule.appliesToAll"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemTypes"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemGroupIds"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemMatchAll"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRule"]- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRule.id"- },- {- $ref: "#/parameters/rowFilter.storageRule.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRule.name"- },- {- $ref: "#/parameters/rowFilter.storageRule.description"- },- {- $ref: "#/parameters/rowFilter.storageRule.message"- },- {- $ref: "#/parameters/rowFilter.storageRule.severity"- },- {- $ref: "#/parameters/rowFilter.storageRule.conditionAst"- },- {- $ref: "#/parameters/rowFilter.storageRule.surfaces"- },- {- $ref: "#/parameters/rowFilter.storageRule.active"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedBy"- },- {- $ref: "#/parameters/rowFilter.storageRule.updatedAt"- },- {- $ref: "#/parameters/rowFilter.storageRule.customFields"- },- {- $ref: "#/parameters/rowFilter.storageRule.targetType"- },- {- $ref: "#/parameters/rowFilter.storageRule.appliesToAll"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemTypes"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemGroupIds"- },- {- $ref: "#/parameters/rowFilter.storageRule.filteredItemMatchAll"- },- {- $ref: "#/parameters/body.storageRule"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRule"]- }- },"/documentLabels": {get: {parameters: [@@ -20763,6 +20502,222 @@ export default {tags: ["jobs"]}},+ "/enforcementRuleAcknowledgment": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleName"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentLineId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.outcome"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.updatedBy"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/enforcementRuleAcknowledgment"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["enforcementRuleAcknowledgment"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.enforcementRuleAcknowledgment"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["enforcementRuleAcknowledgment"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleName"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentLineId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.outcome"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.updatedBy"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRuleAcknowledgment"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.ruleName"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.documentLineId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.outcome"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleAcknowledgment.updatedBy"+ },+ {+ $ref: "#/parameters/body.enforcementRuleAcknowledgment"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRuleAcknowledgment"]+ }+ },"/itemSerialSequences": {get: {parameters: [@@ -26226,6 +26181,150 @@ export default {tags: ["workCenters"]}},+ "/enforcementRuleWorkCenterAssignment": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.workCenterId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.updatedBy"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/enforcementRuleWorkCenterAssignment"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["enforcementRuleWorkCenterAssignment"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.enforcementRuleWorkCenterAssignment"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["enforcementRuleWorkCenterAssignment"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.workCenterId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.updatedBy"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRuleWorkCenterAssignment"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.workCenterId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleWorkCenterAssignment.updatedBy"+ },+ {+ $ref: "#/parameters/body.enforcementRuleWorkCenterAssignment"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRuleWorkCenterAssignment"]+ }+ },"/contractorAbility": {get: {parameters: [@@ -48379,34 +48478,178 @@ export default {},tags: ["supplierContact"]},- patch: {+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.supplierContact.id"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.supplierId"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.contactId"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.supplierLocationId"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.userId"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.customFields"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.tags"+ },+ {+ $ref: "#/parameters/rowFilter.supplierContact.companyId"+ },+ {+ $ref: "#/parameters/body.supplierContact"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["supplierContact"]+ }+ },+ "/enforcementRuleItemAssignment": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.updatedBy"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/enforcementRuleItemAssignment"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["enforcementRuleItemAssignment"]+ },+ post: {parameters: [{- $ref: "#/parameters/rowFilter.supplierContact.id"+ $ref: "#/parameters/body.enforcementRuleItemAssignment"},{- $ref: "#/parameters/rowFilter.supplierContact.supplierId"+ $ref: "#/parameters/select"},{- $ref: "#/parameters/rowFilter.supplierContact.contactId"+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["enforcementRuleItemAssignment"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.itemId"},{- $ref: "#/parameters/rowFilter.supplierContact.supplierLocationId"+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.ruleId"},{- $ref: "#/parameters/rowFilter.supplierContact.userId"+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.companyId"},{- $ref: "#/parameters/rowFilter.supplierContact.customFields"+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdBy"},{- $ref: "#/parameters/rowFilter.supplierContact.tags"+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdAt"},{- $ref: "#/parameters/rowFilter.supplierContact.companyId"+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.updatedBy"},{- $ref: "#/parameters/body.supplierContact"+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRuleItemAssignment"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.ruleId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRuleItemAssignment.updatedBy"+ },+ {+ $ref: "#/parameters/body.enforcementRuleItemAssignment"},{$ref: "#/parameters/preferReturn"@@ -48417,7 +48660,7 @@ export default {description: "No Content"}},- tags: ["supplierContact"]+ tags: ["enforcementRuleItemAssignment"]}},"/oauthClient": {@@ -53784,150 +54027,6 @@ export default {tags: ["companyIntegration"]}},- "/storageRuleWorkCenterAssignment": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.workCenterId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.updatedBy"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/order"- },- {- $ref: "#/parameters/range"- },- {- $ref: "#/parameters/rangeUnit"- },- {- $ref: "#/parameters/offset"- },- {- $ref: "#/parameters/limit"- },- {- $ref: "#/parameters/preferCount"- }- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/storageRuleWorkCenterAssignment"- },- type: "array"- }- },- "206": {- description: "Partial Content"- }- },- tags: ["storageRuleWorkCenterAssignment"]- },- post: {- parameters: [- {- $ref: "#/parameters/body.storageRuleWorkCenterAssignment"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/preferPost"- }- ],- responses: {- "201": {- description: "Created"- }- },- tags: ["storageRuleWorkCenterAssignment"]- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.workCenterId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.updatedBy"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRuleWorkCenterAssignment"]- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.workCenterId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleWorkCenterAssignment.updatedBy"- },- {- $ref: "#/parameters/body.storageRuleWorkCenterAssignment"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRuleWorkCenterAssignment"]- }- },"/salesOrderStatusHistory": {get: {parameters: [@@ -56088,67 +56187,7 @@ export default {description: "OK",schema: {items: {- $ref: "#/definitions/activeMaintenanceDispatchesByLocation"- },- type: "array"- }- },- "206": {- description: "Partial Content"- }- },- tags: ["activeMaintenanceDispatchesByLocation"]- }- },- "/storageRuleItemAssignment": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.itemId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.updatedBy"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/order"- },- {- $ref: "#/parameters/range"- },- {- $ref: "#/parameters/rangeUnit"- },- {- $ref: "#/parameters/offset"- },- {- $ref: "#/parameters/limit"- },- {- $ref: "#/parameters/preferCount"- }- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/storageRuleItemAssignment"+ $ref: "#/definitions/activeMaintenanceDispatchesByLocation"},type: "array"}@@ -56157,91 +56196,7 @@ export default {description: "Partial Content"}},- tags: ["storageRuleItemAssignment"]- },- post: {- parameters: [- {- $ref: "#/parameters/body.storageRuleItemAssignment"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/preferPost"- }- ],- responses: {- "201": {- description: "Created"- }- },- tags: ["storageRuleItemAssignment"]- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.itemId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.updatedBy"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRuleItemAssignment"]- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.itemId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.ruleId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.companyId"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdBy"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.createdAt"- },- {- $ref: "#/parameters/rowFilter.storageRuleItemAssignment.updatedBy"- },- {- $ref: "#/parameters/body.storageRuleItemAssignment"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["storageRuleItemAssignment"]+ tags: ["activeMaintenanceDispatchesByLocation"]}},"/shipmentFixedAssetLine": {@@ -73284,6 +73239,276 @@ export default {tags: ["methodOperationStep"]}},+ "/enforcementRule": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRule.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.family"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.name"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.description"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.conditionAst"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.surfaces"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.targetType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.appliesToAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemTypes"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemGroupIds"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemMatchAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.active"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.customFields"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/enforcementRule"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["enforcementRule"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.enforcementRule"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["enforcementRule"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRule.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.family"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.name"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.description"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.conditionAst"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.surfaces"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.targetType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.appliesToAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemTypes"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemGroupIds"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemMatchAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.active"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.customFields"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRule"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.enforcementRule.id"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.family"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.name"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.description"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.message"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.severity"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.conditionAst"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.surfaces"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.targetType"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.appliesToAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemTypes"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemGroupIds"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.filteredItemMatchAll"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.active"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.updatedAt"+ },+ {+ $ref: "#/parameters/rowFilter.enforcementRule.customFields"+ },+ {+ $ref: "#/parameters/body.enforcementRule"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["enforcementRule"]+ }+ },"/tag": {get: {parameters: [@@ -90561,6 +90786,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -90764,6 +90992,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -90921,6 +91152,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"},+ {+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"+ },{$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"},@@ -105212,125 +105446,6 @@ export default {},type: "object"},- storageRule: {- required: [- "id",- "companyId",- "name",- "message",- "severity",- "conditionAst",- "surfaces",- "active",- "createdBy",- "createdAt",- "targetType",- "appliesToAll",- "filteredItemTypes",- "filteredItemGroupIds",- "filteredItemMatchAll"- ],- properties: {- id: {- default: "public.xid()",- description: "Note:\nThis is a Primary Key.<pk/>",- format: "text",- type: "string"- },- companyId: {- description:- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",- format: "text",- type: "string"- },- name: {- format: "text",- type: "string"- },- description: {- format: "text",- type: "string"- },- message: {- format: "text",- type: "string"- },- severity: {- format: "text",- type: "string"- },- conditionAst: {- format: "jsonb"- },- surfaces: {- format: 'public."transactionSurface"[]',- items: {- type: "string"- },- type: "array"- },- active: {- default: true,- format: "boolean",- type: "boolean"- },- createdBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- },- createdAt: {- default: "now()",- format: "timestamp with time zone",- type: "string"- },- updatedBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- },- updatedAt: {- format: "timestamp with time zone",- type: "string"- },- customFields: {- format: "jsonb"- },- targetType: {- default: "item",- enum: ["item", "workCenter"],- format: 'public."storageRuleTargetType"',- type: "string"- },- appliesToAll: {- default: false,- format: "boolean",- type: "boolean"- },- filteredItemTypes: {- format: "text[]",- items: {- type: "string"- },- type: "array"- },- filteredItemGroupIds: {- format: "text[]",- items: {- type: "string"- },- type: "array"- },- filteredItemMatchAll: {- default: false,- format: "boolean",- type: "boolean"- }- },- type: "object"- },documentLabels: {properties: {label: {@@ -114292,6 +114407,87 @@ export default {},type: "object"},+ enforcementRuleAcknowledgment: {+ required: [+ "id",+ "companyId",+ "documentType",+ "documentId",+ "severity",+ "outcome",+ "message",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id()",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ ruleId: {+ format: "text",+ type: "string"+ },+ ruleName: {+ format: "text",+ type: "string"+ },+ documentType: {+ format: "text",+ type: "string"+ },+ documentId: {+ format: "text",+ type: "string"+ },+ documentLineId: {+ format: "text",+ type: "string"+ },+ itemId: {+ format: "text",+ type: "string"+ },+ severity: {+ format: "text",+ type: "string"+ },+ outcome: {+ format: "text",+ type: "string"+ },+ message: {+ format: "text",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ }+ },+ type: "object"+ },itemSerialSequences: {properties: {id: {@@ -116971,6 +117167,52 @@ export default {},type: "object"},+ enforcementRuleWorkCenterAssignment: {+ required: [+ "workCenterId",+ "ruleId",+ "companyId",+ "createdBy",+ "createdAt"+ ],+ properties: {+ workCenterId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `workCenter.id`.<fk table='workCenter' column='id'/>",+ format: "text",+ type: "string"+ },+ ruleId: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ }+ },+ type: "object"+ },contractorAbility: {required: ["contractorId",@@ -127541,6 +127783,46 @@ export default {},type: "object"},+ enforcementRuleItemAssignment: {+ required: ["itemId", "ruleId", "companyId", "createdBy", "createdAt"],+ properties: {+ itemId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string"+ },+ ruleId: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ }+ },+ type: "object"+ },oauthClient: {required: ["id",@@ -129822,53 +130104,6 @@ export default {},type: "object"},- storageRuleWorkCenterAssignment: {- required: [- "workCenterId",- "ruleId",- "companyId",- "createdBy",- "createdAt"- ],- properties: {- workCenterId: {- description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `workCenter.id`.<fk table='workCenter' column='id'/>",- format: "text",- type: "string"- },- ruleId: {- description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `storageRule.id`.<fk table='storageRule' column='id'/>",- format: "text",- type: "string"- },- companyId: {- description:- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",- format: "text",- type: "string"- },- createdBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- },- createdAt: {- default: "now()",- format: "timestamp with time zone",- type: "string"- },- updatedBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- }- },- type: "object"- },salesOrderStatusHistory: {required: ["id",@@ -130815,47 +131050,6 @@ export default {},type: "object"},- storageRuleItemAssignment: {- required: ["itemId", "ruleId", "companyId", "createdBy", "createdAt"],- properties: {- itemId: {- description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",- format: "text",- type: "string"- },- ruleId: {- description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `storageRule.id`.<fk table='storageRule' column='id'/>",- format: "text",- type: "string"- },- companyId: {- description:- "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",- format: "text",- type: "string"- },- createdBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- },- createdAt: {- default: "now()",- format: "timestamp with time zone",- type: "string"- },- updatedBy: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string"- }- },- type: "object"- },shipmentFixedAssetLine: {required: ["id",@@ -139162,6 +139356,132 @@ export default {},type: "object"},+ enforcementRule: {+ required: [+ "id",+ "companyId",+ "family",+ "name",+ "message",+ "severity",+ "conditionAst",+ "surfaces",+ "targetType",+ "appliesToAll",+ "filteredItemTypes",+ "filteredItemGroupIds",+ "filteredItemMatchAll",+ "active",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id()",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ family: {+ default: "storage",+ enum: ["storage", "sales"],+ format: 'public."enforcementRuleFamily"',+ type: "string"+ },+ name: {+ format: "text",+ type: "string"+ },+ description: {+ format: "text",+ type: "string"+ },+ message: {+ format: "text",+ type: "string"+ },+ severity: {+ format: "text",+ type: "string"+ },+ conditionAst: {+ format: "jsonb"+ },+ surfaces: {+ format: 'public."enforcementRuleSurface"[]',+ items: {+ type: "string"+ },+ type: "array"+ },+ targetType: {+ default: "item",+ enum: ["item", "workCenter"],+ format: 'public."enforcementRuleTargetType"',+ type: "string"+ },+ appliesToAll: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ filteredItemTypes: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ filteredItemGroupIds: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ filteredItemMatchAll: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ active: {+ default: true,+ format: "boolean",+ type: "boolean"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ },+ customFields: {+ format: "jsonb"+ }+ },+ type: "object"+ },tag: {required: ["name", "table", "companyId", "createdAt", "createdBy"],properties: {@@ -147444,6 +147764,7 @@ export default {"incompletePickingListPolicy","includeMaterialsOnTraveler","returnPickedMaterialTiming",+ "salesRuleNotificationGroup","showCurrencyTrailingZeros","requireMfa","allowLowercaseItemIds"@@ -147693,6 +148014,13 @@ export default {format: "text",type: "string"},+ salesRuleNotificationGroup: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },showCurrencyTrailingZeros: {default: true,format: "boolean",@@ -149183,129 +149511,6 @@ export default {in: "query",type: "string"},- "body.storageRule": {- name: "storageRule",- description: "storageRule",- required: false,- in: "body",- schema: {- $ref: "#/definitions/storageRule"- }- },- "rowFilter.storageRule.id": {- name: "id",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.companyId": {- name: "companyId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.name": {- name: "name",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.description": {- name: "description",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.message": {- name: "message",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.severity": {- name: "severity",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.conditionAst": {- name: "conditionAst",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.surfaces": {- name: "surfaces",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.active": {- name: "active",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.createdBy": {- name: "createdBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.createdAt": {- name: "createdAt",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.updatedBy": {- name: "updatedBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.updatedAt": {- name: "updatedAt",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.customFields": {- name: "customFields",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.targetType": {- name: "targetType",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.appliesToAll": {- name: "appliesToAll",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.filteredItemTypes": {- name: "filteredItemTypes",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.filteredItemGroupIds": {- name: "filteredItemGroupIds",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRule.filteredItemMatchAll": {- name: "filteredItemMatchAll",- required: false,- in: "query",- type: "string"- },"body.documentLabels": {name: "documentLabels",description: "documentLabels",@@ -159437,6 +159642,99 @@ export default {in: "query",type: "string"},+ "body.enforcementRuleAcknowledgment": {+ name: "enforcementRuleAcknowledgment",+ description: "enforcementRuleAcknowledgment",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/enforcementRuleAcknowledgment"+ }+ },+ "rowFilter.enforcementRuleAcknowledgment.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.ruleId": {+ name: "ruleId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.ruleName": {+ name: "ruleName",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.documentType": {+ name: "documentType",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.documentId": {+ name: "documentId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.documentLineId": {+ name: "documentLineId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.severity": {+ name: "severity",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.outcome": {+ name: "outcome",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.message": {+ name: "message",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleAcknowledgment.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },"body.itemSerialSequences": {name: "itemSerialSequences",description: "itemSerialSequences",@@ -162454,6 +162752,51 @@ export default {in: "query",type: "string"},+ "body.enforcementRuleWorkCenterAssignment": {+ name: "enforcementRuleWorkCenterAssignment",+ description: "enforcementRuleWorkCenterAssignment",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/enforcementRuleWorkCenterAssignment"+ }+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.workCenterId": {+ name: "workCenterId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.ruleId": {+ name: "ruleId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleWorkCenterAssignment.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },"body.contractorAbility": {name: "contractorAbility",description: "contractorAbility",@@ -174161,6 +174504,51 @@ export default {in: "query",type: "string"},+ "body.enforcementRuleItemAssignment": {+ name: "enforcementRuleItemAssignment",+ description: "enforcementRuleItemAssignment",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/enforcementRuleItemAssignment"+ }+ },+ "rowFilter.enforcementRuleItemAssignment.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleItemAssignment.ruleId": {+ name: "ruleId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleItemAssignment.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleItemAssignment.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleItemAssignment.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRuleItemAssignment.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },"body.oauthClient": {name: "oauthClient",description: "oauthClient",@@ -176742,51 +177130,6 @@ export default {in: "query",type: "string"},- "body.storageRuleWorkCenterAssignment": {- name: "storageRuleWorkCenterAssignment",- description: "storageRuleWorkCenterAssignment",- required: false,- in: "body",- schema: {- $ref: "#/definitions/storageRuleWorkCenterAssignment"- }- },- "rowFilter.storageRuleWorkCenterAssignment.workCenterId": {- name: "workCenterId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleWorkCenterAssignment.ruleId": {- name: "ruleId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleWorkCenterAssignment.companyId": {- name: "companyId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleWorkCenterAssignment.createdBy": {- name: "createdBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleWorkCenterAssignment.createdAt": {- name: "createdAt",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleWorkCenterAssignment.updatedBy": {- name: "updatedBy",- required: false,- in: "query",- type: "string"- },"body.salesOrderStatusHistory": {name: "salesOrderStatusHistory",description: "salesOrderStatusHistory",@@ -177835,51 +178178,6 @@ export default {in: "query",type: "string"},- "body.storageRuleItemAssignment": {- name: "storageRuleItemAssignment",- description: "storageRuleItemAssignment",- required: false,- in: "body",- schema: {- $ref: "#/definitions/storageRuleItemAssignment"- }- },- "rowFilter.storageRuleItemAssignment.itemId": {- name: "itemId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleItemAssignment.ruleId": {- name: "ruleId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleItemAssignment.companyId": {- name: "companyId",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleItemAssignment.createdBy": {- name: "createdBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleItemAssignment.createdAt": {- name: "createdAt",- required: false,- in: "query",- type: "string"- },- "rowFilter.storageRuleItemAssignment.updatedBy": {- name: "updatedBy",- required: false,- in: "query",- type: "string"- },"body.shipmentFixedAssetLine": {name: "shipmentFixedAssetLine",description: "shipmentFixedAssetLine",@@ -187164,6 +187462,135 @@ export default {in: "query",type: "string"},+ "body.enforcementRule": {+ name: "enforcementRule",+ description: "enforcementRule",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/enforcementRule"+ }+ },+ "rowFilter.enforcementRule.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.family": {+ name: "family",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.name": {+ name: "name",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.description": {+ name: "description",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.message": {+ name: "message",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.severity": {+ name: "severity",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.conditionAst": {+ name: "conditionAst",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.surfaces": {+ name: "surfaces",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.targetType": {+ name: "targetType",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.appliesToAll": {+ name: "appliesToAll",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.filteredItemTypes": {+ name: "filteredItemTypes",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.filteredItemGroupIds": {+ name: "filteredItemGroupIds",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.filteredItemMatchAll": {+ name: "filteredItemMatchAll",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.active": {+ name: "active",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.enforcementRule.customFields": {+ name: "customFields",+ required: false,+ in: "query",+ type: "string"+ },"body.tag": {name: "tag",description: "tag",@@ -196583,6 +197010,12 @@ export default {in: "query",type: "string"},+ "rowFilter.companySettings.salesRuleNotificationGroup": {+ name: "salesRuleNotificationGroup",+ required: false,+ in: "query",+ type: "string"+ },"rowFilter.companySettings.showCurrencyTrailingZeros": {name: "showCurrencyTrailingZeros",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 8060cd646c..965e89bea2 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -7419,6 +7419,7 @@ export type Database = {returnPickedMaterialTiming: stringrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]+ salesRuleNotificationGroup: string[]samplingStandard: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize: string | nullshowCurrencyTrailingZeros: boolean@@ -7469,6 +7470,7 @@ export type Database = {returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]+ salesRuleNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize?: string | nullshowCurrencyTrailingZeros?: boolean@@ -7519,6 +7521,7 @@ export type Database = {returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]+ salesRuleNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize?: string | nullshowCurrencyTrailingZeros?: boolean@@ -14019,6 +14022,660 @@ export type Database = {}]}+ enforcementRule: {+ Row: {+ active: boolean+ appliesToAll: boolean+ companyId: string+ conditionAst: Json+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: string | null+ family: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds: string[]+ filteredItemMatchAll: boolean+ filteredItemTypes: string[]+ id: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType: Database["public"]["Enums"]["enforcementRuleTargetType"]+ 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+ family?: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds?: string[]+ filteredItemMatchAll?: boolean+ filteredItemTypes?: string[]+ id?: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"]+ 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+ family?: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds?: string[]+ filteredItemMatchAll?: boolean+ filteredItemTypes?: string[]+ id?: string+ message?: string+ name?: string+ severity?: string+ surfaces?: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleAcknowledgment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ documentId: string+ documentLineId: string | null+ documentType: string+ id: string+ itemId: string | null+ message: string+ outcome: string+ ruleId: string | null+ ruleName: string | null+ severity: string+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ documentId: string+ documentLineId?: string | null+ documentType: string+ id?: string+ itemId?: string | null+ message: string+ outcome: string+ ruleId?: string | null+ ruleName?: string | null+ severity: string+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentId?: string+ documentLineId?: string | null+ documentType?: string+ id?: string+ itemId?: string | null+ message?: string+ outcome?: string+ ruleId?: string | null+ ruleName?: string | null+ severity?: string+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleItemAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ itemId: string+ ruleId: string+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ itemId: string+ ruleId: string+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ itemId?: string+ ruleId?: string+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_rule_fkey"+ columns: ["ruleId", "companyId"]+ isOneToOne: false+ referencedRelation: "enforcementRule"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleWorkCenterAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ updatedBy: string | null+ workCenterId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ updatedBy?: string | null+ workCenterId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ updatedBy?: string | null+ workCenterId?: string+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_rule_fkey"+ columns: ["ruleId", "companyId"]+ isOneToOne: false+ referencedRelation: "enforcementRule"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "riskRegisters"+ referencedColumns: ["workCenterId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenter"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenters"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCentersWithBlockingStatus"+ referencedColumns: ["id"]+ }+ ]+ }eventSystemSubscription: {Row: {active: boolean | null@@ -54905,507 +55562,6 @@ export type Database = {}]}- storageRule: {- Row: {- active: boolean- appliesToAll: boolean- companyId: string- conditionAst: Json- createdAt: string- createdBy: string- customFields: Json | null- description: string | null- filteredItemGroupIds: string[]- filteredItemMatchAll: boolean- filteredItemTypes: string[]- id: string- message: string- name: string- severity: string- surfaces: Database["public"]["Enums"]["transactionSurface"][]- targetType: Database["public"]["Enums"]["storageRuleTargetType"]- 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- filteredItemGroupIds?: string[]- filteredItemMatchAll?: boolean- filteredItemTypes?: string[]- id?: string- message: string- name: string- severity: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- targetType?: Database["public"]["Enums"]["storageRuleTargetType"]- 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- filteredItemGroupIds?: string[]- filteredItemMatchAll?: boolean- filteredItemTypes?: string[]- id?: string- message?: string- name?: string- severity?: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- targetType?: Database["public"]["Enums"]["storageRuleTargetType"]- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- }- ]- }- storageRuleItemAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- itemId: string- ruleId: string- updatedBy: string | null- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- itemId: string- ruleId: string- updatedBy?: string | null- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- itemId?: string- ruleId?: string- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "consumables"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "item"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "materials"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "parts"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "services"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "tools"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "storageRule"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- }- ]- }- storageRuleWorkCenterAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- ruleId: string- updatedBy: string | null- workCenterId: string- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- ruleId: string- updatedBy?: string | null- workCenterId: string- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- ruleId?: string- updatedBy?: string | null- workCenterId?: string- }- Relationships: [- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "storageRule"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "riskRegisters"- referencedColumns: ["workCenterId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCenter"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCenters"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCentersWithBlockingStatus"- referencedColumns: ["id"]- }- ]- }storageType: {Row: {companyId: string@@ -83893,6 +84049,23 @@ export type Database = {| "Model"eliminationKind: "IC Balance" | "IC Revenue"employeeTypeSystemType: "Admin" | "Console Operator"+ enforcementRuleFamily: "storage" | "sales"+ enforcementRuleSurface:+ | "receipt"+ | "shipment"+ | "stockTransfer"+ | "warehouseTransfer"+ | "inventoryAdjustment"+ | "place"+ | "pick"+ | "operationStart"+ | "operationFinish"+ | "materialIssue"+ | "materialReceive"+ | "quoteLine"+ | "salesOrderLine"+ | "salesInvoiceLine"+ enforcementRuleTargetType: "item" | "workCenter"externalLinkDocumentType:| "Quote"| "SupplierQuote"@@ -84370,7 +84543,6 @@ export type Database = {sourcingType: "Specified" | "Drop Ship" | "Ship from Inventory"ssoDomainStatus: "pending" | "verified"stockTransferStatus: "Draft" | "Released" | "In Progress" | "Completed"- storageRuleTargetType: "item" | "workCenter"supersessionMode:| "Consume First"| "Prefer New"@@ -84430,18 +84602,6 @@ export type Database = {| "Numerical"trainingStatus: "Draft" | "Active" | "Archived"trainingType: "Mandatory" | "Optional"- transactionSurface:- | "receipt"- | "shipment"- | "stockTransfer"- | "warehouseTransfer"- | "inventoryAdjustment"- | "place"- | "pick"- | "operationStart"- | "operationFinish"- | "materialIssue"- | "materialReceive"warehouseTransferStatus:| "Draft"| "To Ship and Receive"@@ -85295,6 +85455,24 @@ export const Constants = {],eliminationKind: ["IC Balance", "IC Revenue"],employeeTypeSystemType: ["Admin", "Console Operator"],+ enforcementRuleFamily: ["storage", "sales"],+ enforcementRuleSurface: [+ "receipt",+ "shipment",+ "stockTransfer",+ "warehouseTransfer",+ "inventoryAdjustment",+ "place",+ "pick",+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive",+ "quoteLine",+ "salesOrderLine",+ "salesInvoiceLine",+ ],+ enforcementRuleTargetType: ["item", "workCenter"],externalLinkDocumentType: ["Quote","SupplierQuote",@@ -85816,7 +85994,6 @@ export const Constants = {sourcingType: ["Specified", "Drop Ship", "Ship from Inventory"],ssoDomainStatus: ["pending", "verified"],stockTransferStatus: ["Draft", "Released", "In Progress", "Completed"],- storageRuleTargetType: ["item", "workCenter"],supersessionMode: ["Consume First","Prefer New",@@ -85883,19 +86060,6 @@ export const Constants = {],trainingStatus: ["Draft", "Active", "Archived"],trainingType: ["Mandatory", "Optional"],- transactionSurface: [- "receipt",- "shipment",- "stockTransfer",- "warehouseTransfer",- "inventoryAdjustment",- "place",- "pick",- "operationStart",- "operationFinish",- "materialIssue",- "materialReceive",- ],warehouseTransferStatus: ["Draft","To Ship and Receive",diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 8060cd646c..965e89bea2 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -7419,6 +7419,7 @@ export type Database = {returnPickedMaterialTiming: stringrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]+ salesRuleNotificationGroup: string[]samplingStandard: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize: string | nullshowCurrencyTrailingZeros: boolean@@ -7469,6 +7470,7 @@ export type Database = {returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]+ salesRuleNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize?: string | nullshowCurrencyTrailingZeros?: boolean@@ -7519,6 +7521,7 @@ export type Database = {returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]+ salesRuleNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]shelfLabelSize?: string | nullshowCurrencyTrailingZeros?: boolean@@ -14019,6 +14022,660 @@ export type Database = {}]}+ enforcementRule: {+ Row: {+ active: boolean+ appliesToAll: boolean+ companyId: string+ conditionAst: Json+ createdAt: string+ createdBy: string+ customFields: Json | null+ description: string | null+ family: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds: string[]+ filteredItemMatchAll: boolean+ filteredItemTypes: string[]+ id: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType: Database["public"]["Enums"]["enforcementRuleTargetType"]+ 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+ family?: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds?: string[]+ filteredItemMatchAll?: boolean+ filteredItemTypes?: string[]+ id?: string+ message: string+ name: string+ severity: string+ surfaces: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"]+ 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+ family?: Database["public"]["Enums"]["enforcementRuleFamily"]+ filteredItemGroupIds?: string[]+ filteredItemMatchAll?: boolean+ filteredItemTypes?: string[]+ id?: string+ message?: string+ name?: string+ severity?: string+ surfaces?: Database["public"]["Enums"]["enforcementRuleSurface"][]+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRule_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRule_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleAcknowledgment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ documentId: string+ documentLineId: string | null+ documentType: string+ id: string+ itemId: string | null+ message: string+ outcome: string+ ruleId: string | null+ ruleName: string | null+ severity: string+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ documentId: string+ documentLineId?: string | null+ documentType: string+ id?: string+ itemId?: string | null+ message: string+ outcome: string+ ruleId?: string | null+ ruleName?: string | null+ severity: string+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentId?: string+ documentLineId?: string | null+ documentType?: string+ id?: string+ itemId?: string | null+ message?: string+ outcome?: string+ ruleId?: string | null+ ruleName?: string | null+ severity?: string+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleAcknowledgment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleItemAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ itemId: string+ ruleId: string+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ itemId: string+ ruleId: string+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ itemId?: string+ ruleId?: string+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_rule_fkey"+ columns: ["ruleId", "companyId"]+ isOneToOne: false+ referencedRelation: "enforcementRule"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleItemAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }+ enforcementRuleWorkCenterAssignment: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ ruleId: string+ updatedBy: string | null+ workCenterId: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ ruleId: string+ updatedBy?: string | null+ workCenterId: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ ruleId?: string+ updatedBy?: string | null+ workCenterId?: string+ }+ Relationships: [+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_rule_fkey"+ columns: ["ruleId", "companyId"]+ isOneToOne: false+ referencedRelation: "enforcementRule"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "riskRegisters"+ referencedColumns: ["workCenterId"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenter"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCenters"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "enforcementRuleWorkCenterAssignment_workCenterId_fkey"+ columns: ["workCenterId"]+ isOneToOne: false+ referencedRelation: "workCentersWithBlockingStatus"+ referencedColumns: ["id"]+ }+ ]+ }eventSystemSubscription: {Row: {active: boolean | null@@ -54905,507 +55562,6 @@ export type Database = {}]}- storageRule: {- Row: {- active: boolean- appliesToAll: boolean- companyId: string- conditionAst: Json- createdAt: string- createdBy: string- customFields: Json | null- description: string | null- filteredItemGroupIds: string[]- filteredItemMatchAll: boolean- filteredItemTypes: string[]- id: string- message: string- name: string- severity: string- surfaces: Database["public"]["Enums"]["transactionSurface"][]- targetType: Database["public"]["Enums"]["storageRuleTargetType"]- 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- filteredItemGroupIds?: string[]- filteredItemMatchAll?: boolean- filteredItemTypes?: string[]- id?: string- message: string- name: string- severity: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- targetType?: Database["public"]["Enums"]["storageRuleTargetType"]- 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- filteredItemGroupIds?: string[]- filteredItemMatchAll?: boolean- filteredItemTypes?: string[]- id?: string- message?: string- name?: string- severity?: string- surfaces?: Database["public"]["Enums"]["transactionSurface"][]- targetType?: Database["public"]["Enums"]["storageRuleTargetType"]- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRule_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRule_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- }- ]- }- storageRuleItemAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- itemId: string- ruleId: string- updatedBy: string | null- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- itemId: string- ruleId: string- updatedBy?: string | null- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- itemId?: string- ruleId?: string- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleItemAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "consumables"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "item"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "materials"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "parts"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "services"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_itemId_fkey"- columns: ["itemId"]- isOneToOne: false- referencedRelation: "tools"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "storageRule"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleItemAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- }- ]- }- storageRuleWorkCenterAssignment: {- Row: {- companyId: string- createdAt: string- createdBy: string- ruleId: string- updatedBy: string | null- workCenterId: string- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- ruleId: string- updatedBy?: string | null- workCenterId: string- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- ruleId?: string- updatedBy?: string | null- workCenterId?: string- }- Relationships: [- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_ruleId_fkey"- columns: ["ruleId"]- isOneToOne: false- referencedRelation: "storageRule"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "riskRegisters"- referencedColumns: ["workCenterId"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCenter"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCenters"- referencedColumns: ["id"]- },- {- foreignKeyName: "storageRuleWorkCenterAssignment_workCenterId_fkey"- columns: ["workCenterId"]- isOneToOne: false- referencedRelation: "workCentersWithBlockingStatus"- referencedColumns: ["id"]- }- ]- }storageType: {Row: {companyId: string@@ -83893,6 +84049,23 @@ export type Database = {| "Model"eliminationKind: "IC Balance" | "IC Revenue"employeeTypeSystemType: "Admin" | "Console Operator"+ enforcementRuleFamily: "storage" | "sales"+ enforcementRuleSurface:+ | "receipt"+ | "shipment"+ | "stockTransfer"+ | "warehouseTransfer"+ | "inventoryAdjustment"+ | "place"+ | "pick"+ | "operationStart"+ | "operationFinish"+ | "materialIssue"+ | "materialReceive"+ | "quoteLine"+ | "salesOrderLine"+ | "salesInvoiceLine"+ enforcementRuleTargetType: "item" | "workCenter"externalLinkDocumentType:| "Quote"| "SupplierQuote"@@ -84370,7 +84543,6 @@ export type Database = {sourcingType: "Specified" | "Drop Ship" | "Ship from Inventory"ssoDomainStatus: "pending" | "verified"stockTransferStatus: "Draft" | "Released" | "In Progress" | "Completed"- storageRuleTargetType: "item" | "workCenter"supersessionMode:| "Consume First"| "Prefer New"@@ -84430,18 +84602,6 @@ export type Database = {| "Numerical"trainingStatus: "Draft" | "Active" | "Archived"trainingType: "Mandatory" | "Optional"- transactionSurface:- | "receipt"- | "shipment"- | "stockTransfer"- | "warehouseTransfer"- | "inventoryAdjustment"- | "place"- | "pick"- | "operationStart"- | "operationFinish"- | "materialIssue"- | "materialReceive"warehouseTransferStatus:| "Draft"| "To Ship and Receive"@@ -85295,6 +85455,24 @@ export const Constants = {],eliminationKind: ["IC Balance", "IC Revenue"],employeeTypeSystemType: ["Admin", "Console Operator"],+ enforcementRuleFamily: ["storage", "sales"],+ enforcementRuleSurface: [+ "receipt",+ "shipment",+ "stockTransfer",+ "warehouseTransfer",+ "inventoryAdjustment",+ "place",+ "pick",+ "operationStart",+ "operationFinish",+ "materialIssue",+ "materialReceive",+ "quoteLine",+ "salesOrderLine",+ "salesInvoiceLine",+ ],+ enforcementRuleTargetType: ["item", "workCenter"],externalLinkDocumentType: ["Quote","SupplierQuote",@@ -85816,7 +85994,6 @@ export const Constants = {sourcingType: ["Specified", "Drop Ship", "Ship from Inventory"],ssoDomainStatus: ["pending", "verified"],stockTransferStatus: ["Draft", "Released", "In Progress", "Completed"],- storageRuleTargetType: ["item", "workCenter"],supersessionMode: ["Consume First","Prefer New",@@ -85883,19 +86060,6 @@ export const Constants = {],trainingStatus: ["Draft", "Active", "Archived"],trainingType: ["Mandatory", "Optional"],- transactionSurface: [- "receipt",- "shipment",- "stockTransfer",- "warehouseTransfer",- "inventoryAdjustment",- "place",- "pick",- "operationStart",- "operationFinish",- "materialIssue",- "materialReceive",- ],warehouseTransferStatus: ["Draft","To Ship and Receive",diff --git a/packages/database/supabase/migrations/20260810221652_sales-rule-notification-group.sql b/packages/database/supabase/migrations/20260810221652_sales-rule-notification-group.sqlnew file mode 100644index 0000000000..edc9e366a6--- /dev/null+++ b/packages/database/supabase/migrations/20260810221652_sales-rule-notification-group.sql@@ -0,0 +1,5 @@+-- Who gets notified when a sales rule violation is blocked or acknowledged on+-- a quote / sales order line. Same shape as the sibling notification-group+-- settings (e.g. "supplierQuoteNotificationGroup").+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "salesRuleNotificationGroup" text[] NOT NULL DEFAULT '{}';diff --git a/packages/database/supabase/migrations/20260817143022_enforcement-rules-table.sql b/packages/database/supabase/migrations/20260817143022_enforcement-rules-table.sqlnew file mode 100644index 0000000000..4cf5cb5887--- /dev/null+++ b/packages/database/supabase/migrations/20260817143022_enforcement-rules-table.sql@@ -0,0 +1,299 @@+-- One rule table for both families: storage rules (warehouse/MES surfaces) and+-- sales rules (sales-document surfaces).+--+-- The two families already share one engine (@carbon/utils rules.ts), one+-- evaluator shape (@carbon/ee/rules) and one violation modal, and their schemas+-- are all but identical — so they share the table too, discriminated by+-- "family". This migration creates that schema; the sibling data migration moves+-- the shipped storage rules onto it and drops their old tables. The sales family+-- is built here directly and never had a table of its own.+--+-- The discriminator is "family". What used to be enforced by the column TYPE+-- (a storage rule could not hold a sales surface because the array was typed+-- "transactionSurface") is now enforced by per-family CHECK constraints — see+-- enforcementRule_storage_surfaces / enforcementRule_sales_surfaces below. That+-- swap is the deliberate cost of the merge.++CREATE TYPE "enforcementRuleFamily" AS ENUM ('storage', 'sales');++-- Spans both families: the 11 warehouse/MES values inherited from the retired+-- "transactionSurface" enum (dropped by the data migration once no column+-- references it) plus the 2 sales-document values.+CREATE TYPE "enforcementRuleSurface" AS ENUM (+ -- storage family+ 'receipt',+ 'shipment',+ 'stockTransfer',+ 'warehouseTransfer',+ 'inventoryAdjustment',+ 'place',+ 'pick',+ 'operationStart',+ 'operationFinish',+ 'materialIssue',+ 'materialReceive',+ -- sales family+ 'quoteLine',+ 'salesOrderLine'+);++-- Same two values ('item', 'workCenter'); only the type name generalizes.+ALTER TYPE "storageRuleTargetType" RENAME TO "enforcementRuleTargetType";++CREATE TABLE "enforcementRule" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "family" "enforcementRuleFamily" NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "message" TEXT NOT NULL, -- violation text, {token} interpolation+ "severity" TEXT NOT NULL CHECK ("severity" IN ('error', 'warn')),+ "conditionAst" JSONB NOT NULL, -- {kind: all|any|none, conditions:[{field,op,value}]}+ "surfaces" "enforcementRuleSurface"[] NOT NULL,+ -- Storage-family shape. Sales rules are always item-target broadcasts, pinned+ -- by the CHECK below, so these keep their storage semantics unchanged.+ "targetType" "enforcementRuleTargetType" NOT NULL DEFAULT 'item',+ "appliesToAll" BOOLEAN NOT NULL DEFAULT FALSE, -- workCenter-target broadcast toggle+ -- Item scoping (both families). Empty arrays = every item.+ "filteredItemTypes" TEXT[] NOT NULL DEFAULT '{}',+ "filteredItemGroupIds" TEXT[] NOT NULL DEFAULT '{}',+ "filteredItemMatchAll" BOOLEAN NOT NULL DEFAULT FALSE, -- false = OR, true = AND across the two dimensions+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "customFields" JSONB,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,++ CONSTRAINT "enforcementRule_surfaces_nonempty" CHECK (array_length("surfaces", 1) >= 1),+ -- A rule may only subscribe to surfaces of its own family. Without these a+ -- storage rule could subscribe to 'quoteLine' and silently never fire.+ CONSTRAINT "enforcementRule_storage_surfaces" CHECK (+ "family" <> 'storage' OR "surfaces" <@ ARRAY[+ 'receipt', 'shipment', 'stockTransfer', 'warehouseTransfer',+ 'inventoryAdjustment', 'place', 'pick', 'operationStart',+ 'operationFinish', 'materialIssue', 'materialReceive'+ ]::"enforcementRuleSurface"[]+ ),+ CONSTRAINT "enforcementRule_sales_surfaces" CHECK (+ "family" <> 'sales' OR "surfaces" <@ ARRAY[+ 'quoteLine', 'salesOrderLine'+ ]::"enforcementRuleSurface"[]+ ),+ -- Sales rules have no work-center target and no appliesToAll broadcast.+ CONSTRAINT "enforcementRule_sales_shape" CHECK (+ "family" <> 'sales' OR ("targetType" = 'item' AND "appliesToAll" = FALSE)+ )+);++-- Name uniqueness is per family: the two source tables allowed the same name in+-- each, so a global (companyId, name) unique would reject valid existing data.+ALTER TABLE "enforcementRule" ADD CONSTRAINT "enforcementRule_companyId_family_name_key"+ UNIQUE ("companyId", "family", "name");++CREATE INDEX "enforcementRule_companyId_idx" ON "enforcementRule" ("companyId");+CREATE INDEX "enforcementRule_createdBy_idx" ON "enforcementRule" ("createdBy");+CREATE INDEX "enforcementRule_companyId_family_active_idx"+ ON "enforcementRule" ("companyId", "family") WHERE "active" = TRUE;+CREATE INDEX "enforcementRule_companyId_targetType_active_idx"+ ON "enforcementRule" ("companyId", "targetType") WHERE "active" = TRUE;++ALTER TABLE "public"."enforcementRule" ENABLE ROW LEVEL SECURITY;++-- Writes are gated by the OWNING FAMILY's module permission, preserving exactly+-- what each source table required: storage → inventory_*, sales → sales_*.+CREATE POLICY "SELECT" ON "public"."enforcementRule"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++CREATE POLICY "INSERT" ON "public"."enforcementRule"+FOR INSERT WITH CHECK (+ ("family" = 'storage' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_create'))::text[]))+ OR+ ("family" = 'sales' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]))+);++-- WITH CHECK mirrors USING so a row cannot be edited into a family the caller+-- lacks permission for (USING alone would only guard the pre-update row).+CREATE POLICY "UPDATE" ON "public"."enforcementRule"+FOR UPDATE USING (+ ("family" = 'storage' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]))+ OR+ ("family" = 'sales' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]))+) WITH CHECK (+ ("family" = 'storage' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_update'))::text[]))+ OR+ ("family" = 'sales' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]))+);++CREATE POLICY "DELETE" ON "public"."enforcementRule"+FOR DELETE USING (+ ("family" = 'storage' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('inventory_delete'))::text[]))+ OR+ ("family" = 'sales' AND "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]))+);++-- Item pins for BOTH families (absorbs storageRuleItemAssignment; the sales+-- family writes here directly). Kept as a real table with a real FK to "item" rather+-- than a polymorphic targetId, so ON DELETE CASCADE still cleans up pins when+-- an item is deleted.+CREATE TABLE "enforcementRuleItemAssignment" (+ "itemId" TEXT NOT NULL REFERENCES "item"("id") ON DELETE CASCADE,+ "ruleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),++ CONSTRAINT "enforcementRuleItemAssignment_pkey" PRIMARY KEY ("itemId", "ruleId"),+ CONSTRAINT "enforcementRuleItemAssignment_rule_fkey" FOREIGN KEY ("ruleId", "companyId")+ REFERENCES "enforcementRule"("id", "companyId") ON DELETE CASCADE+);++CREATE INDEX "enforcementRuleItemAssignment_itemId_idx" ON "enforcementRuleItemAssignment" ("itemId");+CREATE INDEX "enforcementRuleItemAssignment_ruleId_idx" ON "enforcementRuleItemAssignment" ("ruleId");+CREATE INDEX "enforcementRuleItemAssignment_companyId_idx" ON "enforcementRuleItemAssignment" ("companyId");+CREATE INDEX "enforcementRuleItemAssignment_itemId_companyId_idx" ON "enforcementRuleItemAssignment" ("itemId", "companyId");+CREATE INDEX "enforcementRuleItemAssignment_createdBy_idx" ON "enforcementRuleItemAssignment" ("createdBy");++ALTER TABLE "public"."enforcementRuleItemAssignment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."enforcementRuleItemAssignment"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++-- One table now holds pins for two families whose source tables required+-- DIFFERENT permissions (storage item pins: parts_*; sales pins: sales_*).+-- The EXISTS resolves the pinned rule's family and applies that family's+-- permission, so the merge changes no caller's authorization.+--+-- The outer row is qualified by table name on purpose. An unqualified+-- "companyId" inside the subquery binds to the INNER table (r), turning the+-- tenant correlation into r."companyId" = r."companyId" — always true. Note+-- "ruleId" needs no qualification because enforcementRule has no such column,+-- which is exactly what makes the mistake hard to see.+CREATE POLICY "INSERT" ON "public"."enforcementRuleItemAssignment"+FOR INSERT WITH CHECK (+ EXISTS (+ SELECT 1 FROM "enforcementRule" r+ WHERE r."id" = "ruleId" AND r."companyId" = "enforcementRuleItemAssignment"."companyId"+ AND (+ (r."family" = 'storage' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[]))+ OR+ (r."family" = 'sales' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]))+ )+ )+);++CREATE POLICY "UPDATE" ON "public"."enforcementRuleItemAssignment"+FOR UPDATE USING (+ EXISTS (+ SELECT 1 FROM "enforcementRule" r+ WHERE r."id" = "ruleId" AND r."companyId" = "enforcementRuleItemAssignment"."companyId"+ AND (+ (r."family" = 'storage' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[]))+ OR+ (r."family" = 'sales' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]))+ )+ )+);++CREATE POLICY "DELETE" ON "public"."enforcementRuleItemAssignment"+FOR DELETE USING (+ EXISTS (+ SELECT 1 FROM "enforcementRule" r+ WHERE r."id" = "ruleId" AND r."companyId" = "enforcementRuleItemAssignment"."companyId"+ AND (+ (r."family" = 'storage' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[]))+ OR+ (r."family" = 'sales' AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]))+ )+ )+);++-- Work-center pins are storage-family only; permissions unchanged (resources_*).+CREATE TABLE "enforcementRuleWorkCenterAssignment" (+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,+ "ruleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),++ CONSTRAINT "enforcementRuleWorkCenterAssignment_pkey" PRIMARY KEY ("workCenterId", "ruleId"),+ CONSTRAINT "enforcementRuleWorkCenterAssignment_rule_fkey" FOREIGN KEY ("ruleId", "companyId")+ REFERENCES "enforcementRule"("id", "companyId") ON DELETE CASCADE+);++CREATE INDEX "enforcementRuleWorkCenterAssignment_workCenterId_idx" ON "enforcementRuleWorkCenterAssignment" ("workCenterId");+CREATE INDEX "enforcementRuleWorkCenterAssignment_ruleId_idx" ON "enforcementRuleWorkCenterAssignment" ("ruleId");+CREATE INDEX "enforcementRuleWorkCenterAssignment_companyId_idx" ON "enforcementRuleWorkCenterAssignment" ("companyId");+CREATE INDEX "enforcementRuleWorkCenterAssignment_workCenterId_companyId_idx" ON "enforcementRuleWorkCenterAssignment" ("workCenterId", "companyId");+CREATE INDEX "enforcementRuleWorkCenterAssignment_createdBy_idx" ON "enforcementRuleWorkCenterAssignment" ("createdBy");++ALTER TABLE "public"."enforcementRuleWorkCenterAssignment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."enforcementRuleWorkCenterAssignment"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++CREATE POLICY "INSERT" ON "public"."enforcementRuleWorkCenterAssignment"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."enforcementRuleWorkCenterAssignment"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])+);++CREATE POLICY "DELETE" ON "public"."enforcementRuleWorkCenterAssignment"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[])+);++-- Append-only override/block evidence. Sales-family only today (storage rules+-- persist no evidence); "documentType" widens if that changes.+CREATE TABLE "enforcementRuleAcknowledgment" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "ruleId" TEXT, -- deliberate SOFT reference (no FK)+ "ruleName" TEXT, -- denormalized: evidence survives rename/delete+ "documentType" TEXT NOT NULL CHECK ("documentType" IN ('quote', 'salesOrder')),+ "documentId" TEXT NOT NULL,+ "documentLineId" TEXT,+ "itemId" TEXT,+ "severity" TEXT NOT NULL CHECK ("severity" IN ('error', 'warn')),+ "outcome" TEXT NOT NULL CHECK ("outcome" IN ('blocked', 'acknowledged')),+ "message" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX "enforcementRuleAcknowledgment_companyId_idx" ON "enforcementRuleAcknowledgment" ("companyId");+CREATE INDEX "enforcementRuleAcknowledgment_ruleId_idx" ON "enforcementRuleAcknowledgment" ("ruleId");+CREATE INDEX "enforcementRuleAcknowledgment_document_idx" ON "enforcementRuleAcknowledgment" ("documentType", "documentId");+CREATE INDEX "enforcementRuleAcknowledgment_createdBy_idx" ON "enforcementRuleAcknowledgment" ("createdBy");++ALTER TABLE "public"."enforcementRuleAcknowledgment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."enforcementRuleAcknowledgment"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++-- Append-only: INSERT only, no UPDATE/DELETE policies.+CREATE POLICY "INSERT" ON "public"."enforcementRuleAcknowledgment"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[])+);diff --git a/packages/database/supabase/migrations/20260817143512_migrate-storage-rules-into-enforcement-rules.sql b/packages/database/supabase/migrations/20260817143512_migrate-storage-rules-into-enforcement-rules.sqlnew file mode 100644index 0000000000..21cd94096b--- /dev/null+++ b/packages/database/supabase/migrations/20260817143512_migrate-storage-rules-into-enforcement-rules.sql@@ -0,0 +1,69 @@+-- Move the shipped storage rules into "enforcementRule", then drop the old+-- tables and the now-unreferenced "transactionSurface" enum.+--+-- Storage is the only family with data to move: the sales family is built+-- directly on "enforcementRule" and has never had a table of its own.+--+-- Ordering matters: rules before assignments (composite FK), and the enum only+-- after every column that used it is gone.+--+-- Every INSERT is ON CONFLICT DO NOTHING so a partial re-run is a no-op.++-- 1. Rules ------------------------------------------------------------------++-- storage: "surfaces" round-trips through text[] because the source array is+-- typed "transactionSurface"; every value exists in the new enum by name.+-- The filteredItem* trio is nullable on storageRule (added in a later migration+-- than the table) and NOT NULL on the merged table, hence the COALESCEs.+INSERT INTO "enforcementRule" (+ "id", "companyId", "family", "name", "description", "message", "severity",+ "conditionAst", "surfaces", "targetType", "appliesToAll",+ "filteredItemTypes", "filteredItemGroupIds", "filteredItemMatchAll",+ "active", "createdBy", "createdAt", "updatedBy", "updatedAt", "customFields"+)+SELECT+ "id", "companyId", 'storage'::"enforcementRuleFamily", "name", "description",+ "message", "severity", "conditionAst",+ "surfaces"::text[]::"enforcementRuleSurface"[],+ "targetType", "appliesToAll",+ COALESCE("filteredItemTypes", '{}'), COALESCE("filteredItemGroupIds", '{}'),+ COALESCE("filteredItemMatchAll", FALSE),+ "active", "createdBy", "createdAt", "updatedBy", "updatedAt", "customFields"+FROM "storageRule"+ON CONFLICT DO NOTHING;+++-- 2. Assignments ------------------------------------------------------------++-- Storage item pins move into the shared pin table (sales pins are written+-- directly there by the sales feature; there is nothing to migrate for them).+INSERT INTO "enforcementRuleItemAssignment" ("itemId", "ruleId", "companyId", "createdBy", "createdAt", "updatedBy")+SELECT "itemId", "ruleId", "companyId", "createdBy", "createdAt", "updatedBy"+FROM "storageRuleItemAssignment"+ON CONFLICT DO NOTHING;+++INSERT INTO "enforcementRuleWorkCenterAssignment" ("workCenterId", "ruleId", "companyId", "createdBy", "createdAt", "updatedBy")+SELECT "workCenterId", "ruleId", "companyId", "createdBy", "createdAt", "updatedBy"+FROM "storageRuleWorkCenterAssignment"+ON CONFLICT DO NOTHING;+++-- 3. Custom fields ----------------------------------------------------------++-- "customField"."table" has an FK to "customFieldTable"."table" with ON UPDATE+-- CASCADE, so renaming the registry row carries every company's storage-rule+-- custom-field definitions (and the values already stored in the rows'+-- "customFields" JSONB) across automatically.+UPDATE "customFieldTable"+SET "table" = 'enforcementRule', "name" = 'Rule'+WHERE "table" = 'storageRule';+++-- 4. Drop the old schema ----------------------------------------------------++DROP TABLE "storageRuleItemAssignment";+DROP TABLE "storageRuleWorkCenterAssignment";+DROP TABLE "storageRule";++DROP TYPE "transactionSurface";diff --git a/packages/database/supabase/migrations/20260825202127_sales-invoice-rule-surface.sql b/packages/database/supabase/migrations/20260825202127_sales-invoice-rule-surface.sqlnew file mode 100644index 0000000000..9c78b6a20a--- /dev/null+++ b/packages/database/supabase/migrations/20260825202127_sales-invoice-rule-surface.sql@@ -0,0 +1,8 @@+-- Third sales-family surface: sales invoice lines. An invoice can be raised+-- with no upstream quote or order, so without this surface a restricted item+-- invoiced directly reaches revenue having passed no gate.+--+-- ALTER TYPE ... ADD VALUE cannot be used by other statements in the same+-- transaction, so the CHECK-constraint widening lives in the follow-up+-- migration (sales-invoice-rule-enforcement).+ALTER TYPE "enforcementRuleSurface" ADD VALUE IF NOT EXISTS 'salesInvoiceLine';diff --git a/packages/database/supabase/migrations/20260825202129_sales-invoice-rule-enforcement.sql b/packages/database/supabase/migrations/20260825202129_sales-invoice-rule-enforcement.sqlnew file mode 100644index 0000000000..f64c2da96b--- /dev/null+++ b/packages/database/supabase/migrations/20260825202129_sales-invoice-rule-enforcement.sql@@ -0,0 +1,24 @@+-- Widen the two CHECK constraints that pin the sales family to its surfaces+-- and the acknowledgment evidence to its document types, now that the+-- 'salesInvoiceLine' enum value exists (added by the previous migration —+-- it cannot be referenced in the same transaction that adds it).++ALTER TABLE "enforcementRule"+ DROP CONSTRAINT IF EXISTS "enforcementRule_sales_surfaces";++ALTER TABLE "enforcementRule"+ ADD CONSTRAINT "enforcementRule_sales_surfaces" CHECK (+ "family" <> 'sales' OR "surfaces" <@ ARRAY[+ 'quoteLine', 'salesOrderLine', 'salesInvoiceLine'+ ]::"enforcementRuleSurface"[]+ );++-- The inline column CHECK gets an auto-generated name; re-add it named so the+-- next widening doesn't have to guess.+ALTER TABLE "enforcementRuleAcknowledgment"+ DROP CONSTRAINT IF EXISTS "enforcementRuleAcknowledgment_documentType_check";++ALTER TABLE "enforcementRuleAcknowledgment"+ ADD CONSTRAINT "enforcementRuleAcknowledgment_documentType_check" CHECK (+ "documentType" IN ('quote', 'salesOrder', 'salesInvoice')+ );diff --git a/packages/database/supabase/migrations/20260917213637_enforcement-rule-restore-and-wc-pin-hardening.sql b/packages/database/supabase/migrations/20260917213637_enforcement-rule-restore-and-wc-pin-hardening.sqlnew file mode 100644index 0000000000..205fa20e1c--- /dev/null+++ b/packages/database/supabase/migrations/20260917213637_enforcement-rule-restore-and-wc-pin-hardening.sql@@ -0,0 +1,44 @@+-- Two hardenings from the sales-rules self-review.++-- 1. Old backups must keep restoring. The storageRule* tables were dropped and+-- their rows moved into "enforcementRule" (20260817143512); TABLE_RENAMES in+-- @carbon/jobs maps the old backup table names onto the new ones. A backup+-- row from before the merge has no "family" column, so the merged table+-- needs a default for the restore load to fill — and 'storage' is by+-- definition what every pre-merge row was. App code always sets the column+-- explicitly; the default exists only for this load path.+ALTER TABLE "enforcementRule" ALTER COLUMN "family" SET DEFAULT 'storage';++-- 2. Work-center pins may only point at a workCenter-target storage rule.+-- The item-pin policies already resolve the pinned rule's family through an+-- EXISTS; the work-center policies did not, so a resources_create holder+-- could pin a sales rule (or an item-target storage rule) to a work center+-- through PostgREST — an orphan row the evaluator ignores, but a lie in the+-- admin UI's counts. The correlation is qualified by table name on purpose:+-- an unqualified "companyId" binds to the inner rule table and turns the+-- tenant check into a tautology.+DROP POLICY "INSERT" ON "public"."enforcementRuleWorkCenterAssignment";+CREATE POLICY "INSERT" ON "public"."enforcementRuleWorkCenterAssignment"+FOR INSERT WITH CHECK (+ EXISTS (+ SELECT 1 FROM "enforcementRule" r+ WHERE r."id" = "ruleId"+ AND r."companyId" = "enforcementRuleWorkCenterAssignment"."companyId"+ AND r."family" = 'storage'+ AND r."targetType" = 'workCenter'+ AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[])+ )+);++DROP POLICY "UPDATE" ON "public"."enforcementRuleWorkCenterAssignment";+CREATE POLICY "UPDATE" ON "public"."enforcementRuleWorkCenterAssignment"+FOR UPDATE USING (+ EXISTS (+ SELECT 1 FROM "enforcementRule" r+ WHERE r."id" = "ruleId"+ AND r."companyId" = "enforcementRuleWorkCenterAssignment"."companyId"+ AND r."family" = 'storage'+ AND r."targetType" = 'workCenter'+ AND r."companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])+ )+);diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 3faf79e934..0d5fedfb93 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -1,6 +1,6 @@# @carbon/ee-Enterprise edition — integrations registry, accounting sync (Xero, QuickBooks Online, Rillet), plan gating, Slack, email, Jira, Linear, Onshape, storage rules, the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)+Enterprise edition — integrations registry, accounting sync (Xero, QuickBooks Online, Rillet), plan gating, Slack, email, Jira, Linear, Onshape, the shared rules layer (storage + sales rules), the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)## Always@@ -42,7 +42,7 @@ pnpm --filter @carbon/ee typecheck # tsgo --noEmit- **Rillet contact import**: the `actions` entry in `src/rillet/config.tsx` posts to `/api/integrations/rillet/import-contacts`, which fires `rillet-import-contacts` (`@carbon/jobs`). It is the only on-demand PULL of master data — `buildRilletSyncConfig` still forces customer/vendor `push-to-accounting`, and the job enqueues `pull-from-accounting` ledger rows by hand. `RilletCustomerSyncer`/`RilletVendorSyncer` implement `mapToLocal`/`upsertLocal` for it and extend `RilletEntitySyncer`; the pull rejections now live in `RilletPushOnlyEntitySyncer` (item + every transaction syncer). Importing exists to write the mapping row: `upsertRemote` reads `getRemoteId(localId)` first, so a Carbon sales invoice for an imported customer PUTs the original Rillet customer instead of creating a duplicate- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`-- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.+- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./rules` (client-safe storage + sales rule services/UI), `./rules.server` (both evaluators), `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.## Cross-Referencesdiff --git a/packages/ee/package.json b/packages/ee/package.jsonindex a9e9583fa8..825d9c33ab 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -8,8 +8,8 @@"./planning": "./src/planning/index.ts","./integrations/secrets": "./src/integrations/secrets.ts","./action-task-entity": "./src/lib/actionTaskEntity.ts",- "./storage-rules": "./src/storage-rules/index.ts",- "./storage-rules.server": "./src/storage-rules/server.ts",+ "./rules": "./src/rules/index.ts",+ "./rules.server": "./src/rules/server.ts","./jira": "./src/jira/lib/index.ts","./jira.server": "./src/jira/lib/index.server.ts","./linear": "./src/linear/lib/index.ts",diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.tsindex 38a0f9f7b5..06e48e22a2 100644--- a/packages/ee/src/plan.server.ts+++ b/packages/ee/src/plan.server.ts@@ -2,6 +2,7 @@ import { CarbonEdition, error, STRIPE_BYPASS_COMPANY_IDS } from "@carbon/auth";import { isCarbonOwnedCompany } from "@carbon/auth/company.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";+import { getLogger } from "@carbon/logger";import { Edition, normalizePlanId, Plan } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { redirect } from "react-router";@@ -12,6 +13,8 @@ import {resolveRequirement} from "./plan";+const logger = getLogger("ee", "plan");+function isBypassCompany(companyId: string): boolean {if (!STRIPE_BYPASS_COMPANY_IDS) return false;return STRIPE_BYPASS_COMPANY_IDS.split(",")@@ -23,12 +26,21 @@ async function getCompanyPlan(client: SupabaseClient<Database>,companyId: string): Promise<Plan> {- const { data } = await client+ const { data, error: planError } = await client.from("companyPlan").select("planId").eq("id", companyId).single();+ // A read error normalizes to the lowest plan, which turns plan-gated+ // ENFORCEMENT (storage/sales rules) off — fail-open. Callers are UI gates+ // and evaluators that should not 500 on a transient blip, so log rather+ // than throw; the signal is what was missing when this silently disabled+ // rules.+ if (planError) {+ logger.error("getCompanyPlan failed", { companyId, error: planError });+ }+return normalizePlanId(data?.planId);}diff --git a/packages/ee/src/plan.ts b/packages/ee/src/plan.tsindex d89b4371d6..f5bbf14087 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, Plan.Partner],+ SALES_RULES: [Plan.Business, Plan.Partner],AUDIT_LOG: [Plan.Business, Plan.Partner],EMAIL_NOTIFICATIONS: [Plan.Business, Plan.Partner],STORAGE_RULES: [Plan.Business, Plan.Partner],diff --git a/packages/ee/src/rules/family-isolation.test.ts b/packages/ee/src/rules/family-isolation.test.tsnew file mode 100644index 0000000000..329e9bb7d4--- /dev/null+++ b/packages/ee/src/rules/family-isolation.test.ts@@ -0,0 +1,215 @@+// Cross-family isolation for the merged "enforcementRule" table.+//+// Storage and sales rules used to live in separate tables with separate pin+// tables, so leakage between the families was structurally impossible. After+// the merge they share `enforcementRule` AND `enforcementRuleItemAssignment`,+// so isolation is now a property of the queries: every read filters on+// `family`, and pin rows are resolved against a family-filtered rule set rather+// than an embed (an embed would happily return the other family's rule).+//+// These tests drive the real service functions against a fake PostgREST client+// that records the filters applied, so a future edit that drops an `.eq("family",+// …)` — or reintroduces an embed on the shared pin table — fails here.++import { describe, expect, it } from "vitest";+import { getActiveSalesRulesForItems } from "./sales/service";+import { getActiveRulesForTargets } from "./storage/service";++type Filter = { col: string; val: unknown };++/**+ * Minimal PostgREST double. Each `.from()` returns a thenable builder that+ * records its filters and resolves to whatever rows the fixture supplies for+ * that table.+ */+function makeClient(rows: Record<string, unknown[]>) {+ const calls: { table: string; filters: Filter[]; select: string }[] = [];++ const client = {+ from(table: string) {+ const filters: Filter[] = [];+ let select = "";+ const builder: Record<string, unknown> = {+ select(cols: string) {+ select = cols;+ calls.push({ table, filters, select });+ return builder;+ },+ eq(col: string, val: unknown) {+ filters.push({ col, val });+ return builder;+ },+ in(col: string, val: unknown) {+ filters.push({ col, val });+ return builder;+ },+ order() {+ return builder;+ },+ then(resolve: (v: { data: unknown[]; error: null }) => unknown) {+ return Promise.resolve({+ data: rows[table] ?? [],+ error: null+ }).then(resolve);+ }+ };+ return builder;+ }+ };++ return { client, calls };+}++const SALES_RULE = {+ id: "rule_sales",+ name: "No export to X",+ severity: "error",+ message: "blocked",+ conditionAst: { kind: "all", conditions: [] },+ surfaces: ["quoteLine"],+ updatedAt: null,+ active: true,+ filteredItemTypes: [],+ filteredItemGroupIds: [],+ filteredItemMatchAll: false+};++describe("enforcementRule family isolation", () => {+ it("scopes the sales rule fetch to the sales family", async () => {+ const { client, calls } = makeClient({ enforcementRule: [SALES_RULE] });++ await getActiveSalesRulesForItems(+ // biome-ignore lint/suspicious/noExplicitAny: test double+ client as any,+ "company_1",+ ["item_1"]+ );++ const ruleCall = calls.find((c) => c.table === "enforcementRule");+ expect(ruleCall).toBeDefined();+ expect(ruleCall?.filters).toContainEqual({ col: "family", val: "sales" });+ expect(ruleCall?.filters).toContainEqual({+ col: "companyId",+ val: "company_1"+ });+ });++ it("drops a pin whose ruleId the family-filtered fetch did not return", async () => {+ // NOTE: the fake serves fixture rows regardless of filters, so this pins+ // only the join-side behavior — that the rule QUERY carries the family+ // filter is pinned by the filter-recording test above.+ // The shared pin table returns a row for a STORAGE rule id. The sales rule+ // fetch never returns that id, so it must not become a sales assignment.+ const { client } = makeClient({+ enforcementRule: [SALES_RULE],+ enforcementRuleItemAssignment: [+ { itemId: "item_1", ruleId: "rule_sales" },+ { itemId: "item_1", ruleId: "rule_storage_pinned_to_same_item" }+ ]+ });++ const { rules, assignmentsByItemId, error } =+ await getActiveSalesRulesForItems(+ // biome-ignore lint/suspicious/noExplicitAny: test double+ client as any,+ "company_1",+ ["item_1"]+ );++ expect(error).toBeNull();+ expect(rules.map((r) => r.id)).toEqual(["rule_sales"]);++ const pinned = assignmentsByItemId.get("item_1");+ expect(pinned).toBeDefined();+ expect([...(pinned ?? [])]).toEqual(["rule_sales"]);+ expect(pinned?.has("rule_storage_pinned_to_same_item")).toBe(false);+ });++ it("reads pins from the shared assignment table", async () => {+ const { client, calls } = makeClient({ enforcementRule: [SALES_RULE] });++ await getActiveSalesRulesForItems(+ // biome-ignore lint/suspicious/noExplicitAny: test double+ client as any,+ "company_1",+ ["item_1"]+ );++ const pinCall = calls.find(+ (c) => c.table === "enforcementRuleItemAssignment"+ );+ expect(pinCall).toBeDefined();+ // No embed on the shared table — it would cross the family boundary.+ expect(pinCall?.select).not.toContain("(");+ });++ // The reverse direction: the storage fetches must be pinned to the storage+ // family the same way. Without these, dropping an `.eq("family", "storage")`+ // in storage/service.ts would only ever be caught in production.++ const STORAGE_RULE = {+ id: "rule_storage",+ targetType: "item",+ severity: "error",+ message: "blocked",+ conditionAst: { kind: "all", conditions: [] },+ surfaces: ["receipt"],+ updatedAt: null,+ active: true,+ filteredItemTypes: [],+ filteredItemGroupIds: [],+ filteredItemMatchAll: false+ };++ it("scopes every storage rule fetch to the storage family", async () => {+ const { client, calls } = makeClient({+ enforcementRule: [STORAGE_RULE],+ enforcementRuleItemAssignment: [+ { itemId: "item_1", ruleId: "rule_storage" }+ ]+ });++ await getActiveRulesForTargets(+ // biome-ignore lint/suspicious/noExplicitAny: test double+ client as any,+ { targetType: "item", targetIds: ["item_1"], companyId: "company_1" }+ );++ const ruleCalls = calls.filter((c) => c.table === "enforcementRule");+ // Broadcast fetch + explicit-pin resolution — both must carry the family.+ expect(ruleCalls.length).toBeGreaterThanOrEqual(2);+ for (const call of ruleCalls) {+ expect(call.filters).toContainEqual({ col: "family", val: "storage" });+ expect(call.filters).toContainEqual({+ col: "companyId",+ val: "company_1"+ });+ }+ });++ it("drops a pin whose ruleId the family-filtered fetch did not return", async () => {+ // NOTE: the fake serves fixture rows regardless of filters, so this pins+ // only the join-side behavior — that the rule QUERY carries the family+ // filter is pinned by the filter-recording test above.+ // The shared pin table returns a row for a SALES rule id. The+ // family-filtered rule fetch never returns that id, so it must not become+ // a storage assignment.+ const { client } = makeClient({+ enforcementRule: [STORAGE_RULE],+ enforcementRuleItemAssignment: [+ { itemId: "item_1", ruleId: "rule_storage" },+ { itemId: "item_1", ruleId: "rule_sales_pinned_to_same_item" }+ ]+ });++ const { data, error } = await getActiveRulesForTargets(+ // biome-ignore lint/suspicious/noExplicitAny: test double+ client as any,+ { targetType: "item", targetIds: ["item_1"], companyId: "company_1" }+ );++ expect(error).toBeNull();+ const assigned = data.get("item_1") ?? [];+ expect(assigned.map((r) => r.id)).toEqual(["rule_storage"]);+ });+});diff --git a/packages/ee/src/rules/index.ts b/packages/ee/src/rules/index.tsnew file mode 100644index 0000000000..5832275ddc--- /dev/null+++ b/packages/ee/src/rules/index.ts@@ -0,0 +1,15 @@+// Public exports for cross-app consumers (ERP + MES). Client-safe only —+// the server evaluators/plan gates live in `./server.ts` and are imported+// via `@carbon/ee/rules.server`.+//+// Covers both rule families sharing the `@carbon/utils` engine:+// - storage rules (`./storage`): warehouse/MES transaction surfaces+// - sales rules (`./sales`): sales-document surfaces+export * from "./sales";+export * from "./storage/context";+export * from "./storage/service";+export {+ type RuleViolationPayload,+ useRuleViolations+} from "./use-violations";+export { default as RuleViolationModal } from "./violation-modal";diff --git a/packages/ee/src/rules/sales/context.test.ts b/packages/ee/src/rules/sales/context.test.tsnew file mode 100644index 0000000000..0af50fda28--- /dev/null+++ b/packages/ee/src/rules/sales/context.test.ts@@ -0,0 +1,152 @@+// Anti-drift contract test for sales rules. Locks the registry (what the+// sales-rule builder offers) to the runtime code path (what+// `buildSalesRuleLineContext` actually populates) per sales-document surface.+//+// If someone adds a field to SALES_RULE_FIELD_REGISTRY (or widens+// `getFieldsForSalesRules`) without populating it in `buildSalesRuleLineContext`+// / the server SELECTs, or edits SALES_RULE_SURFACE_CONTEXT_AVAILABILITY out of+// sync — one of these assertions fails. Mirrors+// `../storage/context.test.ts`.++import {+ buildResolver,+ type FieldContext,+ getFieldsForSalesRuleSurfaces,+ SALES_RULE_SURFACE_CONTEXT_AVAILABILITY,+ SALES_RULE_SURFACES,+ type SalesRuleSurface+} from "@carbon/utils";+import { describe, expect, it } from "vitest";+import {+ buildSalesRuleLineContext,+ type CustomerCtxInput,+ type SalesRuleLineInput+} from "./context";++// Fully-populated rows mirroring the shape `evaluateSalesRuleLines` builds+// AFTER its post-query flattening (itemPostingGroupId off itemCost; readable+// id onto `id`; ship-to country onto `customer.location`). Every+// registry-referenced key is present.+const ITEM_ROW = {+ id: "ITEM-1",+ type: "Part",+ replenishmentSystem: "Buy",+ itemTrackingType: "Inventory",+ itemPostingGroupId: "ipg_1"+};+const CUSTOMER_ROW: CustomerCtxInput = {+ id: "cust_1",+ customerTypeId: "ct_1",+ customerStatusId: "cs_1",+ location: { countryCode: "US" }+};++// Sales-rule FieldContext values map 1:1 onto RuleContext root keys (no+// "storage" → "storageUnit" remap on these surfaces).+const ctxRootKeyFor = (context: FieldContext): string => context;++const lineFor = (): SalesRuleLineInput => ({+ lineId: "line_1",+ itemId: ITEM_ROW.id,+ quantity: 5+});++const ctxFor = (surface: SalesRuleSurface) =>+ buildSalesRuleLineContext({+ line: lineFor(),+ surface,+ userId: "user_1",+ item: ITEM_ROW,+ customer: CUSTOMER_ROW+ });++describe("registry ↔ runtime ctx contract (sales rules)", () => {+ for (const surface of SALES_RULE_SURFACES) {+ it(`every field offered on "${surface}" resolves in the runtime ctx`, () => {+ const ctx = ctxFor(surface);+ const offered = getFieldsForSalesRuleSurfaces([surface]);+ expect(offered.length).toBeGreaterThan(0);+ for (const f of offered) {+ expect(+ buildResolver(f.path)(ctx),+ `"${f.path}" offered on "${surface}" but resolved to undefined`+ ).not.toBeUndefined();+ }+ });++ it(`ctx for "${surface}" populates exactly the declared contexts`, () => {+ const ctx = ctxFor(surface) as Record<string, unknown>;+ for (const context of SALES_RULE_SURFACE_CONTEXT_AVAILABILITY[surface]) {+ expect(+ ctx[ctxRootKeyFor(context)],+ `context "${context}" declared available on "${surface}" but not built`+ ).not.toBeUndefined();+ }+ // No storage/workCenter/operation roots may leak into sales-document+ // surfaces — those contexts belong to the storage-rules evaluator.+ expect(ctx.storageUnit).toBeUndefined();+ expect(ctx.workCenter).toBeUndefined();+ expect(ctx.operation).toBeUndefined();+ });+ }+});++describe("customer location semantics", () => {+ it("missing location yields customer.location === undefined", () => {+ const ctx = buildSalesRuleLineContext({+ line: lineFor(),+ surface: "quoteLine",+ userId: "user_1",+ item: ITEM_ROW,+ customer: { id: "cust_1", customerTypeId: "ct_1" }+ });+ expect((ctx.customer as Record<string, unknown>).location).toBeUndefined();+ // Required-field semantics depend on the path resolving to undefined —+ // an empty-object location would break this.+ expect(buildResolver("customer.location.countryCode")(ctx)).toBeUndefined();+ });++ it("null location normalizes to undefined (never {})", () => {+ const ctx = buildSalesRuleLineContext({+ line: lineFor(),+ surface: "salesOrderLine",+ userId: "user_1",+ item: ITEM_ROW,+ customer: { id: "cust_1", location: null }+ });+ expect((ctx.customer as Record<string, unknown>).location).toBeUndefined();+ });++ it("no customer yields customer === undefined", () => {+ const ctx = buildSalesRuleLineContext({+ line: lineFor(),+ surface: "quoteLine",+ userId: "user_1",+ item: ITEM_ROW+ });+ expect(ctx.customer).toBeUndefined();+ expect(buildResolver("customer.customerTypeId")(ctx)).toBeUndefined();+ });+});++describe("item fallback", () => {+ it("missing item row falls back to id-only ctx so {item.id} tokens resolve", () => {+ const ctx = buildSalesRuleLineContext({+ line: { lineId: "line_1", itemId: "item_x", quantity: 1 },+ surface: "quoteLine",+ userId: "user_1",+ customer: CUSTOMER_ROW+ });+ expect(buildResolver("item.id")(ctx)).toBe("item_x");+ });++ it("line without an item builds no item ctx", () => {+ const ctx = buildSalesRuleLineContext({+ line: { lineId: "line_1", itemId: null, quantity: 1 },+ surface: "salesOrderLine",+ userId: "user_1",+ customer: CUSTOMER_ROW+ });+ expect(ctx.item).toBeUndefined();+ });+});diff --git a/packages/ee/src/rules/sales/context.ts b/packages/ee/src/rules/sales/context.tsnew file mode 100644index 0000000000..991cde7b3b--- /dev/null+++ b/packages/ee/src/rules/sales/context.ts@@ -0,0 +1,75 @@+// Pure RuleContext assembly for sales-rules evaluation (sales-document+// surfaces). Deliberately side-effect-free (no auth/env/DB imports) so the+// registry↔code-path contract can be unit-tested without booting the server+// environment. `server.ts` owns the DB I/O and calls `buildSalesRuleLineContext`+// with the rows it loaded. Mirrors `../storage/context.ts`.++import type { RuleContext, SalesRuleSurface } from "@carbon/utils";++export type SalesRuleLineInput = {+ /** Diagnostic identifier — not used in eval. */+ lineId: string;+ /** Item the sales-document line references. */+ itemId?: string | null;+ /** Quantity for `transaction.quantity` predicates. */+ quantity: number;+};++export type SalesRuleItemCtxRow = Record<string, unknown> & {+ customFields?: Record<string, unknown>;+};++/**+ * Customer context input assembled by `server.ts` from the `customer` row and+ * the resolved ship-to country. `location` MUST stay undefined (never `{}`)+ * when no country is resolvable so `customer.location.countryCode` resolves+ * undefined and required-field semantics fire for rules referencing it.+ */+export type CustomerCtxInput = {+ id: string;+ customerTypeId?: string | null;+ customerStatusId?: string | null;+ customFields?: Record<string, unknown>;+ location?: { countryCode?: string | null } | null;+};++/**+ * Assemble the `RuleContext` for a single sales-document line. Pure — so the+ * registry↔code-path contract (which root contexts get populated per surface)+ * can be unit-tested without a DB client. See the anti-drift test in+ * `context.test.ts` and `SALES_RULE_SURFACE_CONTEXT_AVAILABILITY` in+ * `@carbon/utils`.+ *+ * `item` is the row loaded from the DB (or undefined when the lookup missed);+ * the id-only fallback keeps token interpolation working when a join didn't+ * materialize (RLS, late insert).+ */+export const buildSalesRuleLineContext = (args: {+ line: SalesRuleLineInput;+ surface: SalesRuleSurface;+ userId: string;+ item?: SalesRuleItemCtxRow;+ customer?: CustomerCtxInput;+}): RuleContext => {+ const { line, surface, userId } = args;+ return {+ item: line.itemId ? (args.item ?? { id: line.itemId }) : undefined,+ customer: args.customer+ ? {+ id: args.customer.id,+ customerTypeId: args.customer.customerTypeId,+ customerStatusId: args.customer.customerStatusId,+ customFields: args.customer.customFields,+ // `?? undefined` normalizes null → undefined; NEVER default to `{}`+ // (an empty object would defeat required-field semantics for+ // `customer.location.countryCode`).+ location: args.customer.location ?? undefined+ }+ : undefined,+ transaction: {+ kind: surface,+ quantity: line.quantity,+ userId+ }+ };+};diff --git a/packages/ee/src/rules/sales/index.ts b/packages/ee/src/rules/sales/index.tsnew file mode 100644index 0000000000..d78b03b9a0--- /dev/null+++ b/packages/ee/src/rules/sales/index.ts@@ -0,0 +1,10 @@+// Public exports for cross-app consumers. Client-safe only — `server.ts`+// (evaluator + plan gate) is NOT exported here; import it via+// `@carbon/ee/rules.server`.+export {+ buildSalesRuleLineContext,+ type CustomerCtxInput,+ type SalesRuleItemCtxRow,+ type SalesRuleLineInput+} from "./context";+export * from "./service";diff --git a/packages/ee/src/rules/sales/invoice-shipto.test.ts b/packages/ee/src/rules/sales/invoice-shipto.test.tsnew file mode 100644index 0000000000..25ef93765c--- /dev/null+++ b/packages/ee/src/rules/sales/invoice-shipto.test.ts@@ -0,0 +1,299 @@+// Ship-to resolution for the sales-invoice document gate.+//+// An invoice raised with no upstream document is the bypass this surface+// exists to close: a standalone line has no ship-to and none may be invented,+// so a destination rule must fail CLOSED (required-field violation) rather+// than pass — and must never fall back to the bill-to, which is a different+// address and frequently a different country. An order-derived line resolves+// the real destination through its source order, drop-ship included.+//+// These tests drive the real document evaluator against a fake PostgREST+// client, so a future "fix" that substitutes the bill-to — or reads the order+// header instead of the drop shipment — fails here.++import { describe, expect, it, vi } from "vitest";++vi.mock("../../plan.server", () => ({+ companyHasPlan: async () => true+}));++import { evaluateSalesRulesForSalesDocument } from "./server";++const COMPANY_ID = "co_1";++/**+ * Minimal PostgREST double that APPLIES `.eq()` / `.in()` filters against the+ * fixture rows (the evaluator selects specific rows by id, so recording alone+ * is not enough). Embeds are served by storing the embedded object inline on+ * the fixture row.+ */+function makeClient(rows: Record<string, Record<string, unknown>[]>) {+ return {+ from(table: string) {+ let matched = rows[table] ?? [];+ const builder: any = {+ select: () => builder,+ eq: (col: string, val: unknown) => {+ matched = matched.filter((r) => r[col] === val);+ return builder;+ },+ in: (col: string, vals: unknown[]) => {+ matched = matched.filter((r) => vals.includes(r[col]));+ return builder;+ },+ order: () => builder,+ maybeSingle: async () => ({ data: matched[0] ?? null, error: null }),+ single: async () =>+ matched[0]+ ? { data: matched[0], error: null }+ : { data: null, error: { message: `no row in ${table}` } },+ then: (resolve: (v: unknown) => unknown) =>+ resolve({ data: matched, error: null })+ };+ return builder;+ }+ } as any;+}++// Permitted state: the destination country is NOT embargoed. Shipping to "IR"+// fails the predicate; an unresolvable country trips required-field semantics.+const COUNTRY_RULE = {+ id: "rule_embargo",+ companyId: COMPANY_ID,+ family: "sales",+ name: "Embargoed destinations",+ message: "Cannot sell {item.name} to this destination",+ severity: "error",+ conditionAst: {+ kind: "all",+ conditions: [+ { field: "customer.location.countryCode", op: "notIn", value: ["IR"] }+ ]+ },+ surfaces: ["salesInvoiceLine"],+ targetType: "item",+ appliesToAll: false,+ filteredItemTypes: [],+ filteredItemGroupIds: [],+ filteredItemMatchAll: false,+ active: true,+ updatedAt: "2026-08-26T00:00:00Z"+};++const BASE_ROWS: Record<string, Record<string, unknown>[]> = {+ enforcementRule: [COUNTRY_RULE],+ enforcementRuleItemAssignment: [],+ customer: [+ {+ id: "cust_1",+ companyId: COMPANY_ID,+ customerTypeId: null,+ customerStatusId: null,+ customFields: null+ }+ ],+ customerLocation: [+ { id: "loc_us", companyId: COMPANY_ID, address: { countryCode: "US" } },+ { id: "loc_ir", companyId: COMPANY_ID, address: { countryCode: "IR" } }+ ],+ item: [+ {+ id: "item_1",+ companyId: COMPANY_ID,+ readableIdWithRevision: "WIDGET-1",+ name: "Widget",+ type: "Part",+ replenishmentSystem: "Buy",+ itemTrackingType: "Inventory",+ itemCost: null+ }+ ]+};++function evaluateInvoice(rows: Record<string, Record<string, unknown>[]>) {+ return evaluateSalesRulesForSalesDocument({+ client: makeClient(rows),+ companyId: COMPANY_ID,+ userId: "user_1",+ documentType: "salesInvoice",+ documentId: "inv_1"+ });+}++describe("sales invoice ship-to resolution", () => {+ it("a standalone line fails closed with the required-field violation — never the bill-to", async () => {+ const { violations } = await evaluateInvoice({+ ...BASE_ROWS,+ salesInvoice: [+ {+ id: "inv_1",+ companyId: COMPANY_ID,+ customerId: "cust_1",+ // A safe-country bill-to on the invoice. If someone later "fixes"+ // the missing ship-to by substituting it, the rule clears and this+ // test fails — which is the point.+ invoiceCustomerLocationId: "loc_us"+ }+ ],+ salesInvoiceLine: [+ {+ id: "line_standalone",+ companyId: COMPANY_ID,+ invoiceId: "inv_1",+ itemId: "item_1",+ quantity: 2,+ salesOrderId: null+ }+ ]+ });++ expect(violations).toHaveLength(1);+ expect(violations[0]).toMatchObject({+ ruleId: "rule_embargo",+ severity: "error",+ message: "Customer country is required",+ lineId: "line_standalone"+ });+ });++ it("an order-derived line resolves the ship-to through its source order", async () => {+ const rows = {+ ...BASE_ROWS,+ salesInvoice: [+ { id: "inv_1", companyId: COMPANY_ID, customerId: "cust_1" }+ ],+ salesInvoiceLine: [+ {+ id: "line_so",+ companyId: COMPANY_ID,+ invoiceId: "inv_1",+ itemId: "item_1",+ quantity: 1,+ salesOrderId: "so_1"+ }+ ],+ salesOrder: [+ {+ id: "so_1",+ companyId: COMPANY_ID,+ customerId: "cust_1",+ customerLocationId: "loc_us"+ }+ ],+ salesOrderShipment: []+ };++ // Order ships to a permitted country → no violation.+ expect((await evaluateInvoice(rows)).violations).toEqual([]);++ // Same shape, order ships to the embargoed country → the rule fires with+ // its own message (the country RESOLVED — this is not the required-field+ // path).+ const { violations } = await evaluateInvoice({+ ...rows,+ salesOrder: [+ {+ id: "so_1",+ companyId: COMPANY_ID,+ customerId: "cust_1",+ customerLocationId: "loc_ir"+ }+ ]+ });+ expect(violations).toHaveLength(1);+ expect(violations[0]).toMatchObject({+ ruleId: "rule_embargo",+ message: "Cannot sell Widget to this destination",+ lineId: "line_so"+ });+ });++ it("a drop shipment's destination overrides the order header", async () => {+ const { violations } = await evaluateInvoice({+ ...BASE_ROWS,+ salesInvoice: [+ { id: "inv_1", companyId: COMPANY_ID, customerId: "cust_1" }+ ],+ salesInvoiceLine: [+ {+ id: "line_drop",+ companyId: COMPANY_ID,+ invoiceId: "inv_1",+ itemId: "item_1",+ quantity: 1,+ salesOrderId: "so_1"+ }+ ],+ // Header points at a permitted country; the drop shipment is the real+ // destination and it is embargoed.+ salesOrder: [+ {+ id: "so_1",+ companyId: COMPANY_ID,+ customerId: "cust_1",+ customerLocationId: "loc_us"+ }+ ],+ salesOrderShipment: [+ {+ id: "so_1",+ companyId: COMPANY_ID,+ dropShipment: true,+ customerId: "cust_1",+ customerLocationId: "loc_ir"+ }+ ]+ });++ expect(violations).toHaveLength(1);+ expect(violations[0]).toMatchObject({+ ruleId: "rule_embargo",+ message: "Cannot sell Widget to this destination",+ lineId: "line_drop"+ });+ });++ it("mixed standalone and order-derived lines each evaluate against their own destination", async () => {+ const { violations } = await evaluateInvoice({+ ...BASE_ROWS,+ salesInvoice: [+ { id: "inv_1", companyId: COMPANY_ID, customerId: "cust_1" }+ ],+ salesInvoiceLine: [+ {+ id: "line_standalone",+ companyId: COMPANY_ID,+ invoiceId: "inv_1",+ itemId: "item_1",+ quantity: 1,+ salesOrderId: null+ },+ {+ id: "line_so",+ companyId: COMPANY_ID,+ invoiceId: "inv_1",+ itemId: "item_1",+ quantity: 1,+ salesOrderId: "so_1"+ }+ ],+ salesOrder: [+ {+ id: "so_1",+ companyId: COMPANY_ID,+ customerId: "cust_1",+ customerLocationId: "loc_us"+ }+ ],+ salesOrderShipment: []+ });++ // Only the standalone line violates (required field); the order-derived+ // line resolved a permitted destination.+ expect(violations).toHaveLength(1);+ expect(violations[0]).toMatchObject({+ lineId: "line_standalone",+ message: "Customer country is required"+ });+ });+});diff --git a/packages/ee/src/rules/sales/server.ts b/packages/ee/src/rules/sales/server.tsnew file mode 100644index 0000000000..a2fa56cbce--- /dev/null+++ b/packages/ee/src/rules/sales/server.ts@@ -0,0 +1,630 @@+// Server-side sales-rules evaluator. Cross-app entry point — the ERP quote /+// sales-order / sales-invoice line actions call `evaluateSalesRuleLines`.+// Mirrors `../storage/server.ts`.+//+// All functions here are server-only. Never import from a client module.++import type { Database } from "@carbon/database";+import {+ breakQuantities,+ type CompiledRule,+ compileSalesRuleWithCache,+ evaluateRules,+ type ItemFilter,+ ruleAppliesToItem,+ type SalesRuleSurface,+ toItemFilter,+ type Violation+} from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import { companyHasPlan } from "../../plan.server";+import { itemPostingGroupIdFromEmbed } from "../storage/context";+import {+ buildConditionValueResolver,+ dedupeViolations+} from "../storage/server";+import {+ buildSalesRuleLineContext,+ type CustomerCtxInput,+ type SalesRuleItemCtxRow,+ type SalesRuleLineInput+} from "./context";+import { getActiveSalesRulesForItems } from "./service";++// Block/dedupe semantics are identical to storage rules — the+// `@carbon/ee/rules.server` barrel (`../server.ts`) re-exports `isBlocked` /+// `dedupeViolations` from `../storage/server` for both families.++type Client = SupabaseClient<Database>;++// ---------------------------------------------------------------------------+// Plan gate+// ---------------------------------------------------------------------------++export const isSalesRulesEnabledForCompany = (+ client: Client,+ companyId: string+): Promise<boolean> =>+ companyHasPlan(client, companyId, { feature: "SALES_RULES" });++// ---------------------------------------------------------------------------+// Per-line evaluator — single entry point the sales line actions call+// ---------------------------------------------------------------------------++export type EvaluateSalesRuleLinesArgs = {+ client: Client;+ companyId: string;+ userId: string;+ surface: SalesRuleSurface;+ lines: SalesRuleLineInput[];+ /** The sales document's customer. null → no customer ctx is built. */+ customerId: string | null;+ /** The document's ship-to location; resolves `customer.location.countryCode`. */+ customerLocationId: string | null;+};++export type EvaluateSalesRuleLinesResult = {+ violations: Violation[];+ ruleNames: Record<string, string>;+};++// Fresh object per call — a shared literal returned by reference is one+// caller mutation away from poisoning every subsequent evaluation.+const emptyResult = (): EvaluateSalesRuleLinesResult => ({+ violations: [],+ ruleNames: {}+});++export async function evaluateSalesRuleLines({+ client,+ companyId,+ userId,+ surface,+ lines,+ customerId,+ customerLocationId+}: EvaluateSalesRuleLinesArgs): Promise<EvaluateSalesRuleLinesResult> {+ if (lines.length === 0) {+ return emptyResult();+ }+ if (!(await isSalesRulesEnabledForCompany(client, companyId))) {+ return emptyResult();+ }++ const itemIds = new Set<string>();+ for (const line of lines) {+ if (line.itemId) itemIds.add(line.itemId);+ }++ const [customerRes, locationRes, itemsRes, rulesRes] = await Promise.all([+ customerId+ ? client+ .from("customer")+ .select("id, customerTypeId, customerStatusId, customFields")+ .eq("id", customerId)+ .eq("companyId", companyId)+ .maybeSingle()+ : Promise.resolve({ data: null, error: null }),+ customerLocationId+ ? client+ .from("customerLocation")+ .select("id, address(countryCode)")+ .eq("id", customerLocationId)+ // companyId scope matters here: the invoice-post gate evaluates with+ // the service-role client, so RLS is not backstopping this read.+ // maybeSingle: a missing location is an expected state — the null+ // country flows into required-field semantics (fail closed).+ .eq("companyId", companyId)+ .maybeSingle()+ : Promise.resolve({ data: null, error: null }),+ itemIds.size > 0+ ? client+ .from("item")+ // `itemPostingGroupId` lives on the 1:1 `itemCost` row — embed it+ // so the `item.itemPostingGroupId` rule field + filters resolve.+ // NOTE: `item` has no `customFields` column — custom fields live on+ // the subtype tables (part/material/tool/consumable/service). Selecting+ // it here made PostgREST fail the whole query (42703), which silently+ // produced zero items and skipped every broadcast rule.+ .select(+ "id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, itemCost(itemPostingGroupId)"+ )+ .in("id", Array.from(itemIds))+ .eq("companyId", companyId)+ : Promise.resolve({ data: [], error: null }),+ getActiveSalesRulesForItems(client, companyId, Array.from(itemIds))+ ]);++ const { rules, assignmentsByItemId } = rulesRes;++ // Same reasoning as the item load below: a failed rule fetch returns an empty+ // `rules` array, which reads as "nothing to enforce" and lets the line through.+ if (rulesRes.error) {+ throw new Error(+ `Sales rule evaluation could not load rules: ${+ (rulesRes.error as { message?: string }).message ??+ String(rulesRes.error)+ }`+ );+ }++ // A failed item load must never pass silently. Without item rows every+ // BROADCAST rule is skipped (`!itemForLine` below), so a bad select turns+ // enforcement off with no signal — which is exactly how a missing column+ // went unnoticed. Surface it instead.+ if (itemsRes.error) {+ throw new Error(+ `Sales rule evaluation could not load items: ${+ itemsRes.error.message ?? String(itemsRes.error)+ }`+ );+ }++ // A failed customer or location read is indistinguishable from "no type /+ // no country": the ctx would be built with nulls and a rule on those fields+ // would emit a misleading "required" violation. Fail loud like the rule and+ // item loads above.+ if (customerRes.error || locationRes.error) {+ const err = customerRes.error ?? locationRes.error;+ throw new Error(+ `Sales rule evaluation could not load the customer context: ${+ (err as { message?: string })?.message ?? String(err)+ }`+ );+ }++ // If no active rules exist, nothing can fire.+ if (rules.length === 0) {+ return emptyResult();+ }++ // Resolve the ship-to country off the customerLocation → address embed+ // (PostgREST may materialize the 1:1 embed as object or array).+ const countryCode = (() => {+ const row = locationRes.data as { address?: unknown } | null;+ if (!row) return null;+ const address = Array.isArray(row.address) ? row.address[0] : row.address;+ return (+ (address as { countryCode?: string | null } | undefined)?.countryCode ??+ null+ );+ })();++ // Id-only fallback when the customer row lookup missed (RLS, deleted row)+ // keeps `{customer.id}` tokens resolving; unresolved fields then trip+ // required-field semantics. `location` stays undefined — NEVER `{}` — when+ // no country resolves, so `customer.location.countryCode` rules fire their+ // required-field violation.+ const customer: CustomerCtxInput | undefined = customerId+ ? {+ id: customerId,+ customerTypeId: customerRes.data?.customerTypeId ?? null,+ customerStatusId: customerRes.data?.customerStatusId ?? null,+ customFields:+ (customerRes.data?.customFields as+ | Record<string, unknown>+ | null+ | undefined) ?? undefined,+ location: countryCode ? { countryCode } : undefined+ }+ : undefined;++ const itemsById = new Map<string, SalesRuleItemCtxRow>();+ for (const it of itemsRes.data ?? []) {+ const row = it as unknown as Record<string, unknown>;+ const readable = row.readableIdWithRevision as string | null | undefined;+ // Flatten the 1:1 `itemCost` embed's posting group onto the item ctx; drop+ // the nested object. `id` becomes the readable id for token interpolation+ // (mirrors the storage evaluator).+ const { itemCost, ...rest } = row;+ itemsById.set(row.id as string, {+ ...rest,+ id: readable ?? (row.id as string),+ itemPostingGroupId: itemPostingGroupIdFromEmbed(itemCost) ?? undefined+ });+ }++ const compiledById = new Map<string, CompiledRule>();+ const filtersById = new Map<string, ItemFilter>();+ const ruleNamesById = new Map<string, string>();+ for (const rule of rules) {+ compiledById.set(rule.id, compileSalesRuleWithCache(rule));+ filtersById.set(rule.id, toItemFilter(rule));+ ruleNamesById.set(rule.id, rule.name);+ }++ // `{condition[N].name}` tokens resolve stored ids (customer type, status,+ // country) to their labels — same resolver the storage evaluator uses.+ const resolveConditionValue = await buildConditionValueResolver(+ client,+ companyId,+ (function* () {+ for (const rule of compiledById.values()) yield* rule.conditions;+ })()+ );++ const violations: Violation[] = [];+ for (const line of lines) {+ const explicit = line.itemId+ ? assignmentsByItemId.get(line.itemId)+ : undefined;+ // Keyed by real item id; ctx `id` is the readable id.+ const itemForLine = line.itemId ? itemsById.get(line.itemId) : undefined;++ // Per-line rule set: explicit assignments fire unconditionally; broadcasts+ // are gated per item by the rule's type/group filters (empty filters =+ // every item). A line whose item row didn't load can't match a broadcast+ // (mirrors the storage evaluator) — only its explicit assignments fire.+ const compiledForLine: CompiledRule[] = [];+ for (const rule of rules) {+ const isExplicit = explicit?.has(rule.id) ?? false;+ if (!isExplicit) {+ if (!itemForLine) continue;+ const filter = filtersById.get(rule.id) ?? {};+ if (!ruleAppliesToItem(itemForLine, filter)) continue;+ }+ compiledForLine.push(compiledById.get(rule.id)!);+ }++ if (compiledForLine.length === 0) continue;++ const ctx = buildSalesRuleLineContext({+ line,+ surface,+ userId,+ item: itemForLine,+ customer+ });++ const ruleViolations = evaluateRules(compiledForLine, ctx, surface, {+ resolveConditionValue+ });+ for (let i = 0; i < ruleViolations.length; i++) {+ // Stamp the originating line so a document-level gate can attribute the+ // violation and deep-link to it.+ violations.push({ ...ruleViolations[i]!, lineId: line.lineId });+ }+ }++ const deduped = dedupeViolations(violations);+ if (deduped.length === 0) {+ return { violations: deduped, ruleNames: {} };+ }++ // Names come off the already-loaded rule rows — no second query.+ const ruleNames: Record<string, string> = {};+ for (let i = 0; i < deduped.length; i++) {+ const ruleId = deduped[i]!.ruleId;+ const name = ruleNamesById.get(ruleId);+ if (name) ruleNames[ruleId] = name;+ }++ return { violations: deduped, ruleNames };+}++// ---------------------------------------------------------------------------+// Document evaluator — the terminal-gate entry point+// ---------------------------------------------------------------------------++export type SalesDocumentType =+ | "salesRfq"+ | "quote"+ | "salesOrder"+ | "salesInvoice";++export type EvaluateSalesRulesForSalesDocumentArgs = {+ client: Client;+ companyId: string;+ userId: string;+ documentType: SalesDocumentType;+ documentId: string;+};++/**+ * Resolve the ship-to location a sales order actually delivers to.+ *+ * A drop shipment overrides the header: the goods go to the drop-ship customer+ * location, not the ordering customer's. Evaluating the header alone would+ * clear an order that ships somewhere else entirely — which defeats any rule+ * keyed on `customer.location.countryCode`.+ */+export async function resolveSalesOrderShipTo(+ client: Client,+ salesOrderId: string,+ companyId: string+): Promise<{ customerId: string | null; customerLocationId: string | null }> {+ const [orderRes, shipmentRes] = await Promise.all([+ client+ .from("salesOrder")+ .select("customerId, customerLocationId")+ .eq("id", salesOrderId)+ .eq("companyId", companyId)+ .maybeSingle(),+ client+ .from("salesOrderShipment")+ .select("dropShipment, customerId, customerLocationId")+ .eq("id", salesOrderId)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);++ // This resolves WHERE the goods go, which is what country rules gate on.+ // Guessing on a failed read would evaluate the wrong destination.+ if (orderRes.error || shipmentRes.error) {+ const err = orderRes.error ?? shipmentRes.error;+ throw new Error(+ `Sales rule evaluation could not resolve the ship-to for ${salesOrderId}: ${+ (err as { message?: string })?.message ?? String(err)+ }`+ );+ }++ const shipment = shipmentRes.data;+ if (shipment?.dropShipment) {+ // A drop shipment's real destination is the shipment's, never the header's.+ // If it is missing we return null rather than falling back: the header+ // address is a DIFFERENT country, so falling back would silently clear a+ // rule that should have blocked. Null flows into the engine's required-field+ // semantics and surfaces "Customer location is required" at the rule's+ // severity. (The form validator requires the pair, but the column is+ // nullable, so API and legacy rows can still reach here without it.)+ return {+ customerId: shipment.customerId ?? orderRes.data?.customerId ?? null,+ customerLocationId: shipment.customerLocationId ?? null+ };+ }++ return {+ customerId: orderRes.data?.customerId ?? null,+ customerLocationId: orderRes.data?.customerLocationId ?? null+ };+}++/**+ * Evaluate every item-bearing line on a sales document, using the context as it+ * stands right now.+ *+ * This is the terminal-gate counterpart to `evaluateSalesRuleLines`: rather than+ * trusting that each line was checked when it was written, it re-reads the+ * whole document. That covers lines created by paths that never ran the+ * per-line check (conversions, duplication, integrations, the API) and catches+ * staleness — a rule authored later, a ship-to that changed, an item whose+ * attributes moved.+ *+ * Returned violations carry `lineId`, so callers can attribute them.+ */+export async function evaluateSalesRulesForSalesDocument({+ client,+ companyId,+ userId,+ documentType,+ documentId+}: EvaluateSalesRulesForSalesDocumentArgs): Promise<EvaluateSalesRuleLinesResult> {+ if (!(await isSalesRulesEnabledForCompany(client, companyId))) {+ return emptyResult();+ }++ // A sales RFQ has no surface of its own — its lines are evaluated under+ // `quoteLine`, because converting is precisely what turns them into quote+ // lines. Only lines that already carry an item can be evaluated: convert+ // mints placeholder items for the rest, and a just-created item has no rule+ // assignments and only default attributes, so nothing could fire on it.+ if (documentType === "salesRfq") {+ const [rfqRes, linesRes] = await Promise.all([+ client+ .from("salesRfq")+ .select("customerId, customerLocationId")+ .eq("id", documentId)+ .eq("companyId", companyId)+ .maybeSingle(),+ client+ .from("salesRfqLine")+ .select("id, itemId, quantity")+ .eq("salesRfqId", documentId)+ .eq("companyId", companyId)+ ]);++ // A read error that silently yields zero lines (or a null header, whose+ // missing customer would soften country rules) turns the gate off.+ if (rfqRes.error || linesRes.error) {+ const err = rfqRes.error ?? linesRes.error;+ throw new Error(+ `Sales rule evaluation could not load salesRfq ${documentId}: ${err?.message}`+ );+ }++ // Evaluate every quantity break — a min-quantity rule fires on the+ // smallest break, a max-quantity rule on the largest; no single break is+ // conservative for both. Dedupe collapses same-message repeats per line.+ const lines: SalesRuleLineInput[] = (linesRes.data ?? [])+ .filter((l) => !!l.itemId)+ .flatMap((l) =>+ breakQuantities(l.quantity).map((quantity) => ({+ lineId: l.id,+ itemId: l.itemId,+ quantity+ }))+ );++ return evaluateSalesRuleLines({+ client,+ companyId,+ userId,+ surface: "quoteLine",+ lines,+ customerId: rfqRes.data?.customerId ?? null,+ customerLocationId: rfqRes.data?.customerLocationId ?? null+ });+ }++ if (documentType === "quote") {+ const [quoteRes, linesRes] = await Promise.all([+ client+ .from("quote")+ .select("customerId, customerLocationId")+ .eq("id", documentId)+ .eq("companyId", companyId)+ .maybeSingle(),+ client+ .from("quoteLine")+ .select("id, itemId, quantity")+ .eq("quoteId", documentId)+ .eq("companyId", companyId)+ ]);++ // A read error that silently yields zero lines (or a null header, whose+ // missing customer would soften country rules) turns the gate off.+ if (quoteRes.error || linesRes.error) {+ const err = quoteRes.error ?? linesRes.error;+ throw new Error(+ `Sales rule evaluation could not load quote ${documentId}: ${err?.message}`+ );+ }++ // A quote line carries an array of quantity breaks; evaluate each one —+ // a min-quantity rule fires on the smallest break, a max-quantity rule on+ // the largest. Dedupe collapses same-message repeats per line.+ const lines: SalesRuleLineInput[] = (linesRes.data ?? [])+ .filter((l) => !!l.itemId)+ .flatMap((l) =>+ breakQuantities(l.quantity).map((quantity) => ({+ lineId: l.id,+ itemId: l.itemId,+ quantity+ }))+ );++ return evaluateSalesRuleLines({+ client,+ companyId,+ userId,+ surface: "quoteLine",+ lines,+ customerId: quoteRes.data?.customerId ?? null,+ customerLocationId: quoteRes.data?.customerLocationId ?? null+ });+ }++ // A sales invoice can be raised with no upstream document at all, so this+ // gate is the only checkpoint such an invoice ever passes. Ship-to is+ // resolved PER SOURCE ORDER: a line converted from a sales order carries+ // `salesOrderId` and resolves the real destination through that order+ // (drop-ship included, staleness re-checked); a standalone line has no+ // ship-to and none may be invented — the bill-to+ // (`invoiceCustomerLocationId`) is a different address and frequently a+ // different country, so substituting it would clear a rule that should+ // have blocked. A null location flows into the engine's required-field+ // semantics ("Customer country is required" at the rule's severity), so+ // the information-poorer path fails closed rather than open.+ if (documentType === "salesInvoice") {+ const [invoiceRes, linesRes] = await Promise.all([+ client+ .from("salesInvoice")+ .select("customerId")+ .eq("id", documentId)+ .eq("companyId", companyId)+ .maybeSingle(),+ client+ .from("salesInvoiceLine")+ .select("id, itemId, quantity, salesOrderId")+ .eq("invoiceId", documentId)+ .eq("companyId", companyId)+ ]);++ // A read error that silently yields zero lines turns the gate off.+ if (invoiceRes.error || linesRes.error) {+ const err = invoiceRes.error ?? linesRes.error;+ throw new Error(+ `Sales rule evaluation could not load sales invoice ${documentId}: ${err?.message}`+ );+ }++ const itemLines = (linesRes.data ?? []).filter((l) => !!l.itemId);++ // Group by source order so each group evaluates against the destination+ // its goods actually ship to. The null key holds the standalone lines.+ const groups = new Map<string | null, typeof itemLines>();+ for (const line of itemLines) {+ const key = line.salesOrderId ?? null;+ const group = groups.get(key);+ if (group) {+ group.push(line);+ } else {+ groups.set(key, [line]);+ }+ }++ // Per-group loads are bounded by the number of DISTINCT source orders on+ // one invoice (typically 1–3), not by line count.+ const results = await Promise.all(+ [...groups].map(async ([salesOrderId, groupLines]) => {+ const shipTo = salesOrderId+ ? await resolveSalesOrderShipTo(client, salesOrderId, companyId)+ : {+ customerId: invoiceRes.data?.customerId ?? null,+ customerLocationId: null+ };+ return evaluateSalesRuleLines({+ client,+ companyId,+ userId,+ surface: "salesInvoiceLine",+ lines: groupLines.map((l) => ({+ lineId: l.id,+ itemId: l.itemId,+ quantity: l.quantity ?? 1+ })),+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ })+ );++ return {+ violations: dedupeViolations(results.flatMap((r) => r.violations)),+ ruleNames: Object.assign({}, ...results.map((r) => r.ruleNames))+ };+ }++ if (documentType === "salesOrder") {+ const [shipTo, linesRes] = await Promise.all([+ resolveSalesOrderShipTo(client, documentId, companyId),+ client+ .from("salesOrderLine")+ .select("id, itemId, saleQuantity")+ .eq("salesOrderId", documentId)+ .eq("companyId", companyId)+ ]);++ // A lines-read error that silently yields zero lines turns the gate off.+ if (linesRes.error) {+ throw new Error(+ `Sales rule evaluation could not load sales order lines for ${documentId}: ${linesRes.error.message}`+ );+ }++ const lines: SalesRuleLineInput[] = (linesRes.data ?? [])+ .filter((l) => !!l.itemId)+ .map((l) => ({+ lineId: l.id,+ itemId: l.itemId,+ quantity: l.saleQuantity ?? 1+ }));++ return evaluateSalesRuleLines({+ client,+ companyId,+ userId,+ surface: "salesOrderLine",+ lines,+ customerId: shipTo.customerId,+ customerLocationId: shipTo.customerLocationId+ });+ }++ // Exhaustiveness: a new document type must get its own branch — falling+ // through to another document's query would silently evaluate nothing.+ throw new Error(+ `Unknown sales document type: ${documentType satisfies never}`+ );+}diff --git a/packages/ee/src/rules/sales/service.ts b/packages/ee/src/rules/sales/service.tsnew file mode 100644index 0000000000..1bcc1912c0--- /dev/null+++ b/packages/ee/src/rules/sales/service.ts@@ -0,0 +1,335 @@+// Cross-app DB queries for Sales Rules (sales-document surfaces). The ERP+// admin UI and the enforcement actions both import from here. Mirrors+// `../storage/service.ts`.+//+// 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 ConditionAst,+ type ItemFilter,+ ruleAppliesToItem,+ type SalesRuleSurface,+ type Severity,+ toItemFilter+} from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import { itemPostingGroupIdFromEmbed } from "../storage/context";++// Item-scoping filter columns on every sales-family row. NOT NULL with DB+// defaults, unlike the storage family's nullable trio.+const ITEM_FILTER_COLUMNS =+ "filteredItemTypes, filteredItemGroupIds, filteredItemMatchAll";++const SALES_RULE_EVAL_COLUMNS = `id, name, severity, message, conditionAst, surfaces, updatedAt, active, ${ITEM_FILTER_COLUMNS}`;++/**+ * Raw sales-family `enforcementRule` row shape the evaluator consumes. `conditionAst` arrives as+ * generic Json from PostgREST; rows are cast once at the query boundary.+ */+export type SalesRuleDbRow = {+ id: string;+ name: string;+ severity: Severity;+ message: string;+ conditionAst: ConditionAst;+ surfaces: SalesRuleSurface[];+ updatedAt: string | null;+ active: boolean;+ filteredItemTypes: string[];+ filteredItemGroupIds: string[];+ filteredItemMatchAll: boolean;+};++/**+ * Loads the rules applicable to a set of items:+ * - `rules` — EVERY active sales rule for the company. Each rule fires on a+ * line when it has an explicit assignment for that line's item OR its+ * `filteredItem*` filters match the item (`ruleAppliesToItem`; empty+ * filters = every item). Filter matching happens in `server.ts` where the+ * item rows exist.+ * - `assignmentsByItemId` — explicit `enforcementRuleItemAssignment` rows for+ * `itemIds`, as itemId → Set<ruleId>.+ *+ * Two round-trips. The rules fetch always runs, even when `itemIds` is empty,+ * so a request with no item still sees broadcasts.+ */+export async function getActiveSalesRulesForItems(+ client: SupabaseClient<Database>,+ companyId: string,+ itemIds: string[]+): Promise<{+ rules: SalesRuleDbRow[];+ assignmentsByItemId: Map<string, Set<string>>;+ error: unknown;+}> {+ const assignmentsByItemId = new Map<string, Set<string>>();++ const [rulesRes, assignmentsRes] = await Promise.all([+ client+ .from("enforcementRule")+ .select(SALES_RULE_EVAL_COLUMNS)+ .eq("companyId", companyId)+ .eq("family", "sales")+ .eq("active", true),+ itemIds.length > 0+ ? client+ .from("enforcementRuleItemAssignment")+ .select("itemId, ruleId")+ .in("itemId", itemIds)+ .eq("companyId", companyId)+ : Promise.resolve({ data: [], error: null })+ ]);++ if (rulesRes.error)+ return { rules: [], assignmentsByItemId, error: rulesRes.error };+ if (assignmentsRes.error)+ return { rules: [], assignmentsByItemId, error: assignmentsRes.error };++ // The pin table is shared with the storage family; a storage rule pinned to+ // the same item must not enter the sales evaluation set. The fetched rules+ // are already family-filtered, so they are the authority on what counts.+ const salesRuleIds = new Set(+ ((rulesRes.data ?? []) as unknown as SalesRuleDbRow[]).map((r) => r.id)+ );++ for (const row of assignmentsRes.data ?? []) {+ const itemId = row.itemId as string;+ const ruleId = row.ruleId as string;+ if (!salesRuleIds.has(ruleId)) continue;+ const bucket = assignmentsByItemId.get(itemId);+ if (bucket) bucket.add(ruleId);+ else assignmentsByItemId.set(itemId, new Set([ruleId]));+ }++ return {+ rules: (rulesRes.data ?? []) as unknown as SalesRuleDbRow[],+ assignmentsByItemId,+ error: null+ };+}++/**+ * Loader-style row returned from `getSalesRuleAssignmentsForItem`. Direct+ * assignments leave `inheritedFromId` / `inheritedFromName` null; broadcast+ * rules use the `__all__` sentinel so the UI can render an "All items" /+ * "Matches item filters" badge and suppress unassign. Mirrors+ * `RuleAssignmentRow` in `../storage/service.ts`.+ */+export type SalesRuleAssignmentRow = {+ /** Owner of the assignment row (the item id, or the `__all__` sentinel). */+ ownerId: string;+ ruleId: string;+ createdAt: string | null;+ salesRule: {+ id: string;+ name: string;+ severity: Severity;+ message: string;+ active: boolean;+ surfaces: SalesRuleSurface[];+ };+ /** null when the assignment is direct on `args.itemId`. */+ inheritedFromId: string | null;+ inheritedFromName: string | null;+};++/**+ * Merged explicit + broadcast rule list for one item — powers the per-item+ * Rules drawer section. Broadcasts are gated by the rule's item filters the+ * same way the evaluator gates them, so the drawer shows exactly the set that+ * will fire.+ */+export async function getSalesRuleAssignmentsForItem(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+): Promise<{ data: SalesRuleAssignmentRow[]; error: unknown }> {+ // No embed: the pin table is shared with the storage family, so the pinned+ // rules are resolved in a second, family-filtered pass below.+ const assignmentCols: string = "itemId, ruleId, createdAt";+ const [res, broadcastsRes, itemCtxRes] = await Promise.all([+ client+ .from("enforcementRuleItemAssignment")+ .select(assignmentCols)+ .eq("itemId", args.itemId)+ .eq("companyId", args.companyId),+ client+ .from("enforcementRule")+ .select(+ `id, name, severity, message, active, surfaces, createdAt, ${ITEM_FILTER_COLUMNS}`+ )+ .eq("companyId", args.companyId)+ .eq("family", "sales"),+ // Item type/group for this item so we can gate broadcasts the same way+ // the evaluator does.+ client+ .from("item")+ .select("type, itemCost(itemPostingGroupId)")+ .eq("id", args.itemId)+ .eq("companyId", args.companyId)+ .maybeSingle()+ ]);++ if (res.error) return { data: [], error: res.error };+ if (broadcastsRes.error) return { data: [], error: broadcastsRes.error };+ if (itemCtxRes.error) return { data: [], error: itemCtxRes.error };++ // Flatten itemPostingGroupId off the 1:1 itemCost embed for filter matching.+ const itemCtx = (() => {+ const row = itemCtxRes.data as {+ type?: unknown;+ itemCost?: unknown;+ } | null;+ if (!row) return null;+ return {+ type: row.type,+ itemPostingGroupId: itemPostingGroupIdFromEmbed(row.itemCost)+ };+ })();++ // Item assignments are always direct (no inheritance), so every explicit+ // row's owner is the item itself. Pinned rules are resolved against the+ // family-filtered fetch above — a pin pointing at a storage rule (same shared+ // table) simply finds no match and is skipped.+ const salesRuleById = new Map(+ (+ (broadcastsRes.data ??+ []) as unknown as SalesRuleAssignmentRow["salesRule"][]+ ).map((r) => [r.id, r])+ );++ const byRuleId = new Map<string, SalesRuleAssignmentRow>();+ for (const r of res.data ?? []) {+ const row = r as unknown as {+ [k: string]: unknown;+ ruleId: string;+ };+ const node = salesRuleById.get(row.ruleId);+ if (!node) continue;++ const candidate: SalesRuleAssignmentRow = {+ ownerId: row.itemId as string,+ ruleId: row.ruleId,+ createdAt: (row.createdAt as string | null) ?? null,+ salesRule: node,+ inheritedFromId: null,+ inheritedFromName: null+ };++ if (!byRuleId.has(candidate.ruleId)) {+ byRuleId.set(candidate.ruleId, candidate);+ }+ }++ // Append broadcasts as synthetic rows. Sentinel `__all__` ownerId+ // distinguishes them from real assignment rows; UI keys off+ // `inheritedFromId === "__all__"` to render the badge and suppress unassign.+ for (const b of (broadcastsRes.data ?? []) as unknown as Array<{+ id: string;+ name: string;+ severity: Severity;+ message: string;+ active: boolean;+ surfaces: SalesRuleSurface[];+ createdAt: string | null;+ filteredItemTypes: string[];+ filteredItemGroupIds: string[];+ filteredItemMatchAll: boolean;+ }>) {+ if (b.active === false) continue;+ if (byRuleId.has(b.id)) continue;++ // Only surface rules whose filter matches this item. Label by reach so+ // the drawer reads "All items" vs a filtered match.+ const filter: ItemFilter = toItemFilter(b);+ if (itemCtx && !ruleAppliesToItem(itemCtx, filter)) continue;+ const filterless =+ (filter.filteredItemTypes?.length ?? 0) === 0 &&+ (filter.filteredItemGroupIds?.length ?? 0) === 0;++ byRuleId.set(b.id, {+ ownerId: "__all__",+ ruleId: b.id,+ createdAt: b.createdAt,+ salesRule: {+ id: b.id,+ name: b.name,+ severity: b.severity,+ message: b.message,+ active: b.active,+ surfaces: b.surfaces+ },+ inheritedFromId: "__all__",+ inheritedFromName: filterless ? "All items" : "Matches item filters"+ });+ }++ return { data: Array.from(byRuleId.values()), error: null };+}++export async function getSalesRulesList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return fetchAllFromTable<{+ id: string;+ name: string;+ severity: Severity;+ active: boolean;+ surfaces: SalesRuleSurface[];+ }>(+ client,+ "enforcementRule",+ "id, name, severity, active, surfaces",+ (query) =>+ query.eq("companyId", companyId).eq("family", "sales").order("name")+ );+}++export async function assignSalesRule(+ client: SupabaseClient<Database>,+ args: { itemId: string; ruleId: string; companyId: string; createdBy: string }+) {+ // Preflight: rule must exist in this company. Without this, callers could+ // insert a foreign rule id; the evaluator filters defensively but the+ // orphan row still inflates assignment counts.+ const ruleRes = await client+ .from("enforcementRule")+ .select("id")+ .eq("id", args.ruleId)+ .eq("companyId", args.companyId)+ .eq("family", "sales")+ .single();+ if (ruleRes.error || !ruleRes.data) {+ return {+ data: null,+ error: ruleRes.error ?? new Error("Rule not found")+ };+ }++ return client+ .from("enforcementRuleItemAssignment")+ .insert({+ itemId: args.itemId,+ ruleId: args.ruleId,+ companyId: args.companyId,+ createdBy: args.createdBy+ })+ .select("itemId, ruleId")+ .single();+}++export async function unassignSalesRule(+ client: SupabaseClient<Database>,+ args: { itemId: string; ruleId: string; companyId: string }+) {+ return client+ .from("enforcementRuleItemAssignment")+ .delete()+ .eq("itemId", args.itemId)+ .eq("ruleId", args.ruleId)+ .eq("companyId", args.companyId);+}diff --git a/packages/ee/src/rules/server.ts b/packages/ee/src/rules/server.tsnew file mode 100644index 0000000000..1a47834a99--- /dev/null+++ b/packages/ee/src/rules/server.ts@@ -0,0 +1,25 @@+// Server-only entry point (`@carbon/ee/rules.server`) — re-exports both+// evaluator families. Never import from a client module.+//+// `isBlocked` / `dedupeViolations` are shared: block/dedupe semantics are+// identical for storage and sales rules, so both come from `./storage/server`.++export {+ type EvaluateSalesRuleLinesArgs,+ type EvaluateSalesRuleLinesResult,+ type EvaluateSalesRulesForSalesDocumentArgs,+ evaluateSalesRuleLines,+ evaluateSalesRulesForSalesDocument,+ isSalesRulesEnabledForCompany,+ resolveSalesOrderShipTo,+ type SalesDocumentType+} from "./sales/server";+export {+ dedupeViolations,+ type EvaluateLinesForSurfaceArgs,+ type EvaluateLinesForSurfaceResult,+ evaluateLinesForSurface,+ getStorageRulesDataForTarget,+ isBlocked,+ isStorageRulesEnabledForCompany+} from "./storage/server";diff --git a/packages/ee/src/storage-rules/context.test.ts b/packages/ee/src/rules/storage/context.test.tssimilarity index 100%rename from packages/ee/src/storage-rules/context.test.tsrename to packages/ee/src/rules/storage/context.test.tsdiff --git a/packages/ee/src/storage-rules/context.ts b/packages/ee/src/rules/storage/context.tssimilarity index 100%rename from packages/ee/src/storage-rules/context.tsrename to packages/ee/src/rules/storage/context.tsdiff --git a/packages/ee/src/storage-rules/server.ts b/packages/ee/src/rules/storage/server.tssimilarity index 88%rename from packages/ee/src/storage-rules/server.tsrename to packages/ee/src/rules/storage/server.tsindex 00f6afa5e7..5acd961a85 100644--- a/packages/ee/src/storage-rules/server.ts+++ b/packages/ee/src/rules/storage/server.ts@@ -12,8 +12,8 @@ import {compileWithCache,evaluateRules,getFieldDef,- type ItemRuleFilter,- itemRuleAppliesToItem,+ type ItemFilter,+ ruleAppliesToItem,type Severity,type TargetType,type TransactionSurface,@@ -21,7 +21,8 @@ import {type Violation} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";-import { companyHasPlan } from "../plan.server";+import { companyHasPlan } from "../../plan.server";+import { dedupeViolations, isBlocked } from "../violations";import {buildLineContext,type ItemCtxRow,@@ -52,34 +53,11 @@ export const isStorageRulesEnabledForCompany = (// 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;-};+// `isBlocked` / `dedupeViolations` are pure and live in `../violations` so they+// are unit-testable without this file's plan-gate import chain. Imported (this+// file uses `dedupeViolations` below) and re-exported so every existing import+// path — here and via `../server.ts` — keeps resolving.+export { dedupeViolations, isBlocked };// ---------------------------------------------------------------------------// Per-target Rules tab data (loader helper)@@ -140,7 +118,7 @@ async function loadCompiledRulesForTargets(): Promise<{byTarget: Map<string, CompiledRule[]>;broadcasts: CompiledRule[];- broadcastFilters: Map<string, ItemRuleFilter>;+ broadcastFilters: Map<string, ItemFilter>;}> {const byTarget = new Map<string, CompiledRule[]>();@@ -215,12 +193,35 @@ const LOADERS: Record<ValueOptionsLoader, LoaderFn | null> = {// Static enums — value is already the label.itemTypes: null,replenishmentSystems: null,- itemTrackingTypes: null+ itemTrackingTypes: null,+ // Sales-rule loaders (customer-context fields).+ customerTypes: async (c, id) => {+ const { data } = await c+ .from("customerType")+ .select("id, name")+ .eq("companyId", id);+ return (data ?? []) as { id: string; name: string }[];+ },+ customerStatuses: async (c, id) => {+ const { data } = await c+ .from("customerStatus")+ .select("id, name")+ .eq("companyId", id);+ return (data ?? []) as { id: string; name: string }[];+ },+ // Countries are global (no companyId); the stored condition value is the+ // alpha-2 code, so it plays the `id` role here.+ countries: async (c) => {+ const { data } = await c.from("country").select("alpha2, name");+ return (data ?? []).map((r) => ({ id: r.alpha2, name: r.name }));+ }};const EMPTY_RESOLVER = (): undefined => undefined;-async function buildConditionValueResolver(+// Exported for the sales evaluator (`../sales/server.ts`) — same loaders,+// same `{condition[N].name}` semantics, one implementation.+export async function buildConditionValueResolver(client: Client,companyId: string,conditions: Iterable<Condition>@@ -344,7 +345,7 @@ export async function evaluateLinesForSurface({if (line.workCenterId) workCenterIds.add(line.workCenterId);if (line.operation?.itemId) itemIds.add(line.operation.itemId);}- // No early-return on empty targetIds — broadcasts (all active item rules, or+ // No early-return on empty targetIds — broadcasts (all active storage rules, or// appliesToAll rules for non-item targets) must still fire against every line.// Explicit-assignment lookup short-circuits inside `getActiveRulesForTargets`// when targetIds is empty.@@ -352,7 +353,7 @@ export async function evaluateLinesForSurface({// Walk the storage-unit tree for every line that carries a bin id so 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 (item rules referencing+ // populating `ctx.storageUnit.storageTypeId` below (storage rules referencing// `storageUnit.storageTypeId` on place/pick depend on this). One round-trip;// selects `storageTypeIds` so the union doesn't need a second fetch.const ancestorsByBin = new Map<string, string[]>();@@ -412,6 +413,14 @@ export async function evaluateLinesForSurface({.from("item")// `itemPostingGroupId` lives on the 1:1 `itemCost` row — embed it// so the `item.itemPostingGroupId` rule field resolves.+ //+ // ASYMMETRY, deliberate: the sales evaluator THROWS when this load+ // fails, because zero items means every broadcast rule is skipped+ // and enforcement silently switches off. The same is true here, but+ // this path ships today and turning a silent pass into a hard failure+ // would change behavior for live receipt/shipment posting — so it is+ // left as-is and tracked separately rather than changed inside a+ // refactor. Do not copy this shape into a new evaluator..select("id, type, replenishmentSystem, itemTrackingType, name, readableId, itemCost(itemPostingGroupId)")@@ -526,8 +535,8 @@ export async function evaluateLinesForSurface({if (seen.has(r.id)) continue;if (targetType === "item") {if (!itemForLine) continue;- const filter: ItemRuleFilter = broadcastFilters.get(r.id) ?? {};- if (!itemRuleAppliesToItem(itemForLine, filter)) continue;+ const filter: ItemFilter = broadcastFilters.get(r.id) ?? {};+ if (!ruleAppliesToItem(itemForLine, filter)) continue;}seen.add(r.id);compiledForLine.push(r);@@ -566,10 +575,11 @@ export async function evaluateLinesForSurface({for (let i = 0; i < deduped.length; i++) violatedIds.add(deduped[i]!.ruleId);const { data: namedRules } = await client- .from("storageRule")+ .from("enforcementRule").select("id, name").in("id", Array.from(violatedIds))- .eq("companyId", companyId);+ .eq("companyId", companyId)+ .eq("family", "storage");const ruleNames: Record<string, string> = {};for (const r of namedRules ?? []) {diff --git a/packages/ee/src/storage-rules/service.ts b/packages/ee/src/rules/storage/service.tssimilarity index 71%rename from packages/ee/src/storage-rules/service.tsrename to packages/ee/src/rules/storage/service.tsindex 00912c8e26..4ce8ae94b5 100644--- a/packages/ee/src/storage-rules/service.ts+++ b/packages/ee/src/rules/storage/service.ts@@ -8,22 +8,22 @@import type { Database } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import {- type ItemRuleFilter,- itemRuleAppliesToItem,+ type ItemFilter,+ ruleAppliesToItem,type Severity,type StorageRuleRow,type TargetType,type TransactionSurface,- toItemRuleFilter+ toItemFilter} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { itemPostingGroupIdFromEmbed } from "./context";// Nullable filter columns appended to broadcast selects for item-target rules.-const ITEM_RULE_FILTER_COLUMNS =+const ITEM_FILTER_COLUMNS ="filteredItemTypes, filteredItemGroupIds, filteredItemMatchAll";-// Filter columns carried on broadcast item rules. PostgREST's typed-select+// Filter columns carried on broadcast rules. PostgREST's typed-select// parser can't narrow our dynamically-built select string, so broadcast queries// type their rows explicitly via this shape rather than the generated Row type.type ItemFilterColumns = {@@ -34,12 +34,12 @@ type ItemFilterColumns = {const assignmentTableFor = (targetType: TargetType-): "storageRuleItemAssignment" | "storageRuleWorkCenterAssignment" => {+): "enforcementRuleItemAssignment" | "enforcementRuleWorkCenterAssignment" => {switch (targetType) {case "item":- return "storageRuleItemAssignment";+ return "enforcementRuleItemAssignment";case "workCenter":- return "storageRuleWorkCenterAssignment";+ return "enforcementRuleWorkCenterAssignment";}};@@ -72,7 +72,7 @@ type RuleRowSelect = Pick<* `data` keys are targetIds (explicit-assignment rules only).* `broadcasts` carries rules that fire beyond explicit assignments — caller* merges them into every line:- * - item targets: EVERY active item rule broadcasts, then the caller gates it+ * - item targets: EVERY active storage rule broadcasts, then the caller gates it* per line via the rule's `filteredItem*` filters (see `broadcastFilters`);* empty filters = every item.* - workCenter targets: rules with `appliesToAll = TRUE` only.@@ -93,11 +93,11 @@ export async function getActiveRulesForTargets(): Promise<{data: Map<string, StorageRuleRow[]>;broadcasts: StorageRuleRow[];- broadcastFilters: Map<string, ItemRuleFilter>;+ broadcastFilters: Map<string, ItemFilter>;error: unknown;}> {const out = new Map<string, StorageRuleRow[]>();- const broadcastFilters = new Map<string, ItemRuleFilter>();+ const broadcastFilters = new Map<string, ItemFilter>();const ruleCols ="id, targetType, severity, message, conditionAst, surfaces, updatedAt, active";@@ -106,37 +106,38 @@ export async function getActiveRulesForTargets(// Annotated `string` so PostgREST yields generically-typed rows (the dynamic// select string can't be statically parsed); rows are cast explicitly below.const broadcastCols: string = isItem- ? `${ruleCols}, ${ITEM_RULE_FILTER_COLUMNS}`+ ? `${ruleCols}, ${ITEM_FILTER_COLUMNS}`: ruleCols;const table = assignmentTableFor(args.targetType);const idCol = targetIdColumnFor(args.targetType);const broadcastBase = client- .from("storageRule")+ .from("enforcementRule").select(broadcastCols).eq("companyId", args.companyId)+ .eq("family", "storage").eq("targetType", args.targetType).eq("active", true);- const [explicit, broadcast] = await Promise.all([+ const [assignments, broadcast] = await Promise.all([args.targetIds.length > 0? (client as SupabaseClient<Database>).from(table)- .select(`${idCol}, storageRule:ruleId(${ruleCols})`)+ .select(`${idCol}, ruleId`).in(idCol, args.targetIds).eq("companyId", args.companyId): Promise.resolve({ data: [], error: null }),- // Item rules all broadcast (filtered per item); non-item only when appliesToAll.+ // Item-target rules all broadcast (filtered per item); non-item only when appliesToAll.isItem ? broadcastBase : broadcastBase.eq("appliesToAll", true)]);- if (explicit.error)+ if (assignments.error)return {data: out,broadcasts: [],broadcastFilters,- error: explicit.error+ error: assignments.error};if (broadcast.error)return {@@ -146,20 +147,48 @@ export async function getActiveRulesForTargets(error: broadcast.error};- for (const r of explicit.data ?? []) {- const row = r as unknown as {- [k: string]: unknown;- storageRule: RuleRowSelect | RuleRowSelect[] | null;- };- const targetId = row[idCol] as string;- const node = Array.isArray(row.storageRule)- ? row.storageRule[0]- : row.storageRule;- if (!node || node.active === false) continue;- if (node.targetType !== args.targetType) continue;- const bucket = out.get(targetId);- if (bucket) bucket.push(node as StorageRuleRow);- else out.set(targetId, [node as StorageRuleRow]);+ // The pin table is shared with the sales family, so the rules are fetched in+ // a second pass filtered to this family rather than embedded — an embed would+ // happily return a sales rule pinned to the same item.+ const assignmentRows = (assignments.data ?? []) as unknown as {+ [k: string]: unknown;+ ruleId: string;+ }[];+ const assignedRuleIds = [...new Set(assignmentRows.map((r) => r.ruleId))];++ if (assignedRuleIds.length > 0) {+ const explicit = await client+ .from("enforcementRule")+ .select(ruleCols)+ .in("id", assignedRuleIds)+ .eq("companyId", args.companyId)+ .eq("family", "storage")+ .eq("targetType", args.targetType)+ .eq("active", true);++ if (explicit.error)+ return {+ data: out,+ broadcasts: [],+ broadcastFilters,+ error: explicit.error+ };++ const ruleById = new Map<string, RuleRowSelect>(+ ((explicit.data ?? []) as unknown as RuleRowSelect[]).map((r) => [+ r.id,+ r+ ])+ );++ for (const row of assignmentRows) {+ const node = ruleById.get(row.ruleId);+ if (!node) continue;+ const targetId = row[idCol] as string;+ const bucket = out.get(targetId);+ if (bucket) bucket.push(node as StorageRuleRow);+ else out.set(targetId, [node as StorageRuleRow]);+ }}// `as unknown as` is required: a dynamic select string degrades PostgREST's@@ -169,7 +198,7 @@ export async function getActiveRulesForTargets(if (isItem) {for (const row of broadcasts) {- broadcastFilters.set(row.id, toItemRuleFilter(row));+ broadcastFilters.set(row.id, toItemFilter(row));}}@@ -216,7 +245,7 @@ export async function getRuleAssignmentsForTarget(// 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).- // - item: EVERY active item rule broadcasts, gated per item by its+ // - item: EVERY active storage rule broadcasts, gated per item by its// type/group filters (empty = all items) — mirrors the evaluator.// - workCenter: rules with `appliesToAll = TRUE`.const isItem = args.targetType === "item";@@ -224,20 +253,19 @@ export async function getRuleAssignmentsForTarget("id, name, targetType, severity, message, active, surfaces, appliesToAll, createdAt";// `string` so PostgREST yields generic rows; cast explicitly at the loop.const broadcastCols: string = isItem- ? `${baseBroadcastCols}, ${ITEM_RULE_FILTER_COLUMNS}`+ ? `${baseBroadcastCols}, ${ITEM_FILTER_COLUMNS}`: baseBroadcastCols;const broadcastBase = client- .from("storageRule")+ .from("enforcementRule").select(broadcastCols).eq("companyId", args.companyId)+ .eq("family", "storage").eq("targetType", args.targetType);const [res, broadcastsRes, itemCtxRes] = await Promise.all([(client as SupabaseClient<Database>).from(table)- .select(- `${idCol}, ruleId, createdAt, storageRule:ruleId(id, name, targetType, severity, message, active, surfaces, appliesToAll)`- )+ .select(`${idCol}, ruleId, createdAt`).in(idCol, lookupIds).eq("companyId", args.companyId),isItem ? broadcastBase : broadcastBase.eq("appliesToAll", true),@@ -273,31 +301,50 @@ export async function getRuleAssignmentsForTarget(// Item / workCenter assignments are always direct (no inheritance), so every// row's owner is the target itself.const byRuleId = new Map<string, RuleAssignmentRow>();- for (const r of res.data ?? []) {- const row = r as unknown as {- [k: string]: unknown;- storageRule:- | RuleAssignmentRow["storageRule"]- | RuleAssignmentRow["storageRule"][]- | null;- };- const ownerId = row[idCol] as string;- const node = Array.isArray(row.storageRule)- ? row.storageRule[0]- : row.storageRule;- if (!node) continue;-- const candidate: RuleAssignmentRow = {- ownerId,- ruleId: row.ruleId as string,- createdAt: (row.createdAt as string | null) ?? null,- storageRule: node,- inheritedFromId: null,- inheritedFromName: null- };- if (!byRuleId.has(candidate.ruleId)) {- byRuleId.set(candidate.ruleId, candidate);+ // Second pass rather than an embed: the pin table is shared with the sales+ // family, so the rules must be filtered to this family explicitly.+ const assignmentRows = (res.data ?? []) as unknown as {+ [k: string]: unknown;+ ruleId: string;+ createdAt: string | null;+ }[];+ const assignedRuleIds = [...new Set(assignmentRows.map((r) => r.ruleId))];++ if (assignedRuleIds.length > 0) {+ const rulesRes = await client+ .from("enforcementRule")+ .select(+ "id, name, targetType, severity, message, active, surfaces, appliesToAll"+ )+ .in("id", assignedRuleIds)+ .eq("companyId", args.companyId)+ .eq("family", "storage");++ if (rulesRes.error) return { data: [], error: rulesRes.error };++ const ruleById = new Map(+ (+ (rulesRes.data ?? []) as unknown as RuleAssignmentRow["storageRule"][]+ ).map((r) => [r.id, r])+ );++ for (const row of assignmentRows) {+ const node = ruleById.get(row.ruleId);+ if (!node) continue;++ const candidate: RuleAssignmentRow = {+ ownerId: row[idCol] as string,+ ruleId: row.ruleId,+ createdAt: row.createdAt ?? null,+ storageRule: node,+ inheritedFromId: null,+ inheritedFromName: null+ };++ if (!byRuleId.has(candidate.ruleId)) {+ byRuleId.set(candidate.ruleId, candidate);+ }}}@@ -323,12 +370,12 @@ export async function getRuleAssignmentsForTarget(if (b.active === false) continue;if (byRuleId.has(b.id)) continue;- // Item rules: only surface those whose filter matches this item. Label by+ // Storage rules: only surface those whose filter matches this item. Label by// reach so the drawer reads "All items" vs a filtered match.let label = "Applies to all";if (isItem) {- const filter = toItemRuleFilter(b);- if (itemCtx && !itemRuleAppliesToItem(itemCtx, filter)) continue;+ const filter = toItemFilter(b);+ if (itemCtx && !ruleAppliesToItem(itemCtx, filter)) continue;const filterless =(filter.filteredItemTypes?.length ?? 0) === 0 &&(filter.filteredItemGroupIds?.length ?? 0) === 0;@@ -372,10 +419,13 @@ export async function getStorageRulesList(surfaces: TransactionSurface[];}>(client,- "storageRule",+ "enforcementRule","id, name, targetType, severity, active, appliesToAll, surfaces",(query) => {- let q = query.eq("companyId", companyId).order("name");+ let q = query+ .eq("companyId", companyId)+ .eq("family", "storage")+ .order("name");if (targetType) q = q.eq("targetType", targetType);return q;}@@ -395,15 +445,17 @@ export async function assignStorageRule(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 storageRuleItemAssignment; the evaluator filters defensively but- // the orphan row still inflates getRuleAssignmentCounts.+ // Preflight: rule must exist in this company, belong to the storage family,+ // and its targetType must match the assignment table. Without this, callers+ // could pin a sales rule (or a work-center rule) through the item-assignment+ // table; the evaluator filters defensively but the orphan row still inflates+ // getRuleAssignmentCounts.const ruleRes = await client- .from("storageRule")+ .from("enforcementRule").select("id, targetType").eq("id", args.ruleId).eq("companyId", args.companyId)+ .eq("family", "storage").single();if (ruleRes.error || !ruleRes.data) {return {diff --git a/packages/ee/src/storage-rules/use-violations.tsx b/packages/ee/src/rules/use-violations.tsxsimilarity index 85%rename from packages/ee/src/storage-rules/use-violations.tsxrename to packages/ee/src/rules/use-violations.tsxindex 1433849c16..1dd0aeb483 100644--- a/packages/ee/src/storage-rules/use-violations.tsx+++ b/packages/ee/src/rules/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 StorageRuleViolationModal from "./violation-modal";+import RuleViolationModal from "./violation-modal";/**- * Shape every item-rule-aware server action must return when it wants the+ * Shape every 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 StorageRuleViolationPayload = {+export type RuleViolationPayload = {error?: { message?: string } | null;data?: unknown;violations?: Violation[];ruleNames?: Record<string, string>;};-type UseStorageRuleViolationsOptions = {+type UseRuleViolationsOptions = {/** Server action endpoint that the form is posted to. */action: string;/**@@ -26,7 +26,7 @@ type UseStorageRuleViolationsOptions = {onSuccess?: () => void;};-type UseStorageRuleViolationsResult<T> = {+type UseRuleViolationsResult<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.@@ -41,11 +41,11 @@ type UseStorageRuleViolationsResult<T> = {};/**- * Centralised handler for item rule violations + action errors.+ * Centralised handler for rule violations + action errors.** Wraps a `useFetcher` and:* - toasts any `error.message` returned by the action- * - opens `<StorageRuleViolationModal>` when the action returns `violations`+ * - opens `<RuleViolationModal>` 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 UseStorageRuleViolationsResult<T> = {* Call sites only have to swap `fetcher.submit(...)` for `rules.submit(...)`* and render `<rules.ViolationModal />`. Everything else is wired internally.*/-export function useStorageRuleViolations<T = unknown>({+export function useRuleViolations<T = unknown>({action,onSuccess-}: UseStorageRuleViolationsOptions): UseStorageRuleViolationsResult<T> {+}: UseRuleViolationsOptions): UseRuleViolationsResult<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 useStorageRuleViolations<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<StorageRuleViolationPayload | undefined>(+ const [staged, setStaged] = useState<RuleViolationPayload | undefined>(undefined);const lastSeenDataRef = useRef<unknown>(undefined);@@ -79,7 +79,7 @@ export function useStorageRuleViolations<T = unknown>({// the form submits via `fetcher={...}` prop directly (bypassing `submit()`).const prevIdleRef = useRef(true);- const data = fetcher.data as StorageRuleViolationPayload | undefined;+ const data = fetcher.data as RuleViolationPayload | undefined;const idle = fetcher.state === "idle";const violations = staged?.violations ?? [];const ruleNames = staged?.ruleNames;@@ -122,6 +122,14 @@ export function useStorageRuleViolations<T = unknown>({// Violations — keep modal open, don't fire success.return;}+ // A non-violation failure (`{ success: false, message }` — e.g. a PDF+ // that failed to generate) is not success: don't close the caller's+ // modal over it. The caller's own toast effect surfaces the message;+ // toasting here too would double it up.+ if ((data as { success?: boolean } | undefined)?.success === false) {+ pendingSuccessRef.current = false;+ return;+ }if (!pendingSuccessRef.current) return;pendingSuccessRef.current = false;onSuccess?.();@@ -164,7 +172,7 @@ export function useStorageRuleViolations<T = unknown>({const ViolationModal = useCallback(() => {if (!hasViolations) return null;return (- <StorageRuleViolationModal+ <RuleViolationModalviolations={violations}ruleNames={ruleNames}isSubmitting={!idle}diff --git a/packages/ee/src/storage-rules/violation-modal.tsx b/packages/ee/src/rules/violation-modal.tsxsimilarity index 96%rename from packages/ee/src/storage-rules/violation-modal.tsxrename to packages/ee/src/rules/violation-modal.tsxindex fcbea884c2..0e98312f52 100644--- a/packages/ee/src/storage-rules/violation-modal.tsx+++ b/packages/ee/src/rules/violation-modal.tsx@@ -14,7 +14,7 @@ import { LuOctagonAlert, LuTriangleAlert } from "react-icons/lu";type RuleNameMap = Record<string, string>;-type StorageRuleViolationModalProps = {+type RuleViolationModalProps = {violations: Violation[];ruleNames?: RuleNameMap;onCancel: () => void;@@ -22,13 +22,13 @@ type StorageRuleViolationModalProps = {isSubmitting?: boolean;};-export default function StorageRuleViolationModal({+export default function RuleViolationModal({violations,ruleNames,onCancel,onAcknowledge,isSubmitting-}: StorageRuleViolationModalProps) {+}: RuleViolationModalProps) {const { errors, warns, hasError, onlyWarns } = useMemo(() => {const errs: Violation[] = [];const wrns: Violation[] = [];diff --git a/packages/ee/src/rules/violations.test.ts b/packages/ee/src/rules/violations.test.tsnew file mode 100644index 0000000000..1441521272--- /dev/null+++ b/packages/ee/src/rules/violations.test.ts@@ -0,0 +1,86 @@+import type { Violation } from "@carbon/utils";+import { describe, expect, it } from "vitest";+import { dedupeViolations, isBlocked } from "./violations";++const v = (+ ruleId: string,+ message: string,+ severity: Violation["severity"] = "error",+ lineId?: string+): Violation => ({ ruleId, severity, message, lineId });++describe("isBlocked", () => {+ it("blocks on any error regardless of acknowledgement", () => {+ expect(isBlocked([v("r1", "nope", "error")], true)).toBe(true);+ expect(isBlocked([v("r1", "nope", "error")], false)).toBe(true);+ });++ it("blocks warns until acknowledged", () => {+ expect(isBlocked([v("r1", "careful", "warn")], false)).toBe(true);+ expect(isBlocked([v("r1", "careful", "warn")], true)).toBe(false);+ });++ it("an error alongside acknowledged warns still blocks", () => {+ const violations = [v("r1", "careful", "warn"), v("r2", "nope", "error")];+ expect(isBlocked(violations, true)).toBe(true);+ });++ it("does not block when there is nothing to block on", () => {+ expect(isBlocked([], false)).toBe(false);+ });+});++describe("dedupeViolations", () => {+ it("collapses identical ruleId + message (the storage-rule contract)", () => {+ const out = dedupeViolations([+ v("r1", "same message"),+ v("r1", "same message")+ ]);+ expect(out).toHaveLength(1);+ });++ it("keeps distinct rules and distinct messages", () => {+ const out = dedupeViolations([+ v("r1", "message a"),+ v("r1", "message b"),+ v("r2", "message a")+ ]);+ expect(out).toHaveLength(3);+ });++ it("keeps one entry per line when the same rule fires across lines", () => {+ // A document-level gate needs per-line attribution — collapsing these+ // would lose the ability to point at the offending line.+ const out = dedupeViolations([+ v("r1", "restricted", "error", "line-1"),+ v("r1", "restricted", "error", "line-2")+ ]);+ expect(out).toHaveLength(2);+ expect(out.map((x) => x.lineId)).toEqual(["line-1", "line-2"]);+ });++ it("still collapses repeats within one line", () => {+ const out = dedupeViolations([+ v("r1", "restricted", "error", "line-1"),+ v("r1", "restricted", "error", "line-1")+ ]);+ expect(out).toHaveLength(1);+ });++ it("treats an absent lineId as its own key, not a wildcard", () => {+ const out = dedupeViolations([+ v("r1", "restricted", "error", undefined),+ v("r1", "restricted", "error", "line-1")+ ]);+ expect(out).toHaveLength(2);+ });++ it("preserves first-seen order", () => {+ const out = dedupeViolations([+ v("r2", "second"),+ v("r1", "first"),+ v("r2", "second")+ ]);+ expect(out.map((x) => x.ruleId)).toEqual(["r2", "r1"]);+ });+});diff --git a/packages/ee/src/rules/violations.ts b/packages/ee/src/rules/violations.tsnew file mode 100644index 0000000000..283d62d9a1--- /dev/null+++ b/packages/ee/src/rules/violations.ts@@ -0,0 +1,43 @@+// Block/dedupe semantics shared by both rule families (storage + sales).+//+// Pure — no client, no env, no I/O. It lives outside `storage/server.ts` so it+// can be unit-tested without dragging in the plan gate's `@carbon/auth` import+// chain (which validates env at module load). `storage/server.ts` re-exports+// both functions, so every existing import path still resolves.++import type { Violation } from "@carbon/utils";++/** 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 + lineId`. Call when accumulating+ * results from multiple evaluator invocations (e.g. item pass + storageUnit+ * pass on the same receipt, or several surfaces on one document).+ *+ * `lineId` participates in the key so a document-level gate keeps one entry per+ * offending line — the UI groups and deep-links off it. The storage evaluator+ * leaves `lineId` undefined (the sales evaluator stamps it on every+ * violation), so the collapsing behavior storage rules have always had is+ * unchanged.+ */+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}\x00${v.lineId ?? ""}`;+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(v);+ }+ return out;+};diff --git a/packages/ee/src/storage-rules/index.ts b/packages/ee/src/storage-rules/index.tsdeleted file mode 100644index 2245cc8c73..0000000000--- a/packages/ee/src/storage-rules/index.ts+++ /dev/null@@ -1,7 +0,0 @@-// Public exports for cross-app consumers (ERP + MES).-export * from "./service";-export {- type StorageRuleViolationPayload,- useStorageRuleViolations-} from "./use-violations";-export { default as StorageRuleViolationModal } from "./violation-modal";diff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.tsindex 3fdfa01b30..1e3eed371a 100644--- a/packages/glossary/src/terms.ts+++ b/packages/glossary/src/terms.ts@@ -198,6 +198,10 @@ export const terms = {definition: msg`A priced sales quotation; Draft → Sent → Ordered, or ends Lost, Expired, or Cancelled.`,href: "/docs/reference/quotes"},+ "drop-shipment": {+ term: msg`Drop shipment`,+ definition: msg`A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's.`+ },rfq: {term: msg`RFQ (request for quote)`,definition: msg`A sales RFQ (a customer asks you to quote) or a purchasing RFQ (you ask suppliers); both feed the opportunity thread.`,diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 8f7c043096..1e49cf37fb 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20260916143022",+ "schemaVersion": "20260917213637","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-09-17T06:52:25.706Z",+ "exportedAt": "2026-09-17T17:39:03.902Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -14,107 +14,107 @@"name": "account","rows": 0,"columns": [- "customFields",- "updatedBy",- "isGroup",- "parentId",- "class",- "accountType",+ "incomeBalance",+ "updatedAt",+ "createdBy",+ "number",+ "consolidatedRate",+ "id",+ "active","isSystem",- "tags",- "companyGroupId","name","createdAt",- "active",- "id",- "consolidatedRate",- "incomeBalance",- "number",- "createdBy",- "updatedAt"+ "companyGroupId",+ "tags",+ "updatedBy",+ "isGroup",+ "customFields",+ "accountType",+ "class",+ "parentId"]},{"name": "accountDefault","rows": 0,"columns": [- "serviceChargeAccount",- "supplierWriteOffAccount",- "goodsReceivedNotInvoicedAccount",- "retainedEarningsAccount",- "maintenanceAccount",- "salesAccount",- "prepaymentAccount",- "overheadVarianceAccount",- "salesShippingRevenueAccount",- "realizedExchangeLossAccount",- "purchaseVarianceAccount",- "realizedExchangeGainAccount",- "accumulatedDepreciationOnDisposalAccount",- "bankForeignCurrencyAccount",- "materialVarianceAccount",- "inventoryAdjustmentVarianceAccount",- "assetLossOnDisposalAccount",- "finishedGoodsAccount",- "companyId",- "deferredTaxExpenseAccountId",- "deferredTaxLiabilityAccountId",- "salesTaxPayableAccount",- "purchaseTaxPayableAccount",- "overheadAbsorptionAccount",- "rawMaterialsAccount",- "laborAndMachineVarianceAccount",+ "laborAbsorptionAccount",+ "updatedBy","salesReturnsAccount",+ "laborAndMachineVarianceAccount",+ "rawMaterialsAccount","workInProgressAccount",- "updatedBy",- "laborAbsorptionAccount",- "assetDepreciationExpenseAccount",- "salesDiscountAccount",- "costOfGoodsSoldAccount",- "customerWriteOffAccount",- "assetGainOnDisposalAccount",- "customerPaymentDiscountAccount",- "currencyTranslationAccount",- "reverseChargeSalesTaxPayableAccount",- "supplierPaymentDiscountAccount",- "payablesAccount",- "accumulatedDepreciationAccount",- "intercompanyReceivablesAccount",- "receivablesAccount",- "bankLocalCurrencyAccount",- "scrapAccount",- "subcontractingVarianceAccount",- "assetAquisitionCostOnDisposalAccount",- "bankCashAccount",+ "overheadAbsorptionAccount",+ "purchaseTaxPayableAccount",+ "salesTaxPayableAccount",+ "deferredTaxLiabilityAccountId",+ "inventoryAdjustmentVarianceAccount",+ "deferredTaxExpenseAccountId",+ "companyId",+ "finishedGoodsAccount",+ "assetLossOnDisposalAccount",+ "materialVarianceAccount",+ "bankForeignCurrencyAccount",+ "accumulatedDepreciationOnDisposalAccount",+ "realizedExchangeGainAccount",+ "purchaseVarianceAccount",+ "salesShippingRevenueAccount",+ "overheadVarianceAccount",+ "realizedExchangeLossAccount",+ "prepaymentAccount",+ "salesAccount",+ "maintenanceAccount",+ "retainedEarningsAccount",+ "goodsReceivedNotInvoicedAccount",+ "supplierWriteOffAccount",+ "serviceChargeAccount",+ "interestAccount",+ "assetAquisitionCostAccount",+ "supplierPrepaymentAccount",+ "intercompanyPayablesAccount",+ "lotSizeVarianceAccount","indirectCostAccount",+ "bankCashAccount","roundingAccount",- "lotSizeVarianceAccount",- "intercompanyPayablesAccount",- "supplierPrepaymentAccount",- "assetAquisitionCostAccount",- "interestAccount"+ "scrapAccount",+ "assetAquisitionCostOnDisposalAccount",+ "subcontractingVarianceAccount",+ "bankLocalCurrencyAccount",+ "receivablesAccount",+ "payablesAccount",+ "intercompanyReceivablesAccount",+ "accumulatedDepreciationAccount",+ "supplierPaymentDiscountAccount",+ "reverseChargeSalesTaxPayableAccount",+ "customerPaymentDiscountAccount",+ "currencyTranslationAccount",+ "assetGainOnDisposalAccount",+ "customerWriteOffAccount",+ "salesDiscountAccount",+ "assetDepreciationExpenseAccount",+ "costOfGoodsSoldAccount"]},{"name": "accountingPeriod","rows": 0,"columns": [- "closedAt",+ "status",+ "periodNumber",+ "endDate",+ "closedBy",+ "closeStatus",+ "companyId",+ "lockedAt",+ "startDate",+ "fiscalYear",+ "lockedBy",+ "updatedBy",+ "createdBy","updatedAt","id","createdAt",- "updatedBy",- "createdBy",- "fiscalYear",- "startDate",- "lockedBy",- "lockedAt",- "companyId",- "closeStatus",- "closedBy",- "status",- "periodNumber",- "endDate"+ "closedAt"]},{@@ -122,56 +122,47 @@"rows": 0,"columns": ["endingBalance",+ "createdBy","accountingPeriodId","accountId",- "createdBy",+ "endingBalanceDate","updatedBy","id",- "endingBalanceDate",- "companyId",+ "createdAt","updatedAt",- "createdAt"+ "companyId"]},{"name": "accountingSyncOperation","rows": 0,"columns": [- "completedAt",- "updatedAt",- "entityId",- "createdBy",- "externalId",+ "trigger","integration","errorMessage","entityType",- "createdAt","updatedBy",- "trigger",- "idempotencyKey",- "id",- "lastAttemptAt",- "direction",+ "createdAt",+ "externalId",+ "createdBy",+ "entityId",+ "completedAt",+ "updatedAt",+ "status",+ "attemptCount","metadata",- "companyId","errorCode",- "status",- "attemptCount"+ "companyId",+ "direction",+ "idempotencyKey",+ "id",+ "lastAttemptAt"]},{"name": "accountingSyncTieOut","rows": 0,"columns": [- "docBackedAmount",- "pendingAmount",- "createdBy",- "internalDelta",- "companyId",- "carbonPostedAmount",- "excludedAmount",- "id",- "blockedAmount","syncedAmount","integration","externalDelta",@@ -181,23 +172,32 @@"computedAt","createdAt","accountId",- "providerAmount"+ "providerAmount",+ "docBackedAmount",+ "pendingAmount",+ "createdBy",+ "internalDelta",+ "companyId",+ "carbonPostedAmount",+ "excludedAmount",+ "id",+ "blockedAmount"]},{"name": "address","rows": 0,"columns": [- "phone",- "companyId",+ "addressLine2",+ "city",+ "countryCode",+ "stateProvince","addressLine1",- "postalCode",+ "companyId",+ "phone","fax","id",- "countryCode",- "addressLine2",- "city",- "stateProvince"+ "postalCode"]},{@@ -220,111 +220,111 @@"name": "agentMessage","rows": 0,"columns": [- "outputTokens",- "finishReason",- "updatedBy",- "threadId","feedback","createdBy","id","inputTokens",+ "outputTokens",+ "finishReason",+ "updatedBy",+ "threadId",+ "context",+ "createdAt","feedbackNote","role","companyId",- "updatedAt",- "context",- "createdAt"+ "updatedAt"]},{"name": "agentMessagePart","rows": 0,"columns": [- "toolName",- "updatedAt",- "errorMessage",- "companyId",- "orderIndex",- "updatedBy",- "createdBy",- "toolState",- "type",- "toolInput",- "toolClassification",+ "toolOutput",+ "id",+ "toolCallId",+ "textContent","messageId","toolDurationMs","createdAt",- "textContent",- "toolOutput",- "toolCallId",- "id"+ "toolInput",+ "toolClassification",+ "toolState",+ "type",+ "updatedBy",+ "createdBy",+ "updatedAt",+ "orderIndex",+ "companyId",+ "errorMessage",+ "toolName"]},{"name": "approvalRequest","rows": 0,"columns": [- "decisionAt",- "documentType",- "createdBy",- "updatedAt",- "requestedBy",- "decisionNotes",- "id",- "decisionBy","requestedAt",- "status","documentId","createdAt",+ "status","updatedBy","companyId",- "amount"+ "amount",+ "decisionAt",+ "updatedAt",+ "documentType",+ "createdBy",+ "requestedBy",+ "decisionBy",+ "id",+ "decisionNotes"]},{"name": "approvalRule","rows": 0,"columns": [- "enabled",- "approverGroupIds",- "escalationDays",- "updatedAt",- "defaultApproverId","documentType",- "companyId","createdAt",- "createdBy",- "id",+ "companyId","updatedBy",- "lowerBoundAmount"+ "id",+ "createdBy",+ "lowerBoundAmount",+ "approverGroupIds",+ "enabled",+ "escalationDays",+ "defaultApproverId",+ "updatedAt"]},{"name": "auditLogArchive","rows": 0,"columns": [- "sizeBytes",- "startDate",- "archivePath",- "endDate",- "createdAt","companyId",+ "createdAt",+ "id","rowCount",- "id"+ "startDate",+ "archivePath",+ "sizeBytes",+ "endDate"]},{"name": "changeOrderRequiredAction","rows": 0,"columns": [- "companyId","updatedAt",+ "companyId",+ "createdAt","id","customFields",- "createdAt",+ "updatedBy","active","name",- "updatedBy","createdBy"]},@@ -332,207 +332,208 @@"name": "changeOrderType","rows": 0,"columns": [- "companyId",+ "createdBy","createdAt",+ "companyId","updatedBy",- "createdBy",- "name","id",- "updatedAt"+ "updatedAt",+ "name"]},{"name": "companyAccountsPayableBillingAddress","rows": 0,"columns": [- "fax",- "countryCode",- "updatedBy",- "name",- "state",+ "updatedAt",+ "city",+ "addressLine1",+ "addressLine2",+ "postalCode","email","phone","id",- "postalCode",- "addressLine1",- "addressLine2",- "city",- "updatedAt"+ "state",+ "name",+ "updatedBy",+ "fax",+ "countryCode"]},{"name": "companyAccountsReceivableBillingAddress","rows": 0,"columns": [+ "updatedAt",+ "city","postalCode","addressLine2","addressLine1",- "city",- "updatedAt",- "countryCode",- "fax",- "updatedBy",- "name","state",+ "email","id","phone",- "email"+ "fax",+ "countryCode",+ "name",+ "updatedBy"]},{"name": "companySettings","rows": 0,"columns": [- "autoSelectMaterialWithoutPickingList",- "digitalQuoteIncludesPurchaseOrders",- "digitalQuoteNotificationGroup",- "purchasePriceUpdateTiming",- "maintenanceDispatchNotificationGroup",- "samplingStandard",- "showSupplierReadableId",- "qualityDispatchNotificationGroup",- "accountsReceivableEmail",- "showCurrencyTrailingZeros",- "printing",- "defaultCustomerCc",- "shelfLabelSize",- "timeCardEnabled",- "defaultSupplierCc",- "assetTaxRate",- "operationsDispatchNotificationGroup",- "kanbanOutput",- "quoteLineCategoryMarkups",- "rfqReadyNotificationGroup",- "assetTaxDepreciationEnabled",- "otherDispatchNotificationGroup",- "supplierQuoteNotificationGroup",- "allowLowercaseItemIds",- "inventoryShelfLife",- "incompletePickingListPolicy",- "consoleEnabled",- "digitalQuoteEnabled",- "gaugeCalibrationExpiredNotificationGroup",- "inventoryJobCompletedNotificationGroup",- "accountsReceivableAddress",- "accountsPayableAddress","returnPickedMaterialTiming","accountingEnabled",- "materialGeneratedIds",- "qualityIssueTarget",+ "accountsReceivableAddress",+ "inventoryJobCompletedNotificationGroup",+ "accountsPayableAddress","includeMaterialsOnTraveler",- "autoStartOperationTimer",+ "qualityIssueTarget",+ "materialGeneratedIds",+ "incompletePickingListPolicy",+ "inventoryShelfLife",+ "gaugeCalibrationExpiredNotificationGroup",+ "digitalQuoteEnabled",+ "consoleEnabled",+ "productLabelSize",+ "showCustomerReadableId","id","plmReleaseControl","salesJobCompletedNotificationGroup",+ "autoStartOperationTimer",+ "updateLeadTimesOnReceipt",+ "enforceInspectionFourEyes",+ "showCurrencyTrailingZeros","accountsPayableEmail",+ "allowLowercaseItemIds","useMetric",+ "printing",+ "defaultCustomerCc",+ "salesRuleNotificationGroup",+ "timeCardEnabled",+ "shelfLabelSize",+ "accountsReceivableEmail",+ "digitalQuoteIncludesPurchaseOrders",+ "purchasePriceUpdateTiming",+ "digitalQuoteNotificationGroup",+ "autoSelectMaterialWithoutPickingList",+ "showSupplierReadableId",+ "qualityDispatchNotificationGroup",+ "samplingStandard",+ "maintenanceDispatchNotificationGroup",+ "assetTaxDepreciationEnabled",+ "supplierQuoteNotificationGroup","requireMfa",- "enforceInspectionFourEyes",- "updateLeadTimesOnReceipt",- "productLabelSize",- "showCustomerReadableId"+ "otherDispatchNotificationGroup",+ "assetTaxRate",+ "defaultSupplierCc",+ "rfqReadyNotificationGroup",+ "operationsDispatchNotificationGroup",+ "quoteLineCategoryMarkups",+ "kanbanOutput"]},{"name": "companyUsage","rows": 0,"columns": [- "aiTokens",- "tasks",- "createdAt",- "nextResetDatetime","users","updatedAt","id",- "companyId"+ "companyId",+ "aiTokens",+ "tasks",+ "createdAt",+ "nextResetDatetime"]},{"name": "consumable","rows": 0,"columns": [+ "customFields",+ "tags","approved","approvedBy","createdBy",- "tags",- "customFields",- "updatedAt",- "createdAt","updatedBy","id",- "companyId"+ "companyId",+ "updatedAt",+ "createdAt"]},{"name": "contact","rows": 0,"columns": [- "homePhone",- "fax",- "firstName",- "title",- "id",- "workPhone",- "mobilePhone",+ "isCustomer",+ "email","lastName","companyId","notes",- "isCustomer",- "email"+ "mobilePhone",+ "workPhone",+ "id",+ "title",+ "firstName",+ "homePhone",+ "fax"]},{"name": "costCenter","rows": 0,"columns": [+ "createdBy",+ "updatedBy",+ "parentCostCenterId",+ "companyId",+ "createdAt","customFields","id",- "createdAt",- "name","ownerId","updatedAt",- "createdBy",- "parentCostCenterId",- "companyId",- "updatedBy"+ "name"]},{"name": "currency","rows": 0,"columns": [- "updatedBy",- "tags",- "historicalExchangeRate",- "code",- "customFields",- "createdAt",- "id",- "decimalPlaces","updatedAt","companyGroupId","createdBy",- "active"+ "active",+ "createdAt",+ "id",+ "decimalPlaces",+ "code",+ "customFields",+ "updatedBy",+ "historicalExchangeRate",+ "tags"]},{"name": "customField","rows": 0,"columns": [- "dataTypeId","updatedBy",- "table",- "required",- "sortOrder",+ "dataTypeId","active",- "id",+ "sortOrder",+ "required",+ "table",+ "listOptions","createdAt",+ "id","updatedAt",- "listOptions",- "tags",- "name","companyId",- "createdBy"+ "createdBy",+ "name",+ "tags"]},{@@ -540,62 +541,62 @@"rows": 0,"columns": ["createdBy",+ "updatedAt","createdAt","companyId",- "updatedAt",+ "updatedBy","id","tags",- "updatedBy",- "name",- "customFields"+ "customFields",+ "name"]},{"name": "customerType","rows": 0,"columns": [- "updatedBy","companyId","protected",+ "updatedBy","createdAt",+ "name","tags","updatedAt",- "name",- "createdBy","id",- "customFields"+ "customFields",+ "createdBy"]},{"name": "department","rows": 0,"columns": [- "tags",- "updatedAt",- "name",- "createdAt",- "customFields",- "id",+ "createdBy","updatedBy",- "parentDepartmentId","companyId",- "createdBy"+ "parentDepartmentId",+ "createdAt",+ "id",+ "customFields",+ "tags",+ "updatedAt",+ "name"]},{"name": "depreciationRun","rows": 0,"columns": [- "companyId",- "status",- "periodEnd",- "postedAt",- "createdAt",- "updatedBy",- "depreciationRunId",- "postedBy",+ "createdBy","id",- "createdBy"+ "postedBy",+ "depreciationRunId",+ "updatedBy",+ "createdAt",+ "postedAt",+ "periodEnd",+ "status",+ "companyId"]},{@@ -603,82 +604,82 @@"rows": 0,"columns": ["active",- "createdBy",- "entityType","companyGroupId",- "required",- "updatedBy",+ "entityType",+ "createdBy","id",- "updatedAt",+ "updatedBy",+ "required",+ "name","createdAt",- "name"+ "updatedAt"]},{"name": "dimensionValue","rows": 0,"columns": [- "updatedBy",- "companyGroupId",- "name",- "createdBy",- "updatedAt",- "dimensionId",+ "id","createdAt",- "id"+ "dimensionId",+ "updatedAt",+ "createdBy",+ "name",+ "companyGroupId",+ "updatedBy"]},{"name": "document","rows": 0,"columns": [- "path",- "createdAt",- "sourceDocument",- "active",- "readGroups",- "companyId",- "id",- "writeGroups","description",- "updatedBy","name",+ "updatedBy","type","createdBy","size","sourceDocumentId",- "updatedAt"+ "updatedAt",+ "sourceDocument",+ "path",+ "createdAt",+ "readGroups",+ "active",+ "id",+ "writeGroups",+ "companyId"]},{"name": "documentExtraction","rows": 0,"columns": [- "storagePath","createdAt",- "sourceDocument",- "updatedAt",- "sourceDocumentId",+ "storagePath","status",- "filteredData",- "id",- "createdBy",+ "sourceDocumentId",+ "updatedAt",+ "sourceDocument","documentType",- "updatedBy",- "companyId",+ "createdBy",+ "id",+ "filteredData",+ "error","extractedData",- "error"+ "companyId",+ "updatedBy"]},{"name": "documentFavorite","rows": 0,- "columns": ["userId", "documentId"]+ "columns": ["documentId", "userId"]},{"name": "documentLabel","rows": 0,- "columns": ["userId", "documentId", "label", "companyId"]+ "columns": ["userId", "documentId", "companyId", "label"]},{"name": "documentSection",@@ -700,196 +701,242 @@"name": "documentTemplate","rows": 0,"columns": [- "formatVersion",- "documentType",- "settings",- "updatedBy",- "blocks",+ "createdBy",+ "headerSectionId","companyId","updatedAt",- "headerSectionId",- "createdBy",+ "theme",+ "createdAt","id","footerSectionId",- "createdAt",- "theme"+ "settings",+ "formatVersion",+ "documentType",+ "updatedBy",+ "blocks"]},{"name": "documentTransaction","rows": 0,"columns": [- "type",- "userId",- "createdAt","documentId","id",- "companyId"+ "companyId",+ "userId",+ "type",+ "createdAt"]},{"name": "employeeType","rows": 0,"columns": [- "systemType",- "protected",- "companyId","createdAt",- "name",+ "companyId",+ "protected",+ "systemType",+ "id","updatedAt",- "id"+ "name"]},{"name": "employee","rows": 0,- "columns": ["companyId", "id", "employeeTypeId", "active", "pin"]+ "columns": ["id", "companyId", "pin", "active", "employeeTypeId"]},{"name": "employeeTypePermission","rows": 0,"columns": [- "createdAt",- "delete",- "create","update",- "updatedAt",- "module",+ "create",+ "delete",+ "createdAt",+ "employeeTypeId","view",- "employeeTypeId"+ "module",+ "updatedAt"]},{- "name": "eventSystemSubscription",+ "name": "enforcementRule","rows": 0,"columns": [- "name",- "config",+ "description",+ "customFields",+ "filteredItemTypes","active",- "id","createdAt",- "filter",+ "name",+ "family",+ "filteredItemMatchAll",+ "updatedAt",+ "updatedBy",+ "severity",+ "id",+ "surfaces",+ "appliesToAll",+ "message",+ "createdBy",+ "filteredItemGroupIds","companyId",- "table",- "handlerType",- "operations"+ "conditionAst",+ "targetType"]},{- "name": "exchangeRateOverride",+ "name": "enforcementRuleAcknowledgment","rows": 0,"columns": [- "updatedAt",+ "ruleName",+ "updatedBy",+ "ruleId",+ "documentLineId",+ "createdBy",+ "documentType","companyId","createdAt",+ "outcome",+ "itemId",+ "message","id",- "updatedBy",- "rate",- "currencyCode",- "createdBy"+ "severity",+ "documentId"]},{- "name": "externalIntegrationMapping",+ "name": "eventSystemSubscription","rows": 0,"columns": [- "allowDuplicateExternalId","id",- "remoteUpdatedAt",- "updatedAt",- "lastSyncedAt","createdAt",- "entityType",+ "filter",+ "name",+ "config",+ "active",+ "operations",+ "table","companyId",- "createdBy",- "externalId",- "metadata",- "integration",- "entityId",- "updatedBy"+ "handlerType"]},{- "name": "fiscalYearSettings",- "rows": 0,- "columns": ["taxStartMonth", "updatedBy", "startMonth", "companyId"]- },- {- "name": "fixedAssetClass",+ "name": "exchangeRateOverride","rows": 0,"columns": [+ "companyId","updatedAt",- "usefulLifeMonths",- "lossOnDisposalAccountId",+ "id","createdAt",- "taxResidualValuePercent",- "createdBy",- "macrsConvention",- "taxUsefulLifeMonths",- "description",- "depreciationMethod",- "companyId",- "bonusDepreciationPercent",- "assetAccountId",+ "rate",+ "currencyCode","updatedBy",- "depreciationExpenseAccountId",- "id",- "writeDownAccountId",- "residualValuePercent",- "gainOnDisposalAccountId",- "macrsPropertyClass",- "taxDepreciationMethod",- "name",- "accumulatedDepreciationAccountId",- "customFields",- "writeOffAccountId"+ "createdBy"]},{- "name": "gaugeType",+ "name": "externalIntegrationMapping","rows": 0,"columns": [- "id",- "createdBy",- "name",+ "entityId","updatedBy",- "createdAt",+ "integration",+ "metadata",+ "createdBy",+ "externalId",+ "entityType","companyId",- "customFields",- "updatedAt"+ "lastSyncedAt",+ "createdAt",+ "remoteUpdatedAt",+ "id",+ "updatedAt",+ "allowDuplicateExternalId"]},{- "name": "group",+ "name": "fiscalYearSettings","rows": 0,- "columns": [- "isEmployeeTypeGroup",- "companyId",- "isIdentityGroup",- "isCustomerTypeGroup",- "isSupplierOrgGroup",+ "columns": ["startMonth", "companyId", "taxStartMonth", "updatedBy"]+ },+ {+ "name": "fixedAssetClass",+ "rows": 0,+ "columns": [+ "name",+ "taxDepreciationMethod",+ "macrsPropertyClass",+ "writeOffAccountId",+ "customFields",+ "accumulatedDepreciationAccountId",+ "writeDownAccountId",+ "depreciationExpenseAccountId","id",+ "gainOnDisposalAccountId",+ "residualValuePercent",+ "bonusDepreciationPercent",+ "companyId",+ "description",+ "taxUsefulLifeMonths",+ "depreciationMethod",+ "assetAccountId",+ "updatedBy",+ "lossOnDisposalAccountId",+ "createdAt",+ "usefulLifeMonths","updatedAt",- "isCustomerOrgGroup",+ "macrsConvention",+ "createdBy",+ "taxResidualValuePercent"+ ]+ },+ {+ "name": "gaugeType",+ "rows": 0,+ "columns": [+ "id",+ "createdBy","name",+ "updatedBy",+ "createdAt",+ "customFields",+ "companyId",+ "updatedAt"+ ]+ },+ {+ "name": "group",+ "rows": 0,+ "columns": [+ "isCustomerOrgGroup",+ "updatedAt",+ "id",+ "isSupplierOrgGroup",+ "createdAt","isSupplierTypeGroup",- "createdAt"+ "name",+ "isEmployeeTypeGroup",+ "isCustomerTypeGroup",+ "isIdentityGroup",+ "companyId"]},{"name": "holiday","rows": 0,"columns": [- "updatedBy",+ "createdAt",+ "date",+ "companyId","customFields",+ "updatedBy","name","createdBy",- "updatedAt",- "id","tags",- "createdAt",- "date",- "companyId"+ "id",+ "updatedAt"]},{@@ -911,292 +958,292 @@"name": "implementationFieldValue","rows": 0,"columns": [- "createdAt",- "id",- "updatedAt",- "companyId","createdBy",- "updatedBy","value",- "fieldKey"+ "fieldKey",+ "updatedBy",+ "id",+ "createdAt",+ "companyId",+ "updatedAt"]},{"name": "implementationRow","rows": 0,"columns": [- "sortOrder",- "createdAt",- "collection",- "payload","createdBy","updatedAt","id","updatedBy",- "companyId"+ "companyId",+ "sortOrder",+ "createdAt",+ "collection",+ "payload"]},{"name": "invite","rows": 0,"columns": [- "attestedBy",- "role",- "createdBy",- "email",- "permissions",+ "revokedAt",+ "createdAt",+ "code",+ "attestedAt","companyId","updatedBy","acceptedAt","id",- "revokedAt",- "createdAt",- "code",- "attestedAt"+ "createdBy",+ "email",+ "permissions",+ "attestedBy",+ "role"]},{"name": "itarCertification","rows": 0,"columns": [+ "createdBy",+ "type",+ "userId",+ "fullLegalName","docVersion","userAgent","createdAt","updatedAt",- "userId",- "type",- "createdBy",- "fullLegalName",- "id",- "complianceContact",- "ipAddress",- "docHash",- "updatedBy","expiresAt","companyId",+ "updatedBy",+ "certifiedAt","title",- "certifiedAt"+ "ipAddress",+ "complianceContact",+ "id",+ "docHash"]},{"name": "itemPostingGroup","rows": 0,"columns": [- "active",+ "companyId","description",+ "active","createdAt",- "companyId",- "name",- "updatedBy",- "customFields",- "id","updatedAt",+ "id","tags",- "createdBy"+ "createdBy",+ "name",+ "updatedBy",+ "customFields"]},{"name": "itemStockQuantities","rows": 0,- "columns": ["locationId", "quantityOnHand", "itemId", "companyId"]+ "columns": ["quantityOnHand", "locationId", "itemId", "companyId"]},{"name": "journal","rows": 0,"columns": [- "customFields",+ "postingDate",+ "reversalOfId",+ "postedBy",+ "updatedAt",+ "eliminationKind",+ "updatedBy","postedAt","accountingPeriodId","companyId",- "updatedBy",- "eliminationKind",- "updatedAt",- "postedBy",- "reversalOfId",- "postingDate",- "tags",- "status",- "createdBy",- "description",- "reversedById",- "createdAt",+ "customFields",+ "sourceType","journalEntryId","id",- "sourceType"+ "createdAt",+ "reversedById",+ "description",+ "createdBy",+ "status",+ "tags"]},{"name": "journalLine","rows": 0,"columns": [- "accountId",+ "documentId",+ "journalLineReference",+ "tags",+ "companyId",+ "journalId",+ "quantity",+ "id",+ "externalDocumentId",+ "documentLineReference",+ "documentType",+ "description",+ "createdAt",+ "updatedBy",+ "updatedAt","createdBy","customFields",- "accrual",- "intercompanyPartnerId",+ "accountId","amount",- "documentType",- "updatedAt",- "updatedBy",- "createdAt",- "description",- "quantity",- "documentLineReference",- "externalDocumentId",- "id",- "journalLineReference",- "documentId",- "journalId",- "companyId",- "tags"+ "intercompanyPartnerId",+ "accrual"]},{"name": "intercompanyTransaction","rows": 0,"columns": [+ "updatedAt","status","sourceJournalLineId",- "updatedAt",- "targetCompanyId",+ "amount","sourceCompanyId","createdAt",- "amount",- "id",+ "targetCompanyId",+ "targetJournalLineId","description",+ "id","documentId",- "targetJournalLineId",- "companyGroupId",- "eliminationJournalId","currencyCode",- "documentType"+ "documentType",+ "companyGroupId",+ "eliminationJournalId"]},{"name": "intercompanyEliminationLine","rows": 0,"columns": [- "itemId",- "createdBy",+ "createdAt",+ "quantity",+ "id",+ "accountId","updatedAt","companyId",- "accountId",- "id",- "quantity",- "createdAt",- "amount",- "role",- "intercompanyTransactionId",+ "createdBy",+ "itemId","journalLineId",- "updatedBy"+ "updatedBy",+ "intercompanyTransactionId",+ "role",+ "amount"]},{"name": "journalLineDimension","rows": 0,"columns": [- "createdAt",- "id","journalLineId",- "companyId",+ "id",+ "createdAt",+ "valueId","dimensionId",- "valueId"+ "companyId"]},{"name": "location","rows": 0,"columns": [- "countryCode",- "latitude","updatedAt","name","createdBy",- "stateProvince",- "id",+ "countryCode",+ "latitude","timezone",+ "id","longitude",- "postalCode",- "addressLine2",+ "stateProvince","addressLine1","createdAt",+ "addressLine2","tags","code",- "customFields",- "updatedBy",- "requiresStaffing",+ "postalCode","companyId",- "city"+ "requiresStaffing",+ "city",+ "customFields",+ "updatedBy"]},{"name": "fixedAsset","rows": 0,"columns": [- "disposalMethod",- "serialNumber",- "companyId",- "taxDepreciationMethod",- "id",- "usefulLifeMonths",- "disposalDate",- "customFields",- "residualValuePercent",- "updatedAt","depreciationMethod",+ "updatedAt","createdBy",- "taxResidualValuePercent",- "fixedAssetId",+ "customFields",+ "residualValuePercent",+ "disposalDate","bonusDepreciationPercent",- "macrsConvention",- "accumulatedTaxDepreciation",+ "fixedAssetId",+ "taxResidualValuePercent",+ "serialNumber",+ "disposalMethod",+ "id",+ "usefulLifeMonths",+ "companyId",+ "taxDepreciationMethod",+ "createdAt",+ "locationId",+ "status",+ "notes",+ "name",+ "fixedAssetClassId",+ "macrsPropertyClass",+ "acquisitionDate",+ "depreciationStartDate","saleProceeds","acquisitionCost",- "description",+ "macrsConvention",+ "accumulatedTaxDepreciation",+ "assetLifetimeUsage","accumulatedDepreciation","updatedBy","taxUsefulLifeMonths",- "assetLifetimeUsage",- "notes",- "locationId",- "status",- "createdAt",- "depreciationStartDate",- "acquisitionDate",- "name",- "macrsPropertyClass",- "fixedAssetClassId"+ "description"]},{"name": "depreciationRunLine","rows": 0,"columns": [- "journalId",- "id",- "depreciationRunId",- "taxAmount","companyId","fixedAssetId",- "amount"+ "amount",+ "taxAmount",+ "depreciationRunId",+ "journalId",+ "id"]},{"name": "fixedAssetDisposal","rows": 0,"columns": [- "gainLoss",- "disposalDate",- "disposalMethod",- "updatedBy",- "saleProceeds",+ "netBookValueAtDisposal",+ "companyId",+ "id",+ "createdBy","journalId","createdAt","fixedAssetId",- "netBookValueAtDisposal",- "id",- "companyId",- "createdBy"+ "saleProceeds",+ "updatedBy",+ "gainLoss",+ "disposalMethod",+ "disposalDate"]},{@@ -1204,50 +1251,50 @@"rows": 0,"columns": ["createdAt",- "periodStart","periodEnd",+ "periodStart","unitsProduced","createdBy","fixedAssetId","companyId",- "updatedBy",- "id"+ "id",+ "updatedBy"]},{"name": "inventoryCount","rows": 0,"columns": [- "locationId",- "updatedBy",- "inventoryCountId",- "scope",- "createdBy",- "status",- "updatedAt",- "companyId",- "createdAt",- "customFields",- "postedBy",- "snapshotAt",+ "isBlind","postedAt","id","notes",- "isBlind"+ "postedBy",+ "snapshotAt",+ "createdAt",+ "companyId",+ "customFields",+ "updatedAt",+ "status",+ "createdBy",+ "scope",+ "locationId",+ "inventoryCountId",+ "updatedBy"]},{"name": "maintenanceFailureMode","rows": 0,"columns": [- "companyId",- "createdBy",- "updatedAt",- "createdAt",+ "id",+ "updatedBy","name","type",- "id",- "updatedBy"+ "createdAt",+ "createdBy",+ "companyId",+ "updatedAt"]},{@@ -1269,132 +1316,132 @@{"name": "materialDimension","rows": 0,- "columns": ["id", "materialFormId", "companyId", "name", "isMetric"]+ "columns": ["name", "isMetric", "companyId", "materialFormId", "id"]},{"name": "materialSubstance","rows": 0,"columns": [- "name",- "updatedAt",+ "updatedBy",+ "customFields",+ "companyId",+ "createdBy","code",- "tags",- "id",+ "updatedAt",+ "name","createdAt",- "companyId",- "customFields",- "updatedBy",- "createdBy"+ "id",+ "tags"]},{"name": "materialFinish","rows": 0,- "columns": ["name", "id", "companyId", "materialSubstanceId"]+ "columns": ["companyId", "materialSubstanceId", "name", "id"]},{"name": "materialGrade","rows": 0,- "columns": ["materialSubstanceId", "id", "name", "companyId"]+ "columns": ["companyId", "name", "id", "materialSubstanceId"]},{"name": "materialType","rows": 0,"columns": [- "companyId",- "id",- "name",- "materialFormId",+ "code","materialSubstanceId",- "code"+ "materialFormId",+ "name",+ "id",+ "companyId"]},{"name": "material","rows": 0,"columns": [+ "companyId",+ "approvedBy",+ "id",+ "createdAt",+ "customFields",+ "approved","createdBy","gradeId","tags",- "materialTypeId","updatedAt",+ "materialTypeId","dimensionId","finishId","materialFormId","updatedBy",- "materialSubstanceId",- "companyId",- "approvedBy",- "id",- "createdAt",- "customFields",- "approved"+ "materialSubstanceId"]},{"name": "membership","rows": 0,- "columns": ["memberGroupId", "memberUserId", "id", "groupId"]+ "columns": ["groupId", "id", "memberUserId", "memberGroupId"]},{"name": "modelUpload","rows": 0,"columns": [- "thumbnailPath",- "name",- "glbPath",- "optimizedSize",- "updatedAt",- "createdAt",- "updatedBy",- "createdBy",- "id",- "originalSize",- "processedAt",- "componentCount",- "processingStatus",- "size",- "modelPath",- "companyId",- "optimizedAt",- "autodeskUrn",- "optimizedModelPath",- "optimizeError","processingError","optimizeStatus",+ "originalPath","graphPath",- "originalPath"+ "optimizeError",+ "autodeskUrn",+ "optimizedModelPath",+ "optimizedAt",+ "companyId",+ "modelPath",+ "size",+ "processingStatus",+ "processedAt",+ "componentCount",+ "originalSize",+ "id",+ "createdBy",+ "updatedBy",+ "createdAt",+ "optimizedSize",+ "updatedAt",+ "glbPath",+ "thumbnailPath",+ "name"]},{"name": "assemblyPlanJob","rows": 0,"columns": [- "modelUploadId",- "createdAt",- "companyId",- "updatedAt",- "id",- "createdBy",- "stats",+ "planPath",+ "error","status","kind",- "error",- "planPath"+ "stats",+ "id",+ "createdBy",+ "updatedAt",+ "companyId",+ "createdAt",+ "modelUploadId"]},{"name": "noQuoteReason","rows": 0,"columns": [- "updatedAt",- "createdAt",- "companyId",- "createdBy",+ "updatedBy",+ "id","customFields","name",- "updatedBy",- "id"+ "createdBy",+ "updatedAt",+ "createdAt",+ "companyId"]},{@@ -1402,449 +1449,449 @@"rows": 0,"columns": ["createdAt",- "updatedAt",- "name","active",- "createdBy",- "systemType",+ "name",+ "updatedAt","id",- "updatedBy",- "companyId"+ "systemType",+ "createdBy",+ "companyId",+ "updatedBy"]},{"name": "nonConformanceType","rows": 0,"columns": [- "createdBy",- "updatedBy",+ "name",+ "customFields",+ "id",+ "updatedAt","createdAt","companyId",- "updatedAt",- "id",- "customFields",- "name"+ "updatedBy",+ "createdBy"]},{"name": "nonConformanceWorkflow","rows": 0,"columns": [+ "createdBy",+ "description",+ "content",+ "requiredActionIds","priority","companyId","updatedAt",- "requiredActionIds",- "content",- "description",- "createdBy",- "tags",- "id",- "approvalRequirements",- "source",+ "updatedBy","createdAt","name",- "updatedBy",- "active"+ "active",+ "approvalRequirements",+ "id",+ "tags",+ "source"]},{"name": "nonConformance","rows": 0,"columns": [- "createdBy",- "status",- "nonConformanceWorkflowId",- "updatedBy",- "id",- "createdAt",- "approvalRequirements",- "requiredActionIds","locationId","nonConformanceId","dueDate",- "customFields",- "openDate",- "closeDate",- "updatedAt",+ "createdAt",+ "approvalRequirements",+ "requiredActionIds",+ "updatedBy",+ "nonConformanceWorkflowId",+ "id",+ "createdBy",+ "status",+ "quantity",+ "description",+ "name",+ "nonConformanceTypeId",+ "companyId",+ "priority","source",- "content","assignee",+ "content","tags",- "priority",- "companyId",- "quantity",- "nonConformanceTypeId",- "name",- "description"+ "openDate",+ "customFields",+ "updatedAt",+ "closeDate"]},{"name": "changeOrder","rows": 0,"columns": [- "reasonForChange",- "name",- "approvalRequirements",- "customFields",- "tags",- "updatedAt",- "status",- "createdBy",- "companyId",- "dueDate",- "description",- "assignee",- "createdAt",- "sourceType",- "sourceId",- "changeOrderId",- "requiredActionIds",+ "type",+ "changeOrderTypeId",+ "id",+ "openDate","priority","nonConformanceId","updatedBy",- "id",- "changeOrderTypeId",- "openDate",- "type"+ "sourceId",+ "changeOrderId",+ "requiredActionIds",+ "assignee",+ "sourceType",+ "createdAt",+ "createdBy",+ "dueDate",+ "companyId",+ "description",+ "status",+ "updatedAt",+ "approvalRequirements",+ "name",+ "reasonForChange",+ "customFields",+ "tags"]},{"name": "changeOrderActionTask","rows": 0,"columns": [- "completedDate",+ "createdAt",+ "dueDate",+ "updatedBy",+ "updatedAt",+ "name",+ "status",+ "assignee","companyId",- "id","sortOrder",- "tags",- "notes",- "createdBy",+ "id",+ "completedDate","changeOrderId",+ "createdBy","actionTypeId",- "updatedBy",- "dueDate",- "createdAt",- "assignee",- "status",- "updatedAt",- "name"+ "tags",+ "notes"]},{"name": "nonConformanceApprovalTask","rows": 0,"columns": [- "notes",- "tags",- "nonConformanceId",- "createdBy",- "completedDate",- "sortOrder",- "id",- "companyId",+ "updatedBy",+ "dueDate",+ "createdAt","assignee",+ "status","updatedAt","approvalType",- "status",- "updatedBy",- "createdAt",- "dueDate"+ "completedDate",+ "id",+ "sortOrder",+ "companyId",+ "notes",+ "tags",+ "createdBy",+ "nonConformanceId"]},{"name": "nonConformanceReviewer","rows": 0,"columns": [- "updatedAt",- "createdAt",- "title",- "assignee",- "updatedBy",- "id",- "createdBy",- "companyId",- "nonConformanceId","status",+ "nonConformanceId",+ "companyId","completedDate",- "notes"+ "notes",+ "title",+ "createdAt",+ "updatedAt",+ "createdBy",+ "id",+ "updatedBy",+ "assignee"]},{"name": "note","rows": 0,"columns": [- "active",- "noteRichText",- "note",- "createdAt",- "id",- "updatedAt",- "companyId","documentId","updatedBy",- "createdBy"+ "createdBy",+ "updatedAt",+ "id",+ "companyId",+ "note",+ "noteRichText",+ "createdAt",+ "active"]},{"name": "notification","rows": 0,"columns": [- "documentType",- "id",- "payload",- "title",- "seenAt",- "userId",- "from",- "documentId",- "event",- "readAt",- "createdAt",+ "description","digestedInto","companyId","topic",- "description"+ "createdAt",+ "readAt",+ "event",+ "from",+ "documentId",+ "userId",+ "seenAt",+ "title",+ "documentType",+ "id",+ "payload"]},{"name": "notificationDelivery","rows": 0,"columns": [- "documentId",- "event",- "userId","lastDeliveryId",- "id",- "createdAt",- "successCount",+ "userId",+ "event",+ "documentId",+ "lastDeliveredAt","companyId",- "lastDeliveredAt"+ "successCount",+ "createdAt",+ "id"]},{"name": "notificationPreference","rows": 0,"columns": [+ "enabled",+ "id",+ "userId",+ "topic","updatedAt","companyId",- "channel",- "topic",- "userId",- "enabled",- "id"+ "channel"]},{"name": "oauthCode","rows": 0,"columns": [- "createdAt",- "clientId",- "userId",- "companyId",+ "redirectUri",+ "id",+ "codeChallenge",+ "scope","expiresAt","codeChallengeMethod","code",- "redirectUri",- "codeChallenge",- "id",- "scope"+ "companyId",+ "createdAt",+ "userId",+ "clientId"]},{"name": "part","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",- "toDate",- "customFields","companyId","createdAt",- "fromDate",- "updatedAt",- "tags",+ "customFields",+ "toDate",+ "id",+ "createdBy",+ "updatedBy",+ "approvedBy","approved",- "approvedBy"+ "tags",+ "fromDate",+ "updatedAt"]},{"name": "paymentTerm","rows": 0,"columns": [- "daysDiscount",- "daysDue",- "tags","active",- "discountPercentage",+ "tags",+ "daysDue",+ "daysDiscount","updatedBy",- "customFields",- "name",- "createdBy",+ "discountPercentage","companyId",- "updatedAt",- "id",+ "createdBy",+ "name",+ "customFields",+ "calculationMethod","createdAt",- "calculationMethod"+ "id",+ "updatedAt"]},{"name": "periodCloseTaskDefinition","rows": 0,"columns": [- "severity",- "isSystem",+ "taskType",+ "updatedBy",+ "name",+ "required",+ "autoCheckKey",+ "createdBy",+ "updatedAt","customFields",- "companyId","createdAt",- "sortOrder",+ "companyId",+ "severity",+ "isSystem","id","active","defaultAssigneeId",- "required",- "taskType",- "name",- "updatedBy",- "updatedAt",- "createdBy",- "autoCheckKey"+ "sortOrder"]},{"name": "periodCloseTask","rows": 0,"columns": [- "taskType","status","required","id",- "severity",- "sortOrder",+ "taskType","completedBy","companyId","evidenceJournalId",- "updatedAt",- "skippedReason",- "notes",+ "severity",+ "sortOrder","name","assigneeId","updatedBy",- "autoCheckKey",+ "updatedAt",+ "skippedReason",+ "notes","createdAt","createdBy","completedAt","accountingPeriodId",- "definitionId"+ "definitionId",+ "autoCheckKey"]},{"name": "pickingList","rows": 0,"columns": [- "createdAt",+ "notes",+ "locationId",+ "status",+ "assignee",+ "updatedAt","companyId",+ "createdAt","customFields","pickingListId","dueDate",- "updatedBy","id","createdBy",- "notes",- "locationId",- "status",- "assignee",- "updatedAt"+ "updatedBy"]},{"name": "pricingRule","rows": 0,"columns": [- "itemIds",- "customerIds",- "id",- "priority",- "validFrom",- "name",- "customerTypeIds",- "maxQuantity",- "amount","itemPostingGroupId","createdAt",+ "amount","updatedAt",- "updatedBy","active",- "createdBy",+ "updatedBy","companyId",- "validTo",+ "createdBy","ruleType",+ "validTo","amountType",- "minQuantity"+ "minQuantity",+ "itemIds",+ "customerIds",+ "id",+ "priority",+ "name",+ "validFrom",+ "customerTypeIds",+ "maxQuantity"]},{"name": "printJob","rows": 0,"columns": [- "attempts",- "companyId",- "updatedAt",- "description","sourceDocumentId",- "origin",- "sourceDocumentReadableId",- "id",+ "description",+ "updatedAt",+ "companyId",+ "attempts","printerUrl",- "completedAt",+ "id",+ "sourceDocumentReadableId",+ "origin",+ "sourceDocument",+ "contentType","status","createdBy",- "contentType",- "sourceDocument",- "content",- "error",+ "completedAt",+ "updatedBy","createdAt",- "updatedBy"+ "error",+ "content"]},{"name": "printerRoute","rows": 0,"columns": [- "name",- "locationId",- "printerUrl",- "format",- "companyId","updatedAt","apiKey",+ "companyId",+ "mediaSizeId","templateId",- "id","createdAt",- "mediaSizeId"+ "id",+ "printerUrl",+ "locationId",+ "name",+ "format"]},{"name": "process","rows": 0,"columns": [- "completeAllOnScan",- "customFields",- "batchRules",- "batchable",- "companyId",- "requiresAbility",- "defaultStandardFactor",- "createdAt",- "id",- "updatedAt",- "tags",- "createdBy",- "batchType",- "name","active",+ "name",+ "batchType",+ "processType","updatedBy",- "processType"+ "tags",+ "updatedAt",+ "id",+ "createdBy",+ "defaultStandardFactor",+ "requiresAbility",+ "companyId",+ "createdAt",+ "customFields",+ "completeAllOnScan",+ "batchable",+ "batchRules"]},{@@ -1853,235 +1900,235 @@"columns": ["active","recertifyEveryDays",+ "createdAt","curve","shadowWeeks",- "createdAt",+ "companyId","updatedAt","id","processId",- "companyId",- "name","createdBy",- "updatedBy"+ "updatedBy",+ "name"]},{"name": "employeeAbility","rows": 0,"columns": [+ "lastTrainingDate",+ "abilityId","id","expiresAt","companyId",- "employeeId",- "lastTrainingDate",- "abilityId"+ "employeeId"]},{"name": "procedure","rows": 0,"columns": [- "version",+ "id",+ "companyId",+ "createdBy",+ "status",+ "name",+ "updatedBy",+ "assignee",+ "createdAt","updatedAt",- "content",+ "version",+ "description","processId","tags",- "description",- "status",- "createdBy",- "companyId",- "id",- "createdAt",- "assignee",- "updatedBy",- "name"+ "content"]},{"name": "procedureParameter","rows": 0,"columns": [- "updatedAt",- "procedureId",- "createdAt",- "updatedBy","id",- "createdBy",- "key",+ "updatedBy",+ "createdAt",+ "procedureId",+ "updatedAt",+ "companyId","value",- "companyId"+ "key",+ "createdBy"]},{"name": "purchasingRfq","rows": 0,"columns": [+ "notes",+ "id",+ "assignee",+ "rfqDate","updatedAt","customFields","rfqId","internalNotes","locationId",- "notes",- "id",- "assignee",- "rfqDate",- "createdAt",- "revisionId",- "status",- "expirationDate","employeeId","companyId","createdBy",- "updatedBy"+ "updatedBy",+ "revisionId",+ "createdAt",+ "status",+ "expirationDate"]},{"name": "purchasingRfqFavorite","rows": 0,- "columns": ["userId", "rfqId"]+ "columns": ["rfqId", "userId"]},{"name": "qualityDocument","rows": 0,"columns": [+ "updatedBy",+ "status","description","version","assignee",- "status",- "updatedBy",- "tags",- "name",- "createdBy",- "companyId",- "updatedAt","createdAt","id",- "content"+ "updatedAt",+ "content",+ "name",+ "tags",+ "companyId",+ "createdBy"]},{"name": "reportPin","rows": 0,"columns": [- "companyId",- "pinned","updatedBy",+ "pinned",+ "companyId","createdBy",- "userId","updatedAt",- "reportKey",- "createdAt"+ "userId",+ "createdAt",+ "reportKey"]},{"name": "reportView","rows": 0,"columns": [+ "visibility","id","updatedBy",- "visibility",- "companyId",- "updatedAt","createdAt",+ "updatedAt",+ "companyId","config",+ "createdBy","name",- "reportKey",- "createdBy"+ "reportKey"]},{"name": "returnReason","rows": 0,"columns": [- "updatedBy","inventoryValueZero","companyId",+ "updatedBy","createdBy",- "updatedAt","name",- "createdAt",+ "updatedAt","customFields",- "id"+ "id",+ "createdAt"]},{"name": "scrapReason","rows": 0,"columns": [- "customFields",- "name",- "updatedBy",- "id",- "updatedAt","createdAt","companyId",- "createdBy"- ]- },- {- "name": "searchIndexRegistry",- "rows": 0,- "columns": ["createdAt", "companyId", "lastRebuiltAt"]+ "updatedAt",+ "createdBy",+ "name",+ "customFields",+ "id",+ "updatedBy"+ ]+ },+ {+ "name": "searchIndexRegistry",+ "rows": 0,+ "columns": ["companyId", "createdAt", "lastRebuiltAt"]},{"name": "sequence","rows": 0,"columns": [- "next",- "companyId",- "updatedBy",- "step",- "updatedAt",- "table","suffix","size",+ "name","prefix",- "name"+ "next",+ "updatedBy",+ "companyId",+ "updatedAt",+ "step",+ "table"]},{"name": "service","rows": 0,"columns": [- "approved",- "updatedAt",- "serviceType",- "toDate","approvedBy","createdAt","tags",- "updatedBy",- "companyId",+ "serviceType",+ "updatedAt",+ "approved",+ "toDate","createdBy",- "id","customFields",- "fromDate"+ "id",+ "fromDate",+ "updatedBy",+ "companyId"]},{"name": "shift","rows": 0,"columns": [+ "id",+ "wednesday",+ "friday",+ "sunday",+ "createdAt",+ "name",+ "active",+ "tuesday",+ "thursday","tags","saturday","locationId","updatedBy","createdBy","endTime",- "startTime","companyId",+ "startTime","updatedAt","customFields",- "monday",- "id",- "wednesday",- "friday",- "sunday",- "createdAt",- "name",- "active",- "tuesday",- "thursday"+ "monday"]},{@@ -2089,17 +2136,17 @@"rows": 0,"columns": ["title",- "shiftId",- "managerId","companyId",+ "managerId",+ "shiftId",+ "startDate","departmentId",- "updatedBy","id",- "startDate",- "locationId",- "tags",+ "updatedBy","customFields",- "updatedAt"+ "updatedAt",+ "locationId",+ "tags"]},{@@ -2112,11 +2159,11 @@"rows": 0,"columns": ["shiftId",- "employeeId","date",+ "employeeId","createdBy",- "updatedBy","id",+ "updatedBy","note","companyId","createdAt",@@ -2127,34 +2174,34 @@"name": "shippingMethod","rows": 0,"columns": [+ "createdAt",+ "updatedAt",+ "name",+ "tags","active","createdBy","id","updatedBy",- "createdAt",- "updatedAt",- "tags",- "name",- "trackingUrl",- "customFields","companyId","carrier",- "carrierAccountId"+ "carrierAccountId",+ "customFields",+ "trackingUrl"]},{"name": "shippingTerm","rows": 0,"columns": [- "updatedBy",- "name",- "createdBy",- "tags",- "id",+ "createdAt","updatedAt",- "active","companyId",- "createdAt"+ "active",+ "createdBy",+ "id",+ "tags",+ "updatedBy",+ "name"]},{@@ -2177,471 +2224,446 @@"name": "ssoConnection","rows": 0,"columns": [- "active",- "createdAt",- "id",- "updatedAt","createdBy","updatedBy","companyId",- "metadataXml",+ "active",+ "id",+ "createdAt",+ "updatedAt","requireSso",+ "metadataUrl","providerId",- "metadataUrl"+ "metadataXml"]},{"name": "ssoDomain","rows": 0,"columns": [- "connectionId",- "domain",- "verifiedAt",- "verificationToken",- "companyId",- "createdBy",- "updatedBy",+ "status",+ "updatedAt","createdAt","id",- "updatedAt",- "status"+ "updatedBy",+ "createdBy",+ "companyId",+ "verificationToken",+ "verifiedAt",+ "connectionId",+ "domain"]},{"name": "stockTransfer","rows": 0,"columns": [- "status",- "tags",- "locationId",- "createdAt",- "completedAt",- "assignee",- "customFields",- "stockTransferId",- "createdBy",- "updatedBy",- "id",- "updatedAt","notes",- "companyId"- ]- },- {- "name": "storageRule",- "rows": 0,- "columns": [- "severity",- "active",- "id",- "createdAt",- "surfaces",- "createdBy",- "appliesToAll","updatedAt",+ "id","companyId",- "targetType",- "filteredItemTypes",- "message",- "updatedBy",- "conditionAst",- "name","customFields",- "description",- "filteredItemMatchAll",- "filteredItemGroupIds"+ "stockTransferId",+ "updatedBy",+ "createdBy",+ "completedAt",+ "assignee",+ "tags",+ "locationId",+ "status",+ "createdAt"]},{"name": "storageType","rows": 0,"columns": [- "updatedAt","createdBy","companyId",+ "updatedAt","createdAt",- "customFields","name",- "updatedBy",- "id"+ "customFields",+ "id",+ "updatedBy"]},{"name": "suggestion","rows": 0,"columns": [- "attachmentPath",- "emoji",- "path",- "userId","createdAt","id","tags","suggestion",- "companyId"+ "companyId",+ "attachmentPath",+ "emoji",+ "path",+ "userId"]},{"name": "supplierType","rows": 0,"columns": [+ "createdAt","updatedBy","companyId","protected",- "createdAt",- "updatedAt",- "tags",- "name","createdBy","id",- "customFields"+ "customFields",+ "updatedAt",+ "tags",+ "name"]},{"name": "tableView","rows": 0,"columns": [+ "updatedBy",+ "type",+ "companyId",+ "columnOrder","table","createdBy","description",- "columnOrder",- "companyId",- "type",- "updatedBy",- "name",- "createdAt",- "filters",- "columnPinning",+ "sortOrder","sorts","columnVisibility","id",- "sortOrder"+ "filters",+ "columnPinning",+ "createdAt",+ "name"]},{"name": "tag","rows": 0,"columns": [- "name",- "updatedBy",- "table","createdBy",+ "createdAt","companyId",- "createdAt"+ "updatedBy",+ "name",+ "table"]},{"name": "terms","rows": 0,"columns": [- "salesTerms",- "updatedAt",- "updatedBy",+ "id","purchasingTerms",- "id"+ "updatedBy",+ "salesTerms",+ "updatedAt"]},{"name": "timeCardEntry","rows": 0,"columns": [- "createdAt",+ "clockOut",+ "autoCloseShiftId",+ "clockIn",+ "companyId",+ "note","id",+ "createdAt","updatedAt",- "note",- "employeeId","createdBy","updatedBy",- "clockOut",- "companyId",- "clockIn",- "autoCloseShiftId"+ "employeeId"]},{"name": "tool","rows": 0,"columns": [- "updatedAt",- "createdAt",- "updatedBy",- "id",- "companyId",- "approved",+ "customFields",+ "tags","approvedBy",+ "approved","createdBy",- "tags",- "customFields"+ "id",+ "updatedBy",+ "companyId",+ "createdAt",+ "updatedAt"]},{"name": "trackedActivity","rows": 0,"columns": [- "sourceDocumentReadableId",+ "companyId","sourceDocumentId","sourceDocument",- "companyId",- "id",- "createdBy",- "attributes",- "type",+ "sourceDocumentReadableId","updatedBy",- "createdAt"+ "createdAt",+ "type",+ "attributes",+ "id",+ "createdBy"]},{"name": "training","rows": 0,"columns": [- "status",- "tags",- "id",- "content",- "estimatedDuration",- "type","name","companyId","updatedAt",- "updatedBy",- "createdBy",- "assignee",- "processId",- "frequency",+ "estimatedDuration",+ "type",+ "tags",+ "id",+ "content",+ "status","grantsAbilityId","version","description",- "createdAt"+ "createdAt",+ "frequency",+ "assignee",+ "processId",+ "updatedBy",+ "createdBy"]},{"name": "trainingAssignment","rows": 0,"columns": [- "trainingId",- "updatedBy",- "id",- "createdBy","companyId","groupIds","updatedAt",- "createdAt"+ "createdAt",+ "trainingId",+ "updatedBy",+ "id",+ "createdBy"]},{"name": "trainingCompletion","rows": 0,"columns": [- "completedBy",- "period",+ "trainingAssignmentId",+ "createdBy",+ "updatedBy","id","updatedAt",- "updatedBy",- "createdBy",- "trainingAssignmentId",- "completedAt",- "createdAt",+ "period",+ "completedBy","companyId",- "employeeId"+ "employeeId",+ "createdAt",+ "completedAt"]},{"name": "trainingQuestion","rows": 0,"columns": [- "options","question","createdAt","type",- "createdBy",- "updatedBy",+ "options","sortOrder","tolerance",- "matchingPairs",- "correctAnswers",+ "createdBy",+ "updatedBy","companyId","trainingId","updatedAt",- "required",+ "matchingPairs",+ "correctAnswers","correctNumber","correctBoolean",- "id"+ "id",+ "required"]},{"name": "unitOfMeasure","rows": 0,"columns": [- "createdAt",- "active",- "name",- "companyId",- "updatedBy",- "customFields","code",- "createdBy",+ "customFields",+ "updatedBy",+ "tags","id","updatedAt",- "tags"+ "createdBy",+ "active",+ "name",+ "createdAt",+ "companyId"]},{"name": "item","rows": 0,"columns": [+ "notes",+ "defaultMethodType",+ "changeOrderId",+ "description",+ "name",+ "createdBy",+ "assignee",+ "createdAt",+ "revision",+ "updatedAt","thumbnailPath","type",- "revisionStatus","modelUploadId",- "createdAt",- "updatedAt",- "revision",- "createdBy",- "name",- "description",- "assignee",- "defaultMethodType",- "notes",- "changeOrderId",- "unitOfMeasureCode",- "id",- "replenishmentSystem",- "embedding",+ "revisionStatus",+ "itemTrackingType",+ "mpn",+ "sourcingType",+ "trackingMethod",+ "active","updatedBy","companyId","readableId",- "sourcingType",- "mpn",- "itemTrackingType",- "trackingMethod",- "active"+ "replenishmentSystem",+ "embedding",+ "id",+ "unitOfMeasureCode"]},{"name": "assemblyComponentMapping","rows": 0,"columns": [- "confidence",- "itemId",- "geometryHash",- "createdBy",- "id","updatedBy",+ "id","companyId","modelUploadId","updatedAt",- "createdAt"+ "createdAt",+ "confidence",+ "geometryHash",+ "itemId",+ "createdBy"]},{"name": "assemblyInstruction","rows": 0,"columns": [+ "status",+ "customFields",+ "settings",+ "id","companyId","publishedAt",- "createdBy","name",+ "createdBy","updatedAt",- "status",- "customFields",- "id",- "settings",+ "rootInstructionId",+ "updatedBy",+ "tags",+ "assemblyPlanJobId","version",- "itemId","modelUploadId","createdAt",- "updatedBy",- "rootInstructionId",- "assemblyPlanJobId",- "tags"+ "itemId"]},{"name": "assemblyInstructionStep","rows": 0,"columns": [- "motion",- "createdAt",- "warnings",- "notes",- "maxValue",- "rootStepId",- "fastener",- "title",- "planConfidence",- "updatedAt",- "description",- "durationSeconds",+ "sortOrder",+ "parentStepId",+ "fileTypes","camera","explode",- "fileTypes",- "parentStepId",- "sortOrder",- "createdBy",- "type",- "minValue",- "updatedBy",- "required",- "id",- "unitOfMeasureCode",- "companyId",- "status",- "buildWave",- "instructionText",+ "updatedAt",+ "durationSeconds",+ "description",+ "planConfidence",+ "fastener",+ "rootStepId",+ "maxValue",+ "title",+ "createdAt",+ "motion",+ "notes",+ "warnings",+ "componentNodeIds","assemblyInstructionId","listValues",- "componentNodeIds"+ "instructionText",+ "buildWave",+ "status",+ "unitOfMeasureCode",+ "companyId",+ "id",+ "required",+ "updatedBy",+ "minValue",+ "type",+ "createdBy"]},{"name": "assemblyInstructionStepMaterial","rows": 0,"columns": [- "sortOrder",- "createdBy",- "itemId",- "quantity",- "companyId",- "updatedBy","id",+ "updatedBy",+ "companyId",+ "stepId","createdAt","updatedAt",- "stepId"+ "sortOrder",+ "quantity",+ "itemId",+ "createdBy"]},{"name": "assemblyInstructionStepSlide","rows": 0,"columns": [- "updatedAt","stepId",- "annotations",+ "updatedAt","createdBy",+ "annotations",+ "createdAt","id","companyId",- "createdAt","sortOrder","modelUploadId","imagePath","size",- "caption",- "updatedBy"+ "updatedBy",+ "caption"]},{"name": "assemblyInstructionStepTool","rows": 0,"columns": [- "createdBy",- "itemId",- "quantity",- "sortOrder",+ "stepId","createdAt","updatedAt",- "stepId",- "companyId",+ "id","updatedBy",- "id"+ "companyId",+ "quantity",+ "itemId",+ "createdBy",+ "sortOrder"]},{@@ -2665,67 +2687,67 @@"name": "batchProperty","rows": 0,"columns": [- "itemId",- "createdAt",- "updatedAt",+ "updatedBy","id","createdBy",- "updatedBy","sortOrder",+ "itemId",+ "updatedAt",+ "createdAt",+ "listOptions","dataType","label",- "companyId",- "listOptions"+ "companyId"]},{"name": "changeOrderSupersession","rows": 0,"columns": [- "createdBy",- "companyId","changeOrderId",- "discontinuationDate",- "updatedAt",+ "companyId",+ "createdBy","id","createdAt",- "successorEffectivityDate",+ "updatedAt",+ "discontinuationDate","successorItemId","predecessorItemId",- "supersessionMode",- "updatedBy"+ "successorEffectivityDate",+ "updatedBy",+ "supersessionMode"]},{"name": "configurationParameterGroup","rows": 0,"columns": [- "companyId",- "id","itemId",- "isUngrouped",+ "id",+ "companyId","sortOrder",- "name"+ "name",+ "isUngrouped"]},{"name": "configurationParameter","rows": 0,"columns": [- "listOptions",- "id",- "companyId",- "createdBy",- "sortOrder",- "createdAt",- "itemId",- "updatedBy","updatedAt","dataType",- "configurationParameterGroupId",- "key","label",- "materialFormFilterId"+ "materialFormFilterId",+ "key",+ "configurationParameterGroupId",+ "createdBy",+ "companyId",+ "id",+ "listOptions",+ "itemId",+ "updatedBy",+ "createdAt",+ "sortOrder"]},{@@ -2733,8 +2755,8 @@"rows": 0,"columns": ["field",- "itemId","updatedBy",+ "itemId","companyId","code","updatedAt"@@ -2743,6 +2765,24 @@{"name": "demandForecast","rows": 0,+ "columns": [+ "updatedBy",+ "forecastMethod",+ "periodId",+ "forecastQuantity",+ "notes",+ "createdBy",+ "itemId",+ "updatedAt",+ "confidence",+ "locationId",+ "companyId",+ "createdAt"+ ]+ },+ {+ "name": "demandProjection",+ "rows": 0,"columns": ["confidence","itemId",@@ -2750,163 +2790,157 @@"updatedAt","companyId","createdAt",+ "id","locationId",- "updatedBy","forecastMethod",+ "updatedBy","notes","forecastQuantity","periodId"]},{- "name": "demandProjection",+ "name": "enforcementRuleItemAssignment","rows": 0,"columns": [- "notes",- "forecastQuantity",- "periodId",- "forecastMethod",- "updatedBy","createdAt",+ "createdBy","companyId",- "id",- "locationId",- "confidence",- "updatedAt","itemId",- "createdBy"+ "updatedBy",+ "ruleId"]},{"name": "inspectionDocument","rows": 0,"columns": [- "samplingSampleSize",- "samplingSeverity",- "updatedAt",- "createdBy",- "samplingInspectionLevel",- "version",- "fileName",- "samplingPercentage",- "samplingAql",+ "drawingNumber","updatedBy","partId",- "drawingNumber",- "storagePath",- "uploadedBy",- "defaultPageWidth",- "id",- "defaultPageHeight",- "pageCount",+ "samplingPercentage",+ "samplingAql",+ "fileName",+ "samplingInspectionLevel",+ "createdBy",+ "version",+ "samplingSampleSize",+ "updatedAt",+ "samplingSeverity",+ "samplingPlanType","companyId","createdAt",- "samplingPlanType"+ "pageCount",+ "defaultPageHeight",+ "id",+ "defaultPageWidth",+ "uploadedBy",+ "storagePath"]},{"name": "inspectionFeature","rows": 0,"columns": [+ "description",+ "toleranceMinus",+ "id",+ "createdBy",+ "tolerancePlus",+ "unit",+ "samplingPlanType",+ "updatedBy",+ "inspectionDocumentId","type","samplingSeverity","samplingSampleSize","label",- "samplingInspectionLevel","createdAt",+ "samplingInspectionLevel","nominalValue",- "samplingAql",- "samplingPercentage",- "pageNumber","updatedAt","companyId",- "description",- "createdBy",- "id",- "toleranceMinus",- "unit",- "tolerancePlus",- "updatedBy",- "inspectionDocumentId",- "samplingPlanType"+ "pageNumber",+ "samplingAql",+ "samplingPercentage"]},{"name": "balloon","rows": 0,"columns": [- "regionX",- "regionHeight",- "id",- "yCoordinate",+ "regionY",+ "companyId",+ "updatedBy",+ "inspectionFeatureId",+ "updatedAt",+ "createdBy",+ "pageNumber","regionWidth","xCoordinate","inspectionDocumentId","createdAt",- "updatedAt",- "createdBy",- "pageNumber",- "regionY",- "updatedBy",- "companyId",- "inspectionFeatureId"+ "regionX",+ "regionHeight",+ "id",+ "yCoordinate"]},{"name": "inventoryCountLine","rows": 0,"columns": [- "id",- "systemQuantity","storageUnitId",- "createdAt",- "companyId",- "countedAt",- "readableId",+ "systemQuantity",+ "id","countedQuantity",- "countedBy",- "locationId",- "updatedBy",+ "readableId",+ "countedAt",+ "companyId",+ "createdAt","createdBy",- "itemId",+ "updatedBy",+ "locationId",+ "countedBy",+ "trackedEntityId",+ "customFields",+ "updatedAt","inventoryCountId","postedItemLedgerId",- "updatedAt",- "customFields",- "trackedEntityId"+ "itemId"]},{"name": "itemCost","rows": 0,"columns": [- "itemPostingGroupId",- "tags",- "createdBy",- "updatedBy",+ "costIsAdjusted",+ "updatedAt","itemId","createdAt",- "updatedAt",- "costIsAdjusted",- "standardCost",- "costingMethod",- "companyId",+ "updatedBy",+ "createdBy",+ "itemPostingGroupId",+ "tags","customFields",- "unitCost"+ "unitCost",+ "companyId",+ "standardCost",+ "costingMethod"]},{"name": "itemInspectionDocumentAssignment","rows": 0,"columns": [+ "createdBy",+ "updatedBy","inspectionDocumentId","companyId",- "updatedBy",- "createdBy",- "usage",- "updatedAt",+ "createdAt","itemId",- "createdAt"+ "updatedAt",+ "usage"]},{@@ -2918,17 +2952,17 @@"minimumOrderQuantity","reorderPoint","demandAccumulationSafetyStock",- "itemId","demandAccumulationIncludesInventory",+ "itemId","reorderQuantity","minimumReserveQuantity",- "critical","maximumOrderQuantity","reorderingPolicy",+ "critical","createdAt","updatedBy",- "maximumInventoryQuantity","demandAccumulationPeriod",+ "maximumInventoryQuantity","tags","updatedAt","createdBy",@@ -2942,57 +2976,63 @@"columns": ["updatedAt","suffix",- "size","itemId","prefix",- "next",- "updatedBy",+ "size","createdBy","id",- "createdAt",+ "updatedBy",+ "next",+ "companyId","step",- "companyId"+ "createdAt"]},{"name": "itemShelfLife","rows": 0,"columns": [- "triggerTiming",- "calculateFromBom",- "days",- "triggerProcessId","createdBy",- "updatedBy",- "itemId",- "customFields",- "companyId",- "mode",+ "triggerProcessId",+ "days",+ "calculateFromBom",+ "triggerTiming",+ "updatedAt","createdAt",- "updatedAt"+ "mode",+ "companyId",+ "customFields",+ "itemId",+ "updatedBy"]},{"name": "itemSupersession","rows": 0,"columns": [- "successorEffectivityDate",+ "companyId",+ "updatedBy",+ "createdBy",+ "updatedAt","createdAt","itemId",- "updatedAt",- "createdBy",- "updatedBy",- "companyId",- "discontinuationDate",- "conversionFactor",+ "successorEffectivityDate","supersessionMode",- "successorItemId"+ "successorItemId",+ "conversionFactor",+ "discontinuationDate"]},{"name": "itemUnitSalePrice","rows": 0,"columns": [+ "allowInvoiceDiscount",+ "tags",+ "currencyCode",+ "salesUnitOfMeasureCode",+ "salesBlocked",+ "updatedAt","companyId","createdAt","customFields",@@ -3000,37 +3040,40 @@"priceIncludesTax","createdBy","itemId",- "updatedBy",- "allowInvoiceDiscount",- "currencyCode",- "tags",- "salesUnitOfMeasureCode",- "salesBlocked",- "updatedAt"+ "updatedBy"]},{"name": "makeMethod","rows": 0,"columns": [- "id",- "tags",- "status",- "updatedAt",- "itemId",- "customFields",- "version",- "changeOrderId",- "createdBy",+ "updatedBy","createdAt","companyId",- "updatedBy"+ "createdBy",+ "changeOrderId",+ "customFields",+ "version",+ "itemId",+ "updatedAt",+ "id",+ "tags",+ "status"]},{"name": "changeOrderAffectedItem","rows": 0,"columns": [+ "updatedAt",+ "changeOrderId",+ "companyId",+ "supersessionMode",+ "successorEffectivityDate",+ "discontinuationDate",+ "id",+ "newItemId",+ "draftMakeMethodId","itemId","createdAt","sortOrder",@@ -3038,73 +3081,64 @@"changeSummary","changeType","updatedBy",- "createdBy",- "changeOrderId",- "companyId",- "updatedAt",- "successorEffectivityDate",- "supersessionMode",- "newItemId",- "discontinuationDate",- "id",- "draftMakeMethodId"+ "createdBy"]},{"name": "nonConformanceItem","rows": 0,"columns": [- "disposition",+ "createdAt",+ "companyId",+ "itemId",+ "updatedAt","id",+ "disposition","createdBy","nonConformanceId","quantity",- "updatedBy",- "createdAt",- "itemId",- "companyId",- "updatedAt"+ "updatedBy"]},{"name": "procedureStep","rows": 0,"columns": [- "listValues",+ "fileTypes",+ "required",+ "updatedBy",+ "createdBy",+ "createdAt",+ "name",+ "description",+ "type","minValue","id",+ "listValues","sortOrder",+ "updatedAt","procedureId","companyId",- "updatedAt",- "maxValue","unitOfMeasureCode",- "fileTypes",- "required",- "updatedBy",- "createdBy",- "description",- "name",- "createdAt",- "type"+ "maxValue"]},{"name": "purchasingRfqLine","rows": 0,"columns": [+ "updatedAt","purchasingRfqId","customFields",- "updatedAt",- "internalNotes","conversionFactor",- "externalNotes",+ "internalNotes","id","order",+ "externalNotes","purchaseUnitOfMeasureCode","description",- "itemId","createdAt",+ "itemId","inventoryUnitOfMeasureCode","companyId","quantity",@@ -3116,94 +3150,82 @@"name": "qualityDocumentStep","rows": 0,"columns": [- "id",- "minValue",- "listValues",- "sortOrder",- "updatedAt",- "companyId",- "qualityDocumentId",- "unitOfMeasureCode",- "maxValue",- "required","fileTypes",- "createdBy",+ "required","updatedBy",+ "createdBy","description","createdAt","name",- "type"+ "type",+ "listValues",+ "id",+ "minValue",+ "sortOrder",+ "qualityDocumentId",+ "companyId",+ "updatedAt",+ "maxValue",+ "unitOfMeasureCode"]},{"name": "riskRegister","rows": 0,"columns": [- "assignee",- "itemId",- "id",- "sourceId",- "createdAt",+ "description",+ "updatedAt",+ "title",+ "severity",+ "createdBy",+ "source",+ "updatedBy",+ "notes","companyId",+ "createdAt","type","status","likelihood",- "source",- "createdBy",- "notes",- "updatedBy",- "title",- "updatedAt",- "description",- "severity"- ]- },- {- "name": "storageRuleItemAssignment",- "rows": 0,- "columns": [- "ruleId",+ "assignee",+ "id","itemId",- "updatedBy",- "companyId",- "createdBy",- "createdAt"+ "sourceId"]},{"name": "trackedEntity","rows": 0,"columns": [- "id",- "createdAt",- "readableId",- "sourceDocumentReadableId",- "expirationDate",+ "status",+ "updatedBy",+ "sourceDocument",+ "attributes",+ "itemId",+ "sourceDocumentId","quantity",- "companyId",+ "expirationDate","createdBy",- "sourceDocumentId",- "itemId",- "sourceDocument",- "updatedBy",- "status",- "attributes"+ "companyId",+ "readableId",+ "createdAt",+ "id",+ "sourceDocumentReadableId"]},{"name": "nonConformanceItemTrackedEntity","rows": 0,"columns": [- "companyId",- "updatedAt",- "id",- "updatedBy","createdBy",+ "updatedBy","nonConformanceItemId",- "quantity",+ "companyId",+ "id",+ "updatedAt","createdAt",+ "trackedEntityId","nonConformanceId",- "trackedEntityId"+ "quantity"]},{@@ -3224,12 +3246,12 @@"name": "trackedActivityInput","rows": 0,"columns": [- "trackedEntityId","updatedBy",- "trackedActivityId",+ "trackedEntityId","createdAt",- "quantity",+ "trackedActivityId","createdBy",+ "quantity","companyId"]},@@ -3237,154 +3259,166 @@"name": "trackedActivityOutput","rows": 0,"columns": [- "trackedEntityId",- "createdBy",- "trackedActivityId",- "updatedBy",+ "createdAt","quantity","companyId",- "createdAt"+ "updatedBy",+ "trackedActivityId",+ "createdBy",+ "trackedEntityId"]},{"name": "userAttributeCategory","rows": 0,"columns": [- "id",+ "companyId",+ "public",+ "protected",+ "createdAt","updatedAt",+ "id","emoji","active","name","createdBy",- "updatedBy",- "companyId",- "protected",- "public",- "createdAt"+ "updatedBy"]},{"name": "userAttribute","rows": 0,"columns": [- "listOptions",- "id",- "createdAt",- "updatedAt",- "active",- "createdBy",- "name","updatedBy","attributeDataTypeId","canSelfManage",+ "sortOrder","userAttributeCategoryId",- "sortOrder"+ "listOptions",+ "updatedAt",+ "createdAt",+ "id",+ "createdBy",+ "active",+ "name"]},{"name": "userAttributeValue","rows": 0,"columns": [- "valueDate",- "updatedBy",- "valueText","valueBoolean","userId",- "valueNumeric",- "updatedAt",+ "valueText",+ "valueDate",+ "updatedBy",+ "valueFile",+ "userAttributeId",+ "valueUser",+ "createdBy","id","createdAt",- "createdBy",- "valueUser",- "valueFile",- "userAttributeId"+ "updatedAt",+ "valueNumeric"]},{"name": "userModulePreference","rows": 0,"columns": [- "id",- "hidden",- "userId",- "position",- "module","companyId",- "updatedAt"+ "module",+ "updatedAt",+ "position",+ "userId",+ "id",+ "hidden"]},{"name": "userToCompany","rows": 0,- "columns": ["companyId", "userId", "role"]+ "columns": ["userId", "companyId", "role"]},{"name": "warehouse","rows": 0,"columns": [- "updatedAt",- "locationId",- "requiresPick",- "requiresReceive",- "requiresPutAway",- "createdAt",+ "createdBy",+ "id",+ "active",+ "requiresBin","updatedBy","name",- "requiresShipment","companyId",- "active",- "id",- "createdBy",- "requiresBin"+ "requiresShipment",+ "requiresPutAway",+ "createdAt",+ "requiresPick",+ "updatedAt",+ "locationId",+ "requiresReceive"]},{"name": "warehouseTransfer","rows": 0,"columns": [- "createdBy",- "id",- "reference",- "transferDate",+ "tags","transferId","updatedBy",- "tags",- "companyId","notes",- "createdAt",- "status",- "customFields",+ "companyId",+ "id",+ "reference",+ "createdBy",+ "transferDate","toLocationId",- "updatedAt","fromLocationId",- "expectedReceiptDate"+ "updatedAt",+ "expectedReceiptDate",+ "createdAt",+ "status",+ "customFields"]},{"name": "workCenter","rows": 0,"columns": [- "updatedAt",- "createdBy",- "name",- "locationId",- "active",+ "companyId","requiredAbilityId","id",- "companyId",- "description",- "createdAt",- "tags",- "overheadRate",- "defaultStandardFactor",- "minimumBatchQuantity",- "batchCapacity",+ "active",+ "locationId",+ "createdBy",+ "name",+ "updatedAt",+ "alwaysOn",+ "updatedBy",+ "machineRate","laborRate","customFields","departmentId",+ "batchCapacity",+ "defaultStandardFactor",+ "minimumBatchQuantity",+ "tags",+ "overheadRate",+ "description",+ "createdAt"+ ]+ },+ {+ "name": "enforcementRuleWorkCenterAssignment",+ "rows": 0,+ "columns": [+ "createdAt",+ "createdBy",+ "companyId",+ "workCenterId","updatedBy",- "alwaysOn",- "machineRate"+ "ruleId"]},{@@ -3392,17 +3426,17 @@"rows": 0,"columns": ["status",- "companyId","processId",- "updatedBy",+ "companyId","workCenterId",+ "updatedBy","notes","createdBy",- "readableId","updatedAt",+ "readableId","locationId",- "customFields","id",+ "customFields","createdAt"]},@@ -3410,95 +3444,95 @@"name": "maintenanceSchedule","rows": 0,"columns": [- "estimatedDuration",- "skipHolidays",- "thursday",- "wednesday",- "description","updatedBy",+ "description","workCenterId",- "saturday",- "updatedAt",- "tuesday",- "takesWorkCenterOffline",+ "thursday",+ "wednesday",+ "estimatedDuration",+ "skipHolidays",+ "sunday","frequency","createdBy","friday",- "sunday",- "locationId",- "nextDueAt",- "active",+ "updatedAt",+ "saturday",+ "tuesday",+ "takesWorkCenterOffline",+ "monday","createdAt","name",- "monday",- "procedureId",- "priority",- "companyId",+ "active",+ "locationId",+ "nextDueAt","lastGeneratedAt",- "id"+ "id",+ "companyId",+ "priority",+ "procedureId"]},{"name": "maintenanceDispatch","rows": 0,"columns": [- "plannedEndTime",- "maintenanceDispatchId",- "procedureId",- "workCenterId",- "takesWorkCenterOffline",- "updatedAt",- "suspectedFailureModeId",- "maintenanceScheduleId",- "id",- "actualFailureModeId",- "severity",- "source",- "oeeImpact",- "content",- "actualStartTime",- "status",- "assignee",- "completedAt",- "updatedBy",- "locationId",+ "actualEndTime",+ "createdBy",+ "nonConformanceId","createdAt","priority",- "plannedStartTime","companyId",- "actualEndTime",- "createdBy",- "nonConformanceId"+ "plannedStartTime",+ "updatedBy",+ "locationId",+ "status",+ "actualStartTime",+ "content",+ "assignee",+ "completedAt",+ "source",+ "oeeImpact",+ "id",+ "maintenanceScheduleId",+ "severity",+ "actualFailureModeId",+ "takesWorkCenterOffline",+ "workCenterId",+ "procedureId",+ "updatedAt",+ "suspectedFailureModeId",+ "plannedEndTime",+ "maintenanceDispatchId"]},{"name": "maintenanceDispatchComment","rows": 0,"columns": [- "createdBy",- "comment",- "companyId","updatedBy",- "id",- "createdAt",+ "companyId",+ "comment",+ "createdBy",+ "updatedAt","maintenanceDispatchId",- "updatedAt"+ "createdAt",+ "id"]},{"name": "maintenanceDispatchEvent","rows": 0,"columns": [- "createdBy","maintenanceDispatchId","updatedAt",- "endTime",+ "createdBy",+ "createdAt","companyId","id",- "createdAt",- "notes",+ "endTime","employeeId","workCenterId",+ "notes","updatedBy","startTime"]@@ -3507,17 +3541,17 @@"name": "maintenanceDispatchItem","rows": 0,"columns": [+ "itemId",+ "quantity",+ "unitOfMeasureCode",+ "updatedAt","createdAt","companyId","maintenanceDispatchId","unitCost","updatedBy","createdBy",- "id",- "itemId",- "quantity",- "unitOfMeasureCode",- "updatedAt"+ "id"]},{@@ -3541,8 +3575,8 @@"columns": ["createdBy","updatedBy",- "workCenterId","companyId",+ "workCenterId","createdAt","id","updatedAt",@@ -3553,48 +3587,36 @@"name": "maintenanceScheduleItem","rows": 0,"columns": [- "createdBy",- "itemId","quantity",+ "itemId",+ "createdBy","unitOfMeasureCode",- "createdAt",- "updatedAt","maintenanceScheduleId",- "companyId",+ "updatedAt",+ "createdAt",+ "id","updatedBy",- "id"+ "companyId"]},{"name": "peopleAssignment","rows": 0,"columns": [+ "employeeId",+ "updatedAt","shiftId","workCenterId","hours","locationId",- "updatedAt",- "employeeId",- "note",- "createdAt",- "companyId",- "overtimeHours","date",+ "updatedBy","id","createdBy",- "updatedBy"- ]- },- {- "name": "storageRuleWorkCenterAssignment",- "rows": 0,- "columns": [- "workCenterId",- "updatedBy",- "ruleId","createdAt",- "companyId",- "createdBy"+ "note",+ "overtimeHours",+ "companyId"]},{@@ -3608,302 +3630,302 @@"workCenterId","companyId","tags",- "customFields","updatedBy",+ "customFields",+ "isWorkCenterDefault","parentId","locationId",- "isWorkCenterDefault","createdBy",- "name","updatedAt",- "id"+ "id",+ "name"]},{"name": "itemLedger","rows": 0,"columns": [- "documentLineId",- "companyId",- "entryNumber",+ "documentId",+ "id",+ "storageUnitId","itemId","scrapReasonId","locationId",- "id",- "storageUnitId",- "documentId",- "entryType",- "postingDate",- "createdAt",- "trackedEntityId",- "correctionOfItemLedgerId",- "externalDocumentId",+ "documentLineId",+ "companyId",+ "entryNumber",+ "createdBy",+ "trackedEntityStatus","updatedBy","documentType","comment","quantity",- "trackedEntityStatus",- "createdBy"+ "correctionOfItemLedgerId",+ "externalDocumentId",+ "entryType",+ "createdAt",+ "postingDate",+ "trackedEntityId"]},{"name": "pickMethod","rows": 0,"columns": [- "createdAt",+ "locationId",+ "updatedAt",+ "sortMethod","customFields","itemId",- "sortMethod",- "updatedAt",- "locationId",- "createdBy",- "updatedBy",+ "createdAt","defaultStorageUnitId",- "companyId"+ "companyId",+ "updatedBy",+ "createdBy"]},{"name": "warehouseTransferLine","rows": 0,"columns": [- "fromStorageUnitId","toStorageUnitId",- "updatedBy",- "transferId",+ "fromStorageUnitId","companyId",+ "transferId",+ "updatedBy","receivedQuantity",- "toLocationId",- "id","unitOfMeasureCode",+ "id",+ "toLocationId","fromLocationId",- "itemId",- "createdBy",- "quantity","customFields",- "updatedAt",+ "quantity",+ "createdBy",+ "itemId","createdAt",- "notes",- "shippedQuantity"+ "updatedAt",+ "shippedQuantity",+ "notes"]},{"name": "workCenterProcess","rows": 0,"columns": [- "processId","workCenterId","updatedBy",- "createdBy",+ "processId",+ "createdAt","companyId",- "updatedAt",- "createdAt"+ "createdBy",+ "updatedAt"]},{"name": "workCenterReplacementPart","rows": 0,"columns": [- "companyId",- "id",- "updatedBy",- "createdAt",- "updatedAt",- "workCenterId",- "unitOfMeasureCode","createdBy",+ "itemId","quantity",- "itemId"+ "unitOfMeasureCode",+ "updatedAt",+ "createdAt",+ "workCenterId",+ "companyId",+ "updatedBy",+ "id"]},{"name": "workCenterShift","rows": 0,"columns": [- "createdBy",- "shiftId",- "workCenterId",- "updatedBy",- "id",- "createdAt",+ "updatedAt","companyId",- "updatedAt"+ "createdAt",+ "id",+ "updatedBy",+ "workCenterId",+ "shiftId",+ "createdBy"]},{"name": "contractor","rows": 0,"columns": [- "createdAt",- "id","customFields",- "tags",- "updatedAt",+ "id",+ "createdAt","hoursPerWeek",+ "updatedAt",+ "tags","createdBy",- "updatedBy",+ "active","companyId",- "active"+ "updatedBy"]},{"name": "contractorAbility","rows": 0,"columns": [- "createdAt",- "createdBy","companyId",- "abilityId",+ "createdBy",+ "createdAt","contractorId",- "updatedBy"+ "updatedBy",+ "abilityId"]},{"name": "costLedger","rows": 0,"columns": [+ "companyId",+ "supplierId",+ "costLedgerType",+ "quantity","documentType",- "itemLedgerType","postingDate","nominalCost",- "remainingQuantity",+ "itemLedgerType","appliesToCostLedgerId",- "supplierId",- "companyId",- "quantity",- "costLedgerType",+ "remainingQuantity",+ "adjustment",+ "externalDocumentId",+ "id","documentId","itemId","createdAt",- "entryNumber","cost",- "adjustment",- "id",- "externalDocumentId"+ "entryNumber"]},{"name": "customer","rows": 0,"columns": [- "fax",- "currencyCode",- "tags",- "taxPercent",- "updatedAt",- "embedding",- "salesContactId",- "logo",- "website",- "customerStatusId",- "customerTypeId",- "customFields",- "defaultCc",- "accountManagerId",+ "updatedBy",+ "name",+ "phone",+ "createdAt",+ "assignee",+ "readableId","intercompanyCompanyId","createdBy","id","companyId",- "createdAt",- "assignee",- "readableId",- "name",- "updatedBy",- "phone"+ "defaultCc",+ "accountManagerId",+ "website",+ "customerStatusId",+ "customFields",+ "customerTypeId",+ "salesContactId",+ "logo",+ "taxPercent",+ "updatedAt",+ "embedding",+ "currencyCode",+ "tags",+ "fax"]},{"name": "customerAccount","rows": 0,- "columns": ["customerId", "id", "active", "companyId"]+ "columns": ["active", "companyId", "customerId", "id"]},{"name": "customerBankAccount","rows": 0,"columns": [- "accountNumber",- "countryCode",- "isPrimary",- "companyId",- "createdBy",- "bankName",- "bankCode",- "currencyCode",- "id",+ "tags",+ "notes",+ "createdAt",+ "accountHolderName",+ "swiftBic",+ "customFields","bankAddress","updatedAt","updatedBy",- "active","customerId",+ "active","name",- "notes",- "tags",- "createdAt",- "accountHolderName",- "swiftBic",- "customFields"+ "bankName",+ "bankCode",+ "currencyCode",+ "id",+ "accountNumber",+ "countryCode",+ "isPrimary",+ "companyId",+ "createdBy"]},{"name": "customerItemPriceOverride","rows": 0,"columns": [- "validTo",- "itemId",- "updatedAt",- "customerTypeId",- "notes",- "createdAt",- "companyId","active",- "updatedBy",+ "companyId","customerId",+ "updatedBy","validFrom",- "createdBy",+ "applyRulesOnTop","id",- "applyRulesOnTop"+ "createdBy",+ "validTo",+ "updatedAt",+ "customerTypeId",+ "itemId",+ "createdAt",+ "notes"]},{"name": "customerItemPriceOverrideBreak","rows": 0,"columns": [- "companyId",- "id",- "updatedBy",+ "createdBy",+ "quantity",+ "overridePrice",+ "active","createdAt","updatedAt","customerItemPriceOverrideId",- "active",- "createdBy",- "overridePrice",- "quantity"+ "companyId",+ "updatedBy",+ "id"]},{"name": "customerLocation","rows": 0,"columns": [- "customerId",- "companyId",+ "name",+ "addressId",+ "customFields","id","tags",- "customFields",- "addressId",- "name"+ "customerId",+ "companyId"]},{"name": "customerContact","rows": 0,"columns": [- "contactId",+ "userId","customerLocationId",+ "contactId","tags",- "userId",- "customerId",- "companyId","id",- "customFields"+ "customFields",+ "customerId",+ "companyId"]},{@@ -3913,8 +3935,8 @@"customerPartId","customerId","id",- "customerPartRevision","itemId",+ "customerPartRevision","companyId"]},@@ -3936,32 +3958,32 @@"name": "customerShipping","rows": 0,"columns": [- "incotermLocation",- "updatedBy",- "customerId",- "shippingMethodId",- "shippingCustomerId",- "incoterm","updatedAt",- "shippingTermId",- "shippingCustomerLocationId",+ "incoterm",+ "shippingCustomerId",+ "shippingMethodId",+ "customerId",+ "updatedBy",+ "incotermLocation",+ "companyId","shippingCustomerContactId",- "companyId"+ "shippingCustomerLocationId",+ "shippingTermId"]},{"name": "customerTax","rows": 0,"columns": [- "vatNumber","eori",+ "vatNumber","taxExemptionCertificateNumber","taxExempt","taxId","taxExemptionCertificatePath","updatedAt",- "companyId","customerId",+ "companyId","updatedBy","taxExemptionReason"]@@ -3970,32 +3992,32 @@"name": "fixture","rows": 0,"columns": [- "approvedBy",- "customerId",- "approved",- "companyId",+ "createdBy",+ "updatedBy",+ "tags",+ "itemId",+ "customFields","createdAt","id","updatedAt",- "customFields",- "itemId",- "tags",- "createdBy",- "updatedBy"+ "companyId",+ "customerId",+ "approved",+ "approvedBy"]},{"name": "nonConformanceCustomer","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",- "nonConformanceId",- "createdAt",- "updatedAt","customerId",- "companyId"+ "companyId",+ "updatedAt",+ "createdAt",+ "nonConformanceId",+ "updatedBy",+ "id",+ "createdBy"]},{@@ -4013,35 +4035,35 @@"name": "salesOrder","rows": 0,"columns": [- "createdBy",- "updatedAt",- "revisionId",+ "customFields",+ "companyId",+ "salesOrderId",+ "completedDate",+ "customerEngineeringContactId",+ "customerId",+ "externalNotes",+ "customerContactId",+ "customerLocationId",+ "id",+ "customerReference",+ "sentCompleteDate",+ "internalNotes","closedAt",+ "revisionId","status",- "opportunityId",+ "updatedAt",+ "createdBy","currencyCode","exchangeRateUpdatedAt",+ "opportunityId",+ "exchangeRate",+ "orderDate","assignee","updatedBy",- "orderDate",- "exchangeRate",- "createdAt",- "salesPersonId",- "closedBy","locationId",- "salesOrderId",- "companyId",- "customFields",- "customerContactId",- "externalNotes",- "completedDate",- "customerId",- "customerEngineeringContactId",- "customerReference",- "sentCompleteDate",- "customerLocationId",- "id",- "internalNotes"+ "closedBy",+ "createdAt",+ "salesPersonId"]},{@@ -4053,170 +4075,177 @@"name": "salesOrderLine","rows": 0,"columns": [- "storageUnitId",- "updatedBy",- "pricingRuleId",- "unitOfMeasureCode",- "addOnCost",- "invoicedComplete",- "companyId",- "methodType",- "status",- "assetId",- "nonTaxableAddOnCost",- "createdAt",- "shippingCost",- "setupPrice",- "internalNotes",- "sentComplete",- "salesOrderLineType",- "unitPrice",- "itemId",- "updatedAt",- "quantitySent",+ "taxPercent","priceTrace",+ "quantitySent","customFields",- "taxPercent","saleQuantity","id","sortOrder",- "exchangeRate",- "createdBy",+ "updatedAt",+ "externalNotes",+ "quantityInvoiced",+ "salesOrderId",+ "locationId","sentDate",+ "createdBy",+ "exchangeRate",+ "accountId","modelUploadId",- "description","promisedDate",- "accountId",- "salesOrderId",- "quantityInvoiced",- "externalNotes",- "locationId"+ "description",+ "addOnCost",+ "invoicedComplete",+ "companyId",+ "unitOfMeasureCode",+ "pricingRuleId",+ "storageUnitId",+ "updatedBy",+ "sentComplete",+ "internalNotes",+ "setupPrice",+ "unitPrice",+ "salesOrderLineType",+ "itemId",+ "methodType",+ "assetId",+ "shippingCost",+ "createdAt",+ "nonTaxableAddOnCost",+ "status"]},{"name": "nonConformanceSalesOrderLine","rows": 0,"columns": [- "companyId",- "updatedAt",- "id",- "updatedBy",- "createdBy",- "nonConformanceId","salesOrderReadableId","createdAt",+ "salesOrderId","salesOrderLineId",- "salesOrderId"+ "companyId",+ "id",+ "updatedAt",+ "createdBy",+ "updatedBy",+ "nonConformanceId"]},{"name": "salesOrderPayment","rows": 0,"columns": [- "invoiceCustomerContactId",- "invoiceCustomerLocationId",- "paymentTermId",- "companyId",- "updatedBy","invoiceCustomerId",- "paymentComplete",+ "updatedBy",+ "companyId",+ "customFields","id","updatedAt",- "customFields"+ "paymentComplete",+ "invoiceCustomerContactId",+ "invoiceCustomerLocationId",+ "paymentTermId"]},{"name": "salesOrderShipment","rows": 0,"columns": [- "receiptPromisedDate",- "customerId",- "trackingNumber",- "id",- "dropShipment",- "notes",- "locationId",- "supplierId",- "updatedBy",- "updatedAt",+ "deliveryDate",+ "shippingTermId",+ "shippingMethodId",+ "supplierLocationId",+ "assignee",+ "customFields","companyId","incoterm",- "customerLocationId",- "shippingCost",- "receiptRequestedDate",+ "updatedAt","incotermLocation",- "deliveryDate",- "customFields",- "assignee",- "supplierLocationId",- "shippingMethodId",- "shippingTermId"+ "receiptRequestedDate",+ "shippingCost",+ "customerLocationId",+ "notes",+ "dropShipment",+ "updatedBy",+ "supplierId",+ "locationId",+ "receiptPromisedDate",+ "id",+ "trackingNumber",+ "customerId"]},{"name": "salesOrderStatusHistory","rows": 0,"columns": [- "createdAt",- "status",- "updatedBy",- "createdBy","salesOrderId","id",- "companyId"+ "companyId",+ "status",+ "createdAt",+ "updatedBy",+ "createdBy"]},{"name": "salesOrderTransaction","rows": 0,"columns": [+ "createdAt","type","userId",- "createdAt",- "salesOrderId",+ "companyId","id",- "companyId"+ "salesOrderId"]},{"name": "salesReturnOrder","rows": 0,"columns": [- "currencyCode",- "salesOrderId",- "id",- "customerContactId",- "salesReturnOrderId",- "orderDate","externalNotes",- "replacementSalesOrderId",+ "orderDate",+ "salesReturnOrderId","locationId",- "exchangeRate",- "createdAt",- "customerLocationId",+ "replacementSalesOrderId",+ "id",+ "salesOrderId",+ "currencyCode",+ "customerContactId",+ "customerId",+ "expirationDate",+ "status",+ "createdBy",+ "companyId",+ "customFields",+ "customerReference","updatedAt",- "assignee",+ "customerLocationId",+ "createdAt",+ "exchangeRate","updatedBy","internalNotes",- "companyId",- "createdBy",- "status",- "expirationDate",- "customerId",- "customerReference",- "customFields"+ "assignee"]},{"name": "salesRfq","rows": 0,"columns": [- "companyId",- "customerLocationId",- "tags",- "createdAt",- "employeeId",- "updatedBy",+ "customerEngineeringContactId",+ "customerReference",+ "completedDate",+ "internalNotes",+ "expirationDate",+ "customFields",+ "locationId",+ "rfqId",+ "customerId",+ "salesPersonId",+ "id",+ "rfqDate",+ "noQuoteReasonId","externalNotes","customerContactId","opportunityId",@@ -4225,19 +4254,12 @@"revisionId","updatedAt","createdBy",- "customerId",- "salesPersonId",- "id",- "rfqDate",- "noQuoteReasonId",- "customerEngineeringContactId",- "customerReference",- "completedDate",- "internalNotes",- "expirationDate",- "customFields",- "locationId",- "rfqId"+ "companyId",+ "customerLocationId",+ "tags",+ "createdAt",+ "employeeId",+ "updatedBy"]},{@@ -4249,145 +4271,145 @@"name": "salesRfqLine","rows": 0,"columns": [- "description",- "order",- "id",- "externalNotes","unitOfMeasureCode","internalNotes","updatedAt","salesRfqId","customFields",- "updatedBy",- "createdBy",- "tags",- "companyId",- "customerPartRevision",- "itemId",+ "description",+ "id",+ "order",+ "externalNotes","quantity","createdAt","modelUploadId",- "customerPartId"+ "customerPartId",+ "updatedBy",+ "tags",+ "createdBy",+ "customerPartRevision",+ "companyId",+ "itemId"]},{"name": "externalLink","rows": 0,"columns": [- "companyId","documentId","customerId",+ "companyId","createdAt",- "supplierId","documentType",- "expiresAt",- "id"+ "supplierId",+ "id",+ "expiresAt"]},{"name": "quote","rows": 0,"columns": [- "exchangeRateUpdatedAt","customerId",- "id",+ "exchangeRateUpdatedAt","salesPersonId",+ "id","currencyCode","expirationDate",- "customerContactId",- "opportunityId","quoteId",+ "opportunityId",+ "customerContactId","assignee",- "internalNotes",- "estimatorId","digitalQuoteRejectedByEmail",- "digitalQuoteAcceptedByEmail",+ "estimatorId",+ "internalNotes","digitalQuoteAcceptedBy",- "dueDate",- "createdBy",- "customerLocationId",+ "digitalQuoteAcceptedByEmail","tags",+ "customerLocationId",+ "createdBy",+ "dueDate","updatedBy",- "updatedAt",- "locationId",- "exchangeRate","customFields",- "createdAt",+ "exchangeRate",+ "locationId",+ "updatedAt","companyId",- "revisionId",+ "createdAt","customerReference",+ "revisionId","digitalQuoteRejectedBy",- "externalNotes",- "customerEngineeringContactId",- "status",+ "externalLinkId","completedDate",- "externalLinkId"+ "status",+ "customerEngineeringContactId",+ "externalNotes"]},{"name": "job","rows": 0,"columns": [- "completedDate",- "customFields",+ "createdBy",+ "salesOrderLineId",+ "notes",+ "quantityReceivedToInventory",+ "assignee",+ "modelUploadId",+ "releasedDate",+ "customerId",+ "updatedBy","startDate",+ "customFields","status",- "updatedBy",- "quoteLineId",- "quoteId",- "projectedCompletionAt",+ "completedDate","unitOfMeasureCode","itemId","quantityShipped",- "notes",- "quantityReceivedToInventory",- "createdBy",- "salesOrderLineId",- "customerId",- "modelUploadId",- "releasedDate",- "assignee",- "companyId",- "quantity",- "estimatedTime",+ "quoteId",+ "projectedCompletionAt",+ "quoteLineId",+ "scheduleOutdatedAt",+ "locationId",+ "createdAt",+ "id",+ "deadlineType",+ "updatedAt",+ "scrapQuantity",+ "priority",+ "storageUnitId","dueDate","configuration","tags",- "quantityComplete",- "scheduleOutdatedReason",+ "quantity",+ "estimatedTime",+ "companyId",+ "salesOrderId","actualTime","jobId",- "salesOrderId",- "createdAt",- "scheduleOutdatedAt",- "locationId",- "priority",- "storageUnitId",- "updatedAt",- "scrapQuantity",- "id",- "deadlineType"+ "quantityComplete",+ "scheduleOutdatedReason"]},{"name": "fulfillment","rows": 0,"columns": [- "quantity",- "type",- "createdAt",- "jobId",- "salesOrderLineId",- "createdBy",- "id",+ "companyId","updatedBy",- "companyId"+ "id",+ "createdBy",+ "salesOrderLineId",+ "jobId",+ "createdAt",+ "type",+ "quantity"]},{"name": "jobFavorite","rows": 0,- "columns": ["userId", "jobId"]+ "columns": ["jobId", "userId"]},{"name": "quoteFavorite",@@ -4398,58 +4420,58 @@"name": "quoteLine","rows": 0,"columns": [+ "taxPercent",+ "itemId","unitPricePrecision","customerPartRevision","id","description",- "taxPercent",- "itemId",- "unitOfMeasureCode",- "quoteId",- "createdBy","noQuoteReason","customerPartId",- "pricingRuleId","itemType",+ "pricingRuleId","configuration",+ "unitOfMeasureCode",+ "quoteId",+ "createdBy",+ "quantity",+ "companyId",+ "tags",+ "updatedAt","estimatorId","modelUploadId",- "priceTrace","methodType",+ "priceTrace","additionalCharges",- "companyId",- "quantity",- "tags",- "updatedAt",+ "sortOrder",+ "locationId",+ "externalNotes","customFields","updatedBy","status",- "internalNotes","quoteRevisionId",- "sortOrder",- "locationId",- "externalNotes"+ "internalNotes"]},{"name": "quoteLinePrice","rows": 0,"columns": [- "shippingCost",- "exchangeRate",- "updatedAt",- "discountPercent",- "unitPrice",- "quoteLineId",- "quantity",- "categoryMarkups",- "leadTime",- "createdBy","priceSource","createdAt","companyId","updatedBy",- "quoteId"+ "quoteId",+ "categoryMarkups",+ "leadTime",+ "createdBy",+ "discountPercent",+ "quantity",+ "unitPrice",+ "quoteLineId",+ "shippingCost",+ "exchangeRate",+ "updatedAt"]},{@@ -4459,11 +4481,11 @@"updatedAt","customFields","invoiceCustomerId",- "updatedBy","id",+ "updatedBy","companyId",- "invoiceCustomerLocationId","invoiceCustomerContactId",+ "invoiceCustomerLocationId","paymentTermId"]},@@ -4471,70 +4493,70 @@"name": "quoteShipment","rows": 0,"columns": [- "incotermLocation",- "receiptRequestedDate",+ "updatedBy","shippingTermId","shippingMethodId",- "updatedBy",- "id",- "shippingCost",- "incoterm",- "companyId",+ "incotermLocation",+ "receiptRequestedDate",+ "updatedAt","locationId",- "updatedAt"+ "companyId",+ "incoterm",+ "id",+ "shippingCost"]},{"name": "capacityReservation","rows": 0,"columns": [+ "endAt",+ "createdBy",+ "workHours","updatedAt","companyId",- "workHours",- "createdBy",- "endAt",- "createdAt",- "scenarioId",- "id","jobId",- "jobOperationBatchId",- "earliestStartAt",- "resourceKind",- "resourceId",+ "id",+ "scenarioId",+ "createdAt","startAt",- "operationId",- "updatedBy",+ "resourceId",+ "resourceKind",+ "earliestStartAt",+ "jobOperationBatchId","scheduleNote",- "isPlaceholder"+ "isPlaceholder",+ "operationId",+ "updatedBy"]},{"name": "gauge","rows": 0,"columns": [- "storageUnitId",- "gaugeId",- "lastCalibrationDate",- "gaugeTypeId",- "gaugeStatus",- "gaugeCalibrationStatus",- "id",- "gaugeRole",- "description",- "nextCalibrationDate",+ "updatedBy",+ "serialNumber",+ "calibrationIntervalInMonths",+ "createdBy",+ "locationId",+ "updatedAt",+ "companyId","supplierId",+ "nextCalibrationDate","modelNumber",- "customFields","createdAt",+ "customFields","dateAcquired","lastCalibrationStatus",- "updatedBy",- "calibrationIntervalInMonths",- "createdBy",- "serialNumber",- "companyId",- "locationId",- "updatedAt"+ "gaugeCalibrationStatus",+ "id",+ "gaugeRole",+ "description",+ "storageUnitId",+ "lastCalibrationDate",+ "gaugeId",+ "gaugeTypeId",+ "gaugeStatus"]},{@@ -4546,20 +4568,20 @@"createdAt","requiresAdjustment","temperature",- "gaugeId","updatedAt",+ "gaugeId","notes","companyId",+ "requiresAction","createdBy","calibrationAttempts",- "requiresAction",- "humidity","supplierId",+ "humidity","dateCalibrated","updatedBy","inspectionStatus",- "approvedBy","measurementStandard",+ "approvedBy","requiresRepair"]},@@ -4567,89 +4589,89 @@"name": "inspection","rows": 0,"columns": [- "updatedAt",- "itemReadableId",- "sampleSize",- "inspectionDocumentId",- "samplingStandard",- "id",- "samplingPlanType",- "createdBy",- "sourceDocumentId",- "lotSize",- "sourceDocumentLineId",- "inspectionId",- "rejectionNumber",- "severity",- "codeLetter",- "updatedBy",- "inspectionLevel",- "dispositionedAt",- "sourceDocumentReadableId",+ "companyId","acceptanceNumber",+ "sourceDocumentReadableId","dispositionedBy","itemId",- "companyId",+ "codeLetter",+ "updatedBy",+ "dispositionedAt",+ "inspectionLevel",+ "aql",+ "status",+ "notes","sourceDocument","supplierId","createdAt",- "status",- "notes",- "aql"+ "samplingStandard",+ "id",+ "sampleSize",+ "inspectionDocumentId",+ "itemReadableId",+ "updatedAt",+ "severity",+ "inspectionId",+ "rejectionNumber",+ "sourceDocumentId",+ "lotSize",+ "sourceDocumentLineId",+ "samplingPlanType",+ "createdBy"]},{"name": "inspectionSample","rows": 0,"columns": [- "notes",- "updatedBy",- "inspectedAt",- "status",- "trackedEntityId","inspectedBy","updatedAt",- "id","createdAt",+ "id","createdBy","companyId",- "inspectionId"+ "inspectionId",+ "notes",+ "updatedBy",+ "inspectedAt",+ "trackedEntityId",+ "status"]},{"name": "inspectionMeasurement","rows": 0,"columns": [- "createdAt","value",+ "createdAt",+ "notes","inspectionFeatureId","inspectionSampleId","updatedAt",- "notes",+ "status","createdBy","id","inspectedAt",- "status",- "inspectionId",- "updatedBy","companyId",- "inspectedBy"+ "inspectedBy",+ "updatedBy",+ "inspectionId"]},{"name": "inspectionSamplingPlan","rows": 0,"columns": [- "companyId","createdAt",+ "companyId","inspectionId","rejectionNumber",- "createdBy",- "id","updatedBy",+ "id",+ "createdBy","codeLetter",- "inspectionFeatureId","sampleSize",+ "inspectionFeatureId","acceptanceNumber","updatedAt"]@@ -4658,162 +4680,149 @@"name": "nonConformanceInspection","rows": 0,"columns": [- "createdBy",- "id",- "nonConformanceId","createdAt",- "updatedBy","companyId",- "inspectionId"+ "inspectionId",+ "updatedBy",+ "id",+ "createdBy",+ "nonConformanceId"]},{"name": "inspectionHistory","rows": 0,"columns": [- "severity",- "id",- "lotSize",- "defectsFound",- "aql",- "sampleSize",- "updatedBy",- "companyId","inspectionId",- "createdBy",- "samplingStandard",- "outcome",- "inspectionLevel",- "supplierId",+ "companyId",+ "updatedBy",+ "sampleSize",+ "aql",+ "defectsFound",+ "lotSize",+ "id",+ "severity","createdAt",- "itemId"+ "itemId",+ "supplierId",+ "inspectionLevel",+ "outcome",+ "samplingStandard",+ "createdBy"]},{"name": "itemReplenishment","rows": 0,"columns": [- "leadTime",- "tags","purchasingUnitOfMeasureCode","updatedBy",- "conversionFactor",- "createdBy",- "updatedAt",+ "tags",+ "leadTime","scrapPercentage",- "createdAt",- "preferredSupplierId",- "customFields",- "lotSize",+ "updatedAt",+ "createdBy",+ "conversionFactor","manufacturingBlocked",- "companyId",+ "lotSize",+ "customFields",+ "preferredSupplierId",+ "createdAt",+ "purchasingBlocked","itemId","requiresConfiguration",- "purchasingBlocked"+ "companyId"]},{"name": "jobMakeMethod","rows": 0,"columns": [- "createdAt",- "parentMaterialId",- "requiresBatchTracking",- "itemId","version","trackedEntityId","quantityPerParent",+ "createdAt",+ "itemId",+ "parentMaterialId",+ "requiresBatchTracking",+ "companyId",+ "id",+ "updatedAt",+ "customFields","createdBy","updatedBy","itemScrapPercentage","jobId",- "requiresSerialTracking",- "companyId",- "updatedAt",- "id",- "customFields"+ "requiresSerialTracking"]},{"name": "jobMaterial","rows": 0,"columns": [- "quantityIssued",- "methodType",- "id",- "quantity",- "scrapQuantity",- "substitutionFactor",- "storageUnitId",- "description",- "kit",- "requiresBatchTracking",- "jobId",- "unitCost",- "createdBy",- "updatedAt",- "jobOperationId",- "createdAt",- "jobMakeMethodId",- "unitOfMeasureCode",+ "estimatedQuantity","itemScrapPercentage",+ "unitOfMeasureCode",+ "jobMakeMethodId","itemType",- "estimatedQuantity",- "substitutedFromItemId",- "requiresSerialTracking",- "defaultStorageUnit",- "order",+ "updatedAt",+ "createdAt",+ "jobOperationId",+ "companyId",+ "itemId","updatedBy","customFields",- "itemId",- "companyId"- ]- },- {- "name": "stockTransferLine",- "rows": 0,- "columns": [- "itemId",- "requiresBatchTracking",- "createdAt",- "updatedAt",- "jobId",- "companyId",- "jobMaterialId",- "updatedBy",- "toStorageUnitId",- "pickedQuantity",+ "requiresSerialTracking",+ "order",+ "defaultStorageUnit",+ "substitutedFromItemId",+ "quantity","id",- "trackedEntityId",- "fromStorageUnitId",+ "methodType",+ "quantityIssued","createdBy",- "requiresSerialTracking",+ "jobId",+ "unitCost",+ "requiresBatchTracking",+ "kit",+ "description",+ "substitutionFactor",+ "scrapQuantity",+ "storageUnitId"+ ]+ },+ {+ "name": "stockTransferLine",+ "rows": 0,+ "columns": ["stockTransferId",- "quantity"+ "requiresSerialTracking",+ "createdBy",+ "quantity",+ "trackedEntityId",+ "id",+ "pickedQuantity",+ "fromStorageUnitId",+ "updatedBy",+ "jobMaterialId",+ "companyId",+ "jobId",+ "toStorageUnitId",+ "requiresBatchTracking",+ "itemId",+ "updatedAt",+ "createdAt"]},{"name": "jobMaterialStep","rows": 0,- "columns": ["quantity", "jobMaterialId", "jobOperationStepId"]+ "columns": ["quantity", "jobOperationStepId", "jobMaterialId"]},{"name": "jobOperation","rows": 0,"columns": [- "setupTime",- "operationQuantity",- "customFields",- "targetQuantity",- "laborTime",- "quantityReworked",- "companyId",- "conflictReason",- "overheadRate",- "status",- "jobId",- "machineUnit",- "dueDate","hasConflict","workCenterId","createdAt",@@ -4824,269 +4833,282 @@"setupUnit","updatedAt","laborUnit",- "procedureId","tags",+ "procedureId",+ "setupTime",+ "operationQuantity",+ "customFields",+ "targetQuantity",+ "quantityReworked",+ "laborTime",+ "companyId",+ "conflictReason",+ "overheadRate",+ "status",+ "jobId",+ "dueDate",+ "machineUnit",+ "manuallyScheduled",+ "createdBy",+ "machineRate",+ "laborRate",+ "operationUnitCost",+ "operationSupplierProcessId",+ "reworkId",+ "operationLeadTime",+ "quantityComplete",+ "machineTime",+ "processId","updatedBy","assignee","workInstruction",- "description","priority",+ "description","quantityScrapped","jobOperationBatchId","order","jobMakeMethodId","operationOrder",- "operationType","startDate",+ "operationType","assemblyInstructionId",- "operationMinimumCost",- "manuallyScheduled",- "createdBy",- "machineRate",- "operationUnitCost",- "laborRate",- "operationSupplierProcessId",- "reworkId",- "operationLeadTime",- "machineTime",- "quantityComplete",- "processId"+ "operationMinimumCost"]},{"name": "jobOperationDependency","rows": 0,"columns": [- "operationId",- "dependsOnId","createdAt","jobId",- "companyId"+ "companyId",+ "operationId",+ "dependsOnId"]},{"name": "jobOperationParameter","rows": 0,"columns": [- "updatedBy",- "id",- "createdAt",+ "operationId",+ "value",+ "createdBy",+ "companyId","key","updatedAt",- "companyId",- "value",- "operationId",- "createdBy"+ "id",+ "updatedBy",+ "createdAt"]},{"name": "jobOperationTool","rows": 0,"columns": [- "quantity",- "toolId",- "createdBy",- "companyId",- "operationId",- "updatedAt",+ "createdAt","id","updatedBy",- "createdAt"+ "updatedAt",+ "operationId",+ "companyId",+ "createdBy",+ "quantity",+ "toolId"]},{"name": "nonConformanceJobOperation","rows": 0,"columns": [- "jobReadableId","createdAt","jobOperationId","jobId",- "companyId",- "updatedAt",- "id",+ "jobReadableId","updatedBy","createdBy",- "nonConformanceId"+ "nonConformanceId",+ "companyId",+ "updatedAt",+ "id"]},{"name": "pickingListLine","rows": 0,"columns": [- "jobOperationId",+ "id",+ "toStorageUnitId",+ "itemId",+ "updatedBy",+ "pickingListId",+ "companyId",+ "quantityPicked",+ "storageUnitId","status",- "createdAt",+ "jobOperationId","updatedAt",- "quantityReturned",- "customFields",+ "createdAt","jobId","createdBy","jobMaterialId",- "quantityToPick",- "toStorageUnitId",- "id",- "itemId",- "companyId",- "pickingListId",- "updatedBy",- "storageUnitId",- "quantityPicked"+ "customFields",+ "quantityReturned",+ "quantityToPick"]},{"name": "pickingListLineTrackedEntity","rows": 0,"columns": [- "pickingListLineId","trackedEntityId",- "companyId",+ "pickingListLineId",+ "quantity","quantityPicked",- "quantity"+ "companyId"]},{"name": "productionEvent","rows": 0,"columns": [- "postedToGL",- "jobOperationId",- "updatedBy",- "workCenterId","createdAt",+ "workCenterId",+ "updatedBy",+ "jobOperationId",+ "postedToGL",+ "createdBy","companyId","id",- "createdBy",+ "employeeId","type","startTime",- "employeeId",- "updatedAt",- "endTime",+ "notes","jobOperationBatchId",- "notes"+ "endTime",+ "updatedAt"]},{"name": "productionQuantity","rows": 0,"columns": [+ "inspectionId",+ "setupProductionEventId",+ "updatedAt",+ "machineProductionEventId","quantity","scrapReasonId","type",- "machineProductionEventId",- "updatedAt",- "setupProductionEventId",- "inspectionId",- "inspectionSampleId",- "jobOperationId",- "updatedBy",- "notes",- "createdAt",+ "laborProductionEventId","id","companyId","createdBy",- "laborProductionEventId"+ "notes",+ "createdAt",+ "inspectionSampleId",+ "updatedBy",+ "jobOperationId"]},{"name": "jobOperationNote","rows": 0,"columns": [- "companyId",- "note",- "updatedBy","createdAt",- "jobOperationId",- "updatedAt",- "id",+ "updatedBy",+ "note",+ "companyId",+ "createdBy","productionQuantityId",- "createdBy"+ "id",+ "updatedAt",+ "jobOperationId"]},{"name": "rework","rows": 0,"columns": [+ "reason",+ "updatedAt","targetJobOperationId","triggeredAtJobOperationId",- "updatedAt",- "reason",- "companyId",- "requestedById",- "jobId","quantity","createdAt","id",- "completedAt"+ "completedAt",+ "companyId",+ "requestedById",+ "jobId"]},{"name": "jobOperationStep","rows": 0,"columns": [- "createdBy",- "assemblyInstructionStepId",- "updatedBy",- "sortOrder",- "nonConformanceInvestigationId",- "operationId",- "unitOfMeasureCode",+ "updatedAt",+ "companyId",+ "name",+ "minValue",+ "listValues",+ "id",+ "maxValue",+ "fileTypes",+ "type","required","createdAt","nonConformanceActionId","description",- "type",- "id",- "maxValue",- "fileTypes",- "minValue",- "listValues",- "updatedAt",- "companyId",- "name"+ "unitOfMeasureCode",+ "sortOrder",+ "nonConformanceInvestigationId",+ "operationId",+ "assemblyInstructionStepId",+ "createdBy",+ "updatedBy"]},{"name": "jobOperationStepRecord","rows": 0,"columns": [- "companyId",+ "userValue",+ "index",+ "booleanValue",+ "numericValue",+ "createdAt","jobOperationStepId","updatedAt","id",- "createdBy",- "updatedBy",+ "companyId","value",- "index",- "userValue",- "createdAt",- "booleanValue",- "numericValue"+ "createdBy",+ "updatedBy"]},{"name": "jobOperationStepSlide","rows": 0,"columns": [- "caption",- "imagePath",- "createdBy",- "sortOrder",- "annotations",+ "size",+ "updatedBy",+ "id",+ "companyId","modelUploadId","stepId","updatedAt","createdAt",- "size",- "id",- "updatedBy",- "companyId"+ "sortOrder",+ "annotations",+ "imagePath",+ "caption",+ "createdBy"]},{"name": "jobOperationToolStep","rows": 0,- "columns": ["jobOperationStepId", "jobOperationToolId"]+ "columns": ["jobOperationToolId", "jobOperationStepId"]},{"name": "kanban",@@ -5099,13 +5121,13 @@"supplierId","fromStorageUnitId","jobId",- "quantity",- "updatedAt","replenishmentSystem",+ "updatedAt",+ "quantity","storageUnitId","companyId",- "id","conversionFactor",+ "id","autoRelease","purchaseUnitOfMeasureCode","createdBy",@@ -5117,27 +5139,27 @@"name": "methodMaterial","rows": 0,"columns": [- "tags",- "order",- "itemType",- "updatedAt","kit","quantity",- "scrapQuantity","methodOperationId",+ "scrapQuantity","materialMakeMethodId","methodType","customFields",+ "order",+ "tags",+ "updatedAt",+ "itemType",+ "createdAt",+ "storageUnitIds",+ "unitOfMeasureCode",+ "makeMethodId",+ "updatedBy","sourcingType","itemId","createdBy","id",- "companyId",- "storageUnitIds",- "createdAt",- "unitOfMeasureCode",- "updatedBy",- "makeMethodId"+ "companyId"]},{@@ -5149,108 +5171,108 @@"name": "methodOperation","rows": 0,"columns": [- "operationType",- "id",- "workInstruction",- "companyId",- "operationMinimumCost",- "procedureId",- "machineUnit",- "assemblyInstructionId","customFields","createdBy","inspectionDocumentId","makeMethodId",- "updatedBy",- "laborTime",- "operationSupplierProcessId",- "processId",- "laborUnit",- "setupUnit",- "operationLeadTime",- "createdAt",- "machineTime",- "description",- "tags",- "operationUnitCost",+ "operationMinimumCost",+ "procedureId",+ "machineUnit",+ "assemblyInstructionId",+ "id",+ "workInstruction",+ "companyId",+ "operationType","operationOrder","order","updatedAt","setupTime",- "workCenterId"+ "workCenterId",+ "machineTime",+ "description",+ "tags",+ "operationUnitCost",+ "laborUnit",+ "setupUnit",+ "createdAt",+ "operationLeadTime",+ "laborTime",+ "updatedBy",+ "operationSupplierProcessId",+ "processId"]},{"name": "methodOperationParameter","rows": 0,"columns": [- "createdAt",+ "value",+ "operationId",+ "createdBy",+ "companyId",+ "key",+ "updatedAt","updatedBy","id",- "updatedAt",- "key",- "companyId",- "createdBy",- "value",- "operationId"+ "createdAt"]},{"name": "methodOperationStep","rows": 0,"columns": [+ "sortOrder",+ "operationId",+ "createdBy",+ "updatedBy",+ "assemblyInstructionStepId",+ "description",+ "createdAt",+ "required",+ "unitOfMeasureCode",+ "fileTypes","maxValue","id",- "fileTypes","type",- "updatedAt",- "name","companyId",- "minValue",+ "name",+ "updatedAt","listValues",- "operationId",- "sortOrder",- "updatedBy",- "createdBy",- "createdAt",- "required",- "description",- "assemblyInstructionStepId",- "unitOfMeasureCode"+ "minValue"]},{"name": "methodOperationStepSlide","rows": 0,"columns": [- "createdBy",- "imagePath",- "caption",- "annotations","sortOrder",- "updatedAt",- "createdAt",- "stepId",- "modelUploadId",- "companyId",- "size",+ "annotations",+ "caption",+ "imagePath",+ "createdBy",+ "id","updatedBy",- "id"+ "size",+ "companyId",+ "modelUploadId",+ "stepId",+ "createdAt",+ "updatedAt"]},{"name": "methodOperationTool","rows": 0,"columns": [- "toolId",- "quantity",- "createdBy",- "companyId",- "operationId",- "updatedAt",+ "createdAt","updatedBy","id",- "createdAt"+ "updatedAt",+ "operationId",+ "companyId",+ "createdBy",+ "toolId",+ "quantity"]},{@@ -5262,36 +5284,36 @@"name": "nonConformanceActionProcess","rows": 0,"columns": [- "createdBy",- "id",- "updatedBy",- "actionTaskId","createdAt","updatedAt","companyId",- "processId"+ "processId",+ "createdBy",+ "id",+ "updatedBy",+ "actionTaskId"]},{"name": "nonConformanceActionTask","rows": 0,"columns": [- "createdBy",- "nonConformanceId",- "actionTypeId",+ "assignee",+ "status",+ "updatedAt",+ "supplierId",+ "updatedBy",+ "createdAt",+ "dueDate","tags","notes",+ "nonConformanceId",+ "createdBy",+ "actionTypeId",+ "completedDate","companyId",- "sortOrder","id",- "completedDate",- "updatedAt",- "status",- "assignee",- "dueDate",- "createdAt",- "updatedBy",- "supplierId"+ "sortOrder"]},{@@ -5300,12 +5322,12 @@"columns": ["purchaseReturnOrderReadableId","companyId",- "purchaseReturnOrderLineId","purchaseReturnOrderId",+ "purchaseReturnOrderLineId","quantity","updatedBy",- "createdBy","id",+ "createdBy","updatedAt","createdAt","nonConformanceId"@@ -5315,116 +5337,107 @@"name": "nonConformanceSalesReturnOrderLine","rows": 0,"columns": [- "salesReturnOrderReadableId",- "salesReturnOrderId",- "salesReturnOrderLineId",- "createdAt",+ "updatedBy",+ "createdBy",+ "nonConformanceId",+ "companyId","id","updatedAt",- "companyId",- "nonConformanceId",- "createdBy",- "updatedBy"+ "createdAt",+ "salesReturnOrderId",+ "salesReturnOrderLineId",+ "salesReturnOrderReadableId"]},{"name": "nonConformanceSupplier","rows": 0,"columns": [- "createdAt",- "updatedAt",- "companyId",- "supplierId",- "createdBy",+ "nonConformanceId",+ "updatedBy","id","externalLinkId",- "updatedBy",- "nonConformanceId"+ "createdBy",+ "companyId",+ "supplierId",+ "updatedAt",+ "createdAt"]},{"name": "partner","rows": 0,"columns": [+ "companyId",+ "createdAt","abilityId","active",- "createdAt",- "companyId",- "hoursPerWeek",- "updatedBy",- "customFields",+ "createdBy","updatedAt","id","tags",- "createdBy"+ "updatedBy",+ "customFields",+ "hoursPerWeek"]},{"name": "payment","rows": 0,"columns": [- "postingDate",- "exchangeRate",- "updatedAt","postedAt",- "paymentId","reference",- "supplierId",- "customFields",- "currencyCode",+ "paymentId",+ "postingDate",+ "updatedAt",+ "exchangeRate","id",+ "currencyCode","totalAmount",- "paymentDate",- "updatedBy",+ "supplierId",+ "customFields",+ "status","memo","paymentType",- "status",- "voidedAt","voidedBy",- "postedBy",- "journalId",- "createdBy",+ "voidedAt",+ "updatedBy",+ "paymentDate","createdAt",- "bankAccount",+ "customerId","companyId",- "customerId"+ "bankAccount",+ "createdBy",+ "journalId",+ "postedBy"]},{"name": "purchaseInvoiceDelivery","rows": 0,"columns": [- "supplierShippingCost",+ "updatedBy","shippingTermId","shippingMethodId",- "updatedBy",+ "supplierShippingCost",+ "incoterm",+ "updatedAt",+ "locationId",+ "companyId","incotermLocation","id",- "customFields",- "companyId",- "locationId",- "incoterm",- "updatedAt"+ "customFields"]},{"name": "purchaseInvoiceStatusHistory","rows": 0,- "columns": ["invoiceId", "status", "id", "companyId", "createdAt"]+ "columns": ["createdAt", "companyId", "invoiceId", "id", "status"]},{"name": "purchaseOrderDelivery","rows": 0,"columns": [- "receiptPromisedDate",- "customerId",- "trackingNumber",- "id",- "dropShipment",- "notes",- "companyId",- "locationId",- "customFields","updatedAt","tags","receiptRequestedDate",@@ -5435,7 +5448,16 @@"supplierShippingCost","updatedBy","shippingMethodId",- "shippingTermId"+ "shippingTermId",+ "receiptPromisedDate",+ "customerId",+ "trackingNumber",+ "id",+ "dropShipment",+ "notes",+ "companyId",+ "locationId",+ "customFields"]},{@@ -5447,104 +5469,104 @@"name": "purchaseOrderLine","rows": 0,"columns": [- "updatedAt",- "locationId",- "costCenterId",- "inventoryUnitOfMeasureCode",- "invoicedComplete",- "taxPercent",- "quantityShipped",- "receivedComplete",- "jobOperationId",- "internalNotes",- "customFields",- "sortOrder",- "companyId",- "assetId",- "storageUnitId",- "setupPrice",- "promisedDate",- "itemId",- "purchaseOrderLineType",- "supplierUnitPrice",- "createdBy",- "supplierPartId",- "accountId",- "supplierTaxAmount",- "requiredDate",- "updatedBy",- "quantityReceived",- "supplierShippingCost",- "id",- "purchaseQuantity",+ "conversionFactor",+ "receivedDate",+ "tags",+ "description","externalNotes","createdAt",- "description",- "tags",- "receivedDate",- "conversionFactor",- "jobId",- "exchangeRate",+ "purchaseUnitOfMeasureCode","purchaseOrderId",- "modelUploadId",- "quantityInvoiced",+ "exchangeRate",+ "jobId","ownerId",- "purchaseUnitOfMeasureCode"+ "quantityInvoiced",+ "modelUploadId",+ "supplierTaxAmount",+ "accountId",+ "supplierPartId",+ "requiredDate",+ "createdBy",+ "purchaseQuantity",+ "id",+ "quantityReceived",+ "updatedBy",+ "supplierShippingCost",+ "sortOrder",+ "customFields",+ "assetId",+ "companyId",+ "internalNotes",+ "promisedDate",+ "supplierUnitPrice",+ "purchaseOrderLineType",+ "itemId",+ "storageUnitId",+ "setupPrice",+ "locationId",+ "updatedAt",+ "quantityShipped",+ "taxPercent",+ "invoicedComplete",+ "costCenterId",+ "inventoryUnitOfMeasureCode",+ "jobOperationId",+ "receivedComplete"]},{"name": "nonConformancePurchaseOrderLine","rows": 0,"columns": [- "purchaseOrderReadableId",- "createdAt",- "purchaseOrderId",- "purchaseOrderLineId","companyId","id","updatedAt",- "updatedBy","createdBy",- "nonConformanceId"+ "updatedBy",+ "nonConformanceId",+ "purchaseOrderReadableId",+ "createdAt",+ "purchaseOrderId",+ "purchaseOrderLineId"]},{"name": "purchaseOrderStatusHistory","rows": 0,"columns": [- "id",- "companyId",- "purchaseOrderId","createdBy","createdAt","status",- "updatedBy"+ "updatedBy",+ "id",+ "companyId",+ "purchaseOrderId"]},{"name": "purchaseOrderTransaction","rows": 0,"columns": [- "purchaseOrderId",- "companyId","id",- "type",+ "companyId",+ "purchaseOrderId",+ "createdAt","userId",- "createdAt"+ "type"]},{"name": "purchaseReturnOrderLineTrackedEntity","rows": 0,"columns": [+ "purchaseReturnOrderLineId",+ "createdAt",+ "trackedEntityId",+ "updatedAt","createdBy",- "updatedBy","companyId","quantity",- "createdAt",- "purchaseReturnOrderLineId",- "updatedAt",- "trackedEntityId"+ "updatedBy"]},{@@ -5553,8 +5575,8 @@"columns": ["createdAt","updatedBy",- "supplierId","companyId",+ "supplierId","createdBy","id","purchasingRfqId"@@ -5568,173 +5590,173 @@{"name": "purchasingRfqToSupplierQuote","rows": 0,- "columns": ["supplierQuoteId", "purchasingRfqId", "companyId"]+ "columns": ["companyId", "purchasingRfqId", "supplierQuoteId"]},{"name": "quoteMakeMethod","rows": 0,"columns": [- "itemId",- "customFields",+ "parentMaterialId","quoteLineId","version",- "parentMaterialId","companyId",- "createdBy",- "id",- "updatedBy",- "quantityPerParent",+ "itemId",+ "customFields","tags","quoteId","createdAt",- "updatedAt"+ "updatedAt",+ "id",+ "createdBy",+ "updatedBy",+ "quantityPerParent"]},{"name": "quoteMaterial","rows": 0,"columns": [- "createdBy",- "scrapQuantity",- "storageUnitId",- "updatedBy",- "quoteOperationId",- "unitCost",- "tags",- "methodType",- "unitCostSource",- "itemId",- "createdAt","quoteLineId",- "quoteMakeMethodId",+ "createdAt",+ "itemId","customFields",- "itemType",- "kit",- "id",- "description",- "unitOfMeasureCode",- "order",- "quantity",+ "quoteMakeMethodId",+ "unitCostSource",+ "methodType",+ "tags",+ "unitCost",+ "quoteOperationId",+ "updatedBy",+ "storageUnitId",+ "scrapQuantity",+ "createdBy","updatedAt",+ "quoteId","companyId",- "quoteId"+ "order",+ "quantity",+ "description",+ "id",+ "unitOfMeasureCode",+ "itemType",+ "kit"]},{"name": "quoteMaterialStep","rows": 0,- "columns": ["quoteMaterialId", "quoteOperationStepId", "quantity"]+ "columns": ["quantity", "quoteOperationStepId", "quoteMaterialId"]},{"name": "quoteOperation","rows": 0,"columns": [- "customFields",- "overheadRate",- "laborTime",- "createdAt",- "processId",- "order",- "updatedBy",- "operationOrder",- "operationType",+ "quoteMakeMethodId",+ "quoteLineId",+ "laborRate",+ "assemblyInstructionId",+ "createdBy",+ "updatedAt",+ "machineTime","workCenterId","workInstruction","operationSupplierProcessId",- "machineTime","operationMinimumCost",- "quoteMakeMethodId",- "laborRate",- "quoteLineId",- "updatedAt",- "createdBy",- "assemblyInstructionId",- "setupUnit",- "id",- "procedureId",- "tags",- "laborUnit",- "machineRate",+ "processId",+ "updatedBy",+ "operationType",+ "operationOrder",+ "order",+ "laborTime",+ "createdAt",+ "overheadRate",+ "customFields",+ "companyId",+ "operationUnitCost",+ "quoteId",+ "inspectionDocumentId","description",+ "machineRate","machineUnit",- "setupTime","operationLeadTime",- "companyId",- "inspectionDocumentId",- "quoteId",- "operationUnitCost"+ "setupTime",+ "id",+ "laborUnit",+ "tags",+ "procedureId",+ "setupUnit"]},{"name": "quoteOperationParameter","rows": 0,"columns": [- "operationId",- "value",- "createdBy",- "companyId",- "key","updatedAt",+ "key",+ "createdAt","id","updatedBy",- "createdAt"+ "createdBy",+ "operationId",+ "value",+ "companyId"]},{"name": "quoteOperationStep","rows": 0,"columns": [- "fileTypes",- "id",- "maxValue",- "type",- "name",- "companyId",- "updatedAt",- "listValues",- "minValue",- "operationId",- "sortOrder",- "updatedBy",- "createdBy",+ "unitOfMeasureCode","description","required","createdAt",- "unitOfMeasureCode"+ "updatedBy",+ "createdBy",+ "operationId",+ "sortOrder",+ "listValues",+ "minValue",+ "name",+ "companyId",+ "updatedAt",+ "type",+ "fileTypes",+ "id",+ "maxValue"]},{"name": "quoteOperationStepSlide","rows": 0,"columns": [- "createdBy",- "caption","imagePath",+ "caption",+ "createdBy","annotations","sortOrder",- "updatedAt",- "createdAt","stepId","modelUploadId",- "companyId",+ "updatedAt",+ "createdAt","size",+ "updatedBy","id",- "updatedBy"+ "companyId"]},{"name": "quoteOperationTool","rows": 0,"columns": [+ "createdBy",+ "quantity",+ "toolId",+ "companyId","updatedAt","operationId","createdAt","id",- "updatedBy",- "createdBy",- "quantity",- "toolId",- "companyId"+ "updatedBy"]},{@@ -5746,180 +5768,180 @@"name": "receiptFixedAssetLine","rows": 0,"columns": [- "companyId",- "id","updatedAt",+ "id",+ "companyId",+ "receiptId","createdAt","updatedBy",- "receiptId","serialNumber",- "createdBy",+ "purchaseOrderLineId","received",- "purchaseOrderLineId"+ "createdBy"]},{"name": "receiptLine","rows": 0,"columns": [- "requiresBatchTracking",- "unitPrice",- "createdBy",- "updatedBy",- "requiresSerialTracking",- "conversionFactor",- "itemId",- "lineId",- "createdAt",- "outstandingQuantity",+ "receiptId",+ "companyId",+ "updatedAt",+ "storageUnitId",+ "receivedQuantity","unitOfMeasure","id","locationId","orderQuantity",- "companyId",- "receiptId",- "updatedAt",- "storageUnitId",- "receivedQuantity"+ "conversionFactor",+ "requiresSerialTracking",+ "itemId",+ "createdAt",+ "lineId",+ "outstandingQuantity",+ "requiresBatchTracking",+ "unitPrice",+ "updatedBy",+ "createdBy"]},{"name": "nonConformanceReceiptLine","rows": 0,"columns": [+ "createdAt",+ "receiptLineId",+ "receiptId",+ "receiptReadableId","createdBy","updatedBy","nonConformanceId","companyId",- "id","updatedAt",- "createdAt",- "receiptId",- "receiptLineId",- "receiptReadableId"+ "id"]},{"name": "salesInvoice","rows": 0,"columns": [- "dateIssued",- "customFields",- "paymentTermId",- "id",- "assignee",- "invoiceCustomerId",- "datePaid",- "updatedBy",- "invoiceId",- "subtotal",- "shipmentId",- "updatedAt",- "postingDate",- "externalNotes",- "invoiceCustomerContactId",- "tags",+ "locationId",+ "status",+ "customerId",+ "totalTax",+ "totalAmount",+ "invoiceCustomerLocationId",+ "opportunityId",+ "internalNotes",+ "createdBy",+ "exchangeRateUpdatedAt","customerReference",- "createdAt","dateDue",- "exchangeRateUpdatedAt",- "currencyCode",+ "createdAt","exchangeRate",+ "currencyCode","totalDiscount","companyId",- "totalTax",- "totalAmount",- "status",- "locationId",- "customerId",- "createdBy",- "invoiceCustomerLocationId",- "opportunityId",- "internalNotes"+ "subtotal",+ "datePaid",+ "invoiceId",+ "updatedBy",+ "externalNotes",+ "tags",+ "invoiceCustomerContactId",+ "shipmentId",+ "postingDate",+ "updatedAt",+ "paymentTermId",+ "id",+ "dateIssued",+ "customFields",+ "invoiceCustomerId",+ "assignee"]},{"name": "salesInvoiceLine","rows": 0,"columns": [- "addOnCost",- "modelUploadId",- "unitPrice",- "companyId",- "locationId",- "itemId",- "createdAt",- "salesOrderId",- "updatedBy",- "accountId",- "sortOrder",- "shippingCost",- "taxPercent",- "invoiceLineType",- "exchangeRate",- "description",- "internalNotes","methodType",- "unitOfMeasureCode",+ "internalNotes",+ "id",+ "assetId","opportunityId",+ "unitOfMeasureCode","nonTaxableAddOnCost",- "assetId",- "id",- "createdBy",+ "customFields",+ "salesOrderLineId","quantity",+ "createdBy","externalNotes",- "salesOrderLineId",- "customFields",+ "setupPrice","updatedAt","invoiceId","storageUnitId",- "setupPrice"+ "modelUploadId",+ "addOnCost",+ "unitPrice",+ "locationId",+ "companyId",+ "itemId",+ "salesOrderId",+ "accountId",+ "updatedBy",+ "createdAt",+ "description",+ "invoiceLineType",+ "exchangeRate",+ "shippingCost",+ "sortOrder",+ "taxPercent"]},{"name": "salesInvoiceShipment","rows": 0,"columns": [- "incoterm",- "shippingTermId","companyId","locationId","shippingMethodId",- "customFields",- "createdBy",- "id",- "updatedBy",+ "incoterm",+ "shippingTermId","createdAt","updatedAt","shippingCost",- "incotermLocation"+ "incotermLocation",+ "customFields",+ "createdBy",+ "id",+ "updatedBy"]},{"name": "salesReturnOrderLine","rows": 0,"columns": [- "updatedBy",- "createdAt",- "disposition",- "lineNumber",- "itemId",- "unitOfMeasureCode",- "quantity",- "shipmentLineId",- "updatedAt",- "closedComplete",- "customFields",- "createdBy",+ "unitPrice",+ "returnReasonId",+ "companyId","salesInvoiceLineId","salesReturnOrderId",- "companyId",- "returnReasonId",- "unitPrice",- "salesOrderLineId",+ "quantityReceived","restockFeePercent","id",- "quantityReceived"+ "salesOrderLineId",+ "unitOfMeasureCode",+ "lineNumber",+ "disposition",+ "itemId",+ "updatedBy",+ "createdAt",+ "customFields",+ "closedComplete",+ "createdBy",+ "quantity",+ "shipmentLineId",+ "updatedAt"]},{@@ -5927,8 +5949,8 @@"rows": 0,"columns": ["updatedBy",- "quantity","companyId",+ "quantity","createdBy","updatedAt","trackedEntityId",@@ -5940,142 +5962,142 @@"name": "salesReturnOrderCreditLine","rows": 0,"columns": [- "companyId",- "quantity",- "salesReturnOrderLineId",- "unitPrice",- "createdBy","updatedBy",+ "createdBy","memoId","restockFee",+ "updatedAt","id","createdAt",- "updatedAt"+ "companyId",+ "quantity",+ "salesReturnOrderLineId",+ "unitPrice"]},{"name": "shipmentFixedAssetLine","rows": 0,"columns": [+ "serialNumber","createdBy","salesOrderLineId","shipped",- "serialNumber",- "updatedBy",- "createdAt",- "shipmentId","companyId","updatedAt",- "id"+ "id",+ "createdAt",+ "updatedBy",+ "shipmentId"]},{"name": "shipmentLine","rows": 0,"columns": [- "requiresBatchTracking",- "lineId",- "itemId",- "updatedAt",- "updatedBy",- "outstandingQuantity",- "unitPrice",- "fulfillmentId",- "createdBy",- "companyId",- "createdAt",- "shipmentId",- "requiresSerialTracking","shippedQuantity","storageUnitId",+ "createdAt",+ "requiresSerialTracking",+ "shipmentId",+ "orderQuantity","locationId","id","unitOfMeasure",- "orderQuantity"+ "outstandingQuantity",+ "requiresBatchTracking",+ "lineId",+ "itemId",+ "updatedBy",+ "updatedAt",+ "companyId",+ "createdBy",+ "unitPrice",+ "fulfillmentId"]},{"name": "nonConformanceShipmentLine","rows": 0,"columns": [- "shipmentLineId",- "shipmentId",- "createdAt",- "shipmentReadableId",- "nonConformanceId","createdBy","updatedBy",- "updatedAt",+ "nonConformanceId",+ "companyId","id",- "companyId"+ "updatedAt",+ "createdAt",+ "shipmentId",+ "shipmentLineId",+ "shipmentReadableId"]},{"name": "supplier","rows": 0,"columns": [- "defaultCc",- "accountManagerId",- "createdBy",- "supplierStatus",- "companyId",- "id",+ "website",+ "supplierTypeId",+ "customFields",+ "intercompanyCompanyId",+ "purchasingContactId",+ "logo",+ "tags",+ "updatedAt",+ "embedding",+ "fax",+ "taxPercent",+ "currencyCode",+ "name",+ "updatedBy",+ "phone","createdAt","assignee","readableId",- "updatedBy",- "name",- "phone",- "taxPercent",- "currencyCode",- "fax",- "updatedAt",- "tags",- "embedding",- "logo",- "purchasingContactId",- "intercompanyCompanyId",- "website",- "supplierTypeId",- "customFields"+ "supplierStatus",+ "createdBy",+ "id",+ "companyId",+ "defaultCc",+ "accountManagerId"]},{"name": "supplierAccount","rows": 0,- "columns": ["active", "companyId", "supplierId", "id"]+ "columns": ["active", "companyId", "id", "supplierId"]},{"name": "supplierBankAccount","rows": 0,"columns": [- "bankAddress",- "updatedBy",- "updatedAt",- "name",- "active",- "supplierId",+ "bankName",+ "currencyCode",+ "id",+ "bankCode",+ "countryCode",+ "accountNumber",+ "createdBy",+ "companyId",+ "isPrimary","createdAt","tags","notes",- "customFields","swiftBic",+ "customFields","accountHolderName",- "accountNumber",- "countryCode",- "companyId",- "isPrimary",- "createdBy",- "bankName",- "bankCode",- "id",- "currencyCode"+ "bankAddress",+ "supplierId",+ "active",+ "name",+ "updatedBy",+ "updatedAt"]},{"name": "supplierInteraction","rows": 0,- "columns": ["companyId", "supplierId", "id"]+ "columns": ["id", "supplierId", "companyId"]},{"name": "receipt",@@ -6084,518 +6106,518 @@"supplierId","postingDate","updatedAt",- "receiptId","companyId",+ "receiptId","sourceDocumentReadableId",- "id","status",+ "id","invoiced","externalDocumentId",- "sourceDocument",- "locationId","createdAt",- "customFields",+ "locationId",+ "sourceDocument","tags",- "updatedBy",+ "customFields","createdBy","supplierInteractionId",+ "updatedBy","postedBy",- "internalNotes",+ "sourceDocumentId","assignee",- "sourceDocumentId"+ "internalNotes"]},{"name": "shipment","rows": 0,"columns": [- "sourceDocument",- "locationId",- "assignee",- "companyId",- "createdAt",- "tags",- "shippingMethodId",- "updatedBy",- "createdBy",- "postedBy",- "sourceDocumentId",- "supplierInteractionId",- "opportunityId",- "internalNotes",- "updatedAt",+ "customerId",+ "id",+ "postingDate",+ "externalDocumentId",+ "sourceDocumentReadableId",+ "supplierId","externalNotes",- "shipmentId","invoiced",+ "shipmentId","trackingNumber",- "status","customFields",- "id",- "customerId",- "externalDocumentId",- "postingDate",- "sourceDocumentReadableId",- "supplierId"+ "status",+ "updatedBy",+ "sourceDocumentId",+ "postedBy",+ "createdBy",+ "internalNotes",+ "updatedAt",+ "opportunityId",+ "supplierInteractionId",+ "locationId",+ "assignee",+ "sourceDocument",+ "createdAt",+ "companyId",+ "shippingMethodId",+ "tags"]},{"name": "supplierLedger","rows": 0,"columns": [- "entryNumber",- "createdAt",- "amount",- "companyId",- "id",- "externalDocumentId",+ "documentId","postingDate","documentType","supplierId",- "documentId"+ "companyId",+ "id",+ "externalDocumentId",+ "entryNumber",+ "amount",+ "createdAt"]},{"name": "supplierLocation","rows": 0,"columns": [+ "name",+ "customFields",+ "addressId","tags","id","companyId",- "supplierId",- "name",- "addressId",- "customFields"+ "supplierId"]},{"name": "supplierContact","rows": 0,"columns": [- "supplierId",- "companyId","id","customFields",- "contactId",+ "supplierId",+ "companyId",+ "userId","supplierLocationId",- "tags",- "userId"+ "contactId",+ "tags"]},{"name": "purchaseInvoice","rows": 0,"columns": [- "createdAt",- "invoiceSupplierId",- "updatedAt",- "exchangeRate",- "id",- "paymentTermId",- "currencyCode",- "createdBy",- "internalNotes","invoiceSupplierContactId",+ "internalNotes","supplierInteractionId",- "invoiceId",- "status",- "dateIssued",+ "createdBy",+ "currencyCode","subtotal",- "updatedBy",- "totalDiscount",- "assignee",- "datePaid",- "postingDate",- "exchangeRateUpdatedAt",- "supplierReference",- "companyId",- "locationId",- "tags",+ "dateIssued",+ "status",+ "invoiceId",+ "invoiceSupplierId",+ "createdAt",+ "id",+ "paymentTermId",+ "updatedAt",+ "exchangeRate","customFields","invoiceSupplierLocationId",- "totalAmount",- "totalTax",+ "tags",+ "locationId","supplierId",- "dateDue"+ "dateDue",+ "totalTax",+ "totalAmount",+ "datePaid",+ "assignee",+ "updatedBy",+ "totalDiscount",+ "companyId",+ "supplierReference",+ "exchangeRateUpdatedAt",+ "postingDate"]},{"name": "purchaseOrder","rows": 0,"columns": [+ "currencyCode",+ "closedBy",+ "createdAt",+ "externalNotes",+ "status",+ "assignee",+ "updatedBy",+ "exchangeRate",+ "exchangeRateUpdatedAt",+ "purchaseOrderType",+ "updatedAt",+ "createdBy",+ "revisionId",+ "closedAt","internalNotes","orderDate","supplierReference","supplierInteractionId","supplierLocationId","id",- "supplierContactId","tags",+ "supplierContactId","jobId","supplierId","jobReadableId",- "purchaseOrderId","companyId",- "customFields",- "createdAt",- "externalNotes",- "closedBy",- "currencyCode",- "assignee",- "updatedBy",- "status",- "exchangeRate",- "purchaseOrderType",- "exchangeRateUpdatedAt",- "createdBy",- "updatedAt",- "revisionId",- "closedAt"+ "purchaseOrderId",+ "customFields"]},{"name": "purchaseInvoiceLine","rows": 0,"columns": [- "tags",- "modelUploadId",- "createdAt",- "supplierTaxAmount",- "exchangeRate",- "sortOrder",- "inventoryUnitOfMeasureCode","costCenterId","invoiceLineType","quantity","purchaseOrderId",+ "exchangeRate",+ "sortOrder",+ "inventoryUnitOfMeasureCode",+ "tags",+ "modelUploadId",+ "createdAt",+ "supplierTaxAmount",+ "taxPercent",+ "createdBy",+ "assetId",+ "purchaseUnitOfMeasureCode",+ "purchaseOrderLineId",+ "jobOperationId","ownerId","customFields","accountId",- "companyId","supplierUnitPrice",- "jobOperationId",- "assetId",- "purchaseUnitOfMeasureCode",- "purchaseOrderLineId",- "taxPercent",- "createdBy",- "storageUnitId",- "supplierShippingCost",- "updatedBy",- "internalNotes",- "serviceId",+ "companyId",+ "requiredDate","invoiceId","description",- "requiredDate",- "updatedAt",- "itemId",- "conversionFactor",+ "internalNotes",+ "serviceId",+ "supplierShippingCost",+ "storageUnitId",+ "updatedBy","locationId",- "id"+ "id",+ "conversionFactor",+ "itemId",+ "updatedAt"]},{"name": "purchaseInvoicePriceChange","rows": 0,"columns": [- "newPrice",- "invoiceLineId",- "previousPrice",- "newQuantity",+ "updatedBy",+ "invoiceId",+ "previousQuantity","companyId","id",- "previousQuantity",- "invoiceId",- "updatedBy"+ "newQuantity",+ "invoiceLineId",+ "previousPrice",+ "newPrice"]},{"name": "purchaseOrderPayment","rows": 0,"columns": [+ "invoiceSupplierLocationId",+ "invoiceSupplierContactId","paymentTermId","tags",- "invoiceSupplierContactId",- "invoiceSupplierLocationId",- "paymentComplete",- "id",- "updatedAt",- "customFields",- "companyId",+ "invoiceSupplierId","updatedBy",- "invoiceSupplierId"+ "companyId",+ "customFields",+ "updatedAt",+ "id",+ "paymentComplete"]},{"name": "purchaseReturnOrder","rows": 0,"columns": [- "currencyCode",- "purchaseOrderId",- "id",- "supplierContactId",+ "replacementPurchaseOrderId",+ "locationId","orderDate","purchaseReturnOrderId","externalNotes",- "replacementPurchaseOrderId",- "locationId",- "supplierLocationId",- "exchangeRate",- "createdAt",- "updatedAt",- "updatedBy",- "internalNotes",- "assignee",+ "supplierContactId",+ "currencyCode",+ "purchaseOrderId",+ "id",+ "supplierReference",+ "customFields","createdBy","companyId","status","expirationDate","supplierId",- "supplierReference",- "customFields"+ "updatedBy",+ "internalNotes",+ "assignee",+ "supplierLocationId",+ "exchangeRate",+ "createdAt",+ "updatedAt"]},{"name": "memo","rows": 0,"columns": [- "voidedBy",- "voidedAt",- "status",- "notes",- "direction",- "updatedBy",- "memoDate",- "customerId",- "companyId",- "reasonAccount",- "createdAt",- "journalId",- "createdBy",- "salesReturnOrderId",- "postedBy",- "reference",- "memoId","postedAt",- "updatedAt",- "exchangeRate",+ "memoId",+ "reference","postingDate",- "purchaseReturnOrderId",- "amount",- "id",+ "exchangeRate",+ "updatedAt","currencyCode",+ "id",+ "amount",+ "purchaseReturnOrderId",+ "supplierId","customFields",- "supplierId"+ "direction",+ "notes",+ "status",+ "voidedAt",+ "voidedBy",+ "memoDate",+ "updatedBy",+ "createdAt",+ "reasonAccount",+ "companyId",+ "customerId",+ "postedBy",+ "salesReturnOrderId",+ "journalId",+ "createdBy"]},{"name": "invoiceSettlement","rows": 0,"columns": [- "discountAmount",- "sourceExchangeRate",- "createdAt",- "appliedDate",- "paymentId",- "targetMemoId",+ "targetExchangeRate","id","writeOffAmount",- "targetExchangeRate",- "appliedAmount",- "targetSalesInvoiceId",- "companyId",- "memoId",- "sourcePaymentId",- "updatedBy",- "createdBy",- "appliedViaPaymentId",+ "targetMemoId",+ "appliedDate",+ "paymentId",+ "createdAt",+ "sourceExchangeRate",+ "discountAmount","targetPurchaseInvoiceId","sourceAmount",- "fxGainLossAmount"+ "fxGainLossAmount",+ "createdBy",+ "appliedViaPaymentId",+ "sourcePaymentId",+ "updatedBy",+ "targetSalesInvoiceId",+ "memoId",+ "companyId",+ "appliedAmount"]},{"name": "purchaseReturnOrderLine","rows": 0,"columns": [+ "unitOfMeasureCode",+ "updatedAt",+ "updatedBy",+ "lineNumber",+ "closedComplete",+ "itemId",+ "companyId",+ "createdAt",+ "quantity",+ "receiptLineId",+ "customFields","returnReasonId","unitPrice",- "purchaseReturnOrderId","purchaseInvoiceLineId",+ "purchaseReturnOrderId","createdBy","quantityShipped","purchaseOrderLineId",- "id","restockFeePercent",- "unitOfMeasureCode",- "updatedBy",- "updatedAt",- "itemId",- "lineNumber",- "closedComplete",- "createdAt",- "companyId",- "customFields",- "receiptLineId",- "quantity"+ "id"]},{"name": "purchaseReturnOrderCreditLine","rows": 0,"columns": [- "unitPrice",- "companyId",- "quantity",- "purchaseReturnOrderLineId",+ "updatedBy",+ "createdBy",+ "memoId","restockFee",+ "updatedAt","id","createdAt",- "updatedAt",- "createdBy",- "updatedBy",- "memoId"+ "companyId",+ "quantity",+ "purchaseReturnOrderLineId",+ "unitPrice"]},{"name": "supplierPart","rows": 0,"columns": [- "updatedBy",- "supplierUnitOfMeasureCode",- "orderMultiple",- "unitPrice",- "supplierPartId",- "customFields","supplierId",+ "customFields",+ "supplierPartId","conversionFactor",- "createdAt",- "id",- "companyId",- "minimumOrderQuantity",- "itemId",- "updatedAt",+ "supplierUnitOfMeasureCode",+ "updatedBy",+ "unitPrice",+ "orderMultiple","tags",+ "updatedAt",+ "itemId",+ "active","createdBy",- "active"+ "companyId",+ "id",+ "createdAt",+ "minimumOrderQuantity"]},{"name": "supplierPartPrice","rows": 0,"columns": [- "sourceType",- "unitPrice",- "createdBy",- "sourceDocumentId","quantity","updatedAt","createdAt","leadTime",- "supplierPartId","updatedBy",- "companyId"+ "supplierPartId",+ "companyId",+ "unitPrice",+ "sourceType",+ "createdBy",+ "sourceDocumentId"]},{"name": "supplierPayment","rows": 0,"columns": [- "invoiceSupplierId",- "customFields",- "updatedAt",- "tags",- "updatedBy",- "supplierId",- "invoiceSupplierLocationId",+ "paymentTermId","invoiceSupplierContactId",+ "invoiceSupplierLocationId","companyId",- "paymentTermId"+ "supplierId",+ "updatedBy",+ "tags",+ "invoiceSupplierId",+ "updatedAt",+ "customFields"]},{"name": "supplierProcess","rows": 0,"columns": [+ "supplierId",+ "tags",+ "createdAt",+ "customFields",+ "updatedBy","createdBy","id",- "updatedBy","leadTime",- "tags",- "supplierId",- "customFields",- "createdAt",- "updatedAt","processId","minimumCost",- "companyId"+ "companyId",+ "updatedAt"]},{"name": "supplierQuote","rows": 0,"columns": [- "externalNotes",- "supplierLocationId",- "supplierInteractionId",- "exchangeRateUpdatedAt",- "supplierQuoteId",- "assignee",- "status",- "supplierQuoteType",- "id",- "supplierId",- "supplierContactId",- "updatedBy",- "internalNotes",- "quotedDate",- "revisionId","currencyCode",+ "revisionId",+ "quotedDate","customFields","tags",- "externalLinkId",- "companyId",- "createdBy",- "exchangeRate",+ "internalNotes",+ "updatedBy","updatedAt",- "createdAt","supplierReference",- "expirationDate"+ "createdAt",+ "expirationDate",+ "companyId",+ "externalLinkId",+ "exchangeRate",+ "createdBy",+ "exchangeRateUpdatedAt",+ "supplierQuoteId",+ "assignee",+ "externalNotes",+ "supplierLocationId",+ "supplierInteractionId",+ "supplierId",+ "id",+ "supplierContactId",+ "status",+ "supplierQuoteType"]},{"name": "supplierQuoteFavorite","rows": 0,- "columns": ["userId", "supplierQuoteId"]+ "columns": ["supplierQuoteId", "userId"]},{"name": "supplierQuoteLine","rows": 0,"columns": [- "supplierQuoteRevisionId",- "quantity",- "updatedBy",- "customFields",- "sortOrder",- "description",- "costCenterId",- "externalNotes",- "conversionFactor",- "tags",- "itemId",+ "supplierQuoteLineType",+ "purchaseUnitOfMeasureCode",+ "ownerId",+ "supplierPartRevision",+ "id",+ "inventoryUnitOfMeasureCode",+ "accountId",+ "supplierPartId",+ "supplierQuoteId",+ "createdBy","updatedAt","requiredDate","internalNotes","companyId",- "createdBy",- "supplierQuoteId",- "supplierPartId",- "inventoryUnitOfMeasureCode",- "accountId",- "supplierPartRevision",- "id",- "purchaseUnitOfMeasureCode",- "ownerId",- "supplierQuoteLineType"+ "conversionFactor",+ "tags",+ "itemId",+ "externalNotes",+ "sortOrder",+ "description",+ "costCenterId",+ "updatedBy",+ "customFields",+ "supplierQuoteRevisionId",+ "quantity"]},{@@ -6606,153 +6628,153 @@"createdAt","updatedBy","leadTime",- "quantity","updatedAt",- "supplierQuoteId",+ "quantity","taxPercent",+ "supplierQuoteId","exchangeRate",- "supplierTaxAmount","createdBy","supplierQuoteLineId",- "companyId",- "supplierShippingCost"+ "supplierTaxAmount",+ "supplierShippingCost",+ "companyId"]},{"name": "supplierShipping","rows": 0,"columns": [- "shippingSupplierLocationId",- "shippingSupplierContactId",- "companyId",- "shippingTermId",- "incoterm",+ "supplierId",+ "updatedBy",+ "tags",+ "shippingMethodId","incotermLocation","shippingSupplierId",- "customFields","updatedAt",- "tags",- "updatedBy",- "supplierId",- "shippingMethodId"+ "customFields",+ "shippingTermId",+ "incoterm",+ "shippingSupplierContactId",+ "shippingSupplierLocationId",+ "companyId"]},{"name": "supplierTax","rows": 0,"columns": [+ "taxExempt",+ "taxExemptionCertificateNumber",+ "eori",+ "vatNumber","taxExemptionReason",- "updatedBy","supplierId","companyId",- "updatedAt",+ "updatedBy","taxExemptionCertificatePath",- "taxId",- "taxExempt",- "taxExemptionCertificateNumber",- "eori",- "vatNumber"+ "updatedAt",+ "taxId"]},{"name": "workflow","rows": 0,"columns": [- "companyId",- "updatedAt","nextRunAt","createdBy",- "canvasState",+ "updatedAt",+ "companyId","id",+ "canvasState","createdAt",- "name",- "description","publishedVersionId",- "updatedBy",- "ownerId"+ "description",+ "name",+ "ownerId",+ "updatedBy"]},{"name": "workflowVersion","rows": 0,"columns": [- "formatVersion",- "edges",- "workflowId",- "versionNumber",+ "createdBy",+ "updatedBy",+ "companyId","nodes",- "updatedAt",- "createdAt","id",- "updatedBy",- "createdBy",- "companyId"+ "createdAt",+ "updatedAt",+ "edges",+ "versionNumber",+ "workflowId",+ "formatVersion"]},{"name": "workflowRun","rows": 0,"columns": [- "workflowVersionId",+ "path",+ "rootRunId",+ "companyId",+ "triggerRecordId",+ "status",+ "ownerId",+ "id",+ "statusReason",+ "sourceEventId","workflowId","causedByRunId",- "completedAt",+ "workflowVersionId","durationMs",+ "completedAt","triggerTable","createdAt",- "error",- "isTest","eventId",- "startedAt",- "depth",+ "isTest",+ "error","compactedAt",- "path",- "companyId",- "rootRunId",- "triggerRecordId",- "status",- "id",- "ownerId",- "statusReason",- "sourceEventId"+ "depth",+ "startedAt"]},{"name": "workflowStepRun","rows": 0,"columns": [- "completedAt",- "runId",- "sequence",- "createdAt",- "detail",- "itemKey",- "branchTaken",- "nodeId",- "compactedAt",- "durationMs",- "error",- "companyId",+ "output",+ "id",+ "statusReason",+ "nodeType","startedAt",- "status",+ "companyId",+ "error","input",- "statusReason",- "id",- "output",- "nodeType"+ "status",+ "nodeId",+ "branchTaken",+ "durationMs",+ "compactedAt",+ "detail",+ "createdAt",+ "sequence",+ "runId",+ "completedAt",+ "itemKey"]},{"name": "workflowTriggerEvent","rows": 0,"columns": [- "id","origin",+ "id","companyId","eventId",+ "createdAt","workflowId",- "workflowVersionId",- "createdAt"+ "workflowVersionId"]}],diff --git a/packages/jobs/src/backups/renames.ts b/packages/jobs/src/backups/renames.tsindex fe0af38b63..c71e2cbbbb 100644--- a/packages/jobs/src/backups/renames.ts+++ b/packages/jobs/src/backups/renames.ts@@ -16,7 +16,14 @@ export const TABLE_RENAMES: Record<string, string | null> = {// rate table never had a writer and held zero rows everywhere; replaced by// the platform-global "exchangeRate" table, which is not tenant-scoped and// therefore never appears in a backup.- exchangeRateHistory: null+ exchangeRateHistory: null,+ // Renamed 2026-09 (sales rules): the storage-rule tables merged into the+ // shared enforcement-rule tables (20260817143512). Column lists carry over+ // 1:1; the new "family" column defaults to 'storage', which is what every+ // pre-merge row was.+ storageRule: "enforcementRule",+ storageRuleItemAssignment: "enforcementRuleItemAssignment",+ storageRuleWorkCenterAssignment: "enforcementRuleWorkCenterAssignment"};/**diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex 445ea3bc12..f17a3ba6d9 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -617,6 +617,92 @@ async function buildEventContent(};}+ case NotificationEvent.SalesRuleViolation: {+ // Compound documentId (same pattern as JobOperation*):+ // "<quote|salesOrder|salesInvoice>:<documentId>:<blocked|acknowledged>"+ const [docType, docId, outcome] = documentId.split(":");+ if (!docId) return null;+ // Service-role lookups below — scope by companyId so a stale or+ // mangled compound id can never surface another company's document.+ const companyId = opts?.companyId;+ if (!companyId) return null;++ const phrase =+ outcome === "blocked"+ ? "blocked by sales rules"+ : "flagged by sales rules and acknowledged";+ const outcomeLabel = outcome === "blocked" ? "Blocked" : "Acknowledged";++ if (docType === "salesInvoice") {+ // salesInvoice has two FKs to customer (customerId and+ // invoiceCustomerId), so the embed must name the one it means.+ const salesInvoice = await client+ .from("salesInvoice")+ .select("invoiceId, customer!salesInvoice_customerId_fkey(name)")+ .eq("id", docId)+ .eq("companyId", companyId)+ .single();++ if (salesInvoice.error) {+ console.error("Failed to get salesInvoice", salesInvoice.error);+ throw salesInvoice.error;+ }++ return {+ description: `A line on Sales Invoice ${salesInvoice.data?.invoiceId} was ${phrase}`,+ reference: salesInvoice.data?.invoiceId ?? undefined,+ details: buildDetails([+ { label: "Customer", value: salesInvoice.data?.customer?.name },+ { label: "Outcome", value: outcomeLabel }+ ])+ };+ }++ if (docType === "salesOrder") {+ const salesOrder = await client+ .from("salesOrder")+ .select("salesOrderId, customer(name)")+ .eq("id", docId)+ .eq("companyId", companyId)+ .single();++ if (salesOrder.error) {+ console.error("Failed to get salesOrder", salesOrder.error);+ throw salesOrder.error;+ }++ return {+ description: `A line on Sales Order ${salesOrder.data?.salesOrderId} was ${phrase}`,+ reference: salesOrder.data?.salesOrderId ?? undefined,+ details: buildDetails([+ { label: "Customer", value: salesOrder.data?.customer?.name },+ { label: "Outcome", value: outcomeLabel }+ ])+ };+ }++ const quote = await client+ .from("quote")+ .select("quoteId, customer(name)")+ .eq("id", docId)+ .eq("companyId", companyId)+ .single();++ if (quote.error) {+ console.error("Failed to get quote", quote.error);+ throw quote.error;+ }++ return {+ description: `A line on Quote ${quote.data?.quoteId} was ${phrase}`,+ reference: quote.data?.quoteId ?? undefined,+ details: buildDetails([+ { label: "Customer", value: quote.data?.customer?.name },+ { label: "Outcome", value: outcomeLabel }+ ])+ };+ }+case NotificationEvent.StockTransferAssignment: {const stockTransfer = await client.from("stockTransfer")@@ -1274,6 +1360,8 @@ export function getActorLabel(type: NotificationEvent): string | null {return "Rejected by";case NotificationEvent.MaintenanceDispatchCreated:return "Created by";+ case NotificationEvent.SalesRuleViolation:+ return "Submitted by";default:return null;}diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex 40f659b35f..ebdd0a44bc 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -76,6 +76,9 @@ const defaultDestinations: Partial<NotificationDestination.Email,NotificationDestination.Slack],+ // Deliberately email-only (no Slack): a compliance heads-up for the sales+ // group, not an actionable assignment.+ [NotificationEvent.SalesRuleViolation]: [NotificationDestination.Email],[NotificationEvent.JobAssignment]: [NotificationDestination.Email,NotificationDestination.Slackdiff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 6b4c61aeca..2961249737 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -881,6 +881,9 @@ msgstr "Ein Kundenauftrag wird gelöscht"msgid "A sales order line contains order details for a particular item"msgstr "Eine Kundenauftragsposition enthält Bestelldetails für einen bestimmten Artikel"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Ein Verkaufsauftrag, der direkt an einen anderen Kunden und Standort als der Kopfadresse des bestellenden Kunden versendet wird; die Versandzieladresse überschreibt die Kopfadresse."+msgid "A sales order's assignee changes"msgstr "Der Bearbeiter eines Kundenauftrags ändert sich"@@ -1640,6 +1643,9 @@ msgstr "Alle Dokumente"msgid "All item types"msgstr "Alle Artikeltypen"+msgid "All items"+msgstr "Alle Elemente"+msgid "All Items"msgstr "Alle Artikel"@@ -6076,6 +6082,9 @@ msgstr "Zeichnungsnummer"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Zeichnung ersetzt. Ballonplatzierungen wurden entfernt; Funktionszeilen bleiben unverändert."+msgid "Drop shipment"+msgstr "Direktversand"+msgid "Drop Shipment"msgstr "Direktlieferung"@@ -6552,6 +6561,9 @@ msgstr "Lieferantentyp bearbeiten"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Bearbeiten Sie die Regel, um das Flag \"Applies to all\" zu entfernen"+msgid "Edit the rule's item filters to remove it"+msgstr "Bearbeiten Sie die Elementfilter der Regel, um sie zu entfernen"+msgid "Edit Timecard"msgstr "Zeitkarte bearbeiten"@@ -6660,6 +6672,9 @@ msgstr "Aktivieren Sie vollständige periodengerechte Buchhaltung mit Buchungssmsgid "Enable in Settings"msgstr "In Einstellungen aktivieren"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Aktivieren Sie Benachrichtigungen, wenn eine Verletzung einer Verkaufsregel auf einem Angebot, Kundenauftrag oder einer Ausgangsrechnung blockiert oder bestätigt wird."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Aktivieren Sie Benachrichtigungen, wenn eine Anfrage als Angebotsbereit gekennzeichnet ist."@@ -6727,6 +6742,12 @@ msgstr "Endet"msgid "Enforce — edits are blocked"msgstr "Erzwingen — Bearbeitungen sind gesperrt"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Überprüfungen auf Angebots-, Verkaufsauftrags- und Verkaufsrechnungszeilen für diesen Artikel erzwingen."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Erzwingen Sie Kunden- und Artikelprüfungen, wenn Artikel zu Angeboten, Verkaufsaufträgen und Verkaufsrechnungen hinzugefügt werden."+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Erzwingen Sie artikelspezifische Validierung und Richtlinien über Wareneingänge, Lieferungen, Umlagerungen und Korrekturen."@@ -12502,6 +12523,9 @@ msgstr "Wählen Sie einen Wert aus einem früheren Schritt"msgid "Pick a variable…"msgstr "Wählen Sie eine Variable…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Wählen Sie eine vorhandene Regel aus der Bibliothek aus oder erstellen Sie eine neue Regel, um Kontrollen für dieses Element zu erzwingen."+msgid "Pick List"msgstr "Pickliste"@@ -14718,6 +14742,15 @@ msgstr "Rücklieferung"msgid "Sales Revenue"msgstr "Umsatzerlöse"+msgid "Sales Rule Violations"+msgstr "Verstöße gegen Verkaufsregeln"++msgid "Sales rules"+msgstr "Verkaufsregeln"++msgid "Sales Rules"+msgstr "Verkaufsregeln"+msgid "Sales Tax Payable"msgstr "Umsatzsteuer zu zahlen"@@ -16262,7 +16295,7 @@ msgid "Stripe Due Date"msgstr "Stripe-Fälligkeitsdatum"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."-msgstr "Stripe sendet die Rechnung per E-Mail an den Kunden, daher ist eine Adresse erforderlich. Dies wird auch im Kontakt in Carbon gespeichert."+msgstr "Stripe sendet die Rechnung per E-Mail an den Kunden, daher ist eine Adresse erforderlich. Diese wird auch im Kontakt in Carbon gespeichert."msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe hat noch keinen Kunden für diesen Carbon-Kunden. Die Buchung wird einen auf Ihrem verbundenen Konto erstellen."@@ -18706,6 +18739,9 @@ msgstr "Upgraden Sie, um {0} Regeln freizuschalten"msgid "Upgrade to unlock audit history"msgstr "Upgrade freischalten, um Audit-Verlauf zu entsperren"+msgid "Upgrade to unlock sales rules"+msgstr "Upgraden Sie, um Verkaufsregeln freizuschalten"+msgid "Upload"msgstr "Hochladen"@@ -19655,6 +19691,9 @@ msgstr "Wer sollte Benachrichtigungen erhalten, wenn eine Anfrage als angebotsbemsgid "Who should receive notifications when a sales job is completed?"msgstr "Wer sollte Benachrichtigungen erhalten, wenn ein Vertriebsfertigungsauftrag fertiggestellt wird?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Wer sollte Benachrichtigungen erhalten, wenn eine Verletzung einer Verkaufsregel blockiert oder bestätigt wird?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Wer sollte benachrichtigt werden, wenn ein Lieferantengebot eingereicht wird?"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 391ba39696..bbf2a082ee 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -881,6 +881,9 @@ msgstr "A sales order is deleted"msgid "A sales order line contains order details for a particular item"msgstr "A sales order line contains order details for a particular item"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgid "A sales order's assignee changes"msgstr "A sales order's assignee changes"@@ -1640,6 +1643,9 @@ msgstr "All Documents"msgid "All item types"msgstr "All item types"+msgid "All items"+msgstr "All items"+msgid "All Items"msgstr "All Items"@@ -6076,6 +6082,9 @@ msgstr "Drawing Number"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Drawing replaced. Balloon placements were removed; feature rows are unchanged."+msgid "Drop shipment"+msgstr "Drop shipment"+msgid "Drop Shipment"msgstr "Drop Shipment"@@ -6552,6 +6561,9 @@ 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 the rule's item filters to remove it"+msgstr "Edit the rule's item filters to remove it"+msgid "Edit Timecard"msgstr "Edit Timecard"@@ -6660,6 +6672,9 @@ msgstr "Enable full accrual accounting with journal entries, financial reports,msgid "Enable in Settings"msgstr "Enable in Settings"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Enable notifications when an RFQ is marked as ready for quote."@@ -6727,6 +6742,12 @@ msgstr "Ends"msgid "Enforce — edits are blocked"msgstr "Enforce — edits are blocked"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Enforce checks on quote, sales order, and sales invoice lines for this item."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+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."@@ -12502,6 +12523,9 @@ msgstr "Pick a value from an earlier step"msgid "Pick a variable…"msgstr "Pick a variable…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgid "Pick List"msgstr "Pick List"@@ -14718,6 +14742,15 @@ msgstr "Sales Return"msgid "Sales Revenue"msgstr "Sales Revenue"+msgid "Sales Rule Violations"+msgstr "Sales Rule Violations"++msgid "Sales rules"+msgstr "Sales rules"++msgid "Sales Rules"+msgstr "Sales Rules"+msgid "Sales Tax Payable"msgstr "Sales Tax Payable"@@ -18706,6 +18739,9 @@ msgstr "Upgrade to unlock {0} rules"msgid "Upgrade to unlock audit history"msgstr "Upgrade to unlock audit history"+msgid "Upgrade to unlock sales rules"+msgstr "Upgrade to unlock sales rules"+msgid "Upload"msgstr "Upload"@@ -19655,6 +19691,9 @@ msgstr "Who should receive notifications when a RFQ is marked ready for quote?"msgid "Who should receive notifications when a sales job is completed?"msgstr "Who should receive notifications when a sales job is completed?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Who should receive notifications when a supplier quote is submitted?"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex b6278d9dfe..d8fa5f91b1 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -881,6 +881,9 @@ msgstr "Se elimina un pedido de venta"msgid "A sales order line contains order details for a particular item"msgstr "Una línea de orden de venta contiene detalles de pedido para un artículo en particular"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Un pedido de venta enviado directamente a un cliente diferente y a una ubicación diferente de la dirección del encabezado del cliente que realiza el pedido; el destino del envío anula el del encabezado."+msgid "A sales order's assignee changes"msgstr "El asignado de un pedido de venta cambia"@@ -1640,6 +1643,9 @@ msgstr "Todos los documentos"msgid "All item types"msgstr "Todos los tipos de artículos"+msgid "All items"+msgstr "Todos los elementos"+msgid "All Items"msgstr "Todos los artículos"@@ -6076,6 +6082,9 @@ msgstr "Número de plano"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Dibujo reemplazado. Las ubicaciones de globos se eliminaron; las filas de características no cambiaron."+msgid "Drop shipment"+msgstr "Envío directo"+msgid "Drop Shipment"msgstr "Envío Directo"@@ -6552,6 +6561,9 @@ msgstr "Editar Tipo de Proveedor"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Editar la regla para quitar la indicación \"Se aplica a todos\""+msgid "Edit the rule's item filters to remove it"+msgstr "Editar los filtros de elementos de la regla para eliminarlo"+msgid "Edit Timecard"msgstr "Editar Tarjeta de Tiempo"@@ -6660,6 +6672,9 @@ msgstr "Habilitar contabilidad de acumulación completa con asientos de diario,msgid "Enable in Settings"msgstr "Habilitar en Configuración"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Habilite notificaciones cuando una infracción de regla de ventas sea bloqueada o confirmada en una cotización, un pedido de venta o una factura de venta."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Habilitar notificaciones cuando una RFQ está marcada como lista para cotizar."@@ -6727,6 +6742,12 @@ msgstr "Termina"msgid "Enforce — edits are blocked"msgstr "Forzar — las ediciones se bloquean"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Aplicar verificaciones en líneas de cotización, pedido de venta y factura de venta para este artículo."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Aplicar verificaciones de cliente y artículo cuando se agregan artículos a cotizaciones, órdenes de venta y facturas de venta."+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."@@ -12502,6 +12523,9 @@ msgstr "Elige un valor de un paso anterior"msgid "Pick a variable…"msgstr "Elige una variable…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Selecciona una regla existente de la biblioteca o crea una nueva para comenzar a aplicar verificaciones en este elemento."+msgid "Pick List"msgstr "Lista de Picking"@@ -14718,6 +14742,15 @@ msgstr "Devolución de venta"msgid "Sales Revenue"msgstr "Ingresos por ventas"+msgid "Sales Rule Violations"+msgstr "Violaciones de reglas de ventas"++msgid "Sales rules"+msgstr "Reglas de ventas"++msgid "Sales Rules"+msgstr "Reglas de ventas"+msgid "Sales Tax Payable"msgstr "Impuesto de venta por pagar"@@ -16262,7 +16295,7 @@ msgid "Stripe Due Date"msgstr "Fecha de vencimiento de Stripe"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."-msgstr "Stripe envía la factura por correo electrónico al cliente, por lo que se requiere una dirección. Esto también se guardará en el contacto en Carbon."+msgstr "Stripe envía la factura por correo electrónico al cliente, por lo que se requiere una dirección. Esto también se guardará en el contacto de Carbon."msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe aún no tiene un cliente para este cliente de Carbon. La contabilización creará uno en su cuenta conectada."@@ -18706,6 +18739,9 @@ msgstr "Actualizar para desbloquear reglas de {0}"msgid "Upgrade to unlock audit history"msgstr "Actualizar para desbloquear el historial de auditoría"+msgid "Upgrade to unlock sales rules"+msgstr "Actualizar para desbloquear reglas de ventas"+msgid "Upload"msgstr "Subir"@@ -19655,6 +19691,9 @@ msgstr "¿Quién debe recibir notificaciones cuando una RFQ está marcada como lmsgid "Who should receive notifications when a sales job is completed?"msgstr "¿Quién debe recibir notificaciones cuando se completa un trabajo de ventas?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "¿Quién debe recibir notificaciones cuando una violación de regla de ventas se bloquea o se reconoce?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "¿Quién debe recibir notificaciones cuando se envía una cotización del proveedor?"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex ad97cf73d7..d0557dca47 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -881,6 +881,9 @@ msgstr "Une commande client est supprimée"msgid "A sales order line contains order details for a particular item"msgstr "Une ligne de commande client contient les détails de la commande pour un article particulier"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Une commande client expédiée directement à un client et un lieu différents de l'adresse d'en-tête du client commandant; la destination de l'expédition remplace celle de l'en-tête."+msgid "A sales order's assignee changes"msgstr "L'assigné d'une commande client change"@@ -1640,6 +1643,9 @@ msgstr "Tous les documents"msgid "All item types"msgstr "Tous les types d'articles"+msgid "All items"+msgstr "Tous les articles"+msgid "All Items"msgstr "Tous les articles"@@ -6076,6 +6082,9 @@ msgstr "Numéro de plan"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Le dessin a été remplacé. Les placements de bulles ont été supprimés ; les lignes de fonctionnalités restent inchangées."+msgid "Drop shipment"+msgstr "Expédition directe"+msgid "Drop Shipment"msgstr "Expédition directe"@@ -6552,6 +6561,9 @@ msgstr "Modifier le type de fournisseur"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Modifier la règle pour supprimer l'indicateur « S'applique à tous »"+msgid "Edit the rule's item filters to remove it"+msgstr "Modifiez les filtres d'articles de la règle pour le supprimer"+msgid "Edit Timecard"msgstr "Modifier la feuille de temps"@@ -6660,6 +6672,9 @@ msgstr "Activez la comptabilité d'exercice complète avec les écritures de joumsgid "Enable in Settings"msgstr "Activer dans les paramètres"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Activez les notifications lorsqu'une violation de règle de vente est bloquée ou confirmée sur un devis, une commande client ou une facture de vente."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Activer les notifications lorsqu'une demande de devis est marquée comme prête pour la cotation."@@ -6727,6 +6742,12 @@ msgstr "Se termine"msgid "Enforce — edits are blocked"msgstr "Appliquer — les modifications sont bloquées"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Appliquer les vérifications sur les lignes de devis, de commande client et de facture de vente pour cet article."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Appliquer les contrôles de client et d'article lors de l'ajout d'articles aux devis, commandes de vente et factures de vente."+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."@@ -12502,6 +12523,9 @@ msgstr "Choisir une valeur d'une étape antérieure"msgid "Pick a variable…"msgstr "Choisir une variable…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Choisissez une règle existante de la bibliothèque ou créez-en une nouvelle pour commencer à appliquer des vérifications sur cet article."+msgid "Pick List"msgstr "Liste de prélèvement"@@ -14718,6 +14742,15 @@ msgstr "Retour de vente"msgid "Sales Revenue"msgstr "Revenus des ventes"+msgid "Sales Rule Violations"+msgstr "Violations de règles de vente"++msgid "Sales rules"+msgstr "Règles de vente"++msgid "Sales Rules"+msgstr "Règles de vente"+msgid "Sales Tax Payable"msgstr "Taxes de vente à payer"@@ -16262,7 +16295,7 @@ msgid "Stripe Due Date"msgstr "Date d'échéance Stripe"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."-msgstr "Stripe envoie la facture par e-mail au client, une adresse est donc requise. Ceci sera également enregistré dans le contact dans Carbon."+msgstr "Stripe envoie la facture par email au client, donc une adresse est requise. Cela sera également enregistré dans le contact dans Carbon."msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe n'a pas encore de client pour ce client Carbon. La comptabilisation en créera un sur votre compte connecté."@@ -17893,7 +17926,7 @@ msgid "This version cannot be opened"msgstr "Cette version ne peut pas être ouverte"msgid "This version is published"-msgstr "Cette version est publiée."+msgstr "Cette version est publiée"msgid "This version is published. Create a new version to edit."msgstr "Cette version est publiée. Créez une nouvelle version à modifier."@@ -18706,6 +18739,9 @@ msgstr "Passer à la version supérieure pour déverrouiller les règles {0}"msgid "Upgrade to unlock audit history"msgstr "Passez à la version supérieure pour déverrouiller l'historique d'audit"+msgid "Upgrade to unlock sales rules"+msgstr "Mettez à niveau pour déverrouiller les règles de vente"+msgid "Upload"msgstr "Téléverser"@@ -19655,6 +19691,9 @@ msgstr "Qui devrait recevoir des notifications quand une RFQ est marquée commemsgid "Who should receive notifications when a sales job is completed?"msgstr "Qui devrait recevoir des notifications lorsqu'une tâche de vente est terminée ?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Qui devrait recevoir des notifications lorsqu'une violation de règle de vente est bloquée ou reconnue?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Qui devrait recevoir des notifications lorsqu'un devis fournisseur est soumis ?"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 65748594f3..22db1ad458 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -881,6 +881,9 @@ msgstr "एक विक्रय आदेश हटाया गया है"msgid "A sales order line contains order details for a particular item"msgstr "एक विक्रय आदेश पंक्ति एक विशेष आइटम के लिए आदेश विवरण शामिल करती है"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "एक बिक्रय आदेश सीधे एक अलग ग्राहक और स्थान पर भेजा गया है, जो आदेश देने वाले ग्राहक के हेडर पते से अलग है; शिपमेंट का गंतव्य हेडर को ओवरराइड करता है।"+msgid "A sales order's assignee changes"msgstr "विक्रय आदेश के असाइनी में परिवर्तन"@@ -1640,6 +1643,9 @@ msgstr "सभी दस्तावेज़"msgid "All item types"msgstr "सभी आइटम प्रकार"+msgid "All items"+msgstr "सभी आइटम"+msgid "All Items"msgstr "सभी आइटम"@@ -6076,6 +6082,9 @@ msgstr "ड्राइंग नंबर"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "ड्राइंग बदल दी गई। बैलून प्लेसमेंट हटा दिए गए; फीचर पंक्तियां अपरिवर्तित हैं।"+msgid "Drop shipment"+msgstr "ड्रॉप शिपमेंट"+msgid "Drop Shipment"msgstr "ड्रॉप शिपमेंट"@@ -6552,6 +6561,9 @@ msgstr "आपूर्तिकर्ता प्रकार संपादmsgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "\"सभी पर लागू\" फ़्लैग को निकालने के लिए नियम संपादित करें"+msgid "Edit the rule's item filters to remove it"+msgstr "इसे निकालने के लिए नियम के आइटम फिल्टर को संपादित करें"+msgid "Edit Timecard"msgstr "टाइमकार्ड संपादित करें"@@ -6660,6 +6672,9 @@ msgstr "पूर्ण प्रोद्भवन लेखांकन कोmsgid "Enable in Settings"msgstr "सेटिंग्स में सक्षम करें"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "जब किसी उद्धरण, विक्रय आदेश या विक्रय चालान पर विक्रय नियम उल्लंघन अवरुद्ध या स्वीकृत किया जाता है, तो सूचनाएँ सक्षम करें।"+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "जब RFQ को कोटेशन के लिए तैयार के रूप में चिह्नित किया जाए तो सूचनाएँ सक्षम करें।"@@ -6727,6 +6742,12 @@ msgstr "समाप्त होता है"msgid "Enforce — edits are blocked"msgstr "लागू करें — संपादन अवरुद्ध हैं"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "इस आइटम के लिए उद्धरण, बिक्रय आदेश और बिक्रय चालान पंक्तियों पर जांच लागू करें।"++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "जब आइटम उद्धरण, बिक्रय आदेश और बिक्रय चालान में जोड़े जाते हैं, तब ग्राहक और आइटम जांच लागू करें।"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "रसीदों, शिपमेंट, ट्रांसफर और समायोजन में प्रति-आइटम सत्यापन और दिशानिर्देश लागू करें।"@@ -12502,6 +12523,9 @@ msgstr "पहले के एक चरण से मान चुनें"msgid "Pick a variable…"msgstr "एक वेरिएबल चुनें…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "इस आइटम पर जांच लागू करना शुरू करने के लिए लाइब्रेरी से एक मौजूदा नियम चुनें या एक नया नियम बनाएं।"+msgid "Pick List"msgstr "पिक लिस्ट"@@ -14718,6 +14742,15 @@ msgstr "विक्रय रिटर्न"msgid "Sales Revenue"msgstr "बिक्रय राजस्व"+msgid "Sales Rule Violations"+msgstr "बिक्री नियम उल्लंघन"++msgid "Sales rules"+msgstr "बिक्री नियम"++msgid "Sales Rules"+msgstr "बिक्री नियम"+msgid "Sales Tax Payable"msgstr "देय बिक्रय कर"@@ -17720,6 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "यह आमंत्रण {0} में शामिल होने के लिए समाप्त हो गया है। आप अपने ईमेल पर भेजने के लिए नया आमंत्रण का अनुरोध कर सकते हैं।"msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "इस चालान की कोई उपयोग योग्य देय तारीख नहीं है — Stripe के लिए एक चुनें।"msgstr "इस चालान का कोई उपयोगी नियत तिथि नहीं है — Stripe के लिए एक चुनें।"msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."@@ -18706,6 +18740,9 @@ msgstr "{0} नियमों को अनलॉक करने के लिmsgid "Upgrade to unlock audit history"msgstr "ऑडिट इतिहास को अनलॉक करने के लिए अपग्रेड करें"+msgid "Upgrade to unlock sales rules"+msgstr "बिक्री नियमों को अनलॉक करने के लिए अपग्रेड करें"+msgid "Upload"msgstr "अपलोड करें"@@ -19655,6 +19692,9 @@ msgstr "जब कोई RFQ कोटेशन के लिए तैयारmsgid "Who should receive notifications when a sales job is completed?"msgstr "बिक्रय कार्य पूर्ण होने पर कौन सूचनाएं प्राप्त करनी चाहिए?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "जब किसी बिक्री नियम उल्लंघन को अवरुद्ध या स्वीकार किया जाता है तो किसे सूचनाएं प्राप्त करनी चाहिए?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "जब कोई आपूर्तिकर्ता कोटेशन प्रस्तुत किया जाता है तो सूचना कौन प्राप्त करे?"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex a43f8bd9f3..259f61013f 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -881,6 +881,9 @@ msgstr "Un ordine di vendita è eliminato"msgid "A sales order line contains order details for a particular item"msgstr "Una riga dell'ordine di vendita contiene i dettagli dell'ordine per un articolo particolare"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Un ordine di vendita spedito direttamente a un cliente e una ubicazione diversi da quelli della testata del cliente ordinante; la destinazione della spedizione sostituisce la testata."+msgid "A sales order's assignee changes"msgstr "L'assegnatario di un ordine di vendita cambia"@@ -1640,6 +1643,9 @@ msgstr "Tutti i documenti"msgid "All item types"msgstr "Tutti i tipi di articoli"+msgid "All items"+msgstr "Tutti gli articoli"+msgid "All Items"msgstr "Tutti gli articoli"@@ -6076,6 +6082,9 @@ msgstr "Numero di Disegno"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Disegno sostituito. I posizionamenti dei palloncini sono stati rimossi; le righe delle funzioni rimangono invariate."+msgid "Drop shipment"+msgstr "Spedizione diretta"+msgid "Drop Shipment"msgstr "Spedizione Diretta"@@ -6552,6 +6561,9 @@ msgstr "Modifica Tipo Fornitore"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Modifica la regola per rimuovere il flag \"Applies to all\""+msgid "Edit the rule's item filters to remove it"+msgstr "Modifica i filtri degli articoli della regola per rimuoverla"+msgid "Edit Timecard"msgstr "Modifica Scheda Orario"@@ -6660,6 +6672,9 @@ msgstr "Abilita la contabilità per competenza completa con registrazioni contabmsgid "Enable in Settings"msgstr "Abilita nelle Impostazioni"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Abilita le notifiche quando una violazione di una regola di vendita viene bloccata o confermata su un preventivo, un ordine di vendita o una fattura di vendita."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Abilita Notifiche quando una RdO è contrassegnata come Pronto per offerta."@@ -6727,6 +6742,12 @@ msgstr "Termina"msgid "Enforce — edits are blocked"msgstr "Applica — le modifiche sono bloccate"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Applica verifiche sulle righe preventivo, ordine di vendita e fattura di vendita per questo articolo."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Applica controlli cliente e articolo quando gli articoli vengono aggiunti a preventivi, ordini di vendita e fatture di vendita."+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."@@ -12502,6 +12523,9 @@ msgstr "Scegli un valore da un passaggio precedente"msgid "Pick a variable…"msgstr "Scegli una variabile…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Seleziona una regola esistente dalla libreria o crea una nuova per iniziare a applicare i controlli su questo articolo."+msgid "Pick List"msgstr "Elenco di prelievo"@@ -14718,6 +14742,15 @@ msgstr "Reso di vendita"msgid "Sales Revenue"msgstr "Ricavi di vendita"+msgid "Sales Rule Violations"+msgstr "Violazioni delle Regole di Vendita"++msgid "Sales rules"+msgstr "Regole di vendita"++msgid "Sales Rules"+msgstr "Regole di Vendita"+msgid "Sales Tax Payable"msgstr "Imposta di vendita dovuta"@@ -18706,6 +18739,9 @@ msgstr "Esegui l'upgrade per sbloccare le regole {0}"msgid "Upgrade to unlock audit history"msgstr "Aggiorna per sbloccare la cronologia di audit"+msgid "Upgrade to unlock sales rules"+msgstr "Aggiorna per sbloccare le regole di vendita"+msgid "Upload"msgstr "Carica"@@ -19655,6 +19691,9 @@ msgstr "Chi dovrebbe ricevere notifiche quando un RdO è contrassegnato come promsgid "Who should receive notifications when a sales job is completed?"msgstr "Chi dovrebbe ricevere notifiche quando un lavoro di vendita è completato?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Chi dovrebbe ricevere notifiche quando una violazione della regola di vendita viene bloccata o riconosciuta?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Chi dovrebbe ricevere notifiche quando un'offerta del fornitore viene presentata?"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex fa6eb5e0f2..3623881c39 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -881,6 +881,9 @@ msgstr "受注が削除される"msgid "A sales order line contains order details for a particular item"msgstr "受注明細には特定の品目の注文詳細が含まれています"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "注文顧客のヘッダーアドレスとは異なる顧客および場所に直接出荷される販売注文。出荷先がヘッダーのアドレスを上書きします。"+msgid "A sales order's assignee changes"msgstr "受注の担当者が変更される"@@ -1640,6 +1643,9 @@ msgstr "すべてのドキュメント"msgid "All item types"msgstr "すべての品目タイプ"+msgid "All items"+msgstr "すべてのアイテム"+msgid "All Items"msgstr "すべてのアイテム"@@ -6076,6 +6082,9 @@ msgstr "図面番号"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "図面が置き換わりました。バルーン配置は削除されました。機能行は変更されていません。"+msgid "Drop shipment"+msgstr "ドロップシップメント"+msgid "Drop Shipment"msgstr "ドロップシップメント"@@ -6552,6 +6561,9 @@ msgstr "仕入先タイプを編集"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "ルールを編集して、\"すべてに適用\" フラグを削除します"+msgid "Edit the rule's item filters to remove it"+msgstr "ルールのアイテムフィルターを編集して削除します"+msgid "Edit Timecard"msgstr "タイムカードを編集"@@ -6660,6 +6672,9 @@ msgstr "完全な発生主義会計を有効にし、仕訳帳エントリ、財msgid "Enable in Settings"msgstr "設定で有効にする"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "見積、受注、または売上請求書で販売ルール違反がブロックまたは承認されたときに通知を有効にします。"+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "見積依頼が見積準備完了の状態になったときに通知を有効にします。"@@ -6727,6 +6742,12 @@ msgstr "終了"msgid "Enforce — edits are blocked"msgstr "強制 - 編集はブロックされます"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "この品目の見積、販売注文、および販売請求書の行に対するチェックを適用します。"++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "見積書、受注、売上請求書に品目を追加する際に、顧客と品目のチェックを実施します。"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "領収書、出荷、転送、および調整全体にわたって、品目ごとの検証とガイドラインを実施します。"@@ -12502,6 +12523,9 @@ msgstr "前のステップの値を選択"msgid "Pick a variable…"msgstr "変数を選択..."+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "ライブラリから既存のルールを選択するか、新しいルールを作成してこのアイテムのチェックを実行し始めます。"+msgid "Pick List"msgstr "ピッキングリスト"@@ -14718,6 +14742,15 @@ msgstr "販売返品"msgid "Sales Revenue"msgstr "販売売上高"+msgid "Sales Rule Violations"+msgstr "販売ルール違反"++msgid "Sales rules"+msgstr "販売ルール"++msgid "Sales Rules"+msgstr "販売ルール"+msgid "Sales Tax Payable"msgstr "支払い売上税"@@ -16256,7 +16289,7 @@ msgid "Stripe"msgstr "Stripe"msgid "Stripe already has a customer with this email"-msgstr "Stripeには既にこのメールアドレスの得意先があります"+msgstr "Stripe にはこのメールアドレスの顧客が既に存在します"msgid "Stripe Due Date"msgstr "Stripe支払期日"@@ -17720,7 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "この{0}への参加への招待は期限切れです。新しい招待をメールで送信されるようにリクエストできます。"msgid "This invoice has no usable due date — choose one for Stripe."-msgstr "この請求書には使用可能な支払期日がありません— Stripeのものを選択してください。"+msgstr "この請求書は使用可能な支払期日がありません。Stripe 用に 1 つ選択してください。"msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "この請求書は、すでにこのCarbon得意先にリンクされているStripe顧客に請求されます。詳細を変更するには、Stripeダッシュボードで編集してください。"@@ -17893,7 +17926,7 @@ msgid "This version cannot be opened"msgstr "このバージョンは開くことができません"msgid "This version is published"-msgstr "このバージョンは公開済です"+msgstr "このバージョンは公開されています"msgid "This version is published. Create a new version to edit."msgstr "このバージョンは公開済です。編集するには新しいバージョンを作成してください。"@@ -18546,7 +18579,7 @@ msgid "Unposted Documents"msgstr "未転記のドキュメント"msgid "Unpublish"-msgstr "非公開にする"+msgstr "公開を取り消す"msgid "Unpublish {name}?"msgstr "{name}の公開を取り消しますか?"@@ -18706,6 +18739,9 @@ msgstr "{0}ルールのロックを解除するにはアップグレード"msgid "Upgrade to unlock audit history"msgstr "監査履歴のロックを解除するにはアップグレードしてください"+msgid "Upgrade to unlock sales rules"+msgstr "販売ルールのロックを解除するにはアップグレードしてください"+msgid "Upload"msgstr "アップロード"@@ -19655,6 +19691,9 @@ msgstr "見積依頼が見積準備完了としてマークされたときに通msgid "Who should receive notifications when a sales job is completed?"msgstr "販売製造指図が完了したときに通知を受け取る必要があるのは誰ですか?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "販売ルール違反がブロックまたは確認されたときに、誰が通知を受け取るべきですか?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "仕入先見積が提出されたときに通知を受け取る必要があるのは誰ですか?"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 9709867e6f..97a8801dda 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -881,6 +881,9 @@ msgstr "수주가 삭제됨"msgid "A sales order line contains order details for a particular item"msgstr "수주 라인은 특정 품목에 대한 주문 세부 정보를 포함합니다"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "주문 고객의 헤더 주소와 다른 고객 및 위치로 직접 배송되는 판매 주문입니다. 배송 목적지가 헤더 주소를 무시합니다."+msgid "A sales order's assignee changes"msgstr "수주의 담당자가 변경됨"@@ -1640,6 +1643,9 @@ msgstr "모든 문서"msgid "All item types"msgstr "모든 품목 유형"+msgid "All items"+msgstr "모든 항목"+msgid "All Items"msgstr "모든 품목"@@ -6076,6 +6082,9 @@ msgstr "도면 번호"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "도면이 교체되었습니다. 벌룬 배치는 제거되었으며, 피처 행은 변경되지 않습니다."+msgid "Drop shipment"+msgstr "직배송"+msgid "Drop Shipment"msgstr "직송 출하"@@ -6552,6 +6561,9 @@ msgstr "공급업체 유형 편집"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "규칙을 편집하여 「모든 항목에 적용」 플래그를 제거하세요"+msgid "Edit the rule's item filters to remove it"+msgstr "규칙의 항목 필터를 편집하여 제거합니다"+msgid "Edit Timecard"msgstr "타임카드 편집"@@ -6660,6 +6672,9 @@ msgstr "전표, 재무 보고서, 총계정원장 전기를 포함한 완전 발msgid "Enable in Settings"msgstr "설정에서 활성화"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "견적, 수주 또는 매출 송장에서 판매 규칙 위반이 차단되거나 승인될 때 알림을 활성화합니다."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "RFQ가 견적 준비 완료로 표시될 때 알림을 활성화하세요."@@ -6727,6 +6742,12 @@ msgstr "끝남"msgid "Enforce — edits are blocked"msgstr "강제 — 편집이 차단되었습니다."+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "이 항목에 대해 견적, 판매 주문, 판매 송장 라인에 점검을 강제합니다."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "견적, 판매 주문 및 판매 송장에 항목이 추가될 때 고객 및 항목 검사를 적용합니다."+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "입고, 출하, 이동, 조정 전반에 걸쳐 품목별 검증 및 지침을 적용합니다."@@ -12502,6 +12523,9 @@ msgstr "이전 단계에서 값 선택"msgid "Pick a variable…"msgstr "변수 선택…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "라이브러리에서 기존 규칙을 선택하거나 새 규칙을 만들어 이 항목에 대한 검사를 시작합니다."+msgid "Pick List"msgstr "피킹 목록"@@ -14718,6 +14742,15 @@ msgstr "판매 반품"msgid "Sales Revenue"msgstr "매출"+msgid "Sales Rule Violations"+msgstr "판매 규칙 위반"++msgid "Sales rules"+msgstr "판매 규칙"++msgid "Sales Rules"+msgstr "판매 규칙"+msgid "Sales Tax Payable"msgstr "매출 세금 납부"@@ -16262,7 +16295,7 @@ msgid "Stripe Due Date"msgstr "스트라이프 마감일"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."-msgstr "Stripe가 송장을 고객에게 이메일로 보내므로 주소가 필요합니다. 이것도 Carbon의 담당자 정보에 저장됩니다."+msgstr "Stripe가 고객에게 송장을 이메일로 보내므로 주소가 필요합니다. 이것도 Carbon의 연락처에 저장됩니다."msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "이 Carbon 고객에 대한 Stripe 고객이 아직 없습니다. 전기하면 연결된 계정에 생성됩니다."@@ -17720,6 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "이 {0}에 가입하라는 초대가 만료되었습니다. 새 초대를 이메일로 보내달라고 요청할 수 있습니다."msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "이 송장에는 사용 가능한 만기일이 없습니다 — Stripe용으로 선택하세요."msgstr "이 송장에는 사용 가능한 마감일이 없습니다 — Stripe를 위해 하나를 선택하세요."msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."@@ -18546,7 +18580,7 @@ msgid "Unposted Documents"msgstr "미전기 문서"msgid "Unpublish"-msgstr "게시 해제"+msgstr "게시 취소"msgid "Unpublish {name}?"msgstr "게시 취소 {name}?"@@ -18706,6 +18740,9 @@ msgstr "{0}개의 규칙을 사용하려면 업그레이드하세요"msgid "Upgrade to unlock audit history"msgstr "업그레이드하여 감사 이력 잠금 해제"+msgid "Upgrade to unlock sales rules"+msgstr "판매 규칙을 잠금 해제하려면 업그레이드하십시오"+msgid "Upload"msgstr "업로드"@@ -19655,6 +19692,9 @@ msgstr "RFQ가 견적 준비 완료로 표시될 때 알림을 누가 받아야msgid "Who should receive notifications when a sales job is completed?"msgstr "판매 작업 지시가 완료될 때 알림을 받아야 하는 사람은 누구입니까?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "판매 규칙 위반이 차단되거나 승인될 때 누가 알림을 받아야 합니까?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "공급업체 견적이 제출될 때 알림을 누가 받아야 합니까?"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 05290db47d..8b01984acf 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -881,6 +881,9 @@ msgstr "Zamówienie sprzedaży jest usuwane"msgid "A sales order line contains order details for a particular item"msgstr "Pozycja zamówienia sprzedaży zawiera szczegóły zamówienia dla konkretnego artykułu"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Zamówienie sprzedaży wysłane bezpośrednio do innego klienta i lokalizacji niż adres główny klienta zamawiającego; miejsce docelowe przesyłki zastępuje główne."+msgid "A sales order's assignee changes"msgstr "Zmiana osoby przypisanej do zamówienia sprzedaży"@@ -1640,6 +1643,9 @@ msgstr "Wszystkie dokumenty"msgid "All item types"msgstr "Wszystkie typy artykułów"+msgid "All items"+msgstr "Wszystkie elementy"+msgid "All Items"msgstr "Wszystkie elementy"@@ -6076,6 +6082,9 @@ msgstr "Numer rysunku"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Rysunek zastąpiony. Umieszczenia balonów zostały usunięte; wiersze funkcji pozostają niezmienione."+msgid "Drop shipment"+msgstr "Przesyłka bezpośrednia"+msgid "Drop Shipment"msgstr "Wysyłka bezpośrednia"@@ -6552,6 +6561,9 @@ msgstr "Edytuj typ dostawcy"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Edytuj regułę, aby usunąć flagę „Dotyczy wszystkich\""+msgid "Edit the rule's item filters to remove it"+msgstr "Edytuj filtry elementów reguły, aby go usunąć"+msgid "Edit Timecard"msgstr "Edytuj Kartę Czasu Pracy"@@ -6660,6 +6672,9 @@ msgstr "Włącz pełną księgowość memoriałową z wpisami dowodów księgowymsgid "Enable in Settings"msgstr "Włącz w Ustawieniach"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Włącz powiadomienia, gdy naruszenie reguły sprzedaży zostanie zablokowane lub potwierdzone na ofercie, zamówieniu sprzedaży lub fakturze sprzedaży."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Włącz powiadomienia, gdy RFQ jest oznaczony jako gotowy do oferty."@@ -6727,6 +6742,12 @@ msgstr "Kończy się"msgid "Enforce — edits are blocked"msgstr "Wymuś — edycje są zablokowane"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Wymusić kontrole na wierszach oferty, zamówienia sprzedaży i faktury sprzedaży dla tego artykułu."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Wymuszaj sprawdzenia klientów i artykułów, gdy artykuły są dodawane do ofert, zamówień sprzedaży i faktur sprzedaży."+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."@@ -12502,6 +12523,9 @@ msgstr "Wybierz wartość z wcześniejszego kroku"msgid "Pick a variable…"msgstr "Wybierz zmienną…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Wybierz istniejącą regułę z biblioteki lub utwórz nową, aby rozpocząć wymuszanie kontroli na tym elemencie."+msgid "Pick List"msgstr "Lista pobrania"@@ -14718,6 +14742,15 @@ msgstr "Zwrot ze sprzedaży"msgid "Sales Revenue"msgstr "Przychód ze sprzedaży"+msgid "Sales Rule Violations"+msgstr "Naruszenia reguł sprzedaży"++msgid "Sales rules"+msgstr "Reguły sprzedaży"++msgid "Sales Rules"+msgstr "Reguły sprzedaży"+msgid "Sales Tax Payable"msgstr "Podatek od sprzedaży do zapłaty"@@ -16259,6 +16292,7 @@ msgid "Stripe already has a customer with this email"msgstr "Stripe już ma klienta z tym adresem e-mail"msgid "Stripe Due Date"+msgstr "Termin płatności Stripe"msgstr "Pasek daty terminu"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."@@ -17720,6 +17754,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "To zaproszenie do dołączenia do {0} wygasło. Możesz poprosić o wysłanie nowego zaproszenia na Twoją wiadomość e-mail."msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "Ta faktura nie ma użytecznego terminu płatności — wybierz jeden dla Stripe."msgstr "Ta faktura nie ma użytecznego terminu — wybierz jeden dla Stripe."msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."@@ -18706,6 +18741,9 @@ msgstr "Uaktualnij, aby odblokować reguły {0}"msgid "Upgrade to unlock audit history"msgstr "Uaktualnij, aby odblokować historię audytu"+msgid "Upgrade to unlock sales rules"+msgstr "Uaktualnij, aby odblokować reguły sprzedaży"+msgid "Upload"msgstr "Prześlij plik"@@ -19655,6 +19693,9 @@ msgstr "Kto powinien otrzymywać powiadomienia, gdy RFQ zostanie oznaczony jakomsgid "Who should receive notifications when a sales job is completed?"msgstr "Kto powinien otrzymywać powiadomienia po zakończeniu zadania sprzedaży?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Kto powinien otrzymać powiadomienia, gdy naruszenie reguły sprzedaży jest zablokowane lub potwierdzone?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Kto powinien otrzymywać powiadomienia, gdy dostawca przesyła ofertę?"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex a34ad9dee2..887d23aafe 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -881,6 +881,9 @@ msgstr "Um pedido de venda é excluído"msgid "A sales order line contains order details for a particular item"msgstr "Uma linha de pedido de venda contém detalhes do pedido para um item específico"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Um pedido de venda enviado diretamente para um cliente e local diferentes do endereço de cabeçalho do cliente solicitante; o destino da remessa substitui o do cabeçalho."+msgid "A sales order's assignee changes"msgstr "O designado do pedido de venda muda"@@ -1640,6 +1643,9 @@ msgstr "Todos os Documentos"msgid "All item types"msgstr "Todos os tipos de item"+msgid "All items"+msgstr "Todos os itens"+msgid "All Items"msgstr "Todos os Itens"@@ -6076,6 +6082,9 @@ msgstr "Número do Desenho"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Desenho substituído. Os posicionamentos de balões foram removidos; as linhas de recursos permanecem inalteradas."+msgid "Drop shipment"+msgstr "Remessa direta"+msgid "Drop Shipment"msgstr "Remessa Direta"@@ -6552,6 +6561,9 @@ msgstr "Editar Tipo de Fornecedor"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Editar a regra para remover a flag \"Aplica-se a todos\""+msgid "Edit the rule's item filters to remove it"+msgstr "Edite os filtros de itens da regra para removê-la"+msgid "Edit Timecard"msgstr "Editar Cartão de Ponto"@@ -6660,6 +6672,9 @@ msgstr "Ativar contabilidade de regime de competência completo com lançamentosmsgid "Enable in Settings"msgstr "Ativar nas Configurações"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Ative notificações quando uma violação de regra de venda for bloqueada ou confirmada em uma cotação, pedido de venda ou fatura de venda."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Ativar notificações quando um RFQ é marcado como pronto para orçamento."@@ -6727,6 +6742,12 @@ msgstr "Termina"msgid "Enforce — edits are blocked"msgstr "Forçar — edições são bloqueadas"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Aplicar verificações em orçamento, pedido de venda e linhas de fatura de venda para este item."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Enforçar verificações de cliente e item quando itens são adicionados a cotações, pedidos de vendas e faturas de vendas."+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."@@ -12502,6 +12523,9 @@ msgstr "Escolha um valor de uma etapa anterior"msgid "Pick a variable…"msgstr "Escolha uma variável…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Escolha uma regra existente da biblioteca ou crie uma nova para começar a aplicar verificações neste item."+msgid "Pick List"msgstr "Lista de Coleta"@@ -14718,6 +14742,15 @@ msgstr "Devolução de venda"msgid "Sales Revenue"msgstr "Receita de Vendas"+msgid "Sales Rule Violations"+msgstr "Violações de Regra de Vendas"++msgid "Sales rules"+msgstr "Regras de vendas"++msgid "Sales Rules"+msgstr "Regras de Vendas"+msgid "Sales Tax Payable"msgstr "Imposto sobre vendas a pagar"@@ -16262,7 +16295,7 @@ msgid "Stripe Due Date"msgstr "Data de Vencimento Stripe"msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."-msgstr "O Stripe envia a fatura por e-mail ao cliente, portanto, um endereço é necessário. Isso também será salvo no contato no Carbon."+msgstr "Stripe envia a fatura por email para o cliente, portanto um endereço é necessário. Isso também será salvo no contato no Carbon."msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe ainda não tem um cliente para este cliente do Carbon. A Contabilização criará um na sua conta conectada."@@ -17720,7 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "Este convite para se juntar a {0} está vencido. Você pode solicitar um novo convite para ser enviado para seu email."msgid "This invoice has no usable due date — choose one for Stripe."-msgstr "Esta fatura não tem uma data de vencimento utilizável — escolha uma para o Stripe."+msgstr "Esta fatura não possui uma data de vencimento utilizável — escolha uma para Stripe."msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Esta fatura será cobrada do cliente Stripe já vinculado a este cliente Carbon. Para alterar seus detalhes, edite-o no painel Stripe."@@ -18546,7 +18579,7 @@ msgid "Unposted Documents"msgstr "Documentos Não Lançados"msgid "Unpublish"-msgstr "Cancelar publicação"+msgstr "Despublicar"msgid "Unpublish {name}?"msgstr "Cancelar Publicação de {name}?"@@ -18706,6 +18739,9 @@ msgstr "Atualize para desbloquear regras de {0}"msgid "Upgrade to unlock audit history"msgstr "Atualize para desbloquear histórico de auditoria"+msgid "Upgrade to unlock sales rules"+msgstr "Atualize para desbloquear regras de vendas"+msgid "Upload"msgstr "Enviar arquivo"@@ -19655,6 +19691,9 @@ msgstr "Quem deve receber notificações quando um RFQ é marcado como pronto pamsgid "Who should receive notifications when a sales job is completed?"msgstr "Quem deve receber notificações quando um trabalho de vendas é concluído?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Quem deve receber notificações quando uma violação de regra de vendas é bloqueada ou confirmada?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Quem deve receber notificações quando uma cotação de fornecedor é enviada?"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 1e72388601..542a5f9c44 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -881,6 +881,9 @@ msgstr "Заказ покупателя удален"msgid "A sales order line contains order details for a particular item"msgstr "Строка заказа покупателя содержит детали заказа для конкретной номенклатуры"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Заказ на продажу, отправленный напрямую другому клиенту и в другое место, чем адрес клиента в заголовке заказа; пункт назначения отправки переопределяет адрес в заголовке."+msgid "A sales order's assignee changes"msgstr "Исполнитель заказа покупателя изменился"@@ -1640,6 +1643,9 @@ msgstr "Все документы"msgid "All item types"msgstr "Все типы номенклатуры"+msgid "All items"+msgstr "Все товары"+msgid "All Items"msgstr "Все элементы"@@ -6076,6 +6082,9 @@ msgstr "Номер чертежа"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Рисунок заменён. Размещение выносок удалено; строки функций не изменены."+msgid "Drop shipment"+msgstr "Прямая отправка"+msgid "Drop Shipment"msgstr "Прямая отгрузка"@@ -6552,6 +6561,9 @@ msgstr "Изменить Тип поставщика"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Измените правило, чтобы удалить флаг «Применяется ко всем»"+msgid "Edit the rule's item filters to remove it"+msgstr "Отредактируйте фильтры товаров правила, чтобы удалить его"+msgid "Edit Timecard"msgstr "Изменить табель"@@ -6660,6 +6672,9 @@ msgstr "Включить полный учет по методу начислеmsgid "Enable in Settings"msgstr "Включить в настройках"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Включите уведомления, когда нарушение правила продаж блокируется или подтверждается в предложении, заказе покупателя или счете-фактуре выданном."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Включить уведомления, когда запрос коммерческого предложения отмечен как готовый к цитированию."@@ -6727,6 +6742,12 @@ msgstr "Заканчивается"msgid "Enforce — edits are blocked"msgstr "Принудительно — редактирование заблокировано"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Применять проверки к строкам предложения, заказа на продажу и счета-фактуры продажи для этого товара."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Применять проверки клиента и товара при добавлении товаров к предложениям, заказам продаж и счетам-фактурам продаж."+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Применить обязательную проверку и указания для каждого элемента в поступлениях, отгрузках, перемещениях и корректировках."@@ -12502,6 +12523,9 @@ msgstr "Выберите значение из предыдущего шага"msgid "Pick a variable…"msgstr "Выберите переменную…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Выберите существующее правило из библиотеки или создайте новое, чтобы начать применять проверки для этого товара."+msgid "Pick List"msgstr "Список подбора"@@ -14718,6 +14742,15 @@ msgstr "Возврат продажи"msgid "Sales Revenue"msgstr "Выручка от продаж"+msgid "Sales Rule Violations"+msgstr "Нарушения правил продаж"++msgid "Sales rules"+msgstr "Правила продаж"++msgid "Sales Rules"+msgstr "Правила продаж"+msgid "Sales Tax Payable"msgstr "Налог на продажи к уплате"@@ -16256,6 +16289,7 @@ msgid "Stripe"msgstr "Stripe"msgid "Stripe already has a customer with this email"+msgstr "Stripe уже имеет клиента с этим адресом электронной почты"msgstr "В Stripe уже есть покупатель с этим адресом электронной почты"msgid "Stripe Due Date"@@ -17720,6 +17754,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "Приглашение присоединиться к {0} истекло. Вы можете запросить отправку нового приглашения на вашу электронную почту."msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "У этого счета нет полезной даты выполнения — выберите один для Stripe."msgstr "Эта Счет-фактура не имеет пригодной даты Срока выполнения — выберите одну для Stripe."msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."@@ -18706,6 +18741,9 @@ msgstr "Обновитесь, чтобы разблокировать правиmsgid "Upgrade to unlock audit history"msgstr "Обновитесь, чтобы разблокировать историю аудита"+msgid "Upgrade to unlock sales rules"+msgstr "Обновите, чтобы разблокировать правила продаж"+msgid "Upload"msgstr "Загрузить"@@ -19655,6 +19693,9 @@ msgstr "Кто должен получать уведомления, когдаmsgid "Who should receive notifications when a sales job is completed?"msgstr "Кто должен получать уведомления при завершении заказа продаж?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Кто должен получать уведомления, когда нарушение правила продаж заблокировано или подтверждено?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Кто должен получать уведомления при отправке предложения поставщика?"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex d02e5064fd..ded9f7afeb 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -881,6 +881,9 @@ msgstr "Bir satış siparişi silindi"msgid "A sales order line contains order details for a particular item"msgstr "Bir satış siparişi satırı belirli bir ürünün sipariş ayrıntılarını içerir"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "Sipariş veren müşterinin başlık adresinden farklı bir müşteriye ve konuma doğrudan gönderilen bir satış siparişi; sevkiyatın hedefi başlığı geçersiz kılar."+msgid "A sales order's assignee changes"msgstr "Satış siparişinin atanmış kişisi değişti"@@ -1640,6 +1643,9 @@ msgstr "Tüm Belgeler"msgid "All item types"msgstr "Tüm Stok kartı türleri"+msgid "All items"+msgstr "Tüm öğeler"+msgid "All Items"msgstr "Tüm Öğeler"@@ -6076,6 +6082,9 @@ msgstr "Resim numarası"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "Çizim değiştirildi. Balon yerleşimleri kaldırıldı; özellik satırları değişmedi."+msgid "Drop shipment"+msgstr "Doğrudan Sevkiyat"+msgid "Drop Shipment"msgstr "Sevkiyatı Başka Bir Yere Gönderme"@@ -6552,6 +6561,9 @@ msgstr "Tedarikçi Türünü Düzenle"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "Kuralı düzenleyerek \"Tümüne uygulanır\" işaretini kaldırın"+msgid "Edit the rule's item filters to remove it"+msgstr "Kuralı kaldırmak için kuralın öğe filtrelerini düzenleyin"+msgid "Edit Timecard"msgstr "Çalışma Saatini Düzenle"@@ -6660,6 +6672,9 @@ msgstr "Muhasebe fişi girişleri, mali raporlar ve Büyük defter muhasebeleştmsgid "Enable in Settings"msgstr "Ayarlarda Etkinleştir"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "Bir teklif, satış siparişi veya satış faturasında bir satış kuralı ihlali engellendiğinde veya onaylandığında bildirimleri etkinleştirin."+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "Bir RFQ teklif için hazır olarak işaretlendiğinde bildirimleri etkinleştir."@@ -6727,6 +6742,12 @@ msgstr "Bitiş"msgid "Enforce — edits are blocked"msgstr "Zorunlu — düzenlemeler engellendi"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "Bu ürün için teklif, satış siparişi ve satış faturası satırlarında kontrolleri zorla."++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "Öğeler tekliflere, satış siparişlerine ve satış faturalarına eklendiğinde müşteri ve öğe kontrolleri uygulayın."+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "Mal kabul, sevkiyat, transfer ve düzeltmelerde madde başına doğrulama ve yönergeleri zorunlu kıl."@@ -12502,6 +12523,9 @@ msgstr "Önceki bir adımdan bir değer seçin"msgid "Pick a variable…"msgstr "Bir değişken seçin…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "Bu öğe üzerinde kontroller uygulamaya başlamak için kitaplıktan mevcut bir kural seçin veya yeni bir kural oluşturun."+msgid "Pick List"msgstr "Seçim Listesi"@@ -14718,6 +14742,15 @@ msgstr "Satış İadesi"msgid "Sales Revenue"msgstr "Satış Hasılat"+msgid "Sales Rule Violations"+msgstr "Satış Kuralı İhlalleri"++msgid "Sales rules"+msgstr "Satış kuralları"++msgid "Sales Rules"+msgstr "Satış Kuralları"+msgid "Sales Tax Payable"msgstr "Ödenmesi gereken satış vergisi"@@ -16256,7 +16289,7 @@ msgid "Stripe"msgstr "Stripe"msgid "Stripe already has a customer with this email"-msgstr "Stripe'ın zaten bu e-posta ile bir müşterisi var"+msgstr "Stripe zaten bu e-posta adresine sahip bir müşteriye sahip"msgid "Stripe Due Date"msgstr "Stripe Son Tarihi"@@ -17720,6 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "{0} grubuna katılma davetinizin süresi doldu. Yeni bir davet talebinde bulunabilirsiniz ve bu e-postanıza gönderilir."msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "Bu fatura kullanılabilir bir son tarih yok — Stripe için birini seçin."msgstr "Bu faturanın kullanılabilir bir son tarihi yok — Stripe için birini seçin."msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."@@ -18546,7 +18580,7 @@ msgid "Unposted Documents"msgstr "Deftere Geçmemiş Belgeler"msgid "Unpublish"-msgstr "Yayını kaldır"+msgstr "Yayınlamayı kaldır"msgid "Unpublish {name}?"msgstr "{name} yayınlaması kaldırılsın mı?"@@ -18706,6 +18740,9 @@ msgstr "Üniforma kurallarını açmak için yükseltin"msgid "Upgrade to unlock audit history"msgstr "Denetim geçmişini açmak için yükseltin"+msgid "Upgrade to unlock sales rules"+msgstr "Satış kurallarının kilidini açmak için yükseltin"+msgid "Upload"msgstr "Yükle"@@ -19655,6 +19692,9 @@ msgstr "Bir RFQ teklif için hazır olarak işaretlendiğinde kim bildirim almalmsgid "Who should receive notifications when a sales job is completed?"msgstr "Satış işi tamamlandığında kimler bildirim almalı?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "Bir satış kuralı ihlali engellendiğinde veya onaylandığında kim bildirimler almalıdır?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "Bir tedarikçi teklifi gönderildiğinde kimler bildirim almalı?"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 9fe219fbe9..98f830b430 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -881,6 +881,9 @@ msgstr "销售订单已删除"msgid "A sales order line contains order details for a particular item"msgstr "销售订单行包含特定项目的订单详情"+msgid "A sales order shipped straight to a different customer and location than the ordering customer's header address; the shipment's destination overrides the header's."+msgstr "销售订单直接运送给与订购客户的抬头地址不同的客户和地点;货运目的地优先于抬头地址。"+msgid "A sales order's assignee changes"msgstr "销售订单的经办人变更"@@ -1640,6 +1643,9 @@ msgstr "所有文档"msgid "All item types"msgstr "所有物料类型"+msgid "All items"+msgstr "所有项目"+msgid "All Items"msgstr "所有物料"@@ -6076,6 +6082,9 @@ msgstr "图号"msgid "Drawing replaced. Balloon placements were removed; feature rows are unchanged."msgstr "图纸已替换。气球位置已移除;功能行保持不变。"+msgid "Drop shipment"+msgstr "直发"+msgid "Drop Shipment"msgstr "直运"@@ -6552,6 +6561,9 @@ msgstr "编辑供应商类型"msgid "Edit the rule to remove the \"Applies to all\" flag"msgstr "编辑规则以移除\"应用于全部\"标志"+msgid "Edit the rule's item filters to remove it"+msgstr "编辑规则的项目过滤器以将其删除"+msgid "Edit Timecard"msgstr "编辑时间卡"@@ -6660,6 +6672,9 @@ msgstr "启用完整权责发生制会计,包括凭证、财务报告和总账msgid "Enable in Settings"msgstr "在设置中启用"+msgid "Enable notifications when a sales rule violation is blocked or acknowledged on a quote, sales order, or sales invoice."+msgstr "当销售规则违规在报价、销售订单或销售发票上被阻止或确认时,启用通知。"+msgid "Enable notifications when an RFQ is marked as ready for quote."msgstr "当询价单标记为可报价时启用通知。"@@ -6727,6 +6742,12 @@ msgstr "结束"msgid "Enforce — edits are blocked"msgstr "强制执行—编辑被阻止"+msgid "Enforce checks on quote, sales order, and sales invoice lines for this item."+msgstr "对本项目的报价单、销售订单和销售发票行执行检查。"++msgid "Enforce customer and item checks when items are added to quotes, sales orders, and sales invoices."+msgstr "当项目添加到报价、销售订单和销售发票时,强制执行客户和项目检查。"+msgid "Enforce per-item validation and guidelines across receipts, shipments, transfers, and adjustments."msgstr "在收据、发货、转移和调整中强制执行按项目验证和指南。"@@ -12502,6 +12523,9 @@ msgstr "从早期步骤选择一个值"msgid "Pick a variable…"msgstr "选择变量…"+msgid "Pick an existing rule from the library or create a new one to start enforcing checks on this item."+msgstr "从库中选择现有规则或创建新规则以开始对此项目强制执行检查。"+msgid "Pick List"msgstr "拣货单"@@ -14718,6 +14742,15 @@ msgstr "销售退货"msgid "Sales Revenue"msgstr "销售收入"+msgid "Sales Rule Violations"+msgstr "销售规则违规"++msgid "Sales rules"+msgstr "销售规则"++msgid "Sales Rules"+msgstr "销售规则"+msgid "Sales Tax Payable"msgstr "应付销售税"@@ -16256,7 +16289,7 @@ msgid "Stripe"msgstr "Stripe"msgid "Stripe already has a customer with this email"-msgstr "Stripe 已经有一个具有此电子邮件的客户"+msgstr "Stripe已经有使用此电子邮件的客户"msgid "Stripe Due Date"msgstr "Stripe 到期日期"@@ -17720,7 +17753,7 @@ msgid "This invitation to join {0} has expired. You can request a new invite tomsgstr "加入 {0} 的邀请已过期。您可以请求将新邀请发送到您的电子邮件。"msgid "This invoice has no usable due date — choose one for Stripe."-msgstr "此发票没有可用的截止日期 — 为 Stripe 选择一个。"+msgstr "此发票没有可用的截止日期——为Stripe选择一个。"msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "此发票将计费给已链接到此 Carbon 客户的 Stripe 客户。要更改其详细信息,请在 Stripe 仪表板中编辑它。"@@ -17893,7 +17926,7 @@ msgid "This version cannot be opened"msgstr "无法打开此版本"msgid "This version is published"-msgstr "这个版本已发布"+msgstr "此版本已发布"msgid "This version is published. Create a new version to edit."msgstr "此版本已发布。创建新版本进行编辑。"@@ -18706,6 +18739,9 @@ msgstr "升级以解锁 {0} 规则"msgid "Upgrade to unlock audit history"msgstr "升级以解锁审计历史记录"+msgid "Upgrade to unlock sales rules"+msgstr "升级以解锁销售规则"+msgid "Upload"msgstr "上传"@@ -19655,6 +19691,9 @@ msgstr "当询价单标记为可报价时,谁应该接收通知?"msgid "Who should receive notifications when a sales job is completed?"msgstr "销售工作完成时,谁应该收到通知?"+msgid "Who should receive notifications when a sales rule violation is blocked or acknowledged?"+msgstr "当销售规则违规被阻止或确认时,谁应该收到通知?"+msgid "Who should receive notifications when a supplier quote is submitted?"msgstr "供应商报价提交时,谁应该收到通知?"diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 545f049175..d859ec5dca 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -41,6 +41,7 @@ export enum NotificationEvent {SalesOrderAssignment = "sales-order-assignment",SalesRfqAssignment = "sales-rfq-assignment",SalesRfqReady = "sales-rfq-ready",+ SalesRuleViolation = "sales-rule-violation",StockTransferAssignment = "stock-transfer-assignment",SuggestionResponse = "suggestion-response",// Weekly digest reminder for outstanding trainings (documentIds-shaped).@@ -142,6 +143,7 @@ export function getNotificationTopic(case NotificationEvent.SupplierQuoteAssignment:case NotificationEvent.SupplierQuoteResponse:return NotificationTopic.Quote;+ case NotificationEvent.SalesRuleViolation:case NotificationEvent.SalesOrderAssignment:case NotificationEvent.SalesRfqAssignment:case NotificationEvent.SalesRfqReady:@@ -225,6 +227,8 @@ export function getNotificationEmailHeading(event: NotificationEvent): string {return "New maintenance dispatch";case NotificationEvent.GaugeCalibrationExpired:return "Gauge calibration expired";+ case NotificationEvent.SalesRuleViolation:+ return "Sales rule violation";case NotificationEvent.NonConformanceAssignment:return "Issue assigned to you";case NotificationEvent.RiskAssignment:@@ -284,6 +288,8 @@ export function getNotificationEmailCtaLabel(event: NotificationEvent): string {return "View suggestion";case NotificationEvent.GaugeCalibrationExpired:return "View gauge";+ case NotificationEvent.SalesRuleViolation:+ return "View document";case NotificationEvent.QuoteExpired:return "View quote";case NotificationEvent.TrainingReminder:diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex 1eb9dfeeb0..ca8717679b 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -1,6 +1,6 @@# @carbon/utils-Pure utility functions shared across all Carbon packages and apps. Covers accounting, arrays, BOM, dates, numeric precision and formatting, math, strings, status helpers, storage rules, URL manipulation, and more.+Pure utility functions shared across all Carbon packages and apps. Covers accounting, arrays, BOM, dates, numeric precision and formatting, math, strings, status helpers, the storage/sales rule engine, URL manipulation, and more.## Always@@ -12,7 +12,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun## Ask First- Adding new dependencies — this package is imported everywhere; new deps increase bundle size across all apps.-- Modifying `storage-rules.ts` — the `Operator` union is shared with `@carbon/workflows`, and the evaluator gates real inventory transactions.+- Modifying `rules.ts` / `field-registry.ts` / `rules-schema.ts` — the rule-evaluation engine (condition AST compiler, operators, field registry) and its zod mirror. The `Operator` union is shared with `@carbon/workflows`; the evaluator gates real inventory transactions and sales-document lines. Used by storage rules (`~/modules/inventory`) and sales rules (`~/modules/sales`) across ERP and MES.- Changing `Edition` enum or `isBrowser` detection — used by `@carbon/env` and auth logic.## Never@@ -24,7 +24,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun## Validation Commands```bash-pnpm --filter @carbon/utils test # Runs storage-rules tests etc.+pnpm --filter @carbon/utils test # Runs rule-engine tests etc.pnpm --filter @carbon/utils typecheck```@@ -48,10 +48,12 @@ pnpm --filter @carbon/utils typecheck| `string` | Slugify, truncate, camelCase/titleCase conversions || `revalidate` | `isSearchParamOnlyNavigation` — shared by both apps' shell `shouldRevalidate` || `status` | Status resolution, status color mapping |-| `storage-rules` | Inventory/storage rule engine: condition AST, the shared `Operator` vocabulary, JIT-compiled evaluator |+| `rules` | Rule engine: condition AST, the shared `Operator` vocabulary, JIT-compiled evaluator + surfaces for storage rules and sales rules |+| `rule-filters` | Item scoping for broadcast rules (`ItemFilter`, `ruleAppliesToItem`, `toItemFilter`) — family-neutral, split out of `rules.ts` |+| `rules-schema` | Zod mirror of the rule AST (`conditionAstSchema`, `conditionAstFormField`, `RULE_OPERATORS`/`RULE_MATCH_KINDS`/`RULE_SEVERITIES`). Shared by both ERP rule form validators so neither module imports the other || `supabase` | Typed Supabase query helpers || `types` | Shared TypeScript types (`Edition`, generic utility types) |-| `field-registry` | Fields a storage rule may test, and which operators each one allows |+| `field-registry` | Fields a rule may test, which operators each one allows, and which fields the builder/evaluator may reference || `labels` | Human-readable label generation || `url` | URL construction and manipulation |diff --git a/packages/utils/src/field-registry.ts b/packages/utils/src/field-registry.tsindex 51a2aa5a85..637f93701a 100644--- a/packages/utils/src/field-registry.ts+++ b/packages/utils/src/field-registry.ts@@ -1,10 +1,10 @@// Field resolver registry — single source of truth for the rule-builder UI and-// the evaluator's field paths. Split out of `storage-rules.ts` to keep that file-// focused on evaluation/compilation. Depends on `storage-rules` only for the core+// the evaluator's field paths. Split out of `rules.ts` to keep that file+// focused on evaluation/compilation. Depends on `rules` only for the core// `Operator` / `TargetType` types (type-only — no runtime cycle).import type { Database } from "@carbon/database";-import type { Operator, TargetType } from "./storage-rules";+import type { Operator, TargetType } from "./rules";type Tables = Database["public"]["Tables"];@@ -34,14 +34,18 @@ export type ValueOptionsLoader =| "itemTypes"| "replenishmentSystems"| "itemTrackingTypes"- | "itemPostingGroups";+ | "itemPostingGroups"+ | "customerTypes"+ | "customerStatuses"+ | "countries";export type FieldContext =| "item"| "storage"| "workCenter"| "operation"- | "transaction";+ | "transaction"+ | "customer";export type FieldDef = {path: string;@@ -216,7 +220,7 @@ export const FIELD_REGISTRY: FieldDef[] = [// ── StorageUnit context (item target) ─────────────────────────────────────// Loaded by the evaluator when `line.storageUnitId` is set. `nullable: true`- // on every entry so item rules can guard with `isSet`/`isNotSet`.+ // on every entry so storage rules can guard with `isSet`/`isNotSet`.fields.synthetic({path: "storageUnit.id",derivedFrom: "The bin chosen on this transaction line.",@@ -303,6 +307,49 @@ export const FIELD_REGISTRY: FieldDef[] = [})];+// SALES_RULE_FIELD_REGISTRY holds fields ONLY sales rules (sales-document+// surfaces) may reference. Kept SEPARATE from FIELD_REGISTRY so the storage+// rule builder/validator never sees customer fields — the storage evaluator+// never builds a `customer` ctx.+export const SALES_RULE_FIELD_REGISTRY: FieldDef[] = [+ fields.database({+ table: "customer",+ column: "customerTypeId",+ nullable: true,+ label: "Customer type",+ type: "id",+ operators: ID_OPS,+ context: "customer",+ targetType: "item",+ ctxKey: "customer",+ valueOptionsLoader: "customerTypes"+ }),+ fields.database({+ table: "customer",+ column: "customerStatusId",+ nullable: true,+ label: "Customer status",+ type: "id",+ operators: ID_OPS,+ context: "customer",+ targetType: "item",+ ctxKey: "customer",+ valueOptionsLoader: "customerStatuses"+ }),+ fields.synthetic({+ path: "customer.location.countryCode",+ derivedFrom:+ "Ship-to country (alpha-2) resolved from the document's customer location address.",+ nullable: true,+ label: "Customer country",+ type: "id",+ operators: ID_OPS,+ context: "customer",+ valueOptionsLoader: "countries",+ targetType: "item"+ })+];+/*** 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@@ -316,6 +363,19 @@ export const getFieldsForTargetType = (targetType: TargetType): FieldDef[] =>return f.targetType === targetType;});+/**+ * Full field set an SALES RULE may reference: the item + shared slice of the+ * storage registry (no storage/workCenter/operation contexts — the sales-rule+ * evaluator never builds those) plus the customer-context fields above.+ * Narrow further by surfaces via `getFieldsForSalesRuleSurfaces`.+ */+export const getFieldsForSalesRules = (): FieldDef[] => [+ ...FIELD_REGISTRY.filter(+ (f) => f.context === "item" || f.targetType === "shared"+ ),+ ...SALES_RULE_FIELD_REGISTRY+];+export const getFieldDef = (path: string): FieldDef | undefined => {// Custom fields are dynamic — accept any item.customFields.* path.if (path.startsWith("item.customFields.")) {@@ -329,5 +389,20 @@ export const getFieldDef = (path: string): FieldDef | undefined => {description: "Custom field on the item record."};}- return FIELD_REGISTRY.find((f) => f.path === path);+ // Same synthesis for customer custom fields (sales-rule surfaces only).+ if (path.startsWith("customer.customFields.")) {+ return {+ path,+ label: path.slice("customer.customFields.".length),+ type: "string",+ operators: SCALAR_OPS,+ context: "customer",+ targetType: "item",+ description: "Custom field on the customer record."+ };+ }+ return (+ FIELD_REGISTRY.find((f) => f.path === path) ??+ SALES_RULE_FIELD_REGISTRY.find((f) => f.path === path)+ );};diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 2e87165da8..436e22b66f 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -31,11 +31,13 @@ export * from "./payment-funding";export * from "./precision";export * from "./receiving";export * from "./revalidate";+export * from "./rule-filters";+export * from "./rules";+export * from "./rules-schema";export * from "./sales-posting-amounts";export * from "./ssr";export * from "./status";export * from "./status-colors";-export * from "./storage-rules";export * from "./string";export * from "./supabase";export * from "./tax";diff --git a/packages/utils/src/receiving.ts b/packages/utils/src/receiving.tsindex 6c66643088..f46474f00f 100644--- a/packages/utils/src/receiving.ts+++ b/packages/utils/src/receiving.ts@@ -1,5 +1,5 @@import { EPSILON, round } from "./precision";-import type { Violation } from "./storage-rules";+import type { Violation } from "./rules";export type OverReceiptReceiptLine = {lineId: string | null;diff --git a/packages/utils/src/rule-filters.ts b/packages/utils/src/rule-filters.tsnew file mode 100644index 0000000000..1484ad6f9e--- /dev/null+++ b/packages/utils/src/rule-filters.ts@@ -0,0 +1,57 @@+// Item scoping for broadcast rules — which items a rule fires on.+//+// Split out of `rules.ts` (which is the AST compiler/evaluator) because this is+// a self-contained matcher with no dependency on the engine: both rule families+// use it to gate a broadcast rule against one item's type/posting group.++// Which items a broadcast rule fires on: optional type/group filters, empty =+// every item. Shared by BOTH rule families — storage rules and sales rules both+// scope their broadcasts this way, so the name carries no family.++export type ItemFilter = {+ filteredItemTypes?: string[];+ filteredItemGroupIds?: string[];+ /** false → OR across the two dimensions (any); true → AND (all). */+ filteredItemMatchAll?: boolean;+};++/**+ * Minimal item shape the filter matcher reads. The index signature keeps it+ * structurally compatible with the looser item-context records the evaluator+ * and loaders build (no cast needed at call sites).+ */+export type ItemCtx = Record<string, unknown> & {+ type?: unknown;+ itemPostingGroupId?: unknown;+};++export const ruleAppliesToItem = (item: ItemCtx, f: ItemFilter): boolean => {+ const types = f.filteredItemTypes ?? [];+ const groups = f.filteredItemGroupIds ?? [];+ if (types.length === 0 && groups.length === 0) return true; // empty = all+ // `null` = dimension not constrained; it drops out of the combination so a+ // single set dimension behaves identically under OR and AND.+ const typeMatch = types.length ? types.includes(item.type as string) : null;+ const groupMatch = groups.length+ ? item.itemPostingGroupId != null &&+ groups.includes(item.itemPostingGroupId as string)+ : null;+ return f.filteredItemMatchAll+ ? (typeMatch ?? true) && (groupMatch ?? true)+ : (typeMatch ?? false) || (groupMatch ?? false);+};++/** Normalize an `enforcementRule` row's nullable filter columns into a filter. */+export const toItemFilter = (row: {+ filteredItemTypes?: string[] | null;+ filteredItemGroupIds?: string[] | null;+ filteredItemMatchAll?: boolean | null;+}): ItemFilter => ({+ filteredItemTypes: row.filteredItemTypes ?? [],+ filteredItemGroupIds: row.filteredItemGroupIds ?? [],+ filteredItemMatchAll: row.filteredItemMatchAll ?? false+});++// Which root `FieldContext`s the evaluator builds per surface — a null value is+// a separate concern, handled by `isSet`/`isNotSet`. `"storage"` maps to the+// `storageUnit` root key. Locked by `packages/ee/src/rules/storage/context.test.ts`.diff --git a/packages/utils/src/rules-schema.ts b/packages/utils/src/rules-schema.tsnew file mode 100644index 0000000000..485a353314--- /dev/null+++ b/packages/utils/src/rules-schema.ts@@ -0,0 +1,67 @@+// Zod mirrors of the rule-engine AST types in `./rules` (`Operator`,+// `MatchKind`, `Condition`, `ConditionAst`).+//+// Lives here rather than in an ERP module because BOTH rule families validate+// the same AST: storage rules (`~/modules/inventory`) and sales rules+// (`~/modules/sales`). Keeping it in the engine package means neither module+// has to import the other for its rule validator.++import { z } from "zod";+import type { MatchKind, Operator, Severity } from "./rules";++export const RULE_OPERATORS = [+ "eq",+ "neq",+ "in",+ "notIn",+ "isSet",+ "isNotSet",+ "gt",+ "lt"+] as const satisfies readonly Operator[];++export const RULE_MATCH_KINDS = [+ "all",+ "any",+ "none"+] as const satisfies readonly MatchKind[];++export const RULE_SEVERITIES = [+ "error",+ "warn"+] as const satisfies readonly Severity[];++const ruleConditionValueSchema = z.union([+ z.string(),+ z.number(),+ z.boolean(),+ z.array(z.union([z.string(), z.number(), z.boolean()])),+ z.null()+]);++const ruleConditionSchema = z.object({+ field: z.string().min(1, { message: "Field is required" }),+ op: z.enum(RULE_OPERATORS),+ value: ruleConditionValueSchema.optional()+});++export const conditionAstSchema = z.object({+ kind: z.enum(RULE_MATCH_KINDS),+ conditions: z+ .array(ruleConditionSchema)+ .min(1, { message: "At least one condition is required" })+});++/**+ * Form-field wrapper: the builder posts the AST as a JSON string, so parse it+ * before the object schema runs. A malformed string falls through unchanged so+ * zod reports a shape error rather than a parse crash.+ */+export const conditionAstFormField = z.preprocess((raw) => {+ if (typeof raw !== "string") return raw;+ try {+ return JSON.parse(raw);+ } catch {+ return raw;+ }+}, conditionAstSchema);diff --git a/packages/utils/src/storage-rules.test.ts b/packages/utils/src/rules.test.tssimilarity index 94%rename from packages/utils/src/storage-rules.test.tsrename to packages/utils/src/rules.test.tsindex 138f5d90a7..afee4482ce 100644--- a/packages/utils/src/storage-rules.test.ts+++ b/packages/utils/src/rules.test.ts@@ -4,21 +4,22 @@ import {getFieldDef,getFieldsForTargetType} from "./field-registry";+import { ruleAppliesToItem } from "./rule-filters";import {__resetStorageRulesCache,__storageRulesCacheSize,+ breakQuantities,compileRule,compileWithCache,evaluateRules,getFieldsForTargetTypeAndSurfaces,interpolateMessage,isFieldAvailableOnSurfaces,- itemRuleAppliesToItem,type RuleContext,type StorageRuleRow,SURFACE_CONTEXT_AVAILABILITY,TRANSACTION_SURFACES-} from "./storage-rules";+} from "./rules";const ruleOf = (conditions: Array<{ field: string; op: string; value?: unknown }>,@@ -629,7 +630,7 @@ describe("per-surface field availability", () => {expect(wcFields.some((f) => f.path === "transaction.quantity")).toBe(true);});- it("item-surface fields stay offered for item rules", () => {+ it("item-surface fields stay offered for storage rules", () => {const itemFields = getFieldsForTargetTypeAndSurfaces("item", ["receipt"]);expect(itemFields.some((f) => f.path === "item.type")).toBe(true);expect(itemFields.some((f) => f.context === "storage")).toBe(true);@@ -654,13 +655,13 @@ describe("per-surface field availability", () => {});});-describe("itemRuleAppliesToItem", () => {+describe("ruleAppliesToItem", () => {const part = { type: "Part", itemPostingGroupId: "grp_a" };it("empty filters → applies to all items", () => {- expect(itemRuleAppliesToItem(part, {})).toBe(true);+ expect(ruleAppliesToItem(part, {})).toBe(true);expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: [],filteredItemGroupIds: []})@@ -669,13 +670,13 @@ describe("itemRuleAppliesToItem", () => {it("single dimension (type) — OR and AND behave the same", () => {expect(- itemRuleAppliesToItem(part, { filteredItemTypes: ["Part", "Material"] })+ ruleAppliesToItem(part, { filteredItemTypes: ["Part", "Material"] })).toBe(true);+ expect(ruleAppliesToItem(part, { filteredItemTypes: ["Material"] })).toBe(+ false+ );expect(- itemRuleAppliesToItem(part, { filteredItemTypes: ["Material"] })- ).toBe(false);- expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: ["Material"],filteredItemMatchAll: true})@@ -683,23 +684,23 @@ describe("itemRuleAppliesToItem", () => {});it("single dimension (group)", () => {- expect(- itemRuleAppliesToItem(part, { filteredItemGroupIds: ["grp_a"] })- ).toBe(true);- expect(- itemRuleAppliesToItem(part, { filteredItemGroupIds: ["grp_b"] })- ).toBe(false);+ expect(ruleAppliesToItem(part, { filteredItemGroupIds: ["grp_a"] })).toBe(+ true+ );+ expect(ruleAppliesToItem(part, { filteredItemGroupIds: ["grp_b"] })).toBe(+ false+ );});it("OR (default) — either dimension matches", () => {expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: ["Material"],filteredItemGroupIds: ["grp_a"]})).toBe(true);expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: ["Material"],filteredItemGroupIds: ["grp_b"]})@@ -708,14 +709,14 @@ describe("itemRuleAppliesToItem", () => {it("AND — both dimensions must match", () => {expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: ["Part"],filteredItemGroupIds: ["grp_a"],filteredItemMatchAll: true})).toBe(true);expect(- itemRuleAppliesToItem(part, {+ ruleAppliesToItem(part, {filteredItemTypes: ["Part"],filteredItemGroupIds: ["grp_b"],filteredItemMatchAll: true@@ -725,10 +726,19 @@ describe("itemRuleAppliesToItem", () => {it("null/absent posting group never matches a group filter", () => {expect(- itemRuleAppliesToItem(+ ruleAppliesToItem({ type: "Part", itemPostingGroupId: null },{ filteredItemGroupIds: ["grp_a"] })).toBe(false);});});++describe("breakQuantities", () => {+ it("returns each unique positive break, falling back to 1", () => {+ expect(breakQuantities([1, 50, 100, 50])).toEqual([1, 50, 100]);+ expect(breakQuantities([])).toEqual([1]);+ expect(breakQuantities(null)).toEqual([1]);+ expect(breakQuantities([0, -5, Number.NaN])).toEqual([1]);+ });+});diff --git a/packages/utils/src/storage-rules.ts b/packages/utils/src/rules.tssimilarity index 73%rename from packages/utils/src/storage-rules.tsrename to packages/utils/src/rules.tsindex fa476ed178..b41824fc2f 100644--- a/packages/utils/src/storage-rules.ts+++ b/packages/utils/src/rules.ts@@ -1,15 +1,18 @@-// Storage Rules evaluator. AST → JIT-compiled closure with LRU cache.-// Used server-side on transactions (receipt, shipment, stock transfer,-// inventory adjustment, place, pick, operation start/finish, material-// issue/receive) to enforce per-entity validation/guideline rules.+// Shared rule engine for storage rules AND sales rules. AST → JIT-compiled+// closure with LRU cache. Used server-side on storage-rule transactions+// (receipt, shipment, stock transfer, inventory adjustment, place, pick,+// operation start/finish, material issue/receive) and on sales-rule sales+// surfaces (quote line, sales order line) to enforce per-entity+// validation/guideline rules.//-// Each rule binds to a single `TargetType` (`item` or `workCenter`). The field-// registry lives in `./field-registry`.+// Each storage rule binds to a single `TargetType` (`item` or `workCenter`);+// sales rules are item-scoped. The field registry lives in `./field-registry`.import {type FieldContext,type FieldDef,getFieldDef,+ getFieldsForSalesRules,getFieldsForTargetType} from "./field-registry";import { fnv1a32 } from "./hash";@@ -38,20 +41,20 @@ 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 `storageRuleTargetType`.+ * Mirrors the Postgres ENUM `enforcementRuleTargetType`.*/export const TARGET_TYPES = ["item", "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- * types, tighten this to:+ * Warehouse/MES transaction surfaces a STORAGE rule may opt into — the+ * storage-legal subset of the Postgres ENUM `enforcementRuleSurface`.*- * import type { Database } from "@carbon/database";- * ...as const satisfies readonly Database["public"]["Enums"]["transactionSurface"][];- *- * The runtime array stays the source of truth for the validator's `z.enum`.+ * Deliberately NOT tightened to the generated DB enum: that enum spans both rule+ * families, so satisfying it would let a storage rule declare a sales surface.+ * The split lives here and in the matching `enforcementRule_storage_surfaces`+ * CHECK constraint; this runtime array is the source of truth for the+ * validator's `z.enum`.*/export const TRANSACTION_SURFACES = ["receipt",@@ -68,14 +71,32 @@ export const TRANSACTION_SURFACES = [] as const;export type TransactionSurface = (typeof TRANSACTION_SURFACES)[number];+/**+ * Sales-document surfaces a SALES rule may opt into — the sales-legal subset of+ * the Postgres ENUM `enforcementRuleSurface`, mirrored by the+ * `enforcementRule_sales_surfaces` CHECK constraint. Sales rules reuse this+ * engine (same AST, operators, compiler, evaluator) but fire when items are+ * added to sales documents, not on warehouse transactions.+ */+export const SALES_RULE_SURFACES = [+ "quoteLine",+ "salesOrderLine",+ "salesInvoiceLine"+] as const;+export type SalesRuleSurface = (typeof SALES_RULE_SURFACES)[number];++/** Any surface the shared engine can evaluate a compiled rule on. */+export type RuleSurface = TransactionSurface | SalesRuleSurface;+/*** 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.*- * Item rules own every inventory/storage surface — including `place`/`pick`- * (bin-level guards that used to live on the now-removed `storageUnit` target).- * They reference bin context via the `storageUnit.*` fields in the registry.+ * Item-target storage rules own every inventory/storage surface — including+ * `place`/`pick` (bin-level guards that used to live on the now-removed+ * `storageUnit` target). They reference bin context via the `storageUnit.*`+ * fields in the registry.*/export const SURFACES_BY_TARGET_TYPE: Record<TargetType,@@ -120,6 +141,13 @@ export type Violation = {ruleId: string;severity: Severity;message: string;+ /**+ * The document line that produced this violation. Set when rules are+ * evaluated across a whole document (a terminal gate) so the UI can group+ * violations by line and deep-link to the offending one. Left undefined by+ * single-line evaluation, where the caller already knows the line.+ */+ lineId?: string;};export type RuleContext = {@@ -129,6 +157,11 @@ export type RuleContext = {workCenter?: Record<string, unknown>;operation?: Record<string, unknown>;transaction?: Record<string, unknown>;+ /** Sales-rule surfaces only — the sales document's customer. */+ customer?: Record<string, unknown> & {+ customFields?: Record<string, unknown>;+ location?: Record<string, unknown>;+ };};export type StorageRuleRow = {@@ -153,7 +186,7 @@ export type CompiledRule = {targetType: TargetType;severity: Severity;rawMessage: string;- surfaces: TransactionSurface[];+ surfaces: readonly RuleSurface[];conditions: Condition[];requiredFieldChecks: {field: string;@@ -172,7 +205,8 @@ const ROOT_KEYS = new Set(["storageUnit","workCenter","operation",- "transaction"+ "transaction",+ "customer"]);export const buildResolver = (path: string): Resolver => {@@ -341,6 +375,46 @@ export const __resetStorageRulesCache = (): void => {export const __storageRulesCacheSize = (): number => cache.size;+// ---------------------------------------------------------------------------+// Sales rules — sales-document rules (`enforcementRule`, family `sales`) reusing this engine+// ---------------------------------------------------------------------------++/**+ * Raw sales-family `enforcementRule` row shape the compiler needs. Unlike `StorageRuleRow` there+ * is no `targetType` column — sales rules are always item-target — and+ * `surfaces` holds `SalesRuleSurface` values (the sales subset of the Postgres ENUM `enforcementRuleSurface`).+ */+export type SalesRuleRow = {+ id: string;+ 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 item+ * rule surfaces".+ */+ surfaces?: SalesRuleSurface[];+ updatedAt?: string | null;+ active?: boolean;+};++/**+ * Compile a sales rule through the shared LRU cache. Normalizes the row to+ * the storage compiler's shape (`targetType: "item"`, defaulted surfaces).+ * The cast is safe: `CompiledRule.surfaces` is typed as the `RuleSurface`+ * union and the evaluator only ever runs `.includes(surface)` on it.+ */+export const compileSalesRuleWithCache = (row: SalesRuleRow): CompiledRule =>+ compileWithCache({+ ...row,+ targetType: "item",+ surfaces: (row.surfaces && row.surfaces.length > 0+ ? row.surfaces+ : [...SALES_RULE_SURFACES]) as unknown as TransactionSurface[]+ });++// ---------------------------------------------------------------------------// Message interpolationconst TOKEN_RE =@@ -426,6 +500,22 @@ export const interpolateMessage = (// Evaluator+/**+ * The quantities a quote line's break array should be evaluated at — every+ * unique positive break, falling back to 1. No single break is conservative+ * for every operator (a min-quantity rule fires on the smallest, a+ * max-quantity rule on the largest), so callers evaluate each and dedupe.+ */+export const breakQuantities = (+ breaks: number[] | null | undefined+): number[] => {+ const out = new Set<number>();+ for (const q of breaks ?? []) {+ if (typeof q === "number" && Number.isFinite(q) && q > 0) out.add(q);+ }+ return out.size > 0 ? Array.from(out) : [1];+};+export type EvaluateRulesOptions = {resolveConditionValue?: (cond: Condition,@@ -464,7 +554,7 @@ const buildRequiredFieldMessage = (export const evaluateRules = (rules: CompiledRule[],ctx: RuleContext,- surface: TransactionSurface,+ surface: RuleSurface,opts?: EvaluateRulesOptions): Violation[] => {const out: Violation[] = [];@@ -496,59 +586,6 @@ export const evaluateRules = (return out;};-// Which items a broadcast item rule fires on: optional type/group filters,-// empty = every item. `server.ts` gates each broadcast through this.--export type ItemRuleFilter = {- filteredItemTypes?: string[];- filteredItemGroupIds?: string[];- /** false → OR across the two dimensions (any); true → AND (all). */- filteredItemMatchAll?: boolean;-};--/**- * Minimal item shape the filter matcher reads. The index signature keeps it- * structurally compatible with the looser item-context records the evaluator- * and loaders build (no cast needed at call sites).- */-export type ItemCtx = Record<string, unknown> & {- type?: unknown;- itemPostingGroupId?: unknown;-};--export const itemRuleAppliesToItem = (- item: ItemCtx,- f: ItemRuleFilter-): boolean => {- const types = f.filteredItemTypes ?? [];- const groups = f.filteredItemGroupIds ?? [];- if (types.length === 0 && groups.length === 0) return true; // empty = all- // `null` = dimension not constrained; it drops out of the combination so a- // single set dimension behaves identically under OR and AND.- const typeMatch = types.length ? types.includes(item.type as string) : null;- const groupMatch = groups.length- ? item.itemPostingGroupId != null &&- groups.includes(item.itemPostingGroupId as string)- : null;- return f.filteredItemMatchAll- ? (typeMatch ?? true) && (groupMatch ?? true)- : (typeMatch ?? false) || (groupMatch ?? false);-};--/** Normalize a raw `storageRule` row's nullable filter columns into a filter. */-export const toItemRuleFilter = (row: {- filteredItemTypes?: string[] | null;- filteredItemGroupIds?: string[] | null;- filteredItemMatchAll?: boolean | null;-}): ItemRuleFilter => ({- filteredItemTypes: row.filteredItemTypes ?? [],- filteredItemGroupIds: row.filteredItemGroupIds ?? [],- filteredItemMatchAll: row.filteredItemMatchAll ?? false-});--// Which root `FieldContext`s the evaluator builds per surface — a null value is-// a separate concern, handled by `isSet`/`isNotSet`. `"storage"` maps to the-// `storageUnit` root key. Locked by `packages/ee/src/storage-rules/context.test.ts`.export const SURFACE_CONTEXT_AVAILABILITY: Record<TransactionSurface,readonly FieldContext[]@@ -591,6 +628,47 @@ export const getFieldsForTargetTypeAndSurfaces = (isFieldAvailableOnSurfaces(f, surfaces));+/**+ * Sales-rule counterpart of `SURFACE_CONTEXT_AVAILABILITY`: which root+ * `FieldContext`s the sales-rule evaluator structurally builds in `RuleContext`+ * for each sales-document surface. Locked by the anti-drift test in+ * `packages/ee/src/rules/sales/context.test.ts`.+ */+export const SALES_RULE_SURFACE_CONTEXT_AVAILABILITY: Record<+ SalesRuleSurface,+ readonly FieldContext[]+> = {+ quoteLine: ["item", "customer", "transaction"],+ salesOrderLine: ["item", "customer", "transaction"],+ salesInvoiceLine: ["item", "customer", "transaction"]+};++/**+ * A field resolves for a sales rule iff its context is structurally available+ * on EVERY surface the rule subscribes to. Empty surfaces → caller hasn't+ * picked surfaces yet; show the full sales-rule field set.+ */+export const isFieldAvailableOnSalesRuleSurfaces = (+ def: FieldDef,+ surfaces: readonly SalesRuleSurface[]+): boolean =>+ surfaces.length === 0 ||+ surfaces.every((s) =>+ SALES_RULE_SURFACE_CONTEXT_AVAILABILITY[s]?.includes(def.context)+ );++/**+ * Registry subset a sales rule may reference when it subscribes to+ * `surfaces`. Narrows `getFieldsForSalesRules` by per-surface context+ * availability. The sales-rule builder field picker filters through this.+ */+export const getFieldsForSalesRuleSurfaces = (+ surfaces: readonly SalesRuleSurface[]+): FieldDef[] =>+ getFieldsForSalesRules().filter((f) =>+ isFieldAvailableOnSalesRuleSurfaces(f, surfaces)+ );+// Fields whose meaning shifts by surface, surfaced to rule authors so a// predicate written for one surface doesn't silently misfire on another.diff --git a/packages/utils/src/sales-rules.test.ts b/packages/utils/src/sales-rules.test.tsnew file mode 100644index 0000000000..bfb1654f81--- /dev/null+++ b/packages/utils/src/sales-rules.test.ts@@ -0,0 +1,152 @@+// Sales-rule extensions of the shared rule engine. Storage-rule behavior is+// covered by rules.test.ts — these cases lock the additive sales-rule+// surface: customer ctx resolution, compileSalesRuleWithCache + evaluateRules+// on sales-document surfaces, and the sales-rule field registry slice.+import { beforeEach, describe, expect, it } from "vitest";+import { getFieldDef } from "./field-registry";+import {+ __resetStorageRulesCache,+ buildResolver,+ compileSalesRuleWithCache,+ evaluateRules,+ getFieldsForSalesRuleSurfaces,+ type RuleContext,+ type SalesRuleRow+} from "./rules";++const salesRuleOf = (overrides: Partial<SalesRuleRow> = {}): SalesRuleRow => ({+ id: overrides.id ?? "item_rule_1",+ severity: overrides.severity ?? "error",+ message: overrides.message ?? "violated",+ conditionAst: overrides.conditionAst ?? {+ kind: "all",+ conditions: [+ { field: "item.type", op: "eq", value: "Part" },+ {+ field: "customer.location.countryCode",+ op: "in",+ value: ["IR", "KP"]+ }+ ]+ },+ surfaces: overrides.surfaces,+ updatedAt: overrides.updatedAt ?? "2026-08-11T00:00:00Z",+ active: true+});++describe("sales rules", () => {+ beforeEach(() => __resetStorageRulesCache());++ it("buildResolver resolves customer.location.countryCode from ctx", () => {+ const resolve = buildResolver("customer.location.countryCode");+ expect(resolve({ customer: { location: { countryCode: "IR" } } })).toBe(+ "IR"+ );+ expect(resolve({ customer: {} })).toBeUndefined();+ expect(resolve({})).toBeUndefined();+ });++ it("compileSalesRuleWithCache + evaluateRules fire a violation on quoteLine when conditions are unsatisfied", () => {+ const compiled = compileSalesRuleWithCache(+ salesRuleOf({ message: "{item.name} fails the embargo rule" })+ );+ // Default surfaces = every sales-rule surface.+ expect(compiled.surfaces).toEqual([+ "quoteLine",+ "salesOrderLine",+ "salesInvoiceLine"+ ]);+ expect(compiled.targetType).toBe("item");++ const failingCtx: RuleContext = {+ item: { name: "Widget", type: "Part" },+ customer: { id: "cust_1", location: { countryCode: "US" } },+ transaction: { kind: "quoteLine", quantity: 1 }+ };+ const violations = evaluateRules([compiled], failingCtx, "quoteLine");+ expect(violations).toEqual([+ {+ ruleId: "item_rule_1",+ severity: "error",+ message: "Widget fails the embargo rule"+ }+ ]);++ // Conditions satisfied → no violation.+ const passingCtx: RuleContext = {+ item: { name: "Widget", type: "Part" },+ customer: { id: "cust_1", location: { countryCode: "IR" } },+ transaction: { kind: "quoteLine", quantity: 1 }+ };+ expect(evaluateRules([compiled], passingCtx, "quoteLine")).toEqual([]);+ });++ it("produces a required-field violation when customer.location is absent", () => {+ const compiled = compileSalesRuleWithCache(salesRuleOf());+ const ctx: RuleContext = {+ item: { name: "Widget", type: "Part" },+ customer: { id: "cust_1" }, // no location → countryCode unresolvable+ transaction: { kind: "quoteLine", quantity: 1 }+ };+ const violations = evaluateRules([compiled], ctx, "quoteLine");+ expect(violations).toHaveLength(1);+ expect(violations[0]?.message).toBe("Customer country is required");+ });++ it("skips rules not subscribed to the evaluated surface", () => {+ const compiled = compileSalesRuleWithCache(+ salesRuleOf({ id: "item_rule_so", surfaces: ["salesOrderLine"] })+ );+ const ctx: RuleContext = {+ item: { name: "Widget", type: "Part" },+ customer: { id: "cust_1", location: { countryCode: "US" } },+ transaction: { kind: "quoteLine", quantity: 1 }+ };+ expect(evaluateRules([compiled], ctx, "quoteLine")).toEqual([]);+ expect(evaluateRules([compiled], ctx, "salesOrderLine")).toHaveLength(1);+ expect(evaluateRules([compiled], ctx, "salesInvoiceLine")).toEqual([]);++ const invoiceOnly = compileSalesRuleWithCache(+ salesRuleOf({ id: "item_rule_inv", surfaces: ["salesInvoiceLine"] })+ );+ expect(evaluateRules([invoiceOnly], ctx, "salesOrderLine")).toEqual([]);+ expect(evaluateRules([invoiceOnly], ctx, "salesInvoiceLine")).toHaveLength(+ 1+ );+ });++ it("getFieldsForSalesRuleSurfaces includes customer fields and excludes storage/workCenter fields", () => {+ const paths = getFieldsForSalesRuleSurfaces(["quoteLine"]).map(+ (f) => f.path+ );+ expect(paths).toContain("customer.customerTypeId");+ expect(paths).toContain("customer.customerStatusId");+ expect(paths).toContain("customer.location.countryCode");+ expect(paths).toContain("item.type");+ expect(paths).toContain("transaction.quantity");+ expect(paths.some((p) => p.startsWith("storageUnit."))).toBe(false);+ expect(paths.some((p) => p.startsWith("workCenter."))).toBe(false);+ expect(paths.some((p) => p.startsWith("operation."))).toBe(false);++ // Same set on all surfaces (identical context availability).+ expect(+ getFieldsForSalesRuleSurfaces([+ "quoteLine",+ "salesOrderLine",+ "salesInvoiceLine"+ ]).map((f) => f.path)+ ).toEqual(paths);+ });++ it("getFieldDef resolves sales-rule registry fields and synthesizes customer custom fields", () => {+ expect(getFieldDef("customer.location.countryCode")?.label).toBe(+ "Customer country"+ );+ expect(getFieldDef("customer.customerTypeId")?.context).toBe("customer");++ const def = getFieldDef("customer.customFields.foo");+ expect(def?.label).toBe("foo");+ expect(def?.context).toBe("customer");+ expect(def?.description).toBe("Custom field on the customer record.");+ });+});