Skip to content

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

chore: refactor custom rules (#855)

Sidc8fe94bf8181
diff --git a/apps/erp/app/modules/customRules/index.ts b/apps/erp/app/modules/customRules/index.ts
deleted file mode 100644
index a367b5a232..0000000000
--- a/apps/erp/app/modules/customRules/index.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// ERP-side Custom Rules module. Re-exports cross-app queries from the
-// `@carbon/ee/custom-rules` package alongside ERP-only admin CRUD + form
-// validators.
-
-export {
- assignCustomRule,
- getActiveRulesForTargets,
- getCustomRulesList,
- getRuleAssignmentsForTarget,
- unassignCustomRule
-} from "@carbon/ee/custom-rules";
-export * from "./customRules.models";
-export * from "./customRules.service";
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
index e7db62ba2d..d340849455 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import {
DatePicker,
Hidden,
@@ -91,7 +91,7 @@ const InventoryStorageUnits = ({
const permissions = usePermissions();
const { t } = useLingui();
const adjustmentModal = useDisclosure();
- const ruleViolations = useCustomRuleViolations({
+ const ruleViolations = useStorageRuleViolations({
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.tsx
index b8da27bc31..be75684cdb 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import {
Alert,
AlertDescription,
@@ -141,7 +141,7 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
validateReceiptTracking();
});
- const ruleViolations = useCustomRuleViolations({
+ const ruleViolations = useStorageRuleViolations({
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.tsx
index 8832da13ca..0b73f87720 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import {
Alert,
AlertDescription,
@@ -227,7 +227,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
validateShipmentTracking();
});
- const ruleViolations = useCustomRuleViolations({
+ const ruleViolations = useStorageRuleViolations({
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.tsx
index 66e7669ad1..a043356bd6 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import {
Button,
Copy,
@@ -59,11 +59,11 @@ const StockTransferHeader = () => {
// Item rules fire on Release + Complete (the "go" transitions). Each gets
// its own fetcher so Release's loading state doesn't disable Complete and
// vice versa, and violations surface via a single shared modal.
- const releaseRules = useCustomRuleViolations({
+ const releaseRules = useStorageRuleViolations({
action: path.to.stockTransferStatus(id)
});
const releaseFetcher = releaseRules.fetcher;
- const completeRules = useCustomRuleViolations({
+ const completeRules = useStorageRuleViolations({
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.tsx
index 025907009a..61f86422c5 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import {
Badge,
Button,
@@ -1215,7 +1215,7 @@ const StockTransferWizardWidget = ({ locationId }: { locationId: string }) => {
// Item Rule pre-flight on Create Transfer (auto-released → stock-commit
// gate sits at the wizard click). Modal surfaces violations before the
// transfer is created.
- const createRules = useCustomRuleViolations<Result>({
+ const createRules = useStorageRuleViolations<Result>({
action: path.to.newStockTransfer,
onSuccess: () => clearStockTransferWizard()
});
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
index 1a7c6a6779..3341ac55e9 100644
--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
@@ -12,8 +12,7 @@ import {
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { LuShieldCheck } from "react-icons/lu";
-import { Link, useFetcher } from "react-router";
+import { useFetcher } from "react-router";
import type { z } from "zod";
import {
Hidden,
@@ -109,28 +108,13 @@ const StorageUnitForm = ({
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
- <HStack className="justify-between w-full">
- {isEditing ? (
- <Button
- asChild
- variant="secondary"
- leftIcon={<LuShieldCheck />}
- >
- <Link to={path.to.storageUnitRules(initialValues.id!)}>
- <Trans>Manage rules</Trans>
- </Link>
- </Button>
- ) : (
- <span />
- )}
- <HStack>
- <Submit isDisabled={isDisabled}>
- <Trans>Save</Trans>
- </Submit>
- <Button size="md" variant="solid" onClick={onClose}>
- <Trans>Cancel</Trans>
- </Button>
- </HStack>
+ <HStack>
+ <Submit isDisabled={isDisabled}>
+ <Trans>Save</Trans>
+ </Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
</HStack>
</ModalDrawerFooter>
</ValidatedForm>
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
index dc5da277a2..24f9e63671 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 { useCustomRuleViolations } from "@carbon/ee/custom-rules";
+import { useStorageRuleViolations } from "@carbon/ee/storage-rules";
import { InputControlled, ValidatedForm } from "@carbon/form";
import {
Button,
@@ -71,7 +71,7 @@ const WarehouseTransferForm = ({
// Item rules eval at every "go" status transition (Confirm/Ship/Receive/
// Complete). Surface violations through the hook's modal rather than the
// plain navigation path.
- const statusRules = useCustomRuleViolations<typeof statusAction>({
+ const statusRules = useStorageRuleViolations<typeof statusAction>({
action: warehouseTransfer?.id
? path.to.warehouseTransferStatus(warehouseTransfer.id)
: ""
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index a4b50d9eb5..3b09a2e358 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -6,6 +6,7 @@ import {
LuNetwork,
LuQrCode,
LuScanQrCode,
+ LuShieldCheck,
LuTag,
LuTally5,
LuTruck,
@@ -98,6 +99,12 @@ export default function useInventorySubmodules() {
icon: <LuTag />,
table: "storageType"
},
+ {
+ name: t`Storage Rules`,
+ to: path.to.storageRules,
+ role: "employee",
+ icon: <LuShieldCheck />
+ },
{
name: t`Shipping Methods`,
to: path.to.shippingMethods,
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 45347c6382..82cd6fa1b4 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -15,7 +15,6 @@ import {
LuLayoutDashboard,
LuNetwork,
LuSheet,
- LuShieldCheck,
LuShoppingCart,
LuSquareStack,
LuUsers,
@@ -151,12 +150,6 @@ export default function useSettingsSubmodules() {
role: "employee",
icon: <LuCircleCheck />
},
- {
- name: t`Custom Rules`,
- to: path.to.customRules,
- role: "employee",
- icon: <LuShieldCheck />
- },
{
name: t`Audit Logs`,
to: path.to.auditLog,
diff --git a/apps/erp/app/modules/storageRules/index.ts b/apps/erp/app/modules/storageRules/index.ts
new file mode 100644
index 0000000000..d7002a02d7
--- /dev/null
+++ b/apps/erp/app/modules/storageRules/index.ts
@@ -0,0 +1,13 @@
+// ERP-side Custom 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 "./storageRules.models";
+export * from "./storageRules.service";
diff --git a/apps/erp/app/modules/customRules/customRules.models.ts b/apps/erp/app/modules/storageRules/storageRules.models.ts
similarity index 71%
rename from apps/erp/app/modules/customRules/customRules.models.ts
rename to apps/erp/app/modules/storageRules/storageRules.models.ts
index ecee78c258..8f2f18c32a 100644
--- a/apps/erp/app/modules/customRules/customRules.models.ts
+++ b/apps/erp/app/modules/storageRules/storageRules.models.ts
@@ -8,9 +8,9 @@ import {
import { z } from "zod";
import { zfd } from "zod-form-data";
-export const customRuleSeverities = ["error", "warn"] as const;
+export const storageRuleSeverities = ["error", "warn"] as const;
-export const customRuleOperators = [
+export const storageRuleOperators = [
"eq",
"neq",
"in",
@@ -21,7 +21,7 @@ export const customRuleOperators = [
"lt"
] as const;
-const customRuleConditionValueSchema = z.union([
+const storageRuleConditionValueSchema = z.union([
z.string(),
z.number(),
z.boolean(),
@@ -29,40 +29,40 @@ const customRuleConditionValueSchema = z.union([
z.null()
]);
-const customRuleConditionSchema = z.object({
+const storageRuleConditionSchema = z.object({
field: z.string().min(1, { message: "Field is required" }),
- op: z.enum(customRuleOperators),
- value: customRuleConditionValueSchema.optional()
+ op: z.enum(storageRuleOperators),
+ value: storageRuleConditionValueSchema.optional()
});
-export const customRuleMatchKinds = ["all", "any", "none"] as const;
+export const storageRuleMatchKinds = ["all", "any", "none"] as const;
-export const customRuleConditionAstSchema = z.object({
- kind: z.enum(customRuleMatchKinds),
+export const storageRuleConditionAstSchema = z.object({
+ kind: z.enum(storageRuleMatchKinds),
conditions: z
- .array(customRuleConditionSchema)
+ .array(storageRuleConditionSchema)
.min(1, { message: "At least one condition is required" })
});
-const customRuleConditionAstFormField = z.preprocess((raw) => {
+const storageRuleConditionAstFormField = z.preprocess((raw) => {
if (typeof raw !== "string") return raw;
try {
return JSON.parse(raw);
} catch {
return raw;
}
-}, customRuleConditionAstSchema);
+}, storageRuleConditionAstSchema);
-export const customRuleValidator = z
+export const storageRuleValidator = z
.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }).max(120),
description: zfd.text(z.string().optional()),
message: z.string().min(1, { message: "Message is required" }).max(500),
- severity: z.enum(customRuleSeverities),
+ severity: z.enum(storageRuleSeverities),
targetType: z.enum(TARGET_TYPES),
- // Broadcast gate for storageUnit / workCenter rules. Item rules ignore this
- // and use the filteredItem* fields instead (empty = all items).
+ // 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(),
@@ -73,7 +73,7 @@ export const customRuleValidator = z
.refine((arr) => arr.length >= 1, {
message: "Pick at least one surface"
}),
- conditionAst: customRuleConditionAstFormField
+ conditionAst: storageRuleConditionAstFormField
})
.superRefine((val, ctx) => {
// Reject any surface that isn't valid for the chosen targetType. Schema
@@ -110,19 +110,14 @@ export const customRuleValidator = z
* action which targetType is in play, then this validator picks the right
* target-id key.
*/
-export const customRuleAssignmentValidator = (
- targetType: "item" | "storageUnit" | "workCenter"
+export const storageRuleAssignmentValidator = (
+ targetType: "item" | "workCenter"
) => {
- const idKey =
- targetType === "item"
- ? "itemId"
- : targetType === "storageUnit"
- ? "storageUnitId"
- : "workCenterId";
+ 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 customRuleAcknowledgeValidator = zfd.checkbox();
+export const storageRuleAcknowledgeValidator = zfd.checkbox();
diff --git a/apps/erp/app/modules/customRules/customRules.service.ts b/apps/erp/app/modules/storageRules/storageRules.service.ts
similarity index 77%
rename from apps/erp/app/modules/customRules/customRules.service.ts
rename to apps/erp/app/modules/storageRules/storageRules.service.ts
index 3327242cee..812c3b5cd8 100644
--- a/apps/erp/app/modules/customRules/customRules.service.ts
+++ b/apps/erp/app/modules/storageRules/storageRules.service.ts
@@ -1,6 +1,6 @@
// ERP-only admin CRUD for the Settings → Custom Rules page.
// Cross-app queries (assignment loaders, list fetch for tab data, polymorphic
-// assign/unassign) live in `@carbon/ee/custom-rules`.
+// assign/unassign) live in `@carbon/ee/storage-rules`.
import type { Database, Json } from "@carbon/database";
import type {
@@ -15,14 +15,14 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
-type CustomRuleFilters = {
+type StorageRuleFilters = {
appliesToAll: boolean;
filteredItemTypes?: string[];
filteredItemGroupIds?: string[];
filteredItemMatchAll?: boolean;
};
-type CustomRuleInsert = CustomRuleFilters & {
+type StorageRuleInsert = StorageRuleFilters & {
name: string;
description?: string | null;
message: string;
@@ -36,7 +36,7 @@ type CustomRuleInsert = CustomRuleFilters & {
customFields?: Json;
};
-type CustomRuleUpdate = CustomRuleFilters & {
+type StorageRuleUpdate = StorageRuleFilters & {
id: string;
name: string;
description?: string | null;
@@ -49,7 +49,7 @@ type CustomRuleUpdate = CustomRuleFilters & {
customFields?: Json;
};
-export async function getCustomRules(
+export async function getStorageRules(
client: SupabaseClient<Database>,
companyId: string,
args?: GenericQueryFilters & {
@@ -58,7 +58,7 @@ export async function getCustomRules(
}
) {
let query = client
- .from("customRule")
+ .from("storageRule")
.select("*", { count: "exact" })
.eq("companyId", companyId);
@@ -75,26 +75,26 @@ export async function getCustomRules(
return query;
}
-export async function getCustomRule(
+export async function getStorageRule(
client: SupabaseClient<Database>,
id: string
) {
- return client.from("customRule").select("*").eq("id", id).single();
+ return client.from("storageRule").select("*").eq("id", id).single();
}
-export async function upsertCustomRule(
+export async function upsertStorageRule(
client: SupabaseClient<Database>,
- rule: CustomRuleInsert | CustomRuleUpdate
+ rule: StorageRuleInsert | StorageRuleUpdate
) {
if ("createdBy" in rule) {
return client
- .from("customRule")
+ .from("storageRule")
.insert({ ...rule, conditionAst: rule.conditionAst as unknown as Json })
.select("id")
.single();
}
return client
- .from("customRule")
+ .from("storageRule")
.update({
...sanitize(rule),
conditionAst: rule.conditionAst as unknown as Json,
@@ -105,31 +105,25 @@ export async function upsertCustomRule(
.single();
}
-export async function deleteCustomRule(
+export async function deleteStorageRule(
client: SupabaseClient<Database>,
id: string
) {
- return client.from("customRule").delete().eq("id", id);
+ return client.from("storageRule").delete().eq("id", id);
}
export async function getRuleAssignmentCounts(
client: SupabaseClient<Database>,
ruleIds: string[]
) {
- // Counts span all three assignment tables. Each rule lives in exactly one
+ // 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<
- | "customRuleItemAssignment"
- | "customRuleStorageUnitAssignment"
- | "customRuleWorkCenterAssignment"
- > = [
- "customRuleItemAssignment",
- "customRuleStorageUnitAssignment",
- "customRuleWorkCenterAssignment"
- ];
+ "storageRuleItemAssignment" | "storageRuleWorkCenterAssignment"
+ > = ["storageRuleItemAssignment", "storageRuleWorkCenterAssignment"];
const results = await Promise.all(
tables.map((table) =>
diff --git a/apps/erp/app/modules/customRules/ui/ConditionRow.tsx b/apps/erp/app/modules/storageRules/ui/ConditionRow.tsx
similarity index 98%
rename from apps/erp/app/modules/customRules/ui/ConditionRow.tsx
rename to apps/erp/app/modules/storageRules/ui/ConditionRow.tsx
index fe38ab799d..54a9d4ff8e 100644
--- a/apps/erp/app/modules/customRules/ui/ConditionRow.tsx
+++ b/apps/erp/app/modules/storageRules/ui/ConditionRow.tsx
@@ -47,7 +47,7 @@ type ConditionRowProps = {
onChange: (index: number, patch: Partial<Condition>) => void;
onRemove: (index: number) => void;
optionsByLoader: ValueOptionsByLoader;
- targetType?: "item" | "storageUnit" | "workCenter";
+ targetType?: "item" | "workCenter";
/**
* Live list of surfaces the parent rule is configured for. When provided,
* the per-surface notes panel filters to this set. Falls back to all
@@ -75,7 +75,7 @@ function ConditionRowImpl({
// A field selected before the surfaces changed may no longer be populated on
// the rule's current surfaces. Flag it so the author re-picks — mirrors the
- // save-time validator gate (customRules.models.ts) client-side.
+ // save-time validator gate (storageRules.models.ts) client-side.
const fieldUnavailable = useMemo(
() =>
!!fieldDef &&
diff --git a/apps/erp/app/modules/customRules/ui/FieldCombobox.tsx b/apps/erp/app/modules/storageRules/ui/FieldCombobox.tsx
similarity index 99%
rename from apps/erp/app/modules/customRules/ui/FieldCombobox.tsx
rename to apps/erp/app/modules/storageRules/ui/FieldCombobox.tsx
index 4c07258bfa..32bd87d5fe 100644
--- a/apps/erp/app/modules/customRules/ui/FieldCombobox.tsx
+++ b/apps/erp/app/modules/storageRules/ui/FieldCombobox.tsx
@@ -67,7 +67,7 @@ type FieldComboboxProps = {
onChange: (path: string) => void;
placeholder?: string;
className?: string;
- targetType?: "item" | "storageUnit" | "workCenter";
+ targetType?: "item" | "workCenter";
/**
* Surfaces the rule subscribes to. Narrows the offered fields to those whose
* root context the evaluator populates on every selected surface, so authors
diff --git a/apps/erp/app/modules/customRules/ui/ItemFilterSelector.tsx b/apps/erp/app/modules/storageRules/ui/ItemFilterSelector.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/ItemFilterSelector.tsx
rename to apps/erp/app/modules/storageRules/ui/ItemFilterSelector.tsx
diff --git a/apps/erp/app/modules/customRules/ui/MessageWithTokens.tsx b/apps/erp/app/modules/storageRules/ui/MessageWithTokens.tsx
similarity index 99%
rename from apps/erp/app/modules/customRules/ui/MessageWithTokens.tsx
rename to apps/erp/app/modules/storageRules/ui/MessageWithTokens.tsx
index 7ebd53eb3f..df420dded0 100644
--- a/apps/erp/app/modules/customRules/ui/MessageWithTokens.tsx
+++ b/apps/erp/app/modules/storageRules/ui/MessageWithTokens.tsx
@@ -46,7 +46,7 @@ type MessageWithTokensProps = {
* Rule's targetType — scopes which fields appear in the token dropdown
* so e.g. workCenter rules don't list `item.replenishmentSystem`.
*/
- targetType?: "item" | "storageUnit" | "workCenter";
+ targetType?: "item" | "workCenter";
};
type TokenItem = { token: string; description: string };
@@ -102,7 +102,7 @@ const ORDERED_CTX: FieldDef["context"][] = ["storage", "transaction"];
// reallocate the icon element (rendering-hoist-jsx).
const BRACES_ICON = <LuBraces />;
-// Mirror of the runtime `TOKEN_RE` in packages/utils/src/customRules.ts so the
+// Mirror of the runtime `TOKEN_RE` in packages/utils/src/storageRules.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.
diff --git a/apps/erp/app/modules/customRules/ui/MultiValueCombobox.tsx b/apps/erp/app/modules/storageRules/ui/MultiValueCombobox.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/MultiValueCombobox.tsx
rename to apps/erp/app/modules/storageRules/ui/MultiValueCombobox.tsx
diff --git a/apps/erp/app/modules/customRules/ui/OperatorCombobox.tsx b/apps/erp/app/modules/storageRules/ui/OperatorCombobox.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/OperatorCombobox.tsx
rename to apps/erp/app/modules/storageRules/ui/OperatorCombobox.tsx
diff --git a/apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsx b/apps/erp/app/modules/storageRules/ui/RuleAssignmentsList.tsx
similarity index 85%
rename from apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsx
rename to apps/erp/app/modules/storageRules/ui/RuleAssignmentsList.tsx
index 4f21f7666c..e513532d21 100644
--- a/apps/erp/app/modules/customRules/ui/RuleAssignmentsList.tsx
+++ b/apps/erp/app/modules/storageRules/ui/RuleAssignmentsList.tsx
@@ -62,7 +62,7 @@ type LibraryRule = {
active: boolean;
};
-type TargetType = "item" | "storageUnit" | "workCenter";
+type TargetType = "item" | "workCenter";
type RuleAssignmentsListProps = {
targetType: TargetType;
@@ -84,11 +84,8 @@ const TARGET_COPY: Record<TargetType, { noun: string; surfaceBlurb: string }> =
{
item: {
noun: "item",
- surfaceBlurb: "receipts, shipments, transfers and inventory adjustments"
- },
- storageUnit: {
- noun: "storage unit",
- surfaceBlurb: "place, pick and transfers"
+ surfaceBlurb:
+ "receipts, shipments, transfers, inventory adjustments and bin moves"
},
workCenter: {
noun: "work center",
@@ -97,20 +94,17 @@ const TARGET_COPY: Record<TargetType, { noun: string; surfaceBlurb: string }> =
};
const ASSIGN_PATH = {
- item: path.to.customRuleAssignItem,
- storageUnit: path.to.customRuleAssignStorageUnit,
- workCenter: path.to.customRuleAssignWorkCenter
+ item: path.to.storageRuleAssignItem,
+ workCenter: path.to.storageRuleAssignWorkCenter
};
const UNASSIGN_PATH = {
- item: path.to.customRuleUnassignItem,
- storageUnit: path.to.customRuleUnassignStorageUnit,
- workCenter: path.to.customRuleUnassignWorkCenter
+ item: path.to.storageRuleUnassignItem,
+ workCenter: path.to.storageRuleUnassignWorkCenter
};
-const PERM_MODULE: Record<TargetType, "parts" | "inventory" | "resources"> = {
+const PERM_MODULE: Record<TargetType, "parts" | "resources"> = {
item: "parts",
- storageUnit: "inventory",
workCenter: "resources"
};
@@ -124,7 +118,7 @@ export default function RuleAssignmentsList({
const { t } = useLingui();
const permissions = usePermissions();
const fetcher = useFetcher();
- const { isGated } = usePlanGate({ feature: "CUSTOM_RULES" });
+ const { isGated } = usePlanGate({ feature: "STORAGE_RULES" });
const module = PERM_MODULE[targetType];
const canCreate = permissions.can("create", module);
const canDelete = permissions.can("delete", module);
@@ -188,7 +182,7 @@ export default function RuleAssignmentsList({
/>
)}
<Button variant="primary" leftIcon={<LuPlus />} asChild>
- <Link to={`${path.to.newCustomRule}?targetType=${targetType}`}>
+ <Link to={`${path.to.newStorageRule}?targetType=${targetType}`}>
<Trans>Add rule</Trans>
</Link>
</Button>
@@ -269,13 +263,12 @@ export default function RuleAssignmentsList({
<Tbody>
{assignments.map((a) => {
const isBroadcast = a.inheritedFromId === "__all__";
- const isInherited = !!a.inheritedFromId && !isBroadcast;
- const isLocked = isInherited || isBroadcast;
+ const isLocked = isBroadcast;
return (
<Tr key={a.ruleId}>
<Td className="whitespace-nowrap">
<HStack className="gap-2 items-center flex-wrap">
- <Hyperlink to={path.to.customRule(a.ruleId)}>
+ <Hyperlink to={path.to.storageRule(a.ruleId)}>
<HStack className="gap-2 items-center">
<LuShieldCheck className="text-muted-foreground shrink-0" />
<span>{a.rule.name}</span>
@@ -289,20 +282,6 @@ export default function RuleAssignmentsList({
<Trans>Applies to all</Trans>
</Badge>
)}
- {isInherited && (
- <Link
- to={path.to.storageUnitRules(a.inheritedFromId!)}
- className="no-underline"
- >
- <Badge
- variant="outline"
- className="cursor-pointer text-[10px] uppercase tracking-wide"
- >
- <Trans>Inherited from</Trans>{" "}
- {a.inheritedFromName ?? "parent"}
- </Badge>
- </Link>
- )}
</HStack>
</Td>
<Td>
@@ -351,16 +330,12 @@ export default function RuleAssignmentsList({
aria-label={
isBroadcast
? t`Edit the rule to remove the "Applies to all" flag`
- : isInherited
- ? t`Unassign from parent unit to remove`
- : t`Unassign rule`
+ : t`Unassign rule`
}
title={
isBroadcast
? t`Edit the rule to remove the "Applies to all" flag`
- : isInherited
- ? t`Unassign from parent unit to remove`
- : undefined
+ : undefined
}
variant="ghost"
size="sm"
@@ -438,7 +413,7 @@ function EmptyState({
size="sm"
leftIcon={<LuPlus />}
>
- <Link to={path.to.newCustomRule}>
+ <Link to={path.to.newStorageRule}>
<Trans>Create new rule</Trans>
</Link>
</Button>
@@ -451,12 +426,12 @@ function EmptyState({
size="sm"
leftIcon={<LuLibrary />}
>
- <Link to={path.to.customRules}>
+ <Link to={path.to.storageRules}>
<Trans>Browse library</Trans>
</Link>
</Button>
<Button asChild size="sm" leftIcon={<LuPlus />}>
- <Link to={path.to.newCustomRule}>
+ <Link to={path.to.newStorageRule}>
<Trans>Create new rule</Trans>
</Link>
</Button>
diff --git a/apps/erp/app/modules/customRules/ui/RuleBuilder.tsx b/apps/erp/app/modules/storageRules/ui/RuleBuilder.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/RuleBuilder.tsx
rename to apps/erp/app/modules/storageRules/ui/RuleBuilder.tsx
diff --git a/apps/erp/app/modules/customRules/ui/SeveritySelect.tsx b/apps/erp/app/modules/storageRules/ui/SeveritySelect.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/SeveritySelect.tsx
rename to apps/erp/app/modules/storageRules/ui/SeveritySelect.tsx
diff --git a/apps/erp/app/modules/customRules/ui/CustomRuleForm.tsx b/apps/erp/app/modules/storageRules/ui/StorageRuleForm.tsx
similarity index 88%
rename from apps/erp/app/modules/customRules/ui/CustomRuleForm.tsx
rename to apps/erp/app/modules/storageRules/ui/StorageRuleForm.tsx
index 03e84fbd46..efd613bfa0 100644
--- a/apps/erp/app/modules/customRules/ui/CustomRuleForm.tsx
+++ b/apps/erp/app/modules/storageRules/ui/StorageRuleForm.tsx
@@ -30,35 +30,35 @@ import {
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import { customRuleValidator } from "../customRules.models";
+import { storageRuleValidator } from "../storageRules.models";
import ItemFilterSelector from "./ItemFilterSelector";
import MessageWithTokens from "./MessageWithTokens";
import RuleBuilder from "./RuleBuilder";
import SeveritySelect from "./SeveritySelect";
import SurfacesField from "./SurfacesField";
-type CustomRuleFormInitial = Partial<z.infer<typeof customRuleValidator>> & {
+type StorageRuleFormInitial = Partial<z.infer<typeof storageRuleValidator>> & {
conditionAst?: ConditionAst;
};
-type CustomRuleFormProps = {
- initialValues: CustomRuleFormInitial;
+type StorageRuleFormProps = {
+ initialValues: StorageRuleFormInitial;
open?: boolean;
onClose: () => void;
};
-export default function CustomRuleForm({
+export default function StorageRuleForm({
initialValues,
open = true,
onClose
-}: CustomRuleFormProps) {
+}: StorageRuleFormProps) {
const { t } = useLingui();
const permissions = usePermissions();
const isEditing = !!initialValues.id;
const isDisabled = isEditing
- ? !permissions.can("update", "settings")
- : !permissions.can("create", "settings");
+ ? !permissions.can("update", "inventory")
+ : !permissions.can("create", "inventory");
const conditionAstInitial: ConditionAst = (initialValues.conditionAst as
| ConditionAst
@@ -77,7 +77,6 @@ export default function CustomRuleForm({
const targetType = (initialValues.targetType ?? "item") as
| "item"
- | "storageUnit"
| "workCenter";
// Default new rules to all surfaces of the chosen targetType. Editing keeps
@@ -120,12 +119,12 @@ export default function CustomRuleForm({
>
<ModalDrawerContent size="lg">
<ValidatedForm
- validator={customRuleValidator}
+ validator={storageRuleValidator}
method="post"
action={
isEditing
- ? path.to.customRule(initialValues.id!)
- : path.to.newCustomRule
+ ? path.to.storageRule(initialValues.id!)
+ : path.to.newStorageRule
}
defaultValues={defaults}
className="flex flex-col h-full"
@@ -157,11 +156,7 @@ export default function CustomRuleForm({
) : (
<Boolean
name="appliesToAll"
- label={
- targetType === "storageUnit"
- ? t`Applies to all storage units`
- : t`Applies to all work centers`
- }
+ label={t`Applies to all work centers`}
description={t`When on, this rule fires for every target of its type. Assignment rows are ignored but preserved.`}
/>
)}
@@ -182,7 +177,7 @@ export default function CustomRuleForm({
conditions={liveConditions}
targetType={targetType}
/>
- <CustomFormFields table="customRule" />
+ <CustomFormFields table="storageRule" />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsx b/apps/erp/app/modules/storageRules/ui/StorageRulesGroups.tsx
similarity index 80%
rename from apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsx
rename to apps/erp/app/modules/storageRules/ui/StorageRulesGroups.tsx
index 829284a836..b53e486665 100644
--- a/apps/erp/app/modules/customRules/ui/CustomRulesGroups.tsx
+++ b/apps/erp/app/modules/storageRules/ui/StorageRulesGroups.tsx
@@ -30,8 +30,7 @@ import {
LuPackage,
LuPencil,
LuPlus,
- LuTrash,
- LuWarehouse
+ LuTrash
} from "react-icons/lu";
import { Link, useNavigate } from "react-router";
import { Empty } from "~/components";
@@ -81,13 +80,12 @@ function ruleReach(rule: RuleListItem): {
};
}
-type CustomRulesGroupsProps = {
+type StorageRulesGroupsProps = {
rules: RuleListItem[];
};
const TARGET_LABEL: Record<TargetType, string> = {
- item: "Item",
- storageUnit: "Storage unit",
+ item: "Storage",
workCenter: "Work center"
};
@@ -136,7 +134,7 @@ const RuleSectionCard = memo(
) : (
<VStack spacing={3} className="items-stretch">
{rules.map((r) => (
- <CustomRuleCard key={r.id} rule={r} />
+ <StorageRuleCard key={r.id} rule={r} />
))}
</VStack>
)}
@@ -146,31 +144,26 @@ const RuleSectionCard = memo(
);
RuleSectionCard.displayName = "RuleSectionCard";
-const CustomRulesGroups = memo(({ rules }: CustomRulesGroupsProps) => {
+const StorageRulesGroups = memo(({ rules }: StorageRulesGroupsProps) => {
const permissions = usePermissions();
- const canCreate = permissions.can("create", "settings");
+ const canCreate = permissions.can("create", "inventory");
- // Split by targetType. Item + storageUnit shown; workCenter hidden until
- // entry point + MES modal ship.
- const { itemRules, storageUnitRules } = useMemo(() => {
- const itemRules: RuleListItem[] = [];
- const storageUnitRules: RuleListItem[] = [];
- for (const r of rules) {
- if (r.targetType === "item") itemRules.push(r);
- else if (r.targetType === "storageUnit") storageUnitRules.push(r);
- }
- return { itemRules, storageUnitRules };
- }, [rules]);
+ // Only item (storage) rules are shown here; workCenter rules are managed via
+ // Resources and hidden until their entry point + MES modal ship.
+ const itemRules = useMemo(
+ () => rules.filter((r) => r.targetType === "item"),
+ [rules]
+ );
return (
- <ScrollArea className="w-full h-[calc(100dvh-49px)]">
+ <ScrollArea className="w-full h-[calc(100dvh-49px)] bg-card">
<VStack
spacing={4}
className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
>
<div className="flex flex-col gap-1 w-full">
<Heading size="h3" className="tracking-tight text-balance">
- Custom Rules
+ Storage Rules
</Heading>
<p className="max-w-[72ch] text-sm text-muted-foreground text-pretty">
Predicate-driven guards that fire on inventory transactions. Block
@@ -179,52 +172,34 @@ const CustomRulesGroups = memo(({ rules }: CustomRulesGroupsProps) => {
</div>
<RuleSectionCard
- title="Item rules"
- description="Fire on receipts, shipments, transfers and inventory adjustments. Target items."
+ title="Storage rules"
+ description="Fire on receipts, shipments, transfers, inventory adjustments and bin moves (place/pick)."
icon={<LuPackage className="size-4 text-muted-foreground" />}
- newRuleHref={`${path.to.newCustomRule}?targetType=item`}
- newRuleLabel="Item Rule"
+ newRuleHref={`${path.to.newStorageRule}?targetType=item`}
+ newRuleLabel="Storage Rule"
canCreate={canCreate}
rules={itemRules}
/>
-
- <RuleSectionCard
- title="Storage unit rules"
- description="Fire on place, pick and transfers. Target storage units."
- icon={<LuWarehouse className="size-4 text-muted-foreground" />}
- newRuleHref={`${path.to.newCustomRule}?targetType=storageUnit`}
- newRuleLabel="Storage Unit Rule"
- canCreate={canCreate}
- rules={storageUnitRules}
- />
-
- {/*
- Production rules card — hidden until work center rule wiring
- (entry point on the work centers list, drawer/tab to manage
- assignments, MES violation modal) ships. To restore: split
- workCenter rules out of `rules` above and render a third
- RuleSectionCard with `newRuleHref` pointing to targetType=workCenter.
- */}
</VStack>
</ScrollArea>
);
});
-CustomRulesGroups.displayName = "CustomRulesGroups";
-export default CustomRulesGroups;
+StorageRulesGroups.displayName = "StorageRulesGroups";
+export default StorageRulesGroups;
-const CustomRuleCard = memo(({ rule }: { rule: RuleListItem }) => {
+const StorageRuleCard = memo(({ rule }: { rule: RuleListItem }) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
const deleteDisclosure = useDisclosure();
- const canEdit = permissions.can("update", "settings");
- const canDelete = permissions.can("delete", "settings");
+ const canEdit = permissions.can("update", "inventory");
+ const canDelete = permissions.can("delete", "inventory");
const { broadcastLabel, showAssignments } = ruleReach(rule);
const handleEdit = useCallback(() => {
- navigate(`${path.to.customRule(rule.id)}?${params.toString()}`);
+ navigate(`${path.to.storageRule(rule.id)}?${params.toString()}`);
}, [navigate, params, rule.id]);
return (
@@ -338,7 +313,7 @@ const CustomRuleCard = memo(({ rule }: { rule: RuleListItem }) => {
</Accordion>
</Card>
<ConfirmDelete
- action={path.to.deleteCustomRule(rule.id)}
+ action={path.to.deleteStorageRule(rule.id)}
isOpen={deleteDisclosure.isOpen}
name={`${TARGET_LABEL[rule.targetType]} rule "${rule.name}"`}
text="Are you sure you want to delete this custom rule? Assignments will also be removed."
@@ -349,4 +324,4 @@ const CustomRuleCard = memo(({ rule }: { rule: RuleListItem }) => {
);
});
-CustomRuleCard.displayName = "CustomRuleCard";
+StorageRuleCard.displayName = "StorageRuleCard";
diff --git a/apps/erp/app/modules/customRules/ui/CustomRulesTable.tsx b/apps/erp/app/modules/storageRules/ui/StorageRulesTable.tsx
similarity index 85%
rename from apps/erp/app/modules/customRules/ui/CustomRulesTable.tsx
rename to apps/erp/app/modules/storageRules/ui/StorageRulesTable.tsx
index a286684526..df6d276774 100644
--- a/apps/erp/app/modules/customRules/ui/CustomRulesTable.tsx
+++ b/apps/erp/app/modules/storageRules/ui/StorageRulesTable.tsx
@@ -13,10 +13,10 @@ import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
import SurfaceChips from "./SurfaceChips";
-type CustomRuleRowView = {
+type StorageRuleRowView = {
id: string;
name: string;
- targetType: "item" | "storageUnit" | "workCenter";
+ targetType: "item" | "workCenter";
severity: "error" | "warn";
active: boolean;
appliesToAll: boolean;
@@ -29,22 +29,21 @@ type CustomRuleRowView = {
};
const TARGET_TYPE_LABELS = {
- item: "Item",
- storageUnit: "Storage unit",
+ item: "Storage",
workCenter: "Work center"
} as const;
-type CustomRulesTableProps = {
- data: CustomRuleRowView[];
+type StorageRulesTableProps = {
+ data: StorageRuleRowView[];
count: number;
};
-const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
+const StorageRulesTable = memo(({ data, count }: StorageRulesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
- const customColumns = useCustomColumns<CustomRuleRowView>("customRule");
+ const customColumns = useCustomColumns<StorageRuleRowView>("storageRule");
const rows = useMemo(() => data, [data]);
@@ -55,7 +54,7 @@ const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
header: t`Name`,
cell: ({ row }) => (
<Hyperlink
- to={`${path.to.customRule(row.original.id)}?${params.toString()}`}
+ to={`${path.to.storageRule(row.original.id)}?${params.toString()}`}
>
<Enumerable value={row.original.name} />
</Hyperlink>
@@ -128,7 +127,7 @@ const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
<MenuItem
disabled={!permissions.can("update", "settings")}
onClick={() => {
- navigate(`${path.to.customRule(row.id)}?${params.toString()}`);
+ navigate(`${path.to.storageRule(row.id)}?${params.toString()}`);
}}
>
<MenuIcon icon={<LuPencil />} />
@@ -139,7 +138,7 @@ const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
destructive
onClick={() => {
navigate(
- `${path.to.deleteCustomRule(row.id)}?${params.toString()}`
+ `${path.to.deleteStorageRule(row.id)}?${params.toString()}`
);
}}
>
@@ -160,7 +159,7 @@ const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
permissions.can("create", "settings") && (
<New
label={t`Rule`}
- to={`${path.to.newCustomRule}?${params.toString()}`}
+ to={`${path.to.newStorageRule}?${params.toString()}`}
/>
)
}
@@ -170,5 +169,5 @@ const CustomRulesTable = memo(({ data, count }: CustomRulesTableProps) => {
);
});
-CustomRulesTable.displayName = "CustomRulesTable";
-export default CustomRulesTable;
+StorageRulesTable.displayName = "StorageRulesTable";
+export default StorageRulesTable;
diff --git a/apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsx b/apps/erp/app/modules/storageRules/ui/StorageRulesUpgradeOverlay.tsx
similarity index 93%
rename from apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsx
rename to apps/erp/app/modules/storageRules/ui/StorageRulesUpgradeOverlay.tsx
index 64a2dbf90d..bf5467abfe 100644
--- a/apps/erp/app/modules/customRules/ui/CustomRulesUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/storageRules/ui/StorageRulesUpgradeOverlay.tsx
@@ -11,7 +11,7 @@ import {
UpgradeOverlayTitle,
UpgradeOverlayUpgradeButton
} from "~/components/UpgradeOverlay";
-import CustomRulesTable from "./CustomRulesTable";
+import StorageRulesTable from "./StorageRulesTable";
const mockRules = [
{
@@ -72,11 +72,11 @@ const mockRules = [
}
];
-export default function CustomRulesUpgradeOverlay() {
+export default function StorageRulesUpgradeOverlay() {
return (
<UpgradeOverlay>
<UpgradeOverlayPreview>
- <CustomRulesTable data={mockRules as never} count={mockRules.length} />
+ <StorageRulesTable data={mockRules as never} count={mockRules.length} />
</UpgradeOverlayPreview>
<UpgradeOverlayCard>
<UpgradeOverlayIcon>
diff --git a/apps/erp/app/modules/customRules/ui/SurfaceChips.tsx b/apps/erp/app/modules/storageRules/ui/SurfaceChips.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/SurfaceChips.tsx
rename to apps/erp/app/modules/storageRules/ui/SurfaceChips.tsx
diff --git a/apps/erp/app/modules/customRules/ui/SurfacesField.tsx b/apps/erp/app/modules/storageRules/ui/SurfacesField.tsx
similarity index 98%
rename from apps/erp/app/modules/customRules/ui/SurfacesField.tsx
rename to apps/erp/app/modules/storageRules/ui/SurfacesField.tsx
index 35f1645c31..6e2000ba3e 100644
--- a/apps/erp/app/modules/customRules/ui/SurfacesField.tsx
+++ b/apps/erp/app/modules/storageRules/ui/SurfacesField.tsx
@@ -85,7 +85,7 @@ const SURFACE_META: Record<
type SurfacesFieldProps = {
name: string;
label?: string;
- targetType?: "item" | "storageUnit" | "workCenter";
+ targetType?: "item" | "workCenter";
/**
* Mirrors the live `value` to the parent so siblings (e.g. ConditionRow's
* per-surface notes panel) can filter against the rule's actual surfaces
diff --git a/apps/erp/app/modules/customRules/ui/ValueCombobox.tsx b/apps/erp/app/modules/storageRules/ui/ValueCombobox.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/ValueCombobox.tsx
rename to apps/erp/app/modules/storageRules/ui/ValueCombobox.tsx
diff --git a/apps/erp/app/modules/customRules/ui/ValueInput.tsx b/apps/erp/app/modules/storageRules/ui/ValueInput.tsx
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/ValueInput.tsx
rename to apps/erp/app/modules/storageRules/ui/ValueInput.tsx
diff --git a/apps/erp/app/modules/customRules/ui/useValueOptions.ts b/apps/erp/app/modules/storageRules/ui/useValueOptions.ts
similarity index 100%
rename from apps/erp/app/modules/customRules/ui/useValueOptions.ts
rename to apps/erp/app/modules/storageRules/ui/useValueOptions.ts
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 5c495c0943..789430c3bd 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-06-03T11:20:53.273Z",
+ "generated": "2026-06-03T15:07:42.524Z",
"totalTools": 1084,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
index 16ce5537ba..a12192b50d 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
+import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
import { pluckUnique } from "@carbon/utils";
@@ -9,7 +9,6 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { useRouteData } from "~/hooks";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
import {
getTrackedEntityExpirations,
InventoryDetails
@@ -28,6 +27,7 @@ import {
} from "~/modules/items";
import { PickMethodForm } from "~/modules/items/ui/Item";
import { getLocationsList } from "~/modules/resources";
+import RuleAssignmentsList from "~/modules/storageRules/ui/RuleAssignmentsList";
import { getUserDefaults } from "~/modules/users/users.server";
import { getDatabaseClient } from "~/services/database.server";
import { useItems } from "~/stores/items";
@@ -165,7 +165,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getItemShelfLife(client, itemId),
getBomHasShelfLifeManagedInput(client, itemId, companyId),
getTrackedEntityExpirations(client, trackedEntityIds),
- getCustomRulesDataForTarget(client, {
+ getStorageRulesDataForTarget(client, {
targetType: "item",
targetId: itemId,
companyId
diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx
index 233ea14946..f59cb7c361 100644
--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx
+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.adjustment.tsx
@@ -6,7 +6,7 @@ import {
dedupeViolations,
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -36,11 +36,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { ...d } = validation.data;
const acknowledged = formData.get("acknowledged") === "true";
- // Business rule evaluation. Item-target rules fire on
- // `inventoryAdjustment` surface. Storage-unit-target rules fire on
- // `place` when the adjustment lands stock in a bin (positive delta) and
- // `pick` when it removes from a bin (negative delta) — so warehouse rules
- // tied to those surfaces also kick in for manual adjustments.
+ // Business rule evaluation. Item 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.
const serviceRole = getCarbonServiceRole();
const qty = Number(d.quantity ?? 0);
const evalLine = [
@@ -66,22 +65,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
const allRuleNames: Record<string, string> = { ...itemPass.ruleNames };
if (d.storageUnitId) {
- // Pick storage-unit surface from `adjustmentType` only. `quantity` is a
+ // 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.
const isNegative = d.adjustmentType === "Negative Adjmt.";
- const storageSurface: "place" | "pick" = isNegative ? "pick" : "place";
+ const binSurface: "place" | "pick" = isNegative ? "pick" : "place";
- const storagePass = await evaluateLinesForSurface({
+ const binPass = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
- targetType: "storageUnit",
- surface: storageSurface,
+ targetType: "item",
+ surface: binSurface,
lines: evalLine
});
- allViolations.push(...storagePass.violations);
- Object.assign(allRuleNames, storagePass.ruleNames);
+ allViolations.push(...binPass.violations);
+ Object.assign(allRuleNames, binPass.ruleNames);
}
const deduped = dedupeViolations(allViolations);
diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
similarity index 73%
rename from apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsx
rename to apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
index 36dbc72589..c6900ef67e 100644
--- a/apps/erp/app/routes/x+/settings+/custom-rules.$id.delete.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
@@ -9,18 +9,18 @@ import type {
} from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteCustomRule, getCustomRule } from "~/modules/customRules";
+import { deleteStorageRule, getStorageRule } from "~/modules/storageRules";
import { getParams, path } from "~/utils/path";
-import { customRulesQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRulesQuery } from "~/utils/react-query";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, { delete: "settings" });
+ const { client } = await requirePermissions(request, { delete: "inventory" });
const { id } = params;
if (!id) throw notFound("id required");
- const rule = await getCustomRule(client, id);
+ const rule = await getStorageRule(client, id);
if (rule.error || !rule.data) {
throw redirect(
- path.to.customRules,
+ path.to.storageRules,
await flash(request, error(rule.error, "Rule not found"))
);
}
@@ -30,52 +30,52 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId } = await requirePermissions(request, {
- delete: "settings"
+ delete: "inventory"
});
await requirePlan({
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { id } = params;
if (!id) throw new Error("id required");
- const result = await deleteCustomRule(client, id);
+ const result = await deleteStorageRule(client, id);
if (result.error) {
throw redirect(
- `${path.to.customRules}?${getParams(request)}`,
+ `${path.to.storageRules}?${getParams(request)}`,
await flash(request, error(result.error, "Failed to delete rule"))
);
}
throw redirect(
- `${path.to.customRules}?${getParams(request)}`,
+ `${path.to.storageRules}?${getParams(request)}`,
await flash(request, success("Rule deleted"))
);
}
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
window?.clientCache?.setQueryData(
- customRulesQuery(getCompanyId()).queryKey,
+ storageRulesQuery(getCompanyId()).queryKey,
null
);
return await serverAction();
}
-export default function DeleteCustomRuleRoute() {
+export default function DeleteStorageRuleRoute() {
const { rule } = useLoaderData<typeof loader>();
const { id } = (rule as { id: string }) ?? { id: "" };
const navigate = useNavigate();
return (
<ConfirmDelete
- action={path.to.deleteCustomRule(id)}
+ action={path.to.deleteStorageRule(id)}
name={(rule as { name?: string })?.name ?? "this rule"}
text="Are you sure you want to delete this rule? Assignments will also be removed."
- onCancel={() => navigate(path.to.customRules)}
+ onCancel={() => navigate(path.to.storageRules)}
/>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.$id.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
similarity index 72%
rename from apps/erp/app/routes/x+/settings+/custom-rules.$id.tsx
rename to apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
index fb094b10a1..eeec28705a 100644
--- a/apps/erp/app/routes/x+/settings+/custom-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
@@ -11,19 +11,19 @@ import type {
} from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import {
- customRuleValidator,
- getCustomRule,
- upsertCustomRule
-} from "~/modules/customRules";
-import CustomRuleForm from "~/modules/customRules/ui/CustomRuleForm";
+ getStorageRule,
+ storageRuleValidator,
+ upsertStorageRule
+} from "~/modules/storageRules";
+import StorageRuleForm from "~/modules/storageRules/ui/StorageRuleForm";
import { getParams, path } from "~/utils/path";
-import { customRulesQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRulesQuery } from "~/utils/react-query";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, { view: "settings" });
+ const { client } = await requirePermissions(request, { view: "inventory" });
const { id } = params;
if (!id) throw notFound("id required");
- const rule = await getCustomRule(client, id);
+ const rule = await getStorageRule(client, id);
if (rule.error || !rule.data) throw notFound("Rule not found");
return { rule: rule.data };
}
@@ -31,25 +31,25 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- update: "settings"
+ update: "inventory"
});
await requirePlan({
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { id } = params;
if (!id) throw new Error("id required");
const formData = await request.formData();
- const validation = await validator(customRuleValidator).validate(formData);
+ const validation = await validator(storageRuleValidator).validate(formData);
if (validation.error) return validation.error;
- const update = await upsertCustomRule(client, {
+ const update = await upsertStorageRule(client, {
...validation.data,
id,
description: validation.data.description ?? null,
@@ -63,22 +63,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
).then(() => null);
}
- throw redirect(`${path.to.customRules}?${getParams(request)}`);
+ throw redirect(`${path.to.storageRules}?${getParams(request)}`);
}
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
window?.clientCache?.setQueryData(
- customRulesQuery(getCompanyId()).queryKey,
+ storageRulesQuery(getCompanyId()).queryKey,
null
);
return await serverAction();
}
-export default function EditCustomRuleRoute() {
+export default function EditStorageRuleRoute() {
const { rule } = useLoaderData<typeof loader>();
const navigate = useNavigate();
return (
- <CustomRuleForm
+ <StorageRuleForm
initialValues={
{
...((rule ?? {}) as Record<string, unknown>),
@@ -86,7 +86,7 @@ export default function EditCustomRuleRoute() {
.conditionAst as unknown as ConditionAst
} as never
}
- onClose={() => navigate(path.to.customRules)}
+ onClose={() => navigate(path.to.storageRules)}
/>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.new.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
similarity index 70%
rename from apps/erp/app/routes/x+/settings+/custom-rules.new.tsx
rename to apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
index 7ad0e5da7e..66409cac7f 100644
--- a/apps/erp/app/routes/x+/settings+/custom-rules.new.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
@@ -10,16 +10,19 @@ import type {
LoaderFunctionArgs
} from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
-import { customRuleValidator, upsertCustomRule } from "~/modules/customRules";
-import CustomRuleForm from "~/modules/customRules/ui/CustomRuleForm";
+import {
+ storageRuleValidator,
+ upsertStorageRule
+} from "~/modules/storageRules";
+import StorageRuleForm from "~/modules/storageRules/ui/StorageRuleForm";
import { getParams, path } from "~/utils/path";
-import { customRulesQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRulesQuery } from "~/utils/react-query";
const isTargetType = (value: string | null): value is TargetType =>
- value === "item" || value === "storageUnit" || value === "workCenter";
+ value === "item" || value === "workCenter";
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, { create: "settings" });
+ await requirePermissions(request, { create: "inventory" });
const url = new URL(request.url);
const raw = url.searchParams.get("targetType");
return { targetType: isTargetType(raw) ? raw : ("item" as TargetType) };
@@ -28,22 +31,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- create: "settings"
+ create: "inventory"
});
await requirePlan({
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const formData = await request.formData();
- const validation = await validator(customRuleValidator).validate(formData);
+ const validation = await validator(storageRuleValidator).validate(formData);
if (validation.error) return validation.error;
- const insert = await upsertCustomRule(client, {
+ const insert = await upsertStorageRule(client, {
...validation.data,
description: validation.data.description ?? null,
companyId,
@@ -57,27 +60,27 @@ export async function action({ request }: ActionFunctionArgs) {
).then(() => null);
}
- throw redirect(`${path.to.customRules}?${getParams(request)}`);
+ throw redirect(`${path.to.storageRules}?${getParams(request)}`);
}
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
window?.clientCache?.setQueryData(
- customRulesQuery(getCompanyId()).queryKey,
+ storageRulesQuery(getCompanyId()).queryKey,
null
);
return await serverAction();
}
-export default function NewCustomRuleRoute() {
+export default function NewStorageRuleRoute() {
const { targetType } = useLoaderData<typeof loader>();
const navigate = useNavigate();
// navigate(-1) breaks when the page was opened directly (no history entry
// to pop). Always navigate forward to the parent list route — closes the
// drawer regardless of how the user got here.
return (
- <CustomRuleForm
+ <StorageRuleForm
initialValues={{ targetType }}
- onClose={() => navigate(path.to.customRules)}
+ onClose={() => navigate(path.to.storageRules)}
/>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/custom-rules.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.tsx
similarity index 62%
rename from apps/erp/app/routes/x+/settings+/custom-rules.tsx
rename to apps/erp/app/routes/x+/inventory+/storage-rules.tsx
index 9bf04f98b4..a5a62bf9fc 100644
--- a/apps/erp/app/routes/x+/settings+/custom-rules.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.tsx
@@ -5,24 +5,27 @@ import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
import { usePlanGate } from "~/hooks/usePlanGate";
-import { getCustomRules, getRuleAssignmentCounts } from "~/modules/customRules";
-import CustomRulesGroups from "~/modules/customRules/ui/CustomRulesGroups";
-import CustomRulesUpgradeOverlay from "~/modules/customRules/ui/CustomRulesUpgradeOverlay";
+import {
+ getRuleAssignmentCounts,
+ getStorageRules
+} from "~/modules/storageRules";
+import StorageRulesGroups from "~/modules/storageRules/ui/StorageRulesGroups";
+import StorageRulesUpgradeOverlay from "~/modules/storageRules/ui/StorageRulesUpgradeOverlay";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
- breadcrumb: msg`Custom Rules`,
- to: path.to.customRules
+ breadcrumb: msg`Storage Rules`,
+ to: path.to.storageRules
};
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
- view: "settings",
+ view: "inventory",
role: "employee"
});
- const rules = await getCustomRules(client, companyId, {
+ const rules = await getStorageRules(client, companyId, {
search: null,
limit: 1000,
offset: 0,
@@ -31,8 +34,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (rules.error) {
throw redirect(
- path.to.settings,
- await flash(request, error(rules.error, "Failed to load custom rules"))
+ path.to.storageUnits,
+ await flash(request, error(rules.error, "Failed to load storage rules"))
);
}
@@ -48,17 +51,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
return { rows };
}
-export default function CustomRulesSettingsRoute() {
+export default function StorageRulesRoute() {
const { rows } = useLoaderData<typeof loader>();
- const { isGated } = usePlanGate({ feature: "CUSTOM_RULES" });
+ const { isGated } = usePlanGate({ feature: "STORAGE_RULES" });
if (isGated) {
- return <CustomRulesUpgradeOverlay />;
+ return <StorageRulesUpgradeOverlay />;
}
return (
<>
- <CustomRulesGroups rules={rows as never} />
+ <StorageRulesGroups rules={rows as never} />
<Outlet />
</>
);
diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsx
deleted file mode 100644
index 9a5d843013..0000000000
--- a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.rules.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { notFound } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
-import {
- Button,
- HStack,
- ModalDrawer,
- ModalDrawerBody,
- ModalDrawerContent,
- ModalDrawerFooter,
- ModalDrawerHeader,
- ModalDrawerProvider,
- ModalDrawerTitle
-} from "@carbon/react";
-import { Trans } from "@lingui/react/macro";
-import type { LoaderFunctionArgs } from "react-router";
-import { useLoaderData, useNavigate } from "react-router";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "inventory",
- role: "employee"
- });
- const { storageUnitId } = params;
- if (!storageUnitId) throw notFound("storageUnitId required");
-
- const data = await getCustomRulesDataForTarget(client, {
- targetType: "storageUnit",
- targetId: storageUnitId,
- companyId
- });
-
- return { storageUnitId, ...data };
-}
-
-export default function StorageUnitRulesRoute() {
- const { storageUnitId, assignments, library } =
- useLoaderData<typeof loader>();
- const navigate = useNavigate();
- const onClose = () => navigate(-1);
-
- return (
- <ModalDrawerProvider type="drawer">
- <ModalDrawer
- open
- onOpenChange={(open) => {
- if (!open) onClose();
- }}
- >
- <ModalDrawerContent size="lg">
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- <Trans>Storage unit rules</Trans>
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <RuleAssignmentsList
- targetType="storageUnit"
- targetId={storageUnitId}
- assignments={assignments as never}
- library={library as never}
- variant="flat"
- />
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack>
- <Button variant="solid" onClick={onClose}>
- <Trans>Close</Trans>
- </Button>
- </HStack>
- </ModalDrawerFooter>
- </ModalDrawerContent>
- </ModalDrawer>
- </ModalDrawerProvider>
- );
-}
diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsx
deleted file mode 100644
index 2c31cd9ac4..0000000000
--- a/apps/erp/app/routes/x+/inventory+/storage-units.rules.assign.$storageUnitId.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import type {
- ActionFunctionArgs,
- ClientActionFunctionArgs
-} from "react-router";
-import { redirect } from "react-router";
-import { assignCustomRule } from "~/modules/customRules";
-import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "inventory"
- });
-
- await requirePlan({
- request,
- client,
- companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
- });
-
- const { storageUnitId } = params;
- if (!storageUnitId) throw new Error("storageUnitId required");
-
- const formData = await request.formData();
- const ruleId = String(formData.get("ruleId") ?? "");
- if (!ruleId) {
- throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
- await flash(request, error(null, "Rule id required"))
- );
- }
-
- const result = await assignCustomRule(client, {
- targetType: "storageUnit",
- targetId: storageUnitId,
- ruleId,
- companyId,
- userId
- });
-
- if (result.error) {
- throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
- await flash(request, error(result.error, "Failed to assign rule"))
- );
- }
-
- throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
- await flash(request, success("Rule assigned"))
- );
-}
-
-export async function clientAction({
- serverAction,
- params
-}: ClientActionFunctionArgs) {
- const { storageUnitId } = params;
- if (storageUnitId) {
- window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("storageUnit", storageUnitId, getCompanyId())
- .queryKey,
- null
- );
- }
- return await serverAction();
-}
diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsx
deleted file mode 100644
index 6f726aae10..0000000000
--- a/apps/erp/app/routes/x+/inventory+/storage-units.rules.unassign.$storageUnitId.$ruleId.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import type {
- ActionFunctionArgs,
- ClientActionFunctionArgs
-} from "react-router";
-import { redirect } from "react-router";
-import { unassignCustomRule } from "~/modules/customRules";
-import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId } = await requirePermissions(request, {
- delete: "inventory"
- });
-
- await requirePlan({
- request,
- client,
- companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
- });
-
- const { storageUnitId, ruleId } = params;
- if (!storageUnitId || !ruleId)
- throw new Error("storageUnitId and ruleId required");
-
- const result = await unassignCustomRule(client, {
- targetType: "storageUnit",
- targetId: storageUnitId,
- ruleId
- });
- if (result.error) {
- throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
- await flash(request, error(result.error, "Failed to unassign rule"))
- );
- }
-
- throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
- await flash(request, success("Rule unassigned"))
- );
-}
-
-export async function clientAction({
- serverAction,
- params
-}: ClientActionFunctionArgs) {
- const { storageUnitId } = params;
- if (storageUnitId) {
- window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("storageUnit", storageUnitId, getCompanyId())
- .queryKey,
- null
- );
- }
- return await serverAction();
-}
diff --git a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
index 73521d1bed..4ed930400d 100644
--- a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
@@ -7,9 +7,9 @@ import type {
ClientActionFunctionArgs
} from "react-router";
import { redirect } from "react-router";
-import { assignCustomRule } from "~/modules/customRules";
+import { assignStorageRule } from "~/modules/storageRules";
import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -21,8 +21,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { itemId } = params;
@@ -32,12 +32,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const ruleId = String(formData.get("ruleId") ?? "");
if (!ruleId) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(null, "Rule id required"))
);
}
- const result = await assignCustomRule(client, {
+ const result = await assignStorageRule(client, {
targetType: "item",
targetId: itemId,
ruleId,
@@ -47,13 +47,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (result.error) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(result.error, "Failed to assign rule"))
);
}
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, success("Rule assigned"))
);
}
@@ -65,7 +65,7 @@ export async function clientAction({
const { itemId } = params;
if (itemId) {
window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,
+ storageRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,
null
);
}
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.tsx
index 43d9c01491..c85d975532 100644
--- a/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx
+++ b/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx
@@ -7,9 +7,9 @@ import type {
ClientActionFunctionArgs
} from "react-router";
import { redirect } from "react-router";
-import { unassignCustomRule } from "~/modules/customRules";
+import { unassignStorageRule } from "~/modules/storageRules";
import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -21,27 +21,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { itemId, ruleId } = params;
if (!itemId || !ruleId) throw new Error("itemId and ruleId required");
- const result = await unassignCustomRule(client, {
+ const result = await unassignStorageRule(client, {
targetType: "item",
targetId: itemId,
ruleId
});
if (result.error) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(result.error, "Failed to unassign rule"))
);
}
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, success("Rule unassigned"))
);
}
@@ -53,7 +53,7 @@ export async function clientAction({
const { itemId } = params;
if (itemId) {
window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,
+ storageRuleAssignmentsQuery("item", itemId, getCompanyId()).queryKey,
null
);
}
diff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
index 9b10300626..3b656d568f 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
+import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
import { pluckUnique } from "@carbon/utils";
@@ -9,7 +9,6 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { useRouteData } from "~/hooks";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
import {
getTrackedEntityExpirations,
InventoryDetails
@@ -28,6 +27,7 @@ import {
} from "~/modules/items";
import { PickMethodForm } from "~/modules/items/ui/Item";
import { getLocationsList } from "~/modules/resources";
+import RuleAssignmentsList from "~/modules/storageRules/ui/RuleAssignmentsList";
import { getUserDefaults } from "~/modules/users/users.server";
import { getDatabaseClient } from "~/services/database.server";
import { useItems } from "~/stores";
@@ -162,7 +162,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getItemShelfLife(client, itemId),
getBomHasShelfLifeManagedInput(client, itemId, companyId),
getTrackedEntityExpirations(client, trackedEntityIds),
- getCustomRulesDataForTarget(client, {
+ getStorageRulesDataForTarget(client, {
targetType: "item",
targetId: itemId,
companyId
diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
index f45fc57a23..7fdd5be2e4 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
+import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
import { pluckUnique } from "@carbon/utils";
@@ -9,7 +9,6 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { useRouteData } from "~/hooks";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
import {
getTrackedEntityExpirations,
InventoryDetails
@@ -28,6 +27,7 @@ import {
} from "~/modules/items";
import { PickMethodForm } from "~/modules/items/ui/Item";
import { getLocationsList } from "~/modules/resources";
+import RuleAssignmentsList from "~/modules/storageRules/ui/RuleAssignmentsList";
import { getUserDefaults } from "~/modules/users/users.server";
import { getDatabaseClient } from "~/services/database.server";
import { useItems } from "~/stores";
@@ -122,7 +122,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getItemStorageUnitQuantities(client, itemId, companyId, locationId),
getItemShelfLife(client, itemId),
getBomHasShelfLifeManagedInput(client, itemId, companyId),
- getCustomRulesDataForTarget(client, {
+ getStorageRulesDataForTarget(client, {
targetType: "item",
targetId: itemId,
companyId
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
index d66c730561..f062c9bb23 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/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -71,18 +71,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
Object.assign(allRuleNames, ruleNames);
}
- // Storage-unit pass — place side of the receipt. Same lines, different
- // target. Transfers double-up via the warehouseTransfer surface.
- const storageUnitSurfaces: ("place" | "warehouseTransfer")[] = ["place"];
+ // Place pass — the bin side of the receipt. Same lines, same item target;
+ // item 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") {
- storageUnitSurfaces.push("warehouseTransfer");
+ placeSurfaces.push("warehouseTransfer");
}
- for (const surface of storageUnitSurfaces) {
+ for (const surface of placeSurfaces) {
const { violations, ruleNames } = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
- targetType: "storageUnit",
+ targetType: "item",
surface,
lines: evalLines
});
diff --git a/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx b/apps/erp/app/routes/x+/resources+/work-centers.$workCenterId.rules.tsx
index 9f888cf36b..2e2c2618f0 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 { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
+import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
+import RuleAssignmentsList from "~/modules/storageRules/ui/RuleAssignmentsList";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -13,7 +13,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { workCenterId } = params;
if (!workCenterId) throw notFound("workCenterId required");
- const data = await getCustomRulesDataForTarget(client, {
+ const data = await getStorageRulesDataForTarget(client, {
targetType: "workCenter",
targetId: workCenterId,
companyId
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.tsx
index 9f3c6a687e..fd4a1a1df2 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
@@ -7,9 +7,9 @@ import type {
ClientActionFunctionArgs
} from "react-router";
import { redirect } from "react-router";
-import { assignCustomRule } from "~/modules/customRules";
+import { assignStorageRule } from "~/modules/storageRules";
import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -21,8 +21,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { workCenterId } = params;
@@ -32,12 +32,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const ruleId = String(formData.get("ruleId") ?? "");
if (!ruleId) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(null, "Rule id required"))
);
}
- const result = await assignCustomRule(client, {
+ const result = await assignStorageRule(client, {
targetType: "workCenter",
targetId: workCenterId,
ruleId,
@@ -47,13 +47,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (result.error) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(result.error, "Failed to assign rule"))
);
}
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, success("Rule assigned"))
);
}
@@ -65,7 +65,7 @@ export async function clientAction({
const { workCenterId } = params;
if (workCenterId) {
window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())
+ storageRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())
.queryKey,
null
);
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.tsx
index f3ca091162..2163b8b275 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
@@ -7,9 +7,9 @@ import type {
ClientActionFunctionArgs
} from "react-router";
import { redirect } from "react-router";
-import { unassignCustomRule } from "~/modules/customRules";
+import { unassignStorageRule } from "~/modules/storageRules";
import { path } from "~/utils/path";
-import { customRuleAssignmentsQuery, getCompanyId } from "~/utils/react-query";
+import { getCompanyId, storageRuleAssignmentsQuery } from "~/utils/react-query";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -21,28 +21,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
request,
client,
companyId,
- feature: "CUSTOM_RULES",
- redirectTo: path.to.customRules
+ feature: "STORAGE_RULES",
+ redirectTo: path.to.storageRules
});
const { workCenterId, ruleId } = params;
if (!workCenterId || !ruleId)
throw new Error("workCenterId and ruleId required");
- const result = await unassignCustomRule(client, {
+ const result = await unassignStorageRule(client, {
targetType: "workCenter",
targetId: workCenterId,
ruleId
});
if (result.error) {
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, error(result.error, "Failed to unassign rule"))
);
}
throw redirect(
- request.headers.get("Referer") ?? path.to.customRules,
+ request.headers.get("Referer") ?? path.to.storageRules,
await flash(request, success("Rule unassigned"))
);
}
@@ -54,7 +54,7 @@ export async function clientAction({
const { workCenterId } = params;
if (workCenterId) {
window?.clientCache?.setQueryData(
- customRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())
+ storageRuleAssignmentsQuery("workCenter", workCenterId, getCompanyId())
.queryKey,
null
);
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index b3c11ca9b5..c58d5c2920 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -6,7 +6,7 @@ import {
dedupeViolations,
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -75,17 +75,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
Object.assign(allRuleNames, ruleNames);
}
- // Storage-unit pass — pick side of the shipment.
- const storageUnitSurfaces: ("pick" | "warehouseTransfer")[] = ["pick"];
+ // Pick pass — the bin side of the shipment. Same lines, same item target;
+ // item 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") {
- storageUnitSurfaces.push("warehouseTransfer");
+ pickSurfaces.push("warehouseTransfer");
}
- for (const surface of storageUnitSurfaces) {
+ for (const surface of pickSurfaces) {
const { violations, ruleNames } = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
- targetType: "storageUnit",
+ targetType: "item",
surface,
lines: evalLines
});
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx
index 108980d528..cea4d8f409 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx
@@ -3,10 +3,9 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import {
- dedupeViolations,
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -59,7 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
locationId: null
}));
- const itemPass = await evaluateLinesForSurface({
+ const { violations, ruleNames } = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
@@ -68,26 +67,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Evaluate against the destination side — that's where stock is landing.
lines: evalLines
});
- const storagePass = await evaluateLinesForSurface({
- client: serviceRole,
- companyId,
- userId,
- targetType: "storageUnit",
- surface: "stockTransfer",
- lines: evalLines
- });
-
- const combined = dedupeViolations([
- ...itemPass.violations,
- ...storagePass.violations
- ]);
- const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };
- if (combined.length > 0 && isBlocked(combined, acknowledged)) {
+ if (violations.length > 0 && isBlocked(violations, acknowledged)) {
return {
error: null,
data: null,
- violations: combined,
+ violations,
ruleNames
};
}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
index 49c37caf33..f862e8189f 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/new.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
@@ -3,10 +3,9 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import {
- dedupeViolations,
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
@@ -70,7 +69,7 @@ export async function action({ request }: ActionFunctionArgs) {
locationId
}));
- const itemPass = await evaluateLinesForSurface({
+ const { violations, ruleNames } = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
@@ -78,26 +77,12 @@ export async function action({ request }: ActionFunctionArgs) {
surface: "stockTransfer",
lines: evalLines
});
- const storagePass = await evaluateLinesForSurface({
- client: serviceRole,
- companyId,
- userId,
- targetType: "storageUnit",
- surface: "stockTransfer",
- lines: evalLines
- });
-
- const combined = dedupeViolations([
- ...itemPass.violations,
- ...storagePass.violations
- ]);
- const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };
- if (combined.length > 0 && isBlocked(combined, acknowledged)) {
+ if (violations.length > 0 && isBlocked(violations, acknowledged)) {
return {
error: null,
data: null,
- violations: combined,
+ violations,
ruleNames
};
}
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
index 31de38940d..bed305e831 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getCustomRulesDataForTarget } from "@carbon/ee/custom-rules.server";
+import { getStorageRulesDataForTarget } from "@carbon/ee/storage-rules.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
import { pluckUnique } from "@carbon/utils";
@@ -9,7 +9,6 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { useRouteData } from "~/hooks";
-import RuleAssignmentsList from "~/modules/customRules/ui/RuleAssignmentsList";
import {
getTrackedEntityExpirations,
InventoryDetails
@@ -28,6 +27,7 @@ import {
} from "~/modules/items";
import { PickMethodForm } from "~/modules/items/ui/Item";
import { getLocationsList } from "~/modules/resources";
+import RuleAssignmentsList from "~/modules/storageRules/ui/RuleAssignmentsList";
import { getUserDefaults } from "~/modules/users/users.server";
import { getDatabaseClient } from "~/services/database.server";
import { useItems } from "~/stores/items";
@@ -154,7 +154,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getItemShelfLife(client, itemId),
getBomHasShelfLifeManagedInput(client, itemId, companyId),
getTrackedEntityExpirations(client, trackedEntityIds),
- getCustomRulesDataForTarget(client, {
+ getStorageRulesDataForTarget(client, {
targetType: "item",
targetId: itemId,
companyId
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx
index b6f457abe2..b5fbb4caeb 100644
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx
@@ -3,10 +3,9 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import {
- dedupeViolations,
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -65,7 +64,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
locationId: l.toLocationId as string | null
}));
- const itemPass = await evaluateLinesForSurface({
+ const { violations, ruleNames } = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
@@ -75,26 +74,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
lines: evalLines
});
- const storagePass = await evaluateLinesForSurface({
- client: serviceRole,
- companyId,
- userId,
- targetType: "storageUnit",
- surface: "warehouseTransfer",
- lines: evalLines
- });
-
- const combined = dedupeViolations([
- ...itemPass.violations,
- ...storagePass.violations
- ]);
- const ruleNames = { ...itemPass.ruleNames, ...storagePass.ruleNames };
-
- if (combined.length > 0 && isBlocked(combined, acknowledged)) {
+ if (violations.length > 0 && isBlocked(violations, acknowledged)) {
return {
error: null,
data: null,
- violations: combined,
+ violations,
ruleNames
};
}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 69be22b28a..6554d2d519 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1290,25 +1290,19 @@ export const path = {
consumableRules: (id: string) =>
generatePath(`${x}/consumable/${id}/rules`),
toolRules: (id: string) => generatePath(`${x}/tool/${id}/rules`),
- customRules: `${x}/settings/custom-rules`,
- customRule: (id: string) =>
- generatePath(`${x}/settings/custom-rules/${id}`),
- newCustomRule: `${x}/settings/custom-rules/new`,
- deleteCustomRule: (id: string) =>
- generatePath(`${x}/settings/custom-rules/${id}/delete`),
- customRuleAssignItem: (itemId: string) =>
+ storageRules: `${x}/inventory/storage-rules`,
+ storageRule: (id: string) =>
+ generatePath(`${x}/inventory/storage-rules/${id}`),
+ newStorageRule: `${x}/inventory/storage-rules/new`,
+ deleteStorageRule: (id: string) =>
+ generatePath(`${x}/inventory/storage-rules/${id}/delete`),
+ storageRuleAssignItem: (itemId: string) =>
generatePath(`${x}/items/rules/assign/${itemId}`),
- customRuleUnassignItem: (itemId: string, ruleId: string) =>
+ storageRuleUnassignItem: (itemId: string, ruleId: string) =>
generatePath(`${x}/items/rules/unassign/${itemId}/${ruleId}`),
- customRuleAssignStorageUnit: (id: string) =>
- generatePath(`${x}/inventory/storage-units/rules/assign/${id}`),
- customRuleUnassignStorageUnit: (id: string, ruleId: string) =>
- generatePath(
- `${x}/inventory/storage-units/rules/unassign/${id}/${ruleId}`
- ),
- customRuleAssignWorkCenter: (id: string) =>
+ storageRuleAssignWorkCenter: (id: string) =>
generatePath(`${x}/resources/work-centers/rules/assign/${id}`),
- customRuleUnassignWorkCenter: (id: string, ruleId: string) =>
+ storageRuleUnassignWorkCenter: (id: string, ruleId: string) =>
generatePath(
`${x}/resources/work-centers/rules/unassign/${id}/${ruleId}`
),
@@ -1645,8 +1639,6 @@ export const path = {
sequences: `${x}/settings/sequences`,
storageUnit: (id: string) =>
generatePath(`${x}/inventory/storage-units/${id}`),
- storageUnitRules: (id: string) =>
- generatePath(`${x}/inventory/storage-units/${id}/rules`),
storageUnits: `${x}/inventory/storage-units`,
storageType: (id: string) =>
generatePath(`${x}/inventory/storage-types/${id}`),
diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.ts
index 2d104bb407..eb198bb93d 100644
--- a/apps/erp/app/utils/react-query.ts
+++ b/apps/erp/app/utils/react-query.ts
@@ -149,21 +149,21 @@ export const uomsQuery = (companyId: string | null) => ({
staleTime: RefreshRate.Medium
});
-export const customRulesQuery = (
+export const storageRulesQuery = (
companyId: string | null,
targetType?: "item" | "storageUnit" | "workCenter" | null
) => ({
- queryKey: ["customRules", targetType ?? "all", companyId ?? "null"],
+ queryKey: ["storageRules", targetType ?? "all", companyId ?? "null"],
staleTime: RefreshRate.Low
});
-export const customRuleAssignmentsQuery = (
+export const storageRuleAssignmentsQuery = (
targetType: "item" | "storageUnit" | "workCenter",
targetId: string,
companyId: string | null
) => ({
queryKey: [
- "customRuleAssignments",
+ "storageRuleAssignments",
targetType,
targetId,
companyId ?? "null"
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index 09f350bcc6..7740efd088 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -5,7 +5,7 @@ import { flash } from "@carbon/auth/session.server";
import {
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-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.tsx
index 2212247e60..14be06f03d 100644
--- a/apps/mes/app/routes/x+/issue.tsx
+++ b/apps/mes/app/routes/x+/issue.tsx
@@ -5,7 +5,7 @@ import { flash } from "@carbon/auth/session.server";
import {
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-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.tsx
index c016322886..346d162830 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -5,7 +5,7 @@ import { flash } from "@carbon/auth/session.server";
import {
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import { getLocalTimeZone, now } from "@internationalized/date";
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.tsx
index fd92133b26..e462f09b2b 100644
--- a/apps/mes/app/routes/x+/unconsume.tsx
+++ b/apps/mes/app/routes/x+/unconsume.tsx
@@ -4,7 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
evaluateLinesForSurface,
isBlocked
-} from "@carbon/ee/custom-rules.server";
+} from "@carbon/ee/storage-rules.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { issueTrackedEntityValidator } from "~/services/models";
diff --git a/llm/tasks/todo.md b/llm/tasks/todo.md
index 16f8dbfd8b..663c02bd7d 100644
--- a/llm/tasks/todo.md
+++ b/llm/tasks/todo.md
@@ -1,14 +1,61 @@
-# Rework Feature Implementation
+# Merge pick/place into item rules; remove storageUnit; rebrand item→Storage rules under Inventory
-Plan: `llm/tasks/rework-plan.md`
-Design: `llm/tasks/rework-design.md`
+## Part A — Merge pick/place, remove storageUnit target
+- [x] A1. customRules.ts: TARGET_TYPES, SURFACES_BY_TARGET_TYPE. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A2. field-registry.ts: targetType ["item","storageUnit"]→"item". Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A3. server.ts: drop storageUnit target branches, keep storageType cascade. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A4. service.ts: drop storageUnit cases. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A5. customRules.models.ts validator. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A6. Call sites: receipt/shipment/adjustment swap; transfers delete pass. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A7. Delete 3 storage-units rules routes. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A8. path.ts + RuleAssignmentsList + StorageUnitForm + getRuleAssignmentCounts + type unions. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A9. Migration file. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] A10. Tests. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-## Tasks
+## Part B — Rebrand item→Storage rules, move to Inventory
+- [x] B1. Relocate 4 admin routes settings→inventory. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] B2. path.ts rename customRules*→storageRules*. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] B3. Nav: remove settings entry, add inventory entry. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] B4. CustomRulesGroups relabel. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+- [x] B5. CustomRulesTable + CustomRuleForm label maps. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] Task 1: Database Migration — rework table, reworkId on jobOperation, views, RLS, completion trigger
-- [x] Task 2: Trigger Rework Edge Function — path resolution, clone ops, wire DAG, trigger reschedule
-- [x] Task 3: Upstream Operations Service + API Route — getUpstreamOperations(), rework-targets loader
-- [x] Task 4: MES Trigger Rework Action Route — validator + action calling edge function
-- [ ] Task 5: ReworkModal Component — modal with target picker, reason, quantity
-- [x] Task 6: Wire ReworkModal into JobOperation — replace QuantityModal for rework
-- [ ] Task 7: Manual Testing — verify full rework flow end-to-end
+## Review
+
+**Done.** All 15 items complete. `packages/utils`, `packages/ee`, `apps/erp`
+typecheck clean (tsgo --noEmit, exit 0). Unit tests pass: utils customRules
+(51) + ee context anti-drift (23).
+
+Key decisions:
+- pick/place merged into item rules by adding them to `SURFACES_BY_TARGET_TYPE.item`
+ and swapping the storageUnit eval pass → item at receipt/shipment/adjustment
+ call sites; transfer call sites just dropped the redundant storageUnit pass.
+- storageUnit target fully removed (TARGET_TYPES, field-registry, evaluator,
+ service, validator, UI unions, 3 assignment routes, path helpers, nav button).
+ Storage-type ancestor cascade KEPT in the evaluator — item rules referencing
+ `storageUnit.storageTypeId` on place/pick still get the unioned value.
+- Migration `20260603120000_remove-storage-unit-rules.sql`: DELETEs storageUnit
+ rules (cascades assignments), DROPs the assignment table, recreates the enum
+ without 'storageUnit'.
+- Item rules rebranded "Storage rules"; admin library relocated settings →
+ `/x/inventory/storage-rules` + Inventory > Configure nav. Pages still gated on
+ `settings` permission (matches `customRule` RLS); switching to inventory perms
+ would need an RLS migration (out of scope).
+
+## Part C — Full rename customRule → storageRule (incl. DB), perms → inventory
+
+Done. Migrations applied + types regenerated by user. ee/erp typecheck exit 0;
+utils/ee tests green.
+- Code: blanket rename `customRule*`/`CustomRule*`/`custom-rules`/`CUSTOM_RULES`
+ → `storageRule*`/`StorageRule*`/`storage-rules`/`STORAGE_RULES` (60 files);
+ `git mv` of utils `storageRules.ts(.test)`, ee `storageRules/` dir, erp
+ `modules/storageRules/` + `StorageRule*` component files; EE export
+ `@carbon/ee/storage-rules(.server)`.
+- DB: migration 130000 renames tables (`storageRule`, `storageRuleItemAssignment`,
+ `storageRuleWorkCenterAssignment`), enum `storageRuleTargetType`, customFieldTable
+ row. Migration 140000 moves `storageRule` RLS → inventory_* (SELECT any-employee).
+ Admin route gates + library UI perms swapped settings → inventory.
+- Left legacy constraint/index names (`customRule_*`) — internal labels only,
+ surface as `foreignKeyName` strings in generated types; never referenced by code.
+
+Manual verification still pending (create a storage rule; receipt/ship to fire
+place/pick; confirm Inventory→Storage Rules nav).
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index fc4823c4b6..268104fc57 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -6615,533 +6615,6 @@ export type Database = {
}
Relationships: []
}
- customRule: {
- 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"]["customRuleTargetType"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- active?: boolean
- appliesToAll?: boolean
- companyId: string
- conditionAst: Json
- createdAt?: string
- createdBy: string
- customFields?: Json | null
- description?: string | null
- filteredItemGroupIds?: string[]
- filteredItemMatchAll?: boolean
- filteredItemTypes?: string[]
- id?: string
- message: string
- name: string
- severity: string
- surfaces?: Database["public"]["Enums"]["transactionSurface"][]
- targetType?: Database["public"]["Enums"]["customRuleTargetType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- active?: boolean
- appliesToAll?: boolean
- companyId?: string
- conditionAst?: Json
- createdAt?: string
- createdBy?: string
- customFields?: Json | null
- description?: string | null
- filteredItemGroupIds?: string[]
- filteredItemMatchAll?: boolean
- filteredItemTypes?: string[]
- id?: string
- message?: string
- name?: string
- severity?: string
- surfaces?: Database["public"]["Enums"]["transactionSurface"][]
- targetType?: Database["public"]["Enums"]["customRuleTargetType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- customRuleItemAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- itemId: string
- ruleId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- itemId: string
- ruleId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- itemId?: string
- ruleId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- ]
- }
- customRuleStorageUnitAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- ruleId: string
- storageUnitId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- ruleId: string
- storageUnitId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- ruleId?: string
- storageUnitId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_storageUnitId_fkey"
- columns: ["storageUnitId"]
- isOneToOne: false
- referencedRelation: "storageUnit"
- referencedColumns: ["id"]
- },
- ]
- }
- customRuleWorkCenterAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- ruleId: string
- workCenterId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- ruleId: string
- workCenterId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- ruleId?: string
- workCenterId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "riskRegisters"
- referencedColumns: ["workCenterId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenter"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenters"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCentersWithBlockingStatus"
- referencedColumns: ["id"]
- },
- ]
- }
demandActual: {
Row: {
actualQuantity: number
@@ -38714,6 +38187,48 @@ export type Database = {
},
]
}
+ searchIndex_MvZGQSEAkgLUthUCevNd2m: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -40856,6 +40371,431 @@ 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: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ storageRuleItemAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ itemId: string
+ ruleId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ itemId: string
+ ruleId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ itemId?: string
+ ruleId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_ruleId_fkey"
+ columns: ["ruleId"]
+ isOneToOne: false
+ referencedRelation: "storageRule"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ storageRuleWorkCenterAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ ruleId: string
+ workCenterId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ ruleId: string
+ workCenterId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ ruleId?: string
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"
+ columns: ["ruleId"]
+ isOneToOne: false
+ referencedRelation: "storageRule"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "riskRegisters"
+ referencedColumns: ["workCenterId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
storageType: {
Row: {
companyId: string
@@ -54337,14 +54277,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -55840,14 +55780,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -59280,14 +59220,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65361,7 +65301,6 @@ export type Database = {
| "Indirect Cost"
| "Variance"
| "Total"
- customRuleTargetType: "item" | "storageUnit" | "workCenter"
deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"
demandForecastSourceType:
| "Job Material"
@@ -65852,6 +65791,7 @@ export type Database = {
shippingCarrier: "UPS" | "FedEx" | "USPS" | "DHL" | "Other"
sourcingType: "Specified" | "Drop Ship" | "Ship from Inventory"
stockTransferStatus: "Draft" | "Released" | "In Progress" | "Completed"
+ storageRuleTargetType: "item" | "workCenter"
supplierLedgerDocumentType:
| "Payment"
| "Invoice"
@@ -66633,7 +66573,6 @@ export const Constants = {
"Variance",
"Total",
],
- customRuleTargetType: ["item", "storageUnit", "workCenter"],
deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],
demandForecastSourceType: [
"Job Material",
@@ -67170,6 +67109,7 @@ export const Constants = {
shippingCarrier: ["UPS", "FedEx", "USPS", "DHL", "Other"],
sourcingType: ["Specified", "Drop Ship", "Ship from Inventory"],
stockTransferStatus: ["Draft", "Released", "In Progress", "Completed"],
+ storageRuleTargetType: ["item", "workCenter"],
supplierLedgerDocumentType: [
"Payment",
"Invoice",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 4683974109..268104fc57 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -6615,533 +6615,6 @@ export type Database = {
}
Relationships: []
}
- customRule: {
- 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"]["customRuleTargetType"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- active?: boolean
- appliesToAll?: boolean
- companyId: string
- conditionAst: Json
- createdAt?: string
- createdBy: string
- customFields?: Json | null
- description?: string | null
- filteredItemGroupIds?: string[]
- filteredItemMatchAll?: boolean
- filteredItemTypes?: string[]
- id?: string
- message: string
- name: string
- severity: string
- surfaces?: Database["public"]["Enums"]["transactionSurface"][]
- targetType?: Database["public"]["Enums"]["customRuleTargetType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- active?: boolean
- appliesToAll?: boolean
- companyId?: string
- conditionAst?: Json
- createdAt?: string
- createdBy?: string
- customFields?: Json | null
- description?: string | null
- filteredItemGroupIds?: string[]
- filteredItemMatchAll?: boolean
- filteredItemTypes?: string[]
- id?: string
- message?: string
- name?: string
- severity?: string
- surfaces?: Database["public"]["Enums"]["transactionSurface"][]
- targetType?: Database["public"]["Enums"]["customRuleTargetType"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRule_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRule_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- customRuleItemAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- itemId: string
- ruleId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- itemId: string
- ruleId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- itemId?: string
- ruleId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "consumables"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "materials"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "parts"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "services"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "tools"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleItemAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- ]
- }
- customRuleStorageUnitAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- ruleId: string
- storageUnitId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- ruleId: string
- storageUnitId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- ruleId?: string
- storageUnitId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleStorageUnitAssignment_storageUnitId_fkey"
- columns: ["storageUnitId"]
- isOneToOne: false
- referencedRelation: "storageUnit"
- referencedColumns: ["id"]
- },
- ]
- }
- customRuleWorkCenterAssignment: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- ruleId: string
- workCenterId: string
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- ruleId: string
- workCenterId: string
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- ruleId?: string
- workCenterId?: string
- }
- Relationships: [
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"
- columns: ["ruleId"]
- isOneToOne: false
- referencedRelation: "customRule"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "riskRegisters"
- referencedColumns: ["workCenterId"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenter"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenters"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCentersWithBlockingStatus"
- referencedColumns: ["id"]
- },
- ]
- }
demandActual: {
Row: {
actualQuantity: number
@@ -38714,6 +38187,48 @@ export type Database = {
},
]
}
+ searchIndex_MvZGQSEAkgLUthUCevNd2m: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -40856,6 +40371,431 @@ 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: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ storageRuleItemAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ itemId: string
+ ruleId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ itemId: string
+ ruleId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ itemId?: string
+ ruleId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleItemAssignment_ruleId_fkey"
+ columns: ["ruleId"]
+ isOneToOne: false
+ referencedRelation: "storageRule"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ storageRuleWorkCenterAssignment: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ ruleId: string
+ workCenterId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ ruleId: string
+ workCenterId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ ruleId?: string
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_ruleId_fkey"
+ columns: ["ruleId"]
+ isOneToOne: false
+ referencedRelation: "storageRule"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "riskRegisters"
+ referencedColumns: ["workCenterId"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customRuleWorkCenterAssignment_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
storageType: {
Row: {
companyId: string
@@ -54337,14 +54277,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -55840,14 +55780,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -59278,13 +59218,6 @@ export type Database = {
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
- {
- foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
- isOneToOne: false
- referencedRelation: "country"
- referencedColumns: ["alpha2"]
- },
{
foreignKeyName: "address_countryCode_fkey"
columns: ["invoiceCountryCode"]
@@ -59294,7 +59227,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65368,7 +65301,6 @@ export type Database = {
| "Indirect Cost"
| "Variance"
| "Total"
- customRuleTargetType: "item" | "storageUnit" | "workCenter"
deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"
demandForecastSourceType:
| "Job Material"
@@ -65859,6 +65791,7 @@ export type Database = {
shippingCarrier: "UPS" | "FedEx" | "USPS" | "DHL" | "Other"
sourcingType: "Specified" | "Drop Ship" | "Ship from Inventory"
stockTransferStatus: "Draft" | "Released" | "In Progress" | "Completed"
+ storageRuleTargetType: "item" | "workCenter"
supplierLedgerDocumentType:
| "Payment"
| "Invoice"
@@ -66640,7 +66573,6 @@ export const Constants = {
"Variance",
"Total",
],
- customRuleTargetType: ["item", "storageUnit", "workCenter"],
deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],
demandForecastSourceType: [
"Job Material",
@@ -67177,6 +67109,7 @@ export const Constants = {
shippingCarrier: ["UPS", "FedEx", "USPS", "DHL", "Other"],
sourcingType: ["Specified", "Drop Ship", "Ship from Inventory"],
stockTransferStatus: ["Draft", "Released", "In Progress", "Completed"],
+ storageRuleTargetType: ["item", "workCenter"],
supplierLedgerDocumentType: [
"Payment",
"Invoice",
diff --git a/packages/database/supabase/migrations/20260603120000_remove-storage-unit-rules.sql b/packages/database/supabase/migrations/20260603120000_remove-storage-unit-rules.sql
new file mode 100644
index 0000000000..3cb9b58ca3
--- /dev/null
+++ b/packages/database/supabase/migrations/20260603120000_remove-storage-unit-rules.sql
@@ -0,0 +1,24 @@
+-- Custom Rules: remove the `storageUnit` target type.
+--
+-- Bin-level `place`/`pick` guards are now owned by item-target rules (which
+-- already expose the `storageUnit.*` context fields), so storage-unit rules are
+-- redundant. The feature is new, so existing storage-unit rules are DELETED
+-- rather than migrated.
+
+-- 1. Drop existing storage-unit rules. FK cascade clears their assignment rows
+-- in customRuleStorageUnitAssignment.
+DELETE FROM "customRule" WHERE "targetType" = 'storageUnit';
+
+-- 2. Drop the storage-unit assignment table (its RLS policies drop with it).
+DROP TABLE "customRuleStorageUnitAssignment";
+
+-- 3. Recreate the target-type enum without 'storageUnit'. Postgres can't drop a
+-- value from an enum in place, so swap the column onto a fresh type.
+ALTER TABLE "customRule" ALTER COLUMN "targetType" DROP DEFAULT;
+ALTER TYPE "customRuleTargetType" RENAME TO "customRuleTargetType_old";
+CREATE TYPE "customRuleTargetType" AS ENUM ('item', 'workCenter');
+ALTER TABLE "customRule"
+ ALTER COLUMN "targetType" TYPE "customRuleTargetType"
+ USING "targetType"::text::"customRuleTargetType";
+ALTER TABLE "customRule" ALTER COLUMN "targetType" SET DEFAULT 'item';
+DROP TYPE "customRuleTargetType_old";
diff --git a/packages/database/supabase/migrations/20260603130000_rename-custom-rule-to-storage-rule.sql b/packages/database/supabase/migrations/20260603130000_rename-custom-rule-to-storage-rule.sql
new file mode 100644
index 0000000000..dfc65b14d5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260603130000_rename-custom-rule-to-storage-rule.sql
@@ -0,0 +1,30 @@
+-- Rename the Custom Rules feature to Storage Rules (now lives in the Inventory
+-- module). Table/enum/customField rename only — the column set is unchanged.
+--
+-- Constraint and index names keep their legacy `customRule*` prefix: they are
+-- internal identifiers never referenced by application code, and renaming them
+-- adds churn + failure surface for no functional gain.
+
+----------------------------------------------------------------------
+-- Core rule table
+----------------------------------------------------------------------
+ALTER TABLE "customRule" RENAME TO "storageRule";
+
+----------------------------------------------------------------------
+-- Assignment tables (storageUnit assignment table was already dropped)
+----------------------------------------------------------------------
+ALTER TABLE "customRuleItemAssignment" RENAME TO "storageRuleItemAssignment";
+ALTER TABLE "customRuleWorkCenterAssignment" RENAME TO "storageRuleWorkCenterAssignment";
+
+----------------------------------------------------------------------
+-- Target-type enum
+----------------------------------------------------------------------
+ALTER TYPE "customRuleTargetType" RENAME TO "storageRuleTargetType";
+
+----------------------------------------------------------------------
+-- Custom field table registration
+----------------------------------------------------------------------
+UPDATE "customFieldTable"
+ SET "table" = 'storageRule',
+ "name" = 'Storage Rule'
+ WHERE "table" = 'customRule';
diff --git a/packages/database/supabase/migrations/20260603140000_storage-rules-inventory-rls.sql b/packages/database/supabase/migrations/20260603140000_storage-rules-inventory-rls.sql
new file mode 100644
index 0000000000..2d0f588f65
--- /dev/null
+++ b/packages/database/supabase/migrations/20260603140000_storage-rules-inventory-rls.sql
@@ -0,0 +1,40 @@
+-- Storage Rules admin lives in the Inventory module. Move the `storageRule`
+-- RLS off settings_* onto inventory_*.
+--
+-- SELECT is widened to any company employee (mirrors the assignment tables) so
+-- the per-item / per-work-center assignment drawers in other modules can still
+-- read rule metadata regardless of the reader's module permissions. Mutations
+-- require inventory_*, matching the relocated admin pages.
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."storageRule";
+DROP POLICY IF EXISTS "INSERT" ON "public"."storageRule";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."storageRule";
+DROP POLICY IF EXISTS "DELETE" ON "public"."storageRule";
+
+CREATE POLICY "SELECT" ON "public"."storageRule"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."storageRule"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_create'))::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."storageRule"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_update'))::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."storageRule"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('inventory_delete'))::text[]
+ )
+);
diff --git a/packages/database/supabase/migrations/20260603150000_rename-storage-rule-constraints.sql b/packages/database/supabase/migrations/20260603150000_rename-storage-rule-constraints.sql
new file mode 100644
index 0000000000..961bb3dcf1
--- /dev/null
+++ b/packages/database/supabase/migrations/20260603150000_rename-storage-rule-constraints.sql
@@ -0,0 +1,45 @@
+-- Cosmetic: rename the constraints + indexes left with the legacy `customRule*`
+-- prefix after the table rename (Postgres keeps constraint/index names across an
+-- ALTER TABLE ... RENAME). Internal identifiers only — no app code references
+-- them; this just keeps the schema self-consistent.
+
+----------------------------------------------------------------------
+-- storageRule (was customRule)
+----------------------------------------------------------------------
+ALTER TABLE "storageRule" RENAME CONSTRAINT "customRule_companyId_fkey" TO "storageRule_companyId_fkey";
+ALTER TABLE "storageRule" RENAME CONSTRAINT "customRule_createdBy_fkey" TO "storageRule_createdBy_fkey";
+ALTER TABLE "storageRule" RENAME CONSTRAINT "customRule_updatedBy_fkey" TO "storageRule_updatedBy_fkey";
+ALTER TABLE "storageRule" RENAME CONSTRAINT "customRule_companyId_name_key" TO "storageRule_companyId_name_key";
+ALTER TABLE "storageRule" RENAME CONSTRAINT "customRule_surfaces_nonempty" TO "storageRule_surfaces_nonempty";
+
+ALTER INDEX IF EXISTS "customRule_companyId_idx" RENAME TO "storageRule_companyId_idx";
+ALTER INDEX IF EXISTS "customRule_companyId_active_partial_idx" RENAME TO "storageRule_companyId_active_partial_idx";
+ALTER INDEX IF EXISTS "customRule_companyId_targetType_active_idx" RENAME TO "storageRule_companyId_targetType_active_idx";
+
+----------------------------------------------------------------------
+-- storageRuleItemAssignment (was customRuleItemAssignment)
+----------------------------------------------------------------------
+ALTER TABLE "storageRuleItemAssignment" RENAME CONSTRAINT "customRuleItemAssignment_pkey" TO "storageRuleItemAssignment_pkey";
+ALTER TABLE "storageRuleItemAssignment" RENAME CONSTRAINT "customRuleItemAssignment_itemId_fkey" TO "storageRuleItemAssignment_itemId_fkey";
+ALTER TABLE "storageRuleItemAssignment" RENAME CONSTRAINT "customRuleItemAssignment_ruleId_fkey" TO "storageRuleItemAssignment_ruleId_fkey";
+ALTER TABLE "storageRuleItemAssignment" RENAME CONSTRAINT "customRuleItemAssignment_companyId_fkey" TO "storageRuleItemAssignment_companyId_fkey";
+ALTER TABLE "storageRuleItemAssignment" RENAME CONSTRAINT "customRuleItemAssignment_createdBy_fkey" TO "storageRuleItemAssignment_createdBy_fkey";
+
+ALTER INDEX IF EXISTS "customRuleItemAssignment_itemId_idx" RENAME TO "storageRuleItemAssignment_itemId_idx";
+ALTER INDEX IF EXISTS "customRuleItemAssignment_ruleId_idx" RENAME TO "storageRuleItemAssignment_ruleId_idx";
+ALTER INDEX IF EXISTS "customRuleItemAssignment_companyId_idx" RENAME TO "storageRuleItemAssignment_companyId_idx";
+ALTER INDEX IF EXISTS "customRuleItemAssignment_itemId_companyId_idx" RENAME TO "storageRuleItemAssignment_itemId_companyId_idx";
+
+----------------------------------------------------------------------
+-- storageRuleWorkCenterAssignment (was customRuleWorkCenterAssignment)
+----------------------------------------------------------------------
+ALTER TABLE "storageRuleWorkCenterAssignment" RENAME CONSTRAINT "customRuleWorkCenterAssignment_pkey" TO "storageRuleWorkCenterAssignment_pkey";
+ALTER TABLE "storageRuleWorkCenterAssignment" RENAME CONSTRAINT "customRuleWorkCenterAssignment_workCenterId_fkey" TO "storageRuleWorkCenterAssignment_workCenterId_fkey";
+ALTER TABLE "storageRuleWorkCenterAssignment" RENAME CONSTRAINT "customRuleWorkCenterAssignment_ruleId_fkey" TO "storageRuleWorkCenterAssignment_ruleId_fkey";
+ALTER TABLE "storageRuleWorkCenterAssignment" RENAME CONSTRAINT "customRuleWorkCenterAssignment_companyId_fkey" TO "storageRuleWorkCenterAssignment_companyId_fkey";
+ALTER TABLE "storageRuleWorkCenterAssignment" RENAME CONSTRAINT "customRuleWorkCenterAssignment_createdBy_fkey" TO "storageRuleWorkCenterAssignment_createdBy_fkey";
+
+ALTER INDEX IF EXISTS "customRuleWorkCenterAssignment_workCenterId_idx" RENAME TO "storageRuleWorkCenterAssignment_workCenterId_idx";
+ALTER INDEX IF EXISTS "customRuleWorkCenterAssignment_ruleId_idx" RENAME TO "storageRuleWorkCenterAssignment_ruleId_idx";
+ALTER INDEX IF EXISTS "customRuleWorkCenterAssignment_companyId_idx" RENAME TO "storageRuleWorkCenterAssignment_companyId_idx";
+ALTER INDEX IF EXISTS "customRuleWorkCenterAssignment_workCenterId_companyId_idx" RENAME TO "storageRuleWorkCenterAssignment_workCenterId_companyId_idx";
diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.ts
index 83156f2c99..d29d15e63e 100644
--- a/packages/dev/src/commands/migrate.ts
+++ b/packages/dev/src/commands/migrate.ts
@@ -12,7 +12,7 @@ import { getWorktreeRoot } from "../worktree.js";
// `crbn up`). Bare `pnpm db:migrate` resolves dotenv relative to cwd and falls
// through to the supabase CLI's linked-project path — `crbn migrate` removes
// that footgun by always targeting the current worktree's DB.
-export async function migrate(opts: { regen?: boolean; force?: boolean } = {}) {
+export async function migrate(opts: { regen?: boolean } = {}) {
const shouldRegen = opts.regen ?? true;
intro("Carbon · dev migrate");
@@ -53,9 +53,7 @@ export async function migrate(opts: { regen?: boolean; force?: boolean } = {}) {
{
title: "Apply database migrations",
task: async () => {
- const r = await applyMigrations(root, portDb, {
- force: opts.force ?? false
- });
+ const r = await applyMigrations(root, portDb);
applied = r.applied;
return r.applied ? "migrations applied" : "schema already up to date";
}
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index dec917a433..2791bcf309 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -92,11 +92,11 @@ const main = defineCommand({
type: "boolean",
default: false,
description:
- "Escalate stale-migration repair via `supabase migration repair --status reverted`"
+ "Schema unreconcilable? Wipe the stack's volumes and re-provision from scratch (prompts to confirm)"
}
},
run: ({ args }) =>
- migrate({ regen: args.regen !== false, force: !!args.force })
+ args.force ? reset() : migrate({ regen: args.regen !== false })
}),
new: defineCommand({
meta: { description: "Interactive: create a worktree on a fresh branch" },
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index a0f3156c7f..425ceee7f1 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -130,8 +130,7 @@ export async function applyBootstrapSql(root: string, port: number) {
// `supabase_migrations.schema_migrations` as `postgres`.
export async function applyMigrations(
root: string,
- dbPort: number,
- opts: { force?: boolean } = {}
+ dbPort: number
): Promise<{ applied: boolean }> {
const dbUrl = `postgresql://supabase_admin:postgres@localhost:${dbPort}/postgres`;
const args = ["migration", "up", "--include-all", "--db-url", dbUrl];
@@ -145,18 +144,8 @@ export async function applyMigrations(
const output = `${r.stderr ?? ""}\n${r.stdout ?? ""}`;
// Auto-repair: DB has migration versions not present locally (stale from
// another branch or incomplete volume wipe). Remove them and retry.
- //
- // Default path diffs local files vs schema_migrations and DELETEs the
- // orphans. --force instead parses the version(s) supabase itself names in
- // its error and runs `migration repair --status reverted` on them — this
- // catches rows the readdir diff misses (e.g. a migration whose timestamp
- // isn't supabase's required 14 digits, which the CLI ignores as a local
- // file while our diff still counts it as present).
if (/remote migration versions not found in local/i.test(output)) {
- const repaired =
- (opts.force ?? false)
- ? await forceRepairMigrations(root, dbPort, output)
- : await repairStaleMigrations(root, dbPort);
+ const repaired = await repairStaleMigrations(root, dbPort);
if (repaired > 0) {
log.warn(`repaired ${repaired} stale migration(s) — retrying`);
const retry = await execa("supabase", args, {
@@ -228,49 +217,6 @@ async function repairStaleMigrations(
return stale.length;
}
-// --force escalation. supabase's "remote migration versions not found in local"
-// error prints the exact recovery command it wants — e.g.
-// `supabase migration repair --status reverted 20260515`. Parse those
-// version(s) out and run that command verbatim (with --db-url), then let the
-// caller retry `migration up`. Unlike repairStaleMigrations this trusts
-// supabase's own view, so it repairs orphans the readdir diff can't see.
-async function forceRepairMigrations(
- root: string,
- dbPort: number,
- supabaseOutput: string
-): Promise<number> {
- const m = supabaseOutput.match(
- /migration repair --status reverted ([0-9 ]+)/
- );
- const versions = m?.[1]?.trim().split(/\s+/).filter(Boolean) ?? [];
- if (versions.length === 0) return 0;
-
- const dbUrl = `postgresql://supabase_admin:postgres@localhost:${dbPort}/postgres`;
- const cwd = join(root, "packages/database");
- log.warn(
- `--force: supabase migration repair --status reverted ${versions.join(" ")}`
- );
- const r = await execa(
- "supabase",
- [
- "migration",
- "repair",
- "--status",
- "reverted",
- ...versions,
- "--db-url",
- dbUrl
- ],
- { cwd, reject: false, preferLocal: true }
- );
- if (r.exitCode !== 0) {
- process.stderr.write(r.stderr?.toString() ?? "");
- process.stdout.write(r.stdout?.toString() ?? "");
- throw new Error(`supabase migration repair failed (exit ${r.exitCode})`);
- }
- return versions.length;
-}
-
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
diff --git a/packages/ee/package.json b/packages/ee/package.json
index da4414b1ca..7fe856fc2e 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -5,8 +5,8 @@
"exports": {
".": "./src/index.ts",
"./accounting": "./src/accounting/index.ts",
- "./custom-rules": "./src/customRules/index.ts",
- "./custom-rules.server": "./src/customRules/server.ts",
+ "./storage-rules": "./src/storageRules/index.ts",
+ "./storage-rules.server": "./src/storageRules/server.ts",
"./exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
"./jira": "./src/jira/lib/index.ts",
"./jira.server": "./src/jira/lib/index.server.ts",
diff --git a/packages/ee/src/customRules/index.ts b/packages/ee/src/customRules/index.ts
deleted file mode 100644
index 90b4de21e2..0000000000
--- a/packages/ee/src/customRules/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// Public exports for cross-app consumers (ERP + MES).
-export * from "./service";
-export {
- type CustomRuleViolationPayload,
- useCustomRuleViolations
-} from "./use-violations";
-export { default as CustomRuleViolationModal } from "./violation-modal";
diff --git a/packages/ee/src/plan.ts b/packages/ee/src/plan.ts
index af8ae7b08e..6698203e31 100644
--- a/packages/ee/src/plan.ts
+++ b/packages/ee/src/plan.ts
@@ -12,7 +12,7 @@ export const FEATURE_PLANS = {
ITEM_RULES: [Plan.Business, Plan.Partner],
AUDIT_LOG: [Plan.Business, Plan.Partner],
EMAIL_NOTIFICATIONS: [Plan.Business, Plan.Partner],
- CUSTOM_RULES: [Plan.Business, Plan.Partner]
+ STORAGE_RULES: [Plan.Business, Plan.Partner]
} as const satisfies Record<string, Plan[]>;
export type Feature = keyof typeof FEATURE_PLANS;
diff --git a/packages/ee/src/customRules/context.test.ts b/packages/ee/src/storageRules/context.test.ts
similarity index 97%
rename from packages/ee/src/customRules/context.test.ts
rename to packages/ee/src/storageRules/context.test.ts
index 831d3d75cb..80d612b5a6 100644
--- a/packages/ee/src/customRules/context.test.ts
+++ b/packages/ee/src/storageRules/context.test.ts
@@ -44,8 +44,7 @@ const WORKCENTER_ROW = { id: "wc_1", locationId: "loc_1", active: true };
const ctxRootKeyFor = (context: FieldContext): string =>
context === "storage" ? "storageUnit" : context;
-// targetTypes a surface belongs to (a surface can serve several, e.g.
-// stockTransfer → item + storageUnit).
+// targetTypes a surface belongs to (item surfaces vs workCenter surfaces).
const targetTypesForSurface = (surface: TransactionSurface): TargetType[] =>
TARGET_TYPES.filter((tt) => SURFACES_BY_TARGET_TYPE[tt].includes(surface));
diff --git a/packages/ee/src/customRules/context.ts b/packages/ee/src/storageRules/context.ts
similarity index 97%
rename from packages/ee/src/customRules/context.ts
rename to packages/ee/src/storageRules/context.ts
index c97dcee094..b8b99b34da 100644
--- a/packages/ee/src/customRules/context.ts
+++ b/packages/ee/src/storageRules/context.ts
@@ -1,4 +1,4 @@
-// Pure RuleContext assembly for custom-rules evaluation. Deliberately
+// Pure RuleContext assembly for storage-rules evaluation. 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 `buildLineContext` with the rows it loaded.
diff --git a/packages/ee/src/storageRules/index.ts b/packages/ee/src/storageRules/index.ts
new file mode 100644
index 0000000000..2245cc8c73
--- /dev/null
+++ b/packages/ee/src/storageRules/index.ts
@@ -0,0 +1,7 @@
+// 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/ee/src/customRules/server.ts b/packages/ee/src/storageRules/server.ts
similarity index 87%
rename from packages/ee/src/customRules/server.ts
rename to packages/ee/src/storageRules/server.ts
index a34cb82e97..99ad602913 100644
--- a/packages/ee/src/customRules/server.ts
+++ b/packages/ee/src/storageRules/server.ts
@@ -1,5 +1,5 @@
-// Server-side custom-rules evaluator. Cross-app entry point — ERP
-// (item/storageUnit surfaces) and MES (workCenter surfaces) both call
+// Server-side storage-rules evaluator. Cross-app entry point — ERP
+// (item surfaces) and MES (workCenter surfaces) both call
// `evaluateLinesForSurface`.
//
// All functions here are server-only. Never import from a client module.
@@ -32,8 +32,8 @@ import {
} from "./context";
import {
getActiveRulesForTargets,
- getCustomRulesList,
- getRuleAssignmentsForTarget
+ getRuleAssignmentsForTarget,
+ getStorageRulesList
} from "./service";
type Client = SupabaseClient<Database>;
@@ -42,11 +42,11 @@ type Client = SupabaseClient<Database>;
// Plan gate
// ---------------------------------------------------------------------------
-export const isCustomRulesEnabledForCompany = (
+export const isStorageRulesEnabledForCompany = (
client: Client,
companyId: string
): Promise<boolean> =>
- companyHasPlan(client, companyId, { feature: "CUSTOM_RULES" });
+ companyHasPlan(client, companyId, { feature: "STORAGE_RULES" });
// ---------------------------------------------------------------------------
// Block decision
@@ -96,13 +96,13 @@ type AssignedRuleNode = {
appliesToAll: boolean;
};
-export async function getCustomRulesDataForTarget(
+export async function getStorageRulesDataForTarget(
client: Client,
args: { targetType: TargetType; targetId: string; companyId: string }
) {
const [assignmentsRes, libraryRes] = await Promise.all([
getRuleAssignmentsForTarget(client, args),
- getCustomRulesList(client, args.companyId, args.targetType)
+ getStorageRulesList(client, args.companyId, args.targetType)
]);
// Forward inheritance metadata so the drawer can tag inherited rows.
@@ -113,7 +113,7 @@ export async function getCustomRulesDataForTarget(
inheritedFromName: string | null;
}[] = [];
for (const row of assignmentsRes.data ?? []) {
- const joined = row.customRule as
+ const joined = row.storageRule as
| AssignedRuleNode
| AssignedRuleNode[]
| null;
@@ -280,9 +280,10 @@ export type EvaluateLinesForSurfaceArgs = {
companyId: string;
userId: string;
/**
- * Which targetType the call is evaluating. Surfaces that apply to multiple
- * targetTypes (e.g. `stockTransfer`) require one call per targetType — the
- * caller concatenates and `dedupeViolations`-es results.
+ * Which targetType the call is evaluating (`item` for ERP inventory
+ * surfaces, `workCenter` for MES). A caller running more than one surface
+ * (e.g. a receipt's `receipt` + `place` passes) concatenates and
+ * `dedupeViolations`-es the results.
*/
targetType: TargetType;
surface: TransactionSurface;
@@ -306,8 +307,6 @@ const lineTargetIdFor = (
switch (targetType) {
case "item":
return line.itemId ?? null;
- case "storageUnit":
- return line.storageUnitId ?? null;
case "workCenter":
return line.workCenterId ?? null;
}
@@ -322,7 +321,7 @@ export async function evaluateLinesForSurface({
lines
}: EvaluateLinesForSurfaceArgs): Promise<EvaluateLinesForSurfaceResult> {
if (lines.length === 0) return EMPTY_RESULT;
- if (!(await isCustomRulesEnabledForCompany(client, companyId)))
+ if (!(await isStorageRulesEnabledForCompany(client, companyId)))
return EMPTY_RESULT;
const targetIds = new Set<string>();
@@ -342,19 +341,14 @@ export async function evaluateLinesForSurface({
// Explicit-assignment lookup short-circuits inside `getActiveRulesForTargets`
// when targetIds is empty.
- // Walk the storage-unit tree for every line that carries a bin id. Two
- // inheritance behaviours hang off this fetch:
- // 1. Rules assigned to a parent bin (e.g. "Grow Room") fire on every
- // descendant — expand the rule-assignment lookup set with each line
- // bin's ancestorPath.
- // 2. Storage types cascade: a child bin implicitly carries every
- // `storageTypeIds` declared on itself OR any ancestor. The evaluator
- // unions them when populating `ctx.storageUnit.storageTypeId` below.
- // One round-trip; selects `storageTypeIds` so the union doesn't need a
- // second fetch.
+ // 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
+ // `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[]>();
const storageTypesByBin = new Map<string, string[]>();
- let expandedTargetIds: string[] = Array.from(targetIds);
if (storageUnitIds.size > 0) {
const ids = Array.from(storageUnitIds);
const ancestorsRes = await (client as Client)
@@ -363,7 +357,6 @@ export async function evaluateLinesForSurface({
.in("id", ids)
.eq("companyId", companyId);
- const expanded = new Set<string>(ids);
const ancestorIds = new Set<string>();
for (const row of (ancestorsRes.data ?? []) as Array<{
id: string;
@@ -376,10 +369,7 @@ export async function evaluateLinesForSurface({
: [row.id];
ancestorsByBin.set(row.id, chain);
if (row.storageTypeIds) storageTypesByBin.set(row.id, row.storageTypeIds);
- for (const a of chain) {
- expanded.add(a);
- ancestorIds.add(a);
- }
+ for (const a of chain) ancestorIds.add(a);
}
for (const id of ids) {
if (!ancestorsByBin.has(id)) ancestorsByBin.set(id, [id]);
@@ -405,12 +395,6 @@ export async function evaluateLinesForSurface({
storageTypesByBin.set(row.id, row.storageTypeIds);
}
}
-
- // Only the storageUnit-target rule lookup uses the expanded set; item /
- // workCenter rule queries still scope to their own target ids.
- if (targetType === "storageUnit") {
- expandedTargetIds = Array.from(expanded);
- }
}
const [itemsRes, storageUnitsRes, workCentersRes, compiled] =
@@ -439,7 +423,7 @@ export async function evaluateLinesForSurface({
: Promise.resolve({ data: [], error: null }),
loadCompiledRulesForTargets(client, {
targetType,
- targetIds: expandedTargetIds,
+ targetIds: Array.from(targetIds),
companyId
})
]);
@@ -506,32 +490,19 @@ export async function evaluateLinesForSurface({
for (const line of lines) {
const targetId = lineTargetIdFor(line, targetType);
- // Per-line compiled rule set: explicit assignments (target-keyed, with
- // ancestor inheritance for storageUnit) + broadcasts. Lines without a
- // targetId of this targetType still match broadcasts.
+ // Per-line compiled rule set: explicit assignments (target-keyed) +
+ // broadcasts. Lines without a targetId of this targetType still match
+ // broadcasts.
const seen = new Set<string>();
const compiledForLine: CompiledRule[] = [];
if (targetId) {
- if (targetType === "storageUnit") {
- const chain = ancestorsByBin.get(targetId) ?? [targetId];
- for (const ancestorId of chain) {
- const rules = compiledByTarget.get(ancestorId);
- if (!rules) continue;
- for (const r of rules) {
- if (seen.has(r.id)) continue;
- seen.add(r.id);
- compiledForLine.push(r);
- }
- }
- } else {
- const rules = compiledByTarget.get(targetId);
- if (rules) {
- for (const r of rules) {
- if (seen.has(r.id)) continue;
- seen.add(r.id);
- compiledForLine.push(r);
- }
+ const rules = compiledByTarget.get(targetId);
+ if (rules) {
+ for (const r of rules) {
+ if (seen.has(r.id)) continue;
+ seen.add(r.id);
+ compiledForLine.push(r);
}
}
}
@@ -587,7 +558,7 @@ export async function evaluateLinesForSurface({
for (let i = 0; i < deduped.length; i++) violatedIds.add(deduped[i]!.ruleId);
const { data: namedRules } = await client
- .from("customRule")
+ .from("storageRule")
.select("id, name")
.in("id", Array.from(violatedIds))
.eq("companyId", companyId);
diff --git a/packages/ee/src/customRules/service.ts b/packages/ee/src/storageRules/service.ts
similarity index 73%
rename from packages/ee/src/customRules/service.ts
rename to packages/ee/src/storageRules/service.ts
index 7eccc7a7d7..58ffb4b6ce 100644
--- a/packages/ee/src/customRules/service.ts
+++ b/packages/ee/src/storageRules/service.ts
@@ -8,10 +8,10 @@
import type { Database } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import {
- type CustomRuleRow,
type ItemRuleFilter,
itemRuleAppliesToItem,
type Severity,
+ type StorageRuleRow,
type TargetType,
type TransactionSurface,
toItemRuleFilter
@@ -34,35 +34,28 @@ type ItemFilterColumns = {
const assignmentTableFor = (
targetType: TargetType
-):
- | "customRuleItemAssignment"
- | "customRuleStorageUnitAssignment"
- | "customRuleWorkCenterAssignment" => {
+): "storageRuleItemAssignment" | "storageRuleWorkCenterAssignment" => {
switch (targetType) {
case "item":
- return "customRuleItemAssignment";
- case "storageUnit":
- return "customRuleStorageUnitAssignment";
+ return "storageRuleItemAssignment";
case "workCenter":
- return "customRuleWorkCenterAssignment";
+ return "storageRuleWorkCenterAssignment";
}
};
const targetIdColumnFor = (
targetType: TargetType
-): "itemId" | "storageUnitId" | "workCenterId" => {
+): "itemId" | "workCenterId" => {
switch (targetType) {
case "item":
return "itemId";
- case "storageUnit":
- return "storageUnitId";
case "workCenter":
return "workCenterId";
}
};
type RuleRowSelect = Pick<
- CustomRuleRow,
+ StorageRuleRow,
| "id"
| "targetType"
| "severity"
@@ -82,7 +75,7 @@ type RuleRowSelect = Pick<
* - item targets: EVERY active item rule broadcasts, then the caller gates it
* per line via the rule's `filteredItem*` filters (see `broadcastFilters`);
* empty filters = every item.
- * - storageUnit / workCenter targets: rules with `appliesToAll = TRUE` only.
+ * - workCenter targets: rules with `appliesToAll = TRUE` only.
*
* `broadcastFilters` maps ruleId → item type/group filter (item targets only).
*
@@ -98,12 +91,12 @@ export async function getActiveRulesForTargets(
companyId: string;
}
): Promise<{
- data: Map<string, CustomRuleRow[]>;
- broadcasts: CustomRuleRow[];
+ data: Map<string, StorageRuleRow[]>;
+ broadcasts: StorageRuleRow[];
broadcastFilters: Map<string, ItemRuleFilter>;
error: unknown;
}> {
- const out = new Map<string, CustomRuleRow[]>();
+ const out = new Map<string, StorageRuleRow[]>();
const broadcastFilters = new Map<string, ItemRuleFilter>();
const ruleCols =
@@ -120,7 +113,7 @@ export async function getActiveRulesForTargets(
const idCol = targetIdColumnFor(args.targetType);
const broadcastBase = client
- .from("customRule")
+ .from("storageRule")
.select(broadcastCols)
.eq("companyId", args.companyId)
.eq("targetType", args.targetType)
@@ -130,7 +123,7 @@ export async function getActiveRulesForTargets(
args.targetIds.length > 0
? (client as SupabaseClient<Database>)
.from(table)
- .select(`${idCol}, customRule:ruleId(${ruleCols})`)
+ .select(`${idCol}, storageRule:ruleId(${ruleCols})`)
.in(idCol, args.targetIds)
.eq("companyId", args.companyId)
: Promise.resolve({ data: [], error: null }),
@@ -156,22 +149,22 @@ export async function getActiveRulesForTargets(
for (const r of explicit.data ?? []) {
const row = r as unknown as {
[k: string]: unknown;
- customRule: RuleRowSelect | RuleRowSelect[] | null;
+ storageRule: RuleRowSelect | RuleRowSelect[] | null;
};
const targetId = row[idCol] as string;
- const node = Array.isArray(row.customRule)
- ? row.customRule[0]
- : row.customRule;
+ 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 CustomRuleRow);
- else out.set(targetId, [node as CustomRuleRow]);
+ 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
// row type to `GenericStringError`, which doesn't overlap our explicit shape.
- const broadcasts = (broadcast.data ?? []) as unknown as (CustomRuleRow &
+ const broadcasts = (broadcast.data ?? []) as unknown as (StorageRuleRow &
ItemFilterColumns)[];
if (isItem) {
@@ -184,17 +177,17 @@ export async function getActiveRulesForTargets(
}
/**
- * Loader-style row returned from `getRuleAssignmentsForTarget`. Adds
- * `inheritedFromId` / `inheritedFromName` so the UI can label rules that
- * came from an ancestor unit (storageUnit hierarchy only) and disable
- * unassign on those rows.
+ * Loader-style row returned from `getRuleAssignmentsForTarget`. Direct
+ * assignments leave `inheritedFromId` / `inheritedFromName` null; broadcast
+ * rules use the `__all__` sentinel so the UI can render an "Applies to all"
+ * badge and suppress unassign.
*/
export type RuleAssignmentRow = {
/** Owner of the assignment row (this target id, or an ancestor unit id). */
ownerId: string;
ruleId: string;
createdAt: string | null;
- customRule: {
+ storageRule: {
id: string;
name: string;
targetType: TargetType;
@@ -216,9 +209,8 @@ export async function getRuleAssignmentsForTarget(
const table = assignmentTableFor(args.targetType);
const idCol = targetIdColumnFor(args.targetType);
- // Storage units inherit assignments from every ancestor in the tree.
- // Item / workCenter targets are flat — keep the simple direct query.
- const lookupIds = await resolveLookupIds(client, args);
+ // Item / workCenter targets are flat — a direct query on the target id.
+ const lookupIds = [args.targetId];
// Broadcast rules govern targets beyond explicit assignments. Surface them
// alongside explicit + inherited rows so the drawer shows the full set the
@@ -226,7 +218,7 @@ export async function getRuleAssignmentsForTarget(
// while broadcasts still triggered).
// - item: EVERY active item rule broadcasts, gated per item by its
// type/group filters (empty = all items) — mirrors the evaluator.
- // - storageUnit / workCenter: rules with `appliesToAll = TRUE`.
+ // - workCenter: rules with `appliesToAll = TRUE`.
const isItem = args.targetType === "item";
const baseBroadcastCols =
"id, name, targetType, severity, message, active, surfaces, appliesToAll, createdAt";
@@ -235,7 +227,7 @@ export async function getRuleAssignmentsForTarget(
? `${baseBroadcastCols}, ${ITEM_RULE_FILTER_COLUMNS}`
: baseBroadcastCols;
const broadcastBase = client
- .from("customRule")
+ .from("storageRule")
.select(broadcastCols)
.eq("companyId", args.companyId)
.eq("targetType", args.targetType);
@@ -244,7 +236,7 @@ export async function getRuleAssignmentsForTarget(
(client as SupabaseClient<Database>)
.from(table)
.select(
- `${idCol}, ruleId, createdAt, customRule:ruleId(id, name, targetType, severity, message, active, surfaces, appliesToAll)`
+ `${idCol}, ruleId, createdAt, storageRule:ruleId(id, name, targetType, severity, message, active, surfaces, appliesToAll)`
)
.in(idCol, lookupIds)
.eq("companyId", args.companyId),
@@ -278,64 +270,33 @@ export async function getRuleAssignmentsForTarget(
};
})();
- // Resolve ancestor names in one extra query so the UI doesn't need to
- // re-fetch. Only the storageUnit case can yield non-self owner ids.
- const inheritedOwnerIds = new Set<string>();
- for (const r of res.data ?? []) {
- const ownerId = (r as unknown as Record<string, unknown>)[idCol] as string;
- if (ownerId && ownerId !== args.targetId) inheritedOwnerIds.add(ownerId);
- }
-
- const ancestorNameById = new Map<string, string>();
- if (args.targetType === "storageUnit" && inheritedOwnerIds.size > 0) {
- const namesRes = await client
- .from("storageUnit")
- .select("id, name")
- .in("id", Array.from(inheritedOwnerIds))
- .eq("companyId", args.companyId);
- for (const row of (namesRes.data ?? []) as Array<{
- id: string;
- name: string;
- }>) {
- ancestorNameById.set(row.id, row.name);
- }
- }
-
- // Dedupe: if the same rule is assigned to both self and an ancestor,
- // keep the direct row (so unassign UI operates on what the user owns).
+ // 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;
- customRule:
- | RuleAssignmentRow["customRule"]
- | RuleAssignmentRow["customRule"][]
+ storageRule:
+ | RuleAssignmentRow["storageRule"]
+ | RuleAssignmentRow["storageRule"][]
| null;
};
const ownerId = row[idCol] as string;
- const node = Array.isArray(row.customRule)
- ? row.customRule[0]
- : row.customRule;
+ const node = Array.isArray(row.storageRule)
+ ? row.storageRule[0]
+ : row.storageRule;
if (!node) continue;
- const isDirect = ownerId === args.targetId;
- const inheritedFromId = isDirect ? null : ownerId;
- const inheritedFromName = inheritedFromId
- ? (ancestorNameById.get(inheritedFromId) ?? null)
- : null;
-
const candidate: RuleAssignmentRow = {
ownerId,
ruleId: row.ruleId as string,
createdAt: (row.createdAt as string | null) ?? null,
- customRule: node,
- inheritedFromId,
- inheritedFromName
+ storageRule: node,
+ inheritedFromId: null,
+ inheritedFromName: null
};
- const existing = byRuleId.get(candidate.ruleId);
- // Prefer direct over inherited when both exist for the same rule.
- if (!existing || (existing.inheritedFromId && !candidate.inheritedFromId)) {
+ if (!byRuleId.has(candidate.ruleId)) {
byRuleId.set(candidate.ruleId, candidate);
}
}
@@ -378,7 +339,7 @@ export async function getRuleAssignmentsForTarget(
ownerId: "__all__",
ruleId: b.id,
createdAt: b.createdAt,
- customRule: {
+ storageRule: {
id: b.id,
name: b.name,
targetType: b.targetType,
@@ -396,33 +357,7 @@ export async function getRuleAssignmentsForTarget(
return { data: Array.from(byRuleId.values()), error: null };
}
-/**
- * Returns the set of unit ids to query assignments under. For storageUnit
- * targets this is the unit + every ancestor (so child drawer sees inherited
- * rules). For other targets it's just the target id.
- */
-async function resolveLookupIds(
- client: SupabaseClient<Database>,
- args: { targetType: TargetType; targetId: string; companyId: string }
-): Promise<string[]> {
- if (args.targetType !== "storageUnit") return [args.targetId];
-
- const { data } = await (client as SupabaseClient<Database>)
- .from("storageUnits_recursive")
- .select("ancestorPath")
- .eq("id", args.targetId)
- .eq("companyId", args.companyId)
- .maybeSingle();
-
- const row = data as { ancestorPath: string[] | null } | null;
- const chain =
- row?.ancestorPath && row.ancestorPath.length > 0
- ? row.ancestorPath
- : [args.targetId];
- return chain;
-}
-
-export async function getCustomRulesList(
+export async function getStorageRulesList(
client: SupabaseClient<Database>,
companyId: string,
targetType?: TargetType
@@ -437,7 +372,7 @@ export async function getCustomRulesList(
surfaces: TransactionSurface[];
}>(
client,
- "customRule",
+ "storageRule",
"id, name, targetType, severity, active, appliesToAll, surfaces",
(query) => {
let q = query.eq("companyId", companyId).order("name");
@@ -447,7 +382,7 @@ export async function getCustomRulesList(
);
}
-export async function assignCustomRule(
+export async function assignStorageRule(
client: SupabaseClient<Database>,
args: {
targetType: TargetType;
@@ -462,10 +397,10 @@ export async function assignCustomRule(
// Preflight: rule must exist in this company and its targetType must match
// the assignment table. Without this, callers could insert a storageUnit-rule
- // id into customRuleItemAssignment; the evaluator filters defensively but
+ // id into storageRuleItemAssignment; the evaluator filters defensively but
// the orphan row still inflates getRuleAssignmentCounts.
const ruleRes = await client
- .from("customRule")
+ .from("storageRule")
.select("id, targetType")
.eq("id", args.ruleId)
.eq("companyId", args.companyId)
@@ -497,7 +432,7 @@ export async function assignCustomRule(
.single();
}
-export async function unassignCustomRule(
+export async function unassignStorageRule(
client: SupabaseClient<Database>,
args: { targetType: TargetType; targetId: string; ruleId: string }
) {
diff --git a/packages/ee/src/customRules/use-violations.tsx b/packages/ee/src/storageRules/use-violations.tsx
similarity index 91%
rename from packages/ee/src/customRules/use-violations.tsx
rename to packages/ee/src/storageRules/use-violations.tsx
index 2b310f6553..1433849c16 100644
--- a/packages/ee/src/customRules/use-violations.tsx
+++ b/packages/ee/src/storageRules/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 CustomRuleViolationModal from "./violation-modal";
+import StorageRuleViolationModal from "./violation-modal";
/**
* Shape every item-rule-aware server action must return when it wants the
* client to surface violations. Mirrors the payload produced by
* `evaluateForItem` + the per-action wrapper that resolves rule names.
*/
-export type CustomRuleViolationPayload = {
+export type StorageRuleViolationPayload = {
error?: { message?: string } | null;
data?: unknown;
violations?: Violation[];
ruleNames?: Record<string, string>;
};
-type UseCustomRuleViolationsOptions = {
+type UseStorageRuleViolationsOptions = {
/** Server action endpoint that the form is posted to. */
action: string;
/**
@@ -26,7 +26,7 @@ type UseCustomRuleViolationsOptions = {
onSuccess?: () => void;
};
-type UseCustomRuleViolationsResult<T> = {
+type UseStorageRuleViolationsResult<T> = {
// `useFetcher<T>` actually returns `FetcherWithComponents<SerializeFrom<T>>`;
// mirror that here so callers see the serialised payload type without us
// having to import the React Router internal `SerializeFrom` helper.
@@ -45,7 +45,7 @@ type UseCustomRuleViolationsResult<T> = {
*
* Wraps a `useFetcher` and:
* - toasts any `error.message` returned by the action
- * - opens `<CustomRuleViolationModal>` when the action returns `violations`
+ * - opens `<StorageRuleViolationModal>` 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 UseCustomRuleViolationsResult<T> = {
* Call sites only have to swap `fetcher.submit(...)` for `rules.submit(...)`
* and render `<rules.ViolationModal />`. Everything else is wired internally.
*/
-export function useCustomRuleViolations<T = unknown>({
+export function useStorageRuleViolations<T = unknown>({
action,
onSuccess
-}: UseCustomRuleViolationsOptions): UseCustomRuleViolationsResult<T> {
+}: UseStorageRuleViolationsOptions): UseStorageRuleViolationsResult<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 useCustomRuleViolations<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<CustomRuleViolationPayload | undefined>(
+ const [staged, setStaged] = useState<StorageRuleViolationPayload | undefined>(
undefined
);
const lastSeenDataRef = useRef<unknown>(undefined);
@@ -79,7 +79,7 @@ export function useCustomRuleViolations<T = unknown>({
// the form submits via `fetcher={...}` prop directly (bypassing `submit()`).
const prevIdleRef = useRef(true);
- const data = fetcher.data as CustomRuleViolationPayload | undefined;
+ const data = fetcher.data as StorageRuleViolationPayload | undefined;
const idle = fetcher.state === "idle";
const violations = staged?.violations ?? [];
const ruleNames = staged?.ruleNames;
@@ -164,7 +164,7 @@ export function useCustomRuleViolations<T = unknown>({
const ViolationModal = useCallback(() => {
if (!hasViolations) return null;
return (
- <CustomRuleViolationModal
+ <StorageRuleViolationModal
violations={violations}
ruleNames={ruleNames}
isSubmitting={!idle}
diff --git a/packages/ee/src/customRules/violation-modal.tsx b/packages/ee/src/storageRules/violation-modal.tsx
similarity index 96%
rename from packages/ee/src/customRules/violation-modal.tsx
rename to packages/ee/src/storageRules/violation-modal.tsx
index d1f65dad59..fcbea884c2 100644
--- a/packages/ee/src/customRules/violation-modal.tsx
+++ b/packages/ee/src/storageRules/violation-modal.tsx
@@ -14,7 +14,7 @@ import { LuOctagonAlert, LuTriangleAlert } from "react-icons/lu";
type RuleNameMap = Record<string, string>;
-type CustomRuleViolationModalProps = {
+type StorageRuleViolationModalProps = {
violations: Violation[];
ruleNames?: RuleNameMap;
onCancel: () => void;
@@ -22,13 +22,13 @@ type CustomRuleViolationModalProps = {
isSubmitting?: boolean;
};
-export default function CustomRuleViolationModal({
+export default function StorageRuleViolationModal({
violations,
ruleNames,
onCancel,
onAcknowledge,
isSubmitting
-}: CustomRuleViolationModalProps) {
+}: StorageRuleViolationModalProps) {
const { errors, warns, hasError, onlyWarns } = useMemo(() => {
const errs: Violation[] = [];
const wrns: Violation[] = [];
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 7beff0606b..b41035c720 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -519,9 +519,6 @@ msgstr "Gilt für"
msgid "Applies to all"
msgstr "Gilt für alle"
-msgid "Applies to all storage units"
-msgstr "Gilt für alle Lagereinheiten"
-
msgid "Applies to all work centers"
msgstr "Gilt für alle Arbeitszentren"
@@ -3972,9 +3969,6 @@ msgstr "Infrastruktur"
msgid "Inherit From Materials"
msgstr "Von Materialien erben"
-msgid "Inherited from"
-msgstr "Geerbt von"
-
msgid "Insert rows"
msgstr "Zeilen einfügen"
@@ -4571,9 +4565,6 @@ msgstr "Verwalten Sie, wie die Haltbarkeit in Ihrem Bestand verfolgt, berechnet
msgid "Manage Ownership"
msgstr "Eigentümerschaft verwalten"
-msgid "Manage rules"
-msgstr "Regeln verwalten"
-
msgid "Manage Subscription"
msgstr "Abonnement verwalten"
@@ -7484,6 +7475,9 @@ msgstr "Bestandsübertragungen"
msgid "Storage client not available"
msgstr "Speicherclient nicht verfügbar"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Lagertyp"
@@ -7493,9 +7487,6 @@ msgstr "Speichertypen"
msgid "Storage Unit"
msgstr "Lagereinheit"
-msgid "Storage unit rules"
-msgstr "Lagerverwaltungsregeln"
-
msgid "Storage Units"
msgstr "Lagereinheiten"
@@ -8172,9 +8163,6 @@ msgstr "Nicht beprobte Entitäten bleiben in Warteschleife, damit Sie weiterhin
msgid "Unapproved Supplier"
msgstr "Nicht genehmigter Lieferant"
-msgid "Unassign from parent unit to remove"
-msgstr "Aus übergeordneter Einheit entfernen zum Löschen"
-
msgid "Unassign rule"
msgstr "Regel entfernen"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 980bc14489..78a7c942b8 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -519,9 +519,6 @@ msgstr "Applies to"
msgid "Applies to all"
msgstr "Applies to all"
-msgid "Applies to all storage units"
-msgstr "Applies to all storage units"
-
msgid "Applies to all work centers"
msgstr "Applies to all work centers"
@@ -3972,9 +3969,6 @@ msgstr "Infrastructure"
msgid "Inherit From Materials"
msgstr "Inherit From Materials"
-msgid "Inherited from"
-msgstr "Inherited from"
-
msgid "Insert rows"
msgstr "Insert rows"
@@ -4571,9 +4565,6 @@ msgstr "Manage how shelf life is tracked, computed, and enforced across inventor
msgid "Manage Ownership"
msgstr "Manage Ownership"
-msgid "Manage rules"
-msgstr "Manage rules"
-
msgid "Manage Subscription"
msgstr "Manage Subscription"
@@ -7484,6 +7475,9 @@ msgstr "Stock Transfers"
msgid "Storage client not available"
msgstr "Storage client not available"
+msgid "Storage Rules"
+msgstr "Storage Rules"
+
msgid "Storage Type"
msgstr "Storage Type"
@@ -7493,9 +7487,6 @@ msgstr "Storage Types"
msgid "Storage Unit"
msgstr "Storage Unit"
-msgid "Storage unit rules"
-msgstr "Storage unit rules"
-
msgid "Storage Units"
msgstr "Storage Units"
@@ -8172,9 +8163,6 @@ msgstr "Un-sampled entities will remain On Hold so you can keep inspecting and d
msgid "Unapproved Supplier"
msgstr "Unapproved Supplier"
-msgid "Unassign from parent unit to remove"
-msgstr "Unassign from parent unit to remove"
-
msgid "Unassign rule"
msgstr "Unassign rule"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 462848fa7e..e40a40b141 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -519,9 +519,6 @@ msgstr "Se aplica a"
msgid "Applies to all"
msgstr "Se aplica a todos"
-msgid "Applies to all storage units"
-msgstr "Se aplica a todas las unidades de almacenamiento"
-
msgid "Applies to all work centers"
msgstr "Se aplica a todos los centros de trabajo"
@@ -3972,9 +3969,6 @@ msgstr "Infraestructura"
msgid "Inherit From Materials"
msgstr "Heredar de Materiales"
-msgid "Inherited from"
-msgstr "Heredado de"
-
msgid "Insert rows"
msgstr "Insertar filas"
@@ -4571,9 +4565,6 @@ msgstr "Administra cómo se rastrea, calcula y aplica la vida útil en todo el i
msgid "Manage Ownership"
msgstr "Gestionar Propiedad"
-msgid "Manage rules"
-msgstr "Gestionar reglas"
-
msgid "Manage Subscription"
msgstr "Administrar Suscripción"
@@ -7484,6 +7475,9 @@ msgstr "Transferencias de Inventario"
msgid "Storage client not available"
msgstr "Cliente de almacenamiento no disponible"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Tipo de Almacenamiento"
@@ -7493,9 +7487,6 @@ msgstr "Tipos de Almacenamiento"
msgid "Storage Unit"
msgstr "Unidad de Almacenamiento"
-msgid "Storage unit rules"
-msgstr "Reglas de unidad de almacenamiento"
-
msgid "Storage Units"
msgstr "Unidades de Almacenamiento"
@@ -8172,9 +8163,6 @@ msgstr "Las entidades no muestreadas permanecerán En Espera para que puedas seg
msgid "Unapproved Supplier"
msgstr "Proveedor No Aprobado"
-msgid "Unassign from parent unit to remove"
-msgstr "Desasignar de la unidad principal para eliminar"
-
msgid "Unassign rule"
msgstr "Desasignar regla"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index ded5a04256..6ee32b0d6c 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -519,9 +519,6 @@ msgstr "S'applique à"
msgid "Applies to all"
msgstr "S'applique à tous"
-msgid "Applies to all storage units"
-msgstr "S'applique à toutes les unités de stockage"
-
msgid "Applies to all work centers"
msgstr "S'applique à tous les centres de travail"
@@ -3972,9 +3969,6 @@ msgstr "Infrastructure"
msgid "Inherit From Materials"
msgstr "Hériter des matériaux"
-msgid "Inherited from"
-msgstr "Hérité de"
-
msgid "Insert rows"
msgstr "Insérer des lignes"
@@ -4571,9 +4565,6 @@ msgstr "Gérez le suivi, le calcul et l'application de la durée de conservation
msgid "Manage Ownership"
msgstr "Gérer la propriété"
-msgid "Manage rules"
-msgstr "Gérer les règles"
-
msgid "Manage Subscription"
msgstr "Gérer l'abonnement"
@@ -7484,6 +7475,9 @@ msgstr "Transferts de Stock"
msgid "Storage client not available"
msgstr "Client de stockage non disponible"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Type de stockage"
@@ -7493,9 +7487,6 @@ msgstr "Types de stockage"
msgid "Storage Unit"
msgstr "Unité de stockage"
-msgid "Storage unit rules"
-msgstr "Règles d'unité de stockage"
-
msgid "Storage Units"
msgstr "Unités de stockage"
@@ -8172,9 +8163,6 @@ msgstr "Les entités non échantillonnées resteront En attente pour que vous pu
msgid "Unapproved Supplier"
msgstr "Fournisseur non approuvé"
-msgid "Unassign from parent unit to remove"
-msgstr "Désassigner de l'unité parent pour supprimer"
-
msgid "Unassign rule"
msgstr "Retirer la règle"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 92adca5e97..14b14626c0 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -519,9 +519,6 @@ msgstr "लागू होता है"
msgid "Applies to all"
msgstr "सभी पर लागू होता है"
-msgid "Applies to all storage units"
-msgstr "सभी स्टोरेज यूनिट्स पर लागू होता है"
-
msgid "Applies to all work centers"
msgstr "सभी कार्य केंद्रों पर लागू होता है"
@@ -3972,9 +3969,6 @@ msgstr "बुनियादी ढांचा"
msgid "Inherit From Materials"
msgstr "सामग्री से विरासत में प्राप्त करें"
-msgid "Inherited from"
-msgstr "से विरासत में मिला"
-
msgid "Insert rows"
msgstr "पंक्तियाँ सम्मिलित करें"
@@ -4571,9 +4565,6 @@ msgstr "शेल्फ लाइफ को कैसे ट्रैक कि
msgid "Manage Ownership"
msgstr "स्वामित्व प्रबंधित करें"
-msgid "Manage rules"
-msgstr "नियमों का प्रबंधन करें"
-
msgid "Manage Subscription"
msgstr "सदस्यता प्रबंधित करें"
@@ -7484,6 +7475,9 @@ msgstr "स्टॉक ट्रांसफर"
msgid "Storage client not available"
msgstr "स्टोरेज क्लाइंट उपलब्ध नहीं है"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "स्टोरेज प्रकार"
@@ -7493,9 +7487,6 @@ msgstr "स्टोरेज प्रकार"
msgid "Storage Unit"
msgstr "भंडारण इकाई"
-msgid "Storage unit rules"
-msgstr "भंडारण इकाई नियम"
-
msgid "Storage Units"
msgstr "भंडारण इकाइयाँ"
@@ -8172,9 +8163,6 @@ msgstr "नमूना न लिए गए इकाइयां On Hold प
msgid "Unapproved Supplier"
msgstr "अनुमोदित नहीं आपूर्तिकर्ता"
-msgid "Unassign from parent unit to remove"
-msgstr "माता-पिता इकाई से हटाने के लिए असाइन करें"
-
msgid "Unassign rule"
msgstr "नियम को अनअसाइन करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index bc6cd968ab..49f4372a5f 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -519,9 +519,6 @@ msgstr "Si applica a"
msgid "Applies to all"
msgstr "Si applica a tutti"
-msgid "Applies to all storage units"
-msgstr "Si applica a tutte le unità di stoccaggio"
-
msgid "Applies to all work centers"
msgstr "Si applica a tutti i centri di lavoro"
@@ -3972,9 +3969,6 @@ msgstr "Infrastruttura"
msgid "Inherit From Materials"
msgstr "Eredita dai Materiali"
-msgid "Inherited from"
-msgstr "Ereditato da"
-
msgid "Insert rows"
msgstr "Inserisci righe"
@@ -4571,9 +4565,6 @@ msgstr "Gestisci come la durata di conservazione viene tracciata, calcolata e ap
msgid "Manage Ownership"
msgstr "Gestisci Proprietà"
-msgid "Manage rules"
-msgstr "Gestisci regole"
-
msgid "Manage Subscription"
msgstr "Gestisci Abbonamento"
@@ -7484,6 +7475,9 @@ msgstr "Trasferimenti di Magazzino"
msgid "Storage client not available"
msgstr "Client di archiviazione non disponibile"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Tipo di Archiviazione"
@@ -7493,9 +7487,6 @@ msgstr "Tipi di Archiviazione"
msgid "Storage Unit"
msgstr "Unità di Stoccaggio"
-msgid "Storage unit rules"
-msgstr "Regole unità di stoccaggio"
-
msgid "Storage Units"
msgstr "Unità di Stoccaggio"
@@ -8172,9 +8163,6 @@ msgstr "Le entità non campionate rimarranno In Sospeso in modo che tu possa con
msgid "Unapproved Supplier"
msgstr "Fornitore non approvato"
-msgid "Unassign from parent unit to remove"
-msgstr "Annulla assegnazione dall'unità padre per rimuovere"
-
msgid "Unassign rule"
msgstr "Annulla assegnazione regola"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 7ae83a3047..7c21a83a67 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -519,9 +519,6 @@ msgstr "適用対象"
msgid "Applies to all"
msgstr "すべてに適用"
-msgid "Applies to all storage units"
-msgstr "すべての保管ユニットに適用"
-
msgid "Applies to all work centers"
msgstr "すべてのワークセンターに適用"
@@ -3972,9 +3969,6 @@ msgstr "インフラストラクチャ"
msgid "Inherit From Materials"
msgstr "材料から継承"
-msgid "Inherited from"
-msgstr "継承元"
-
msgid "Insert rows"
msgstr "行を挿入"
@@ -4571,9 +4565,6 @@ msgstr "棚卸資産全体で賞味期限がどのように追跡、計算、お
msgid "Manage Ownership"
msgstr "所有権を管理"
-msgid "Manage rules"
-msgstr "ルールを管理"
-
msgid "Manage Subscription"
msgstr "サブスクリプションを管理"
@@ -7484,6 +7475,9 @@ msgstr "在庫移動"
msgid "Storage client not available"
msgstr "ストレージクライアントが利用できません"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "ストレージタイプ"
@@ -7493,9 +7487,6 @@ msgstr "ストレージタイプ"
msgid "Storage Unit"
msgstr "保管単位"
-msgid "Storage unit rules"
-msgstr "保管ユニットルール"
-
msgid "Storage Units"
msgstr "保管単位"
@@ -8172,9 +8163,6 @@ msgstr "未サンプリングされたエンティティは保留中のままに
msgid "Unapproved Supplier"
msgstr "未承認サプライヤー"
-msgid "Unassign from parent unit to remove"
-msgstr "親ユニットから割り当て解除して削除"
-
msgid "Unassign rule"
msgstr "ルールの割り当てを解除"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index b9a3053c5b..406b1dc887 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -519,9 +519,6 @@ msgstr "Dotyczy"
msgid "Applies to all"
msgstr "Dotyczy wszystkich"
-msgid "Applies to all storage units"
-msgstr "Dotyczy wszystkich jednostek magazynowych"
-
msgid "Applies to all work centers"
msgstr "Dotyczy wszystkich centrów pracy"
@@ -3972,9 +3969,6 @@ msgstr "Infrastruktura"
msgid "Inherit From Materials"
msgstr "Dziedzicz z Materiałów"
-msgid "Inherited from"
-msgstr "Odziedziczone z"
-
msgid "Insert rows"
msgstr "Wstaw wiersze"
@@ -4571,9 +4565,6 @@ msgstr "Zarządzaj sposobem śledzenia, obliczania i egzekwowania okresu przydat
msgid "Manage Ownership"
msgstr "Zarządzaj własnością"
-msgid "Manage rules"
-msgstr "Zarządzaj regułami"
-
msgid "Manage Subscription"
msgstr "Zarzadzaj subskrypcja"
@@ -7484,6 +7475,9 @@ msgstr "Transfery Zapasów"
msgid "Storage client not available"
msgstr "Klient magazynu niedostępny"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Typ magazynu"
@@ -7493,9 +7487,6 @@ msgstr "Typy magazynowania"
msgid "Storage Unit"
msgstr "Jednostka magazynowa"
-msgid "Storage unit rules"
-msgstr "Reguły jednostki magazynowej"
-
msgid "Storage Units"
msgstr "Jednostki magazynowe"
@@ -8172,9 +8163,6 @@ msgstr "Nieprzetestowane jednostki pozostaną w stanie Wstrzymane, aby można by
msgid "Unapproved Supplier"
msgstr "Niezatwierdzony dostawca"
-msgid "Unassign from parent unit to remove"
-msgstr "Usuń przypisanie z jednostki nadrzędnej, aby usunąć"
-
msgid "Unassign rule"
msgstr "Usuń przypisanie reguły"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index b624fa4552..1eff94f536 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -519,9 +519,6 @@ msgstr "Aplica-se a"
msgid "Applies to all"
msgstr "Aplica-se a todos"
-msgid "Applies to all storage units"
-msgstr "Aplica-se a todas as unidades de armazenamento"
-
msgid "Applies to all work centers"
msgstr "Aplica-se a todos os centros de trabalho"
@@ -3972,9 +3969,6 @@ msgstr "Infraestrutura"
msgid "Inherit From Materials"
msgstr "Herdar de Materiais"
-msgid "Inherited from"
-msgstr "Herdado de"
-
msgid "Insert rows"
msgstr "Inserir linhas"
@@ -4571,9 +4565,6 @@ msgstr "Gerir como a vida útil é rastreada, calculada e aplicada no inventári
msgid "Manage Ownership"
msgstr "Gerenciar Propriedade"
-msgid "Manage rules"
-msgstr "Gerenciar regras"
-
msgid "Manage Subscription"
msgstr "Gerenciar Assinatura"
@@ -7484,6 +7475,9 @@ msgstr "Transferências de Estoque"
msgid "Storage client not available"
msgstr "Cliente de armazenamento não disponível"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Tipo de Armazenamento"
@@ -7493,9 +7487,6 @@ msgstr "Tipos de Armazenamento"
msgid "Storage Unit"
msgstr "Unidade de Armazenamento"
-msgid "Storage unit rules"
-msgstr "Regras da unidade de armazenamento"
-
msgid "Storage Units"
msgstr "Unidades de Armazenamento"
@@ -8172,9 +8163,6 @@ msgstr "Entidades não amostradas permanecerão Em Espera para que você possa c
msgid "Unapproved Supplier"
msgstr "Fornecedor Não Aprovado"
-msgid "Unassign from parent unit to remove"
-msgstr "Desatribuir da unidade pai para remover"
-
msgid "Unassign rule"
msgstr "Desatribuir regra"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 8b5016a933..8e9f427269 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -519,9 +519,6 @@ msgstr "Применяется к"
msgid "Applies to all"
msgstr "Применяется ко всем"
-msgid "Applies to all storage units"
-msgstr "Применяется ко всем складским единицам"
-
msgid "Applies to all work centers"
msgstr "Применяется ко всем рабочим центрам"
@@ -3972,9 +3969,6 @@ msgstr "Инфраструктура"
msgid "Inherit From Materials"
msgstr "Наследовать от материалов"
-msgid "Inherited from"
-msgstr "Унаследовано от"
-
msgid "Insert rows"
msgstr "Вставить строки"
@@ -4571,9 +4565,6 @@ msgstr "Управляйте отслеживанием, расчетом и п
msgid "Manage Ownership"
msgstr "Управление правами собственности"
-msgid "Manage rules"
-msgstr "Управлять правилами"
-
msgid "Manage Subscription"
msgstr "Управление подпиской"
@@ -7484,6 +7475,9 @@ msgstr "Передачи запасов"
msgid "Storage client not available"
msgstr "Клиент хранилища недоступен"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "Тип хранилища"
@@ -7493,9 +7487,6 @@ msgstr "Типы хранилищ"
msgid "Storage Unit"
msgstr "Единица хранения"
-msgid "Storage unit rules"
-msgstr "Правила хранилища"
-
msgid "Storage Units"
msgstr "Единицы хранения"
@@ -8172,9 +8163,6 @@ msgstr "Необработанные сущности останутся в ст
msgid "Unapproved Supplier"
msgstr "Неодобренный поставщик"
-msgid "Unassign from parent unit to remove"
-msgstr "Отменить назначение из родительского подразделения для удаления"
-
msgid "Unassign rule"
msgstr "Отменить назначение правила"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 1245b0d15b..8d3d8d1141 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -519,9 +519,6 @@ msgstr "适用于"
msgid "Applies to all"
msgstr "适用于全部"
-msgid "Applies to all storage units"
-msgstr "适用于所有存储单位"
-
msgid "Applies to all work centers"
msgstr "适用于所有工作中心"
@@ -3972,9 +3969,6 @@ msgstr "基础设施"
msgid "Inherit From Materials"
msgstr "从材料继承"
-msgid "Inherited from"
-msgstr "继承自"
-
msgid "Insert rows"
msgstr "插入行"
@@ -4571,9 +4565,6 @@ msgstr "管理如何在整个库存中跟踪、计算和执行保质期。"
msgid "Manage Ownership"
msgstr "管理所有权"
-msgid "Manage rules"
-msgstr "管理规则"
-
msgid "Manage Subscription"
msgstr "管理订阅"
@@ -7484,6 +7475,9 @@ msgstr "库存转移"
msgid "Storage client not available"
msgstr "存储客户端不可用"
+msgid "Storage Rules"
+msgstr ""
+
msgid "Storage Type"
msgstr "存储类型"
@@ -7493,9 +7487,6 @@ msgstr "存储类型"
msgid "Storage Unit"
msgstr "存储单位"
-msgid "Storage unit rules"
-msgstr "存储单元规则"
-
msgid "Storage Units"
msgstr "存储单位"
@@ -8172,9 +8163,6 @@ msgstr "未采样的实体将保持\"待处理\"状态,以便您可以继续
msgid "Unapproved Supplier"
msgstr "未批准的供应商"
-msgid "Unassign from parent unit to remove"
-msgstr "从父单位取消分配以移除"
-
msgid "Unassign rule"
msgstr "取消分配规则"
diff --git a/packages/utils/src/field-registry.ts b/packages/utils/src/field-registry.ts
index 95d16cc460..46d2f50b9b 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 `customRules.ts` to keep that file
-// focused on evaluation/compilation. Depends on `customRules` only for the core
+// the evaluator's field paths. Split out of `storageRules.ts` to keep that file
+// focused on evaluation/compilation. Depends on `storageRules` only for the core
// `Operator` / `TargetType` types (type-only — no runtime cycle).
import type { Database } from "@carbon/database";
-import type { Operator, TargetType } from "./customRules";
+import type { Operator, TargetType } from "./storageRules";
type Tables = Database["public"]["Tables"];
@@ -52,9 +52,7 @@ export type FieldDef = {
* Which rule `targetType`(s) may reference this field.
* - `"shared"` → visible to every targetType (e.g. `transaction.*`)
* - `TargetType` → visible only to that one targetType
- * - `readonly TargetType[]` → visible to each targetType in the list (e.g.
- * `["item", "storageUnit"]` for storage-unit fields that make sense on
- * both item-target and storageUnit-target rules)
+ * - `readonly TargetType[]` → visible to each targetType in the list
*/
targetType: TargetType | "shared" | readonly TargetType[];
valueOptionsLoader?: ValueOptionsLoader;
@@ -146,12 +144,12 @@ const fields = {
// populated for a subset of surfaces are intentionally excluded — rule
// authors should never write a predicate that silently no-ops on some surface.
//
-// Cross-target fields (e.g. storageUnit.* visible to both item + storageUnit
-// rules) use the array form of `targetType`. For item-target surfaces the
-// storageUnit ctx may be undefined when `line.storageUnitId` is null
-// (inventoryAdjustment without a bin, warehouseTransfer with no destination
-// yet); we mark such fields `nullable: true` so `availableOperators` exposes
-// `isSet`/`isNotSet` and authors can guard explicitly.
+// The `storageUnit.*` fields belong to item-target rules (they own the
+// `place`/`pick` bin guards). The storageUnit ctx may be undefined when
+// `line.storageUnitId` is null (inventoryAdjustment without a bin,
+// warehouseTransfer with no destination yet); we mark such fields
+// `nullable: true` so `availableOperators` exposes `isSet`/`isNotSet` and
+// authors can guard explicitly.
//
// Dropped vs. earlier drafts (kept here as audit trail):
// - shelf.locationId → `shelf` is not a RuleContext root key
@@ -163,10 +161,9 @@ const fields = {
// `itemCost` row and flattens its `itemPostingGroupId` onto the item ctx, so
// the value is guaranteed for every item-target surface (all carry an itemId).
export const FIELD_REGISTRY: FieldDef[] = [
- // ── Item context (item + storageUnit targets) ─────────────────────────────
- // All storageUnit-target surfaces (place, pick, stockTransfer,
- // warehouseTransfer) carry a `line.itemId`, so the evaluator loads item
- // ctx and these fields resolve. Item DB columns are NOT NULL so no
+ // ── Item context (item target) ────────────────────────────────────────────
+ // Every item-target surface carries a `line.itemId`, so the evaluator loads
+ // item ctx and these fields resolve. Item DB columns are NOT NULL so no
// nullable change.
fields.database({
table: "item",
@@ -176,7 +173,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "enum",
operators: ENUM_OPS,
context: "item",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "itemTypes"
}),
fields.database({
@@ -187,7 +184,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "enum",
operators: ENUM_OPS,
context: "item",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "replenishmentSystems"
}),
fields.database({
@@ -198,7 +195,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "enum",
operators: ENUM_OPS,
context: "item",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "itemTrackingTypes"
}),
// Posting group lives on the 1:1 `itemCost` row, not `item`. The evaluator
@@ -212,14 +209,13 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "id",
operators: ID_OPS,
context: "item",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "itemPostingGroups"
}),
- // ── StorageUnit context (item + storageUnit targets) ──────────────────────
- // Always loaded by the evaluator for storageUnit-target rules; loaded when
- // `line.storageUnitId` is set for item-target rules. `nullable: true` on
- // every entry so item rules can guard with `isSet`/`isNotSet`.
+ // ── 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`.
fields.synthetic({
path: "storageUnit.id",
derivedFrom: "The bin chosen on this transaction line.",
@@ -232,7 +228,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
// multi-select UI that doesn't exist. Restrict to scalar ops.
operators: SCALAR_OPS,
context: "storage",
- targetType: ["item", "storageUnit"]
+ targetType: "item"
}),
fields.synthetic({
path: "storageUnit.storageTypeId",
@@ -242,7 +238,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "id",
operators: ID_OPS,
context: "storage",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "storageTypes"
}),
// Useful for `appliesToAll` rules that want to scope by physical location —
@@ -259,7 +255,7 @@ export const FIELD_REGISTRY: FieldDef[] = [
type: "id",
operators: ID_OPS,
context: "storage",
- targetType: ["item", "storageUnit"],
+ targetType: "item",
valueOptionsLoader: "locations"
}),
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 8de5a6a312..cf5090a222 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -6,7 +6,6 @@ export * from "./bom";
export * from "./color";
export * from "./const";
export * from "./country";
-export * from "./customRules";
export * from "./date";
export * from "./duration";
export * from "./field-registry";
@@ -20,6 +19,7 @@ export * from "./math";
export * from "./object";
export * from "./ssr";
export * from "./status";
+export * from "./storageRules";
export * from "./string";
export * from "./supabase";
export * from "./themes";
diff --git a/packages/utils/src/customRules.test.ts b/packages/utils/src/storageRules.test.ts
similarity index 95%
rename from packages/utils/src/customRules.test.ts
rename to packages/utils/src/storageRules.test.ts
index aca62cf00c..02aee781ce 100644
--- a/packages/utils/src/customRules.test.ts
+++ b/packages/utils/src/storageRules.test.ts
@@ -1,8 +1,12 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
- __customRulesCacheSize,
- __resetCustomRulesCache,
- type CustomRuleRow,
+ FIELD_REGISTRY,
+ getFieldDef,
+ getFieldsForTargetType
+} from "./field-registry";
+import {
+ __resetStorageRulesCache,
+ __storageRulesCacheSize,
compileRule,
compileWithCache,
evaluateRules,
@@ -11,19 +15,15 @@ import {
isFieldAvailableOnSurfaces,
itemRuleAppliesToItem,
type RuleContext,
+ type StorageRuleRow,
SURFACE_CONTEXT_AVAILABILITY,
TRANSACTION_SURFACES
-} from "./customRules";
-import {
- FIELD_REGISTRY,
- getFieldDef,
- getFieldsForTargetType
-} from "./field-registry";
+} from "./storageRules";
const ruleOf = (
conditions: Array<{ field: string; op: string; value?: unknown }>,
- overrides: Partial<CustomRuleRow> = {}
-): CustomRuleRow => ({
+ overrides: Partial<StorageRuleRow> = {}
+): StorageRuleRow => ({
id: overrides.id ?? "rule_1",
targetType: overrides.targetType ?? "item",
severity: overrides.severity ?? "error",
@@ -381,7 +381,7 @@ describe("evaluateRules", () => {
});
describe("compileWithCache", () => {
- beforeEach(() => __resetCustomRulesCache());
+ beforeEach(() => __resetStorageRulesCache());
it("returns same compiled instance on cache hit", () => {
const row = ruleOf([{ field: "item.type", op: "eq", value: "Part" }]);
@@ -400,7 +400,7 @@ describe("compileWithCache", () => {
const a = compileWithCache(row1);
const b = compileWithCache(row2);
expect(a).not.toBe(b);
- expect(__customRulesCacheSize()).toBe(2);
+ expect(__storageRulesCacheSize()).toBe(2);
});
it("does not collide across targetTypes with identical content", () => {
@@ -431,7 +431,7 @@ describe("compileWithCache", () => {
})
);
}
- expect(__customRulesCacheSize()).toBeLessThanOrEqual(256);
+ expect(__storageRulesCacheSize()).toBeLessThanOrEqual(256);
});
});
@@ -477,18 +477,6 @@ describe("getFieldsForTargetType", () => {
expect(paths).not.toContain("item.type");
expect(paths.some((p) => p.startsWith("storageUnit."))).toBe(false);
});
-
- it("storageUnit target sees storage + item fields (item ctx loads on every storageUnit-target surface)", () => {
- const fields = getFieldsForTargetType("storageUnit");
- const paths = fields.map((f) => f.path);
- expect(paths).toContain("storageUnit.id");
- expect(paths).toContain("storageUnit.storageTypeId");
- expect(paths).toContain("storageUnit.locationId");
- expect(paths).toContain("transaction.quantity");
- expect(paths).toContain("item.type");
- expect(paths).toContain("item.replenishmentSystem");
- expect(paths).toContain("item.itemTrackingType");
- });
});
describe("required-field pre-check", () => {
diff --git a/packages/utils/src/customRules.ts b/packages/utils/src/storageRules.ts
similarity index 95%
rename from packages/utils/src/customRules.ts
rename to packages/utils/src/storageRules.ts
index b595bbd338..2c26a62269 100644
--- a/packages/utils/src/customRules.ts
+++ b/packages/utils/src/storageRules.ts
@@ -3,8 +3,8 @@
// inventory adjustment, place, pick, operation start/finish, material
// issue/receive) to enforce per-entity validation/guideline rules.
//
-// Each rule binds to a single `TargetType` (`item`, `storageUnit`, or
-// `workCenter`). The field registry lives in `./field-registry`.
+// Each rule binds to a single `TargetType` (`item` or `workCenter`). The field
+// registry lives in `./field-registry`.
import {
type FieldContext,
@@ -28,9 +28,9 @@ export type Severity = "error" | "warn";
/**
* Which entity a rule applies to. Drives the field registry slice the
* builder shows the author, and the assignment table the loader joins.
- * Mirrors the Postgres ENUM `customRuleTargetType`.
+ * Mirrors the Postgres ENUM `storageRuleTargetType`.
*/
-export const TARGET_TYPES = ["item", "storageUnit", "workCenter"] as const;
+export const TARGET_TYPES = ["item", "workCenter"] as const;
export type TargetType = (typeof TARGET_TYPES)[number];
/**
@@ -63,9 +63,9 @@ export type TransactionSurface = (typeof TRANSACTION_SURFACES)[number];
* a rule's `surfaces` array against this map; the evaluator skips surfaces
* a rule didn't subscribe to.
*
- * Transfer surfaces (`stockTransfer`, `warehouseTransfer`) apply to both
- * `item` and `storageUnit` targets — the integration call sites pass each
- * targetType separately, the engine filters by surface intersection.
+ * 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.
*/
export const SURFACES_BY_TARGET_TYPE: Record<
TargetType,
@@ -76,9 +76,10 @@ export const SURFACES_BY_TARGET_TYPE: Record<
"shipment",
"stockTransfer",
"warehouseTransfer",
- "inventoryAdjustment"
+ "inventoryAdjustment",
+ "place",
+ "pick"
],
- storageUnit: ["place", "pick", "stockTransfer", "warehouseTransfer"],
workCenter: [
"operationStart",
"operationFinish",
@@ -120,7 +121,7 @@ export type RuleContext = {
transaction?: Record<string, unknown>;
};
-export type CustomRuleRow = {
+export type StorageRuleRow = {
id: string;
targetType: TargetType;
severity: Severity;
@@ -265,7 +266,7 @@ const defaultSurfacesFor = (
targetType: TargetType
): readonly TransactionSurface[] => SURFACES_BY_TARGET_TYPE[targetType];
-export const compileRule = (row: CustomRuleRow): CompiledRule => ({
+export const compileRule = (row: StorageRuleRow): CompiledRule => ({
id: row.id,
targetType: row.targetType,
severity: row.severity,
@@ -304,7 +305,7 @@ const fnv1a = (s: string): string => {
return h.toString(36);
};
-const cacheKey = (row: CustomRuleRow): string => {
+const cacheKey = (row: StorageRuleRow): string => {
// Hash bits that drive compilation output, including targetType so two
// rules with identical AST but different targets cannot collide.
const contentHash = fnv1a(
@@ -313,7 +314,7 @@ const cacheKey = (row: CustomRuleRow): string => {
return `${row.id}:${row.updatedAt ?? ""}:${contentHash}`;
};
-export const compileWithCache = (row: CustomRuleRow): CompiledRule => {
+export const compileWithCache = (row: StorageRuleRow): CompiledRule => {
const key = cacheKey(row);
const hit = cache.get(key);
if (hit) {
@@ -330,11 +331,11 @@ export const compileWithCache = (row: CustomRuleRow): CompiledRule => {
return compiled;
};
-export const __resetCustomRulesCache = (): void => {
+export const __resetStorageRulesCache = (): void => {
cache.clear();
};
-export const __customRulesCacheSize = (): number => cache.size;
+export const __storageRulesCacheSize = (): number => cache.size;
// ---------------------------------------------------------------------------
// Message interpolation
@@ -525,7 +526,7 @@ export const itemRuleAppliesToItem = (
: (typeMatch ?? false) || (groupMatch ?? false);
};
-/** Normalize a raw `customRule` row's nullable filter columns into a filter. */
+/** Normalize a raw `storageRule` row's nullable filter columns into a filter. */
export const toItemRuleFilter = (row: {
filteredItemTypes?: string[] | null;
filteredItemGroupIds?: string[] | null;
@@ -551,7 +552,7 @@ export const toItemRuleFilter = (row: {
// Note `"storage"` is the `FieldContext` value; it maps to the `storageUnit`
// RuleContext root key.
//
-// Locked by the anti-drift test in `packages/ee/src/customRules/server.test.ts`,
+// Locked by the anti-drift test in `packages/ee/src/storageRules/server.test.ts`,
// which asserts the ctx `evaluateLinesForSurface` builds for each surface
// populates exactly these contexts.
export const SURFACE_CONTEXT_AVAILABILITY: Record<