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.

Expand storage units tree by default (#891)

Brad Barbin1ca0c43e139f
diff --git a/apps/erp/app/components/Form/StorageUnit.tsx b/apps/erp/app/components/Form/StorageUnit.tsx
index a856edcc01..2d159a92dc 100644
--- a/apps/erp/app/components/Form/StorageUnit.tsx
+++ b/apps/erp/app/components/Form/StorageUnit.tsx
@@ -1,98 +1,63 @@
-// Compatibility shim: keeps the historical `<StorageUnit>` form API but
-// renders the hierarchical drill-down picker (Location → tree) underneath.
-// All existing callsites continue to work; new code should prefer
-// `StorageUnitDrillSelectField` directly.
+// `<StorageUnit>` — the storage-unit (bin) picker. One component, two modes:
+// - with `name` -> form-bound (`@carbon/form` CreatableCombobox)
+// - without `name` -> controlled (`value` + `onChange`) for table cells
+//
+// Options are the *leaf* storage units (the storable bins), each with a helper
+// showing on-hand quantity (when `itemId` is given) or its hierarchy path.
+// Built on the canonical `CreatableCombobox`, like every other entity picker.
+//
+// Choosing where a unit sits in the tree (a non-leaf target) is a different,
+// single-purpose interaction handled by `StorageUnitParentSelect`, local to the
+// Storage Unit form.
-import type { ComboboxProps } from "@carbon/form";
-import { forwardRef, useEffect, useMemo } from "react";
+import { CreatableCombobox } from "@carbon/form";
+import {
+ CreatableCombobox as CreatableComboboxBase,
+ useDisclosure
+} from "@carbon/react";
+import type { MouseEventHandler } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useFetcher } from "react-router";
import type { getStorageUnitsList } from "~/modules/inventory";
+import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
-import {
- StorageUnitDrillSelectField,
- type StorageUnitTreeRow
-} from "./StorageUnitDrillSelect";
-
-type StorageUnitSelectProps = Omit<
- ComboboxProps,
- "options" | "onChange" | "inline"
-> & {
- locationId?: string;
- /** Kept for API compat; the drill picker doesn't display per-item qty. */
- itemId?: string;
- inline?: boolean;
- onChange?: (storageUnit: ListItem | null) => void;
- /**
- * Exclude the given storage unit and every one of its descendants — used
- * by `StorageUnitForm`'s Parent picker so a user cannot pick themselves or
- * a child (which would create a cycle). DB enforces the same invariant
- * via `storage_unit_enforce_no_cycle`.
- */
- excludeDescendantsOf?: string;
-};
-
-const StorageUnit = forwardRef<HTMLDivElement, StorageUnitSelectProps>(
- (props, _ref) => {
- const {
- name,
- label,
- inline,
- locationId,
- isReadOnly,
- isOptional,
- excludeDescendantsOf,
- onChange,
- ...rest
- } = props;
-
- // Field name is required to bind to the form. The original component
- // declared `name` via ComboboxProps (also required).
- if (!name) {
- console.warn("<StorageUnit /> requires a `name` prop.");
- return null;
- }
- return (
- <StorageUnitDrillSelectField
- name={name}
- label={typeof label === "string" ? label : undefined}
- inline={inline}
- helperText={
- typeof rest.helperText === "string" ? rest.helperText : undefined
- }
- locationId={locationId}
- isReadOnly={isReadOnly}
- isOptional={isOptional}
- excludeDescendantsOf={excludeDescendantsOf}
- placeholder={
- typeof rest.placeholder === "string"
- ? rest.placeholder
- : "Select storage unit"
- }
- onChange={(row) => {
- if (!onChange) return;
- onChange(rowToListItem(row));
- }}
- />
- );
- }
-);
-StorageUnit.displayName = "StorageUnit";
+// ---------------------------------------------------------------------------
+// Data hooks (shared)
+// ---------------------------------------------------------------------------
-const rowToListItem = (row: StorageUnitTreeRow | null): ListItem | null => {
- if (!row) return null;
- return { id: row.id, name: row.name } as ListItem;
+export type StorageUnitTreeRow = {
+ id: string;
+ name: string;
+ parentId: string | null;
+ depth: number;
+ ancestorPath: string[];
};
-export default StorageUnit;
+/**
+ * Recursive storage-unit tree for a single location. One round-trip per
+ * locationId change; consumers cache by reference identity. Also used by the
+ * parent picker and storage-rule value inputs.
+ */
+export function useStorageUnitsTree(locationId?: string | null) {
+ const fetcher = useFetcher<{
+ data: StorageUnitTreeRow[] | null;
+ error: unknown;
+ }>();
-// ---------------------------------------------------------------------------
-// useStorageUnits — kept exported because table cells / non-form callsites
-// still pull the flat list (with optional per-item qty hints). The drill
-// picker has its own tree fetch; this hook stays as the flat fallback.
-// ---------------------------------------------------------------------------
+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render
+ useEffect(() => {
+ if (locationId) fetcher.load(path.to.api.storageUnitsTree(locationId));
+ }, [locationId]);
+
+ return fetcher.data?.data ?? [];
+}
+/**
+ * Flat storage-unit list for a location, optionally with per-item quantity
+ * helpers. Kept for non-leaf-aware callsites that pull their own options.
+ */
export function useStorageUnits(locationId?: string, itemId?: string) {
const storageUnitsFetcher =
useFetcher<Awaited<ReturnType<typeof getStorageUnitsList>>>();
@@ -125,7 +90,7 @@ export function useStorageUnits(locationId?: string, itemId?: string) {
(storageUnit: any) => !storageUnitIdsWithQuantities.has(storageUnit.id)
);
- const combinedStorageUnits = [
+ return [
...storageUnitsWithQuantities.map((c: any) => ({
value: c.id,
label: c.name,
@@ -136,8 +101,6 @@ export function useStorageUnits(locationId?: string, itemId?: string) {
label: c.name
}))
];
-
- return combinedStorageUnits;
}
return (
@@ -157,3 +120,221 @@ export function useStorageUnits(locationId?: string, itemId?: string) {
return { options, data: storageUnitsFetcher.data };
}
+
+type StorageUnitOption = { value: string; label: string; helper?: string };
+
+/**
+ * Per-unit on-hand quantities for `itemId`, keyed by storage-unit id. Only
+ * fetches when both ids are present, so item-less pickers don't pay for it.
+ */
+function useStorageUnitQuantities(locationId?: string | null, itemId?: string) {
+ const fetcher = useFetcher<{ data: { id: string; quantity: number }[] }>();
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render
+ useEffect(() => {
+ if (locationId && itemId) {
+ fetcher.load(path.to.api.storageUnitsWithQuantities(locationId, itemId));
+ }
+ }, [locationId, itemId]);
+
+ return useMemo(() => {
+ const m = new Map<string, number>();
+ for (const s of fetcher.data?.data ?? []) m.set(s.id, s.quantity);
+ return m;
+ }, [fetcher.data]);
+}
+
+/**
+ * Options for the leaf bins in a location (nodes with no children — the
+ * storable locations). `helper` shows the on-hand quantity when `itemId` is
+ * given, otherwise the hierarchy path to disambiguate same-named bins.
+ */
+export function useStorageUnitLeafOptions(
+ locationId?: string | null,
+ itemId?: string
+): StorageUnitOption[] {
+ const rows = useStorageUnitsTree(locationId);
+ const quantities = useStorageUnitQuantities(locationId, itemId);
+
+ return useMemo(() => {
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ const parentIds = new Set(
+ rows.map((r) => r.parentId).filter((id): id is string => Boolean(id))
+ );
+
+ return rows
+ .filter((r) => !parentIds.has(r.id))
+ .map((r) => {
+ const ancestorPath = (r.ancestorPath ?? [])
+ .slice(0, -1)
+ .map((id) => byId.get(id)?.name)
+ .filter(Boolean)
+ .join(" / ");
+ return {
+ value: r.id,
+ label: r.name,
+ helper: itemId
+ ? `Qty: ${quantities.get(r.id) ?? 0}`
+ : ancestorPath || undefined
+ };
+ })
+ .sort((a, b) => a.label.localeCompare(b.label));
+ }, [rows, quantities, itemId]);
+}
+
+// ---------------------------------------------------------------------------
+// Create-new-unit flow
+// ---------------------------------------------------------------------------
+
+/**
+ * Shared "+ New storage unit" flow. `onCreateOption` seeds the form with the
+ * typed text; closing the modal re-clicks the trigger so the combobox reopens
+ * with the freshly created unit selectable.
+ */
+function useNewStorageUnitModal(locationId?: string | null) {
+ const modal = useDisclosure();
+ const [created, setCreated] = useState("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const node =
+ modal.isOpen && locationId ? (
+ <StorageUnitForm
+ type="modal"
+ locationId={locationId}
+ onClose={() => {
+ setCreated("");
+ modal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{ name: created, locationId, storageTypeIds: [] }}
+ />
+ ) : null;
+
+ const onCreateOption = (value: string) => {
+ setCreated(value);
+ modal.onOpen();
+ };
+
+ return { triggerRef, onCreateOption, node };
+}
+
+const storageUnitPreview = (
+ value: string,
+ options: { value: string; label: string | JSX.Element }[]
+) => {
+ const match = options.find((o) => o.value === value);
+ return <span className="text-sm">{match?.label ?? ""}</span>;
+};
+
+const labelToString = (label: string | JSX.Element) =>
+ typeof label === "string" ? label : "";
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+type StorageUnitProps = {
+ /** Provide `name` for form-bound usage; omit it for controlled usage. */
+ name?: string;
+ /** Form-mode seed value, or the controlled value when `name` is absent. */
+ value?: string | null;
+ label?: string;
+ helperText?: string;
+ placeholder?: string;
+ isReadOnly?: boolean;
+ isOptional?: boolean;
+ disabled?: boolean;
+ className?: string;
+ onClick?: MouseEventHandler<HTMLButtonElement>;
+ locationId?: string | null;
+ itemId?: string;
+ /** Render a compact inline preview (table cells) once a value is set. */
+ inline?: boolean;
+ /** Show the "+ New storage unit" create option. Defaults to `true`. */
+ allowCreate?: boolean;
+ onChange?: (storageUnit: ListItem | null) => void;
+};
+
+const toListItem = (id: string, options: StorageUnitOption[]): ListItem => ({
+ id,
+ name: labelToString(options.find((o) => o.value === id)?.label ?? "")
+});
+
+function StorageUnit({
+ name,
+ value,
+ label,
+ helperText,
+ placeholder = "Select storage unit",
+ isReadOnly,
+ isOptional,
+ disabled,
+ className,
+ onClick,
+ locationId,
+ itemId,
+ inline,
+ allowCreate = true,
+ onChange
+}: StorageUnitProps) {
+ const options = useStorageUnitLeafOptions(locationId, itemId);
+ const { triggerRef, onCreateOption, node } =
+ useNewStorageUnitModal(locationId);
+ const readOnly = isReadOnly || disabled;
+
+ if (name) {
+ return (
+ <>
+ <CreatableCombobox
+ ref={triggerRef}
+ name={name}
+ value={value ?? undefined}
+ options={options}
+ label={label ?? "Storage Unit"}
+ helperText={helperText}
+ placeholder={placeholder}
+ isReadOnly={readOnly}
+ isOptional={isOptional}
+ className={className}
+ onClick={onClick}
+ inline={inline ? storageUnitPreview : undefined}
+ onCreateOption={allowCreate ? onCreateOption : undefined}
+ onChange={(option) =>
+ onChange?.(
+ option
+ ? { id: option.value, name: labelToString(option.label) }
+ : null
+ )
+ }
+ />
+ {node}
+ </>
+ );
+ }
+
+ if (!locationId) return null;
+
+ return (
+ <>
+ <CreatableComboboxBase
+ ref={triggerRef}
+ options={options}
+ value={value ?? undefined}
+ isReadOnly={readOnly}
+ isClearable
+ placeholder={placeholder}
+ className={className}
+ onClick={onClick}
+ onCreateOption={allowCreate ? onCreateOption : undefined}
+ onChange={(selected) =>
+ onChange?.(selected ? toListItem(selected, options) : null)
+ }
+ />
+ {node}
+ </>
+ );
+}
+
+StorageUnit.displayName = "StorageUnit";
+
+export default StorageUnit;
diff --git a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx b/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx
deleted file mode 100644
index 5881e84140..0000000000
--- a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx
+++ /dev/null
@@ -1,520 +0,0 @@
-// Hierarchical (drill-down + breadcrumb + search) storage-unit picker.
-// Backed by `storageUnits_recursive` so children render under their parent.
-//
-// Two exports:
-// - `StorageUnitDrillSelect` — controlled (value/onChange). Use in any
-// non-form context (table cells, custom controllers).
-// - `StorageUnitDrillSelectField` — bound to `@carbon/form` via
-// `useControlField` + `useField`. Drop-in replacement for the flat
-// `<Combobox name="..." />` inside a `ValidatedForm`.
-
-import { useControlField, useField } from "@carbon/form";
-import {
- cn,
- FormControl,
- FormErrorMessage,
- FormHelperText,
- FormLabel,
- HStack,
- IconButton,
- Input,
- Popover,
- PopoverContent,
- PopoverTrigger,
- useDisclosure,
- VStack
-} from "@carbon/react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import {
- LuChevronDown,
- LuChevronRight,
- LuMapPin,
- LuPlus,
- LuSettings2,
- LuX
-} from "react-icons/lu";
-import { useFetcher } from "react-router";
-import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";
-import { path } from "~/utils/path";
-import { useLocations } from "./Location";
-
-export type StorageUnitTreeRow = {
- id: string;
- name: string;
- parentId: string | null;
- depth: number;
- ancestorPath: string[];
-};
-
-/**
- * Fetches the recursive tree for a single location. One round-trip per
- * locationId change; consumers cache by reference identity.
- */
-export function useStorageUnitsTree(locationId?: string | null) {
- const fetcher = useFetcher<{
- data: StorageUnitTreeRow[] | null;
- error: unknown;
- }>();
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render
- useEffect(() => {
- if (locationId) fetcher.load(path.to.api.storageUnitsTree(locationId));
- }, [locationId]);
-
- return fetcher.data?.data ?? [];
-}
-
-type StorageUnitDrillSelectProps = {
- locationId: string | null | undefined;
- value: string | null | undefined;
- onChange: (id: string, row?: StorageUnitTreeRow) => void;
- isReadOnly?: boolean;
- /** Show "+ New storage unit" footer. Defaults to `true`. */
- allowCreate?: boolean;
- placeholder?: string;
- className?: string;
- /**
- * Exclude the given unit and all its descendants from the tree. Used by
- * parent-pickers so a user can't pick themselves / a child (cycle). DB
- * also enforces via `storage_unit_enforce_no_cycle`.
- */
- excludeDescendantsOf?: string;
-};
-
-export function StorageUnitDrillSelect({
- locationId,
- value,
- onChange,
- isReadOnly,
- allowCreate = true,
- placeholder = "Select",
- className,
- excludeDescendantsOf
-}: StorageUnitDrillSelectProps) {
- const allRows = useStorageUnitsTree(locationId);
- const excludedIds = useExcludedDescendantIds(excludeDescendantsOf);
- const rows = useMemo(
- () =>
- excludedIds.size === 0
- ? allRows
- : allRows.filter((r) => !excludedIds.has(r.id)),
- [allRows, excludedIds]
- );
- const newStorageUnitModal = useDisclosure();
- const [created, setCreated] = useState<string>("");
- const [open, setOpen] = useState(false);
- const [stack, setStack] = useState<string[]>([]);
- const [search, setSearch] = useState("");
- const triggerRef = useRef<HTMLButtonElement>(null);
-
- const byId = useMemo(() => {
- const m = new Map<string, StorageUnitTreeRow>();
- rows.forEach((r) => {
- m.set(r.id, r);
- });
- return m;
- }, [rows]);
-
- const childrenOf = useMemo(() => {
- const m = new Map<string | null, StorageUnitTreeRow[]>();
- rows.forEach((r) => {
- const arr = m.get(r.parentId) ?? [];
- arr.push(r);
- m.set(r.parentId, arr);
- });
- m.forEach((arr) => {
- arr.sort((a, b) => a.name.localeCompare(b.name));
- });
- return m;
- }, [rows]);
-
- const currentParentId = stack.length === 0 ? null : stack[stack.length - 1];
- const currentChildren = childrenOf.get(currentParentId) ?? [];
- const breadcrumb = stack
- .map((id) => byId.get(id))
- .filter((r): r is StorageUnitTreeRow => Boolean(r));
-
- const renderPath = useCallback(
- (row: StorageUnitTreeRow) =>
- (row.ancestorPath ?? [])
- .slice(0, -1)
- .map((id) => byId.get(id)?.name)
- .filter(Boolean)
- .join(" / "),
- [byId]
- );
-
- const searchResults = useMemo(() => {
- const q = search.trim().toLowerCase();
- if (!q) return null;
- return rows.filter((r) => {
- if (r.name?.toLowerCase().includes(q)) return true;
- return (r.ancestorPath ?? []).some((id) =>
- byId.get(id)?.name?.toLowerCase().includes(q)
- );
- });
- }, [search, rows, byId]);
-
- const selectedRow = value ? byId.get(value) : undefined;
- const triggerLabel = selectedRow?.name ?? "";
-
- // Look up the current location's name for the breadcrumb root.
- const locations = useLocations();
- const locationLabel = useMemo(() => {
- const match = locations.find((l) => l.value === locationId);
- return match ? (typeof match.label === "string" ? match.label : "") : "";
- }, [locations, locationId]);
-
- // Open with the selected row's parent stack so the user sees the selected
- // unit highlighted in its sibling list on reopen.
- useEffect(() => {
- if (!open) return;
- if (!value) return;
- const row = byId.get(value);
- if (!row) return;
- setStack((row.ancestorPath ?? []).slice(0, -1));
- }, [open, value, byId]);
-
- const reset = () => {
- setStack([]);
- setSearch("");
- };
-
- const select = (id: string) => {
- onChange(id, id ? byId.get(id) : undefined);
- setOpen(false);
- reset();
- };
-
- if (!locationId) return null;
-
- return (
- <>
- <Popover
- open={open}
- onOpenChange={(o) => {
- setOpen(o);
- if (!o) reset();
- }}
- >
- <PopoverTrigger asChild>
- <button
- ref={triggerRef}
- type="button"
- disabled={isReadOnly}
- className={cn(
- "flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-left shadow-xs transition-[color,box-shadow]",
- "outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
- isReadOnly && "opacity-60 cursor-not-allowed",
- !triggerLabel && "text-muted-foreground",
- className
- )}
- >
- <span className="min-w-0 flex-1 truncate">
- {triggerLabel || placeholder}
- </span>
- <span className="flex shrink-0 items-center gap-1">
- {value && !isReadOnly ? (
- <span
- role="button"
- tabIndex={-1}
- aria-label="Clear"
- onClick={(e) => {
- e.stopPropagation();
- onChange("");
- }}
- className="flex h-4 w-4 items-center justify-center rounded opacity-60 hover:bg-muted hover:opacity-100"
- >
- <LuX className="h-3 w-3" />
- </span>
- ) : null}
- <LuChevronDown className="h-4 w-4 opacity-50" />
- </span>
- </button>
- </PopoverTrigger>
- <PopoverContent
- align="start"
- sideOffset={4}
- collisionPadding={12}
- avoidCollisions
- className="w-auto min-w-[280px] max-w-[min(420px,calc(100vw-24px))] p-0"
- >
- {/* Breadcrumb — always visible. Root crumb = location, non-clickable
- (DrillSelect is single-location); subsequent crumbs are parent
- units (clickable to navigate up the tree). */}
- <div className="flex flex-wrap items-center gap-0.5 border-b px-2 py-1.5">
- <button
- type="button"
- onClick={() => setStack([])}
- className={cn(
- "flex items-center gap-1 rounded px-1.5 py-0.5 text-xs hover:bg-muted",
- stack.length === 0
- ? "font-medium text-foreground"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- <LuMapPin className="h-3 w-3 opacity-70" />
- {locationLabel || "Location"}
- </button>
- {breadcrumb.map((row, i) => (
- <span key={row.id} className="flex items-center gap-0.5">
- <LuChevronRight className="h-3 w-3 text-muted-foreground/60" />
- <button
- type="button"
- onClick={() => setStack(stack.slice(0, i + 1))}
- className={cn(
- "rounded px-1.5 py-0.5 text-xs hover:bg-muted",
- i === breadcrumb.length - 1
- ? "font-medium text-foreground"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- {row.name}
- </button>
- </span>
- ))}
- </div>
-
- {/* Search — flush, borderless. */}
- <Input
- autoFocus
- borderless
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="Search storage units…"
- className="h-9 rounded-none border-b border-border bg-transparent px-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"
- />
-
- {/* List */}
- <ul className="max-h-[260px] overflow-y-auto py-1">
- {searchResults ? (
- searchResults.length === 0 ? (
- <li className="px-3 py-6 text-center text-xs text-muted-foreground">
- No matches
- </li>
- ) : (
- searchResults.map((row) => (
- <li key={row.id}>
- <button
- type="button"
- onClick={() => select(row.id)}
- className="flex w-full flex-col items-start gap-0.5 px-3 py-1.5 text-left hover:bg-muted"
- >
- <span className="text-sm">{row.name}</span>
- {renderPath(row) && (
- <span className="text-xs text-muted-foreground">
- {renderPath(row)}
- </span>
- )}
- </button>
- </li>
- ))
- )
- ) : currentChildren.length === 0 ? (
- <li className="px-3 py-6 text-center text-xs text-muted-foreground">
- No storage units
- </li>
- ) : (
- currentChildren.map((row) => {
- const hasChildren = (childrenOf.get(row.id) ?? []).length > 0;
- const isSelected = row.id === value;
- return (
- <li
- key={row.id}
- className="flex items-stretch hover:bg-muted"
- >
- <button
- type="button"
- onClick={() => select(row.id)}
- className={cn(
- "flex-1 truncate px-3 py-1.5 text-left text-sm",
- isSelected && "font-medium text-foreground"
- )}
- >
- {row.name}
- </button>
- {hasChildren && (
- <button
- type="button"
- onClick={() => {
- setStack([...stack, row.id]);
- setSearch("");
- }}
- className="flex w-7 shrink-0 items-center justify-center border-l text-muted-foreground hover:text-foreground"
- aria-label={`Open ${row.name}`}
- >
- <LuChevronRight className="h-3.5 w-3.5" />
- </button>
- )}
- </li>
- );
- })
- )}
- </ul>
-
- {allowCreate && (
- <button
- type="button"
- onClick={() => {
- setOpen(false);
- reset();
- newStorageUnitModal.onOpen();
- setCreated(search);
- }}
- className="flex w-full items-center gap-1 border-t border-border px-3 py-2 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground"
- >
- <span className="text-sm leading-none">+</span>
- New storage unit{search ? `: "${search}"` : ""}
- </button>
- )}
- </PopoverContent>
- </Popover>
- {newStorageUnitModal.isOpen && (
- <StorageUnitForm
- locationId={locationId}
- type="modal"
- onClose={() => {
- setCreated("");
- newStorageUnitModal.onClose();
- triggerRef.current?.click();
- }}
- initialValues={{
- name: created,
- locationId: locationId,
- storageTypeIds: []
- }}
- />
- )}
- </>
- );
-}
-
-// ---------------------------------------------------------------------------
-// useExcludedDescendantIds — fetches the subtree under `rootId` so a
-// parent-picker can exclude self + descendants (cycle prevention).
-// ---------------------------------------------------------------------------
-
-export function useExcludedDescendantIds(rootId?: string): Set<string> {
- const descendantsFetcher = useFetcher<{ data: { id: string }[] }>();
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render
- useEffect(() => {
- if (rootId) {
- descendantsFetcher.load(path.to.api.storageUnitDescendants(rootId));
- }
- }, [rootId]);
-
- return useMemo(() => {
- if (!rootId) return new Set<string>();
- const ids = new Set<string>([rootId]);
- for (const row of descendantsFetcher.data?.data ?? []) {
- if (row.id) ids.add(row.id);
- }
- return ids;
- }, [rootId, descendantsFetcher.data]);
-}
-
-// ---------------------------------------------------------------------------
-// Form-aware variant — binds to `@carbon/form` via name + hidden input.
-// ---------------------------------------------------------------------------
-
-type StorageUnitDrillSelectFieldProps = {
- name: string;
- label?: string;
- inline?: boolean;
- helperText?: string;
- locationId: string | null | undefined;
- isReadOnly?: boolean;
- isOptional?: boolean;
- allowCreate?: boolean;
- placeholder?: string;
- className?: string;
- excludeDescendantsOf?: string;
- /**
- * Callback fired after the form value updates. Receives the chosen row so
- * callers that need name/parent metadata don't have to re-fetch. `null` on
- * clear.
- */
- onChange?: (row: StorageUnitTreeRow | null) => void;
-};
-
-export function StorageUnitDrillSelectField({
- name,
- label,
- inline = false,
- helperText,
- locationId,
- isReadOnly,
- isOptional,
- allowCreate,
- placeholder,
- className,
- excludeDescendantsOf,
- onChange
-}: StorageUnitDrillSelectFieldProps) {
- const { error, getInputProps, isOptional: fieldIsOptional } = useField(name);
- const [value, setValue] = useControlField<string | undefined>(name);
- const [inlineMode, setInlineMode] = useState(inline);
- const rows = useStorageUnitsTree(locationId);
- const displayName = rows.find((r) => r.id === value)?.name ?? "";
-
- if (inlineMode) {
- return (
- <VStack spacing={0}>
- {label && (
- <span className="text-xs text-muted-foreground">{label}</span>
- )}
- <input type="hidden" name={name} value={value ?? ""} />
- <HStack spacing={0} className="w-full justify-between">
- {displayName && (
- <span className="flex-grow text-sm line-clamp-1">
- {displayName}
- </span>
- )}
- <IconButton
- icon={displayName ? <LuSettings2 /> : <LuPlus />}
- aria-label={displayName ? "Edit" : "Add"}
- size="sm"
- variant="secondary"
- isDisabled={isReadOnly}
- onClick={() => setInlineMode(false)}
- />
- </HStack>
- </VStack>
- );
- }
-
- return (
- <FormControl isInvalid={!!error}>
- {label && (
- <FormLabel htmlFor={name} isOptional={isOptional ?? fieldIsOptional}>
- {label}
- </FormLabel>
- )}
- <input
- {...getInputProps({ id: name, type: "hidden" })}
- name={name}
- value={value ?? ""}
- />
- <StorageUnitDrillSelect
- locationId={locationId}
- value={value ?? null}
- onChange={(next, row) => {
- setValue(next || undefined);
- onChange?.(next ? (row ?? null) : null);
- if (inline) setInlineMode(true);
- }}
- isReadOnly={isReadOnly}
- allowCreate={allowCreate}
- placeholder={placeholder}
- className={className}
- excludeDescendantsOf={excludeDescendantsOf}
- />
- {error ? (
- <FormErrorMessage>{error}</FormErrorMessage>
- ) : (
- helperText && <FormHelperText>{helperText}</FormHelperText>
- )}
- </FormControl>
- );
-}
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index cc5b1c4964..95aa314fae 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -674,6 +674,33 @@ export async function getStorageUnitChildren(
.order("name");
}
+// Descendants of the given root ids, from just below the roots (depth > 1) down
+// to `maxDepth` inclusive. A node is a descendant of a root when that root
+// appears in its ancestorPath, so a single `overlaps` query returns the
+// subtrees in one round trip. Used to render the tree expanded by default;
+// the depth cap keeps very deep trees from loading their entire subtree
+// eagerly — anything below `maxDepth` still lazy-loads on demand.
+export async function getStorageUnitSubtrees(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ locationId: string,
+ rootIds: string[],
+ maxDepth: number
+) {
+ if (rootIds.length === 0) {
+ return { data: [] as any[], error: null };
+ }
+ return client
+ .from("storageUnits_recursive")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("locationId", locationId)
+ .gt("depth", 1)
+ .lte("depth", maxDepth)
+ .overlaps("ancestorPath", rootIds)
+ .order("name");
+}
+
// Set of storageUnit ids that have at least one child in the given location.
// Drives whether the table renders an expand chevron on a row.
export async function getStorageUnitParentIdsWithChildren(
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
index 29b3beb46f..77871755de 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
@@ -53,7 +53,7 @@ import { Outlet, useFetcher } from "react-router";
import type { z } from "zod";
import { Enumerable } from "~/components/Enumerable";
import { Input, Location, Select, TextArea } from "~/components/Form";
-import { StorageUnitDrillSelectField } from "~/components/Form/StorageUnitDrillSelect";
+import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { usePermissions, usePrinting } from "~/hooks";
import type {
@@ -349,7 +349,7 @@ const InventoryStorageUnits = ({
<VStack spacing={2}>
<Location name="locationId" label={t`Location`} isReadOnly />
- <StorageUnitDrillSelectField
+ <StorageUnit
name="storageUnitId"
locationId={pickMethod.locationId}
label={t`Storage Unit`}
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 55664393fb..f1419962ac 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -47,7 +47,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
-import { StorageUnitDrillSelect } from "~/components/Form/StorageUnitDrillSelect";
+import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { useUrlParams } from "~/hooks";
@@ -564,11 +564,11 @@ const InventoryTable = memo(
)}
</div>
)}
- <StorageUnitDrillSelect
+ <StorageUnit
locationId={locationId}
value={null}
- onChange={(id) => {
- if (id) toggle(id);
+ onChange={(storageUnit) => {
+ if (storageUnit) toggle(storageUnit.id);
}}
allowCreate={false}
/>
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 97c6d94fbb..de637006e5 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -66,7 +66,7 @@ import {
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
import FileDropzone from "~/components/FileDropzone";
-import { StorageUnitDrillSelect } from "~/components/Form/StorageUnitDrillSelect";
+import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { ConfirmDelete } from "~/components/Modals";
import { useRouteData, useUser } from "~/hooks";
@@ -575,7 +575,7 @@ function ReceiptLineItem({
<label className="text-xs text-muted-foreground">
Storage Unit
</label>
- <StorageUnitDrillSelect
+ <StorageUnit
locationId={line.locationId}
value={line.storageUnitId}
isReadOnly={isReadOnly}
@@ -583,7 +583,7 @@ function ReceiptLineItem({
onUpdate({
lineId: line.id!,
field: "storageUnitId",
- value: storageUnit
+ value: storageUnit?.id ?? ""
});
}}
/>
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
index 00da544683..8f7eda3ac3 100644
--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
@@ -20,12 +20,12 @@ import {
Input,
Location,
StorageTypes,
- StorageUnit,
Submit
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { storageUnitValidator } from "~/modules/inventory";
import { path } from "~/utils/path";
+import { StorageUnitParentSelect } from "./StorageUnitParentSelect";
type StorageUnitFormProps = {
locationId: string;
@@ -93,7 +93,7 @@ const StorageUnitForm = ({
name="locationId"
label={t`Location`}
/>
- <StorageUnit
+ <StorageUnitParentSelect
name="parentId"
label={t`Parent Storage Unit`}
locationId={locationId}
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx
new file mode 100644
index 0000000000..dcee441363
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx
@@ -0,0 +1,385 @@
+// Hierarchical parent-storage-unit picker — drill-down + breadcrumb + search.
+// Local to the Storage Unit form: the only place a *non-leaf* unit is the
+// target (choosing where a unit sits in the tree). Everywhere else picks a
+// leaf bin via the shared `<StorageUnit>` combobox.
+//
+// Backed by the same `useStorageUnitsTree` data hook as `<StorageUnit>`.
+
+import { useControlField, useField } from "@carbon/form";
+import {
+ cn,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@carbon/react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { LuChevronDown, LuChevronRight, LuMapPin, LuX } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { useLocations } from "~/components/Form/Location";
+import {
+ type StorageUnitTreeRow,
+ useStorageUnitsTree
+} from "~/components/Form/StorageUnit";
+import { path } from "~/utils/path";
+
+// ---------------------------------------------------------------------------
+// useExcludedDescendantIds — fetches the subtree under `rootId` so the picker
+// can exclude self + descendants (cycle prevention). DB also enforces this via
+// `storage_unit_enforce_no_cycle`.
+// ---------------------------------------------------------------------------
+
+function useExcludedDescendantIds(rootId?: string): Set<string> {
+ const descendantsFetcher = useFetcher<{ data: { id: string }[] }>();
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render
+ useEffect(() => {
+ if (rootId) {
+ descendantsFetcher.load(path.to.api.storageUnitDescendants(rootId));
+ }
+ }, [rootId]);
+
+ return useMemo(() => {
+ if (!rootId) return new Set<string>();
+ const ids = new Set<string>([rootId]);
+ for (const row of descendantsFetcher.data?.data ?? []) {
+ if (row.id) ids.add(row.id);
+ }
+ return ids;
+ }, [rootId, descendantsFetcher.data]);
+}
+
+// ---------------------------------------------------------------------------
+// Controlled drill-down
+// ---------------------------------------------------------------------------
+
+type DrillSelectProps = {
+ locationId: string | null | undefined;
+ value: string | null | undefined;
+ onChange: (id: string) => void;
+ isReadOnly?: boolean;
+ placeholder?: string;
+ excludeDescendantsOf?: string;
+};
+
+function DrillSelect({
+ locationId,
+ value,
+ onChange,
+ isReadOnly,
+ placeholder = "Select",
+ excludeDescendantsOf
+}: DrillSelectProps) {
+ const allRows = useStorageUnitsTree(locationId);
+ const excludedIds = useExcludedDescendantIds(excludeDescendantsOf);
+ const rows = useMemo(
+ () =>
+ excludedIds.size === 0
+ ? allRows
+ : allRows.filter((r) => !excludedIds.has(r.id)),
+ [allRows, excludedIds]
+ );
+ const [open, setOpen] = useState(false);
+ const [stack, setStack] = useState<string[]>([]);
+ const [search, setSearch] = useState("");
+
+ const byId = useMemo(() => {
+ const m = new Map<string, StorageUnitTreeRow>();
+ rows.forEach((r) => {
+ m.set(r.id, r);
+ });
+ return m;
+ }, [rows]);
+
+ const childrenOf = useMemo(() => {
+ const m = new Map<string | null, StorageUnitTreeRow[]>();
+ rows.forEach((r) => {
+ const arr = m.get(r.parentId) ?? [];
+ arr.push(r);
+ m.set(r.parentId, arr);
+ });
+ m.forEach((arr) => {
+ arr.sort((a, b) => a.name.localeCompare(b.name));
+ });
+ return m;
+ }, [rows]);
+
+ const currentParentId = stack.length === 0 ? null : stack[stack.length - 1];
+ const currentChildren = childrenOf.get(currentParentId) ?? [];
+ const breadcrumb = stack
+ .map((id) => byId.get(id))
+ .filter((r): r is StorageUnitTreeRow => Boolean(r));
+
+ const renderPath = useCallback(
+ (row: StorageUnitTreeRow) =>
+ (row.ancestorPath ?? [])
+ .slice(0, -1)
+ .map((id) => byId.get(id)?.name)
+ .filter(Boolean)
+ .join(" / "),
+ [byId]
+ );
+
+ const searchResults = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ if (!q) return null;
+ return rows.filter((r) => {
+ if (r.name?.toLowerCase().includes(q)) return true;
+ return (r.ancestorPath ?? []).some((id) =>
+ byId.get(id)?.name?.toLowerCase().includes(q)
+ );
+ });
+ }, [search, rows, byId]);
+
+ const selectedRow = value ? byId.get(value) : undefined;
+ const triggerLabel = selectedRow?.name ?? "";
+
+ // Look up the current location's name for the breadcrumb root.
+ const locations = useLocations();
+ const locationLabel = useMemo(() => {
+ const match = locations.find((l) => l.value === locationId);
+ return match ? (typeof match.label === "string" ? match.label : "") : "";
+ }, [locations, locationId]);
+
+ // Open with the selected row's parent stack so the user sees the selected
+ // unit highlighted in its sibling list on reopen.
+ useEffect(() => {
+ if (!open) return;
+ if (!value) return;
+ const row = byId.get(value);
+ if (!row) return;
+ setStack((row.ancestorPath ?? []).slice(0, -1));
+ }, [open, value, byId]);
+
+ const reset = () => {
+ setStack([]);
+ setSearch("");
+ };
+
+ const select = (id: string) => {
+ onChange(id);
+ setOpen(false);
+ reset();
+ };
+
+ if (!locationId) return null;
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(o) => {
+ setOpen(o);
+ if (!o) reset();
+ }}
+ >
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={isReadOnly}
+ className={cn(
+ "flex h-9 w-full items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-left shadow-xs transition-[color,box-shadow]",
+ "outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
+ isReadOnly && "opacity-60 cursor-not-allowed",
+ !triggerLabel && "text-muted-foreground"
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {triggerLabel || placeholder}
+ </span>
+ <span className="flex shrink-0 items-center gap-1">
+ {value && !isReadOnly ? (
+ <span
+ role="button"
+ tabIndex={-1}
+ aria-label="Clear"
+ onClick={(e) => {
+ e.stopPropagation();
+ onChange("");
+ }}
+ className="flex h-4 w-4 items-center justify-center rounded opacity-60 hover:bg-muted hover:opacity-100"
+ >
+ <LuX className="h-3 w-3" />
+ </span>
+ ) : null}
+ <LuChevronDown className="h-4 w-4 opacity-50" />
+ </span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ sideOffset={4}
+ collisionPadding={12}
+ avoidCollisions
+ className="w-auto min-w-[280px] max-w-[min(420px,calc(100vw-24px))] p-0"
+ >
+ {/* Breadcrumb — root crumb = location, non-clickable (single-location);
+ subsequent crumbs are parent units (clickable to navigate up). */}
+ <div className="flex flex-wrap items-center gap-0.5 border-b px-2 py-1.5">
+ <button
+ type="button"
+ onClick={() => setStack([])}
+ className={cn(
+ "flex items-center gap-1 rounded px-1.5 py-0.5 text-xs hover:bg-muted",
+ stack.length === 0
+ ? "font-medium text-foreground"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ <LuMapPin className="h-3 w-3 opacity-70" />
+ {locationLabel || "Location"}
+ </button>
+ {breadcrumb.map((row, i) => (
+ <span key={row.id} className="flex items-center gap-0.5">
+ <LuChevronRight className="h-3 w-3 text-muted-foreground/60" />
+ <button
+ type="button"
+ onClick={() => setStack(stack.slice(0, i + 1))}
+ className={cn(
+ "rounded px-1.5 py-0.5 text-xs hover:bg-muted",
+ i === breadcrumb.length - 1
+ ? "font-medium text-foreground"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ {row.name}
+ </button>
+ </span>
+ ))}
+ </div>
+
+ {/* Search — flush, borderless. */}
+ <Input
+ autoFocus
+ borderless
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search storage units…"
+ className="h-9 rounded-none border-b border-border bg-transparent px-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"
+ />
+
+ {/* List */}
+ <ul className="max-h-[260px] overflow-y-auto py-1">
+ {searchResults ? (
+ searchResults.length === 0 ? (
+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">
+ No matches
+ </li>
+ ) : (
+ searchResults.map((row) => (
+ <li key={row.id}>
+ <button
+ type="button"
+ onClick={() => select(row.id)}
+ className="flex w-full flex-col items-start gap-0.5 px-3 py-1.5 text-left hover:bg-muted"
+ >
+ <span className="text-sm">{row.name}</span>
+ {renderPath(row) && (
+ <span className="text-xs text-muted-foreground">
+ {renderPath(row)}
+ </span>
+ )}
+ </button>
+ </li>
+ ))
+ )
+ ) : currentChildren.length === 0 ? (
+ <li className="px-3 py-6 text-center text-xs text-muted-foreground">
+ No storage units
+ </li>
+ ) : (
+ currentChildren.map((row) => {
+ const hasChildren = (childrenOf.get(row.id) ?? []).length > 0;
+ const isSelected = row.id === value;
+ return (
+ <li key={row.id} className="flex items-stretch hover:bg-muted">
+ <button
+ type="button"
+ onClick={() => select(row.id)}
+ className={cn(
+ "flex-1 truncate px-3 py-1.5 text-left text-sm",
+ isSelected && "font-medium text-foreground"
+ )}
+ >
+ {row.name}
+ </button>
+ {hasChildren && (
+ <button
+ type="button"
+ onClick={() => {
+ setStack([...stack, row.id]);
+ setSearch("");
+ }}
+ className="flex w-7 shrink-0 items-center justify-center border-l text-muted-foreground hover:text-foreground"
+ aria-label={`Open ${row.name}`}
+ >
+ <LuChevronRight className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </li>
+ );
+ })
+ )}
+ </ul>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Form-bound parent picker
+// ---------------------------------------------------------------------------
+
+type StorageUnitParentSelectProps = {
+ name: string;
+ label?: string;
+ helperText?: string;
+ locationId: string | null | undefined;
+ isReadOnly?: boolean;
+ isOptional?: boolean;
+ /** Exclude this unit and its descendants (cycle prevention). */
+ excludeDescendantsOf?: string;
+};
+
+export function StorageUnitParentSelect({
+ name,
+ label,
+ helperText,
+ locationId,
+ isReadOnly,
+ isOptional,
+ excludeDescendantsOf
+}: StorageUnitParentSelectProps) {
+ const { error, getInputProps, isOptional: fieldIsOptional } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ return (
+ <FormControl isInvalid={!!error}>
+ {label && (
+ <FormLabel htmlFor={name} isOptional={isOptional ?? fieldIsOptional}>
+ {label}
+ </FormLabel>
+ )}
+ <input
+ {...getInputProps({ id: name, type: "hidden" })}
+ name={name}
+ value={value ?? ""}
+ />
+ <DrillSelect
+ locationId={locationId}
+ value={value ?? null}
+ onChange={(next) => setValue(next || undefined)}
+ isReadOnly={isReadOnly}
+ excludeDescendantsOf={excludeDescendantsOf}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+}
diff --git a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
index 3eac29c5b1..ea3d22b0d3 100644
--- a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
@@ -44,7 +44,7 @@ import {
ShelfLifeStartTiming,
Submit
} from "~/components/Form";
-import { StorageUnitDrillSelectField } from "~/components/Form/StorageUnitDrillSelect";
+import StorageUnit from "~/components/Form/StorageUnit";
import { usePermissions, useSettings, useUser } from "~/hooks";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
@@ -181,11 +181,10 @@ const PickMethodForm = ({
<Hidden name="itemId" />
<Hidden name="locationId" />
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">
- <StorageUnitDrillSelectField
+ <StorageUnit
name="defaultStorageUnitId"
label={t`Default Storage Unit`}
locationId={initialValues.locationId}
- className="w-full"
/>
{shelfLifeApplicable && (
diff --git a/apps/erp/app/modules/storageRules/ui/ValueInput.tsx b/apps/erp/app/modules/storageRules/ui/ValueInput.tsx
index b953bb5e7f..dff452df2b 100644
--- a/apps/erp/app/modules/storageRules/ui/ValueInput.tsx
+++ b/apps/erp/app/modules/storageRules/ui/ValueInput.tsx
@@ -25,7 +25,7 @@ import { useLocations } from "~/components/Form/Location";
import {
type StorageUnitTreeRow,
useStorageUnitsTree
-} from "~/components/Form/StorageUnitDrillSelect";
+} from "~/components/Form/StorageUnit";
import MultiValueCombobox from "./MultiValueCombobox";
import type { ValueOption } from "./useValueOptions";
import ValueCombobox from "./ValueCombobox";
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 db0f8562af..74f8da962d 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-06-12T08:34:31.151Z",
- "totalTools": 1187,
+ "generated": "2026-06-13T02:22:15.288Z",
+ "totalTools": 1188,
"modules": 15,
"tools": [
{
@@ -4407,6 +4407,45 @@
]
}
},
+ {
+ "name": "inventory_getStorageUnitSubtrees",
+ "module": "inventory",
+ "classification": "READ",
+ "description": "get storage unit subtrees",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "locationId",
+ "rootIds",
+ "maxDepth"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "locationId": {
+ "type": "string"
+ },
+ "rootIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "maxDepth": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "locationId",
+ "rootIds",
+ "maxDepth"
+ ]
+ }
+ },
{
"name": "inventory_getStorageUnitParentIdsWithChildren",
"module": "inventory",
diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.tsx
index c3692edb84..b6b7cf35f0 100644
--- a/apps/erp/app/routes/x+/inventory+/storage-units.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-units.tsx
@@ -9,6 +9,7 @@ import {
getStorageTypesList,
getStorageUnitParentIdsWithChildren,
getStorageUnitRoots,
+ getStorageUnitSubtrees,
searchStorageUnitsWithAncestors
} from "~/modules/inventory";
import StorageUnitsTable from "~/modules/inventory/ui/StorageUnits/StorageUnitsTable";
@@ -24,6 +25,10 @@ export const handle: Handle = {
module: "inventory"
};
+// Deepest level (1-based, roots = 1) the tree eagerly loads and pre-expands.
+// Nodes below this still render with an expand chevron and lazy-load on click.
+const EAGER_EXPAND_MAX_DEPTH = 5;
+
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
view: "inventory",
@@ -119,8 +124,42 @@ export async function loader({ request }: LoaderFunctionArgs) {
)
);
}
- rows = rootsResult.data ?? [];
+ const roots = rootsResult.data ?? [];
count = rootsResult.count ?? 0;
+
+ // Eagerly load the subtrees of the visible (paginated) roots so the tree
+ // renders expanded by default instead of lazily loading one level at a
+ // time. Pagination still applies to roots; each shown root just arrives
+ // with its descendants. The depth cap bounds how much of a deep tree we
+ // pull (and pre-expand) up front — anything below it still lazy-loads.
+ const descendants = await getStorageUnitSubtrees(
+ client,
+ companyId,
+ locationId,
+ roots.map((r) => r.id as string),
+ EAGER_EXPAND_MAX_DEPTH
+ );
+ if (descendants.error) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(
+ request,
+ error(descendants.error, "Failed to fetch storageUnits")
+ )
+ );
+ }
+ rows = [...roots, ...(descendants.data ?? [])];
+
+ // Pre-expand only nodes whose children were actually loaded (i.e. any node
+ // that appears as a parent within the fetched rows). Deriving this from the
+ // loaded set — rather than the location-wide parentIdsWithChildren — keeps
+ // nodes at the depth cap collapsed so their (unfetched) children lazy-load
+ // on click instead of rendering as expanded-but-empty.
+ const expandedParents = new Set<string>();
+ for (const row of rows) {
+ if (row.parentId) expandedParents.add(row.parentId as string);
+ }
+ initialExpanded = Array.from(expandedParents);
}
return {
diff --git a/llm/tasks/lessons.md b/llm/tasks/lessons.md
index a81bd139ff..cd4fdc5399 100644
--- a/llm/tasks/lessons.md
+++ b/llm/tasks/lessons.md
@@ -61,3 +61,15 @@ Patterns learned from corrections. Review at the start of each session.
## Bash fallbacks when tools are missing
- `pandoc` is not on the user's machine. For `.docx` extraction, use the `anthropic-skills:docx` skill's `unpack.py` (needs `defusedxml`; install via `mise x [email protected] -- pip install defusedxml`) or an equivalent Python/JS extraction, rather than assuming pandoc is available.
+
+## Verify which component a callsite actually renders before calling it "broken"
+
+- When auditing a shared component's callsites, confirm the JSX tag resolves to
+ the import you think it does. A name like `<StorageUnit>` can be a *local*
+ function in the same file (ShipmentLines defines its own `StorageUnit` over
+ `useStorageUnits` + `Combobox`), not the shared shim. I wrongly concluded the
+ shim was "broken" and edited the callsite, breaking the type (`storageUnit`
+ was a `string` there, not `ListItem`).
+- Rule: before claiming a callsite is broken or changing its `onChange` shape,
+ grep the file for a local `function <Name>` / `const <Name> =` shadowing the
+ import, and check the actual prop/callback types at that callsite.