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.

fix: inventory count filters (#1154)

Sid60d30b4fb513
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 44ccd97bae..142a297cdd 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -408,3 +408,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** Side effects that must accompany job completion (fulfillment, status propagation, posting) go INSIDE `complete_job_to_inventory` — the single choke point every path crosses. Place them before the `accountingEnabled` / zero-WIP early returns if they must run unconditionally. App-layer completion hooks are only valid for effects the SQL function cannot perform (edge-function invocation — cf. `returnAllocatedRemaindersAtJobComplete`, orchestrated in TS for exactly that reason).
**Applies to:** `complete_job_to_inventory`; `apps/erp/app/routes/x+/job+/$jobId.complete.tsx`; `sync_finish_job_operation`; any future completion-triggered behavior (rev-rec POC recognition events).
+
+## A `@ts-expect-error` on generated DB types is evidence of a dropped column, not a type quirk
+
+**Context:** `InventoryTable.tsx` read `row.original.tags` behind a `// @ts-expect-error TS2339`. The suppression was correct that the property was missing — `20260713235406` had forked `get_inventory_quantities` and dropped the `tags` output added by `20260113122437` (the sibling-branch failure mode above). The regression then hid in plain sight for months: the Tags column silently rendered empty, and the Tags filter sent `.overlaps("tags", …)` → PostgREST 42703 against a nonexistent column.
+
+**Problem:** Generated types are mechanically derived from the live schema, so TS2339 on a generated Row/Returns type is never a false positive — it is the type system reporting that the column does not exist. Suppressing it converts a compile-time regression signal into a silent runtime one. The blast radius was widened by `quantities.tsx` calling `redirect(...)` without `throw`, which discarded the resulting PostgREST error and rendered an empty table instead of surfacing it.
+
+**Rule:** Never `@ts-expect-error` / `@ts-ignore` a missing property on a `@carbon/database` generated type. Grep every migration touching the function or table (`grep -l '<name>' migrations/*.sql | sort`) and find the revision that removed it — the fix is a migration restoring the column, not a suppression. When reviewing, treat a `@ts-expect-error` near generated types as a probable dropped-column regression. Corollary: in a loader, always `return` or `throw redirect(...)` on a service error — a `redirect(...)` that is neither returned nor thrown is a no-op that swallows the error and renders empty data.
+
+**Applies to:** `packages/database/src/types.ts` consumers; `apps/erp/app/modules/**/ui/**` table columns bound to RPC outputs; any loader branching on `{ data, error }`.
+
+## A mutually-exclusive primary/fallback branch breaks when the primary source can be legitimately empty
+
+**Context:** The MES Issue dialog (`IssueMaterialModal`) pre-selects tracked lots from two sources: `pickedAllocation` (lots a picking list already picked) and `suggestedAllocation` (the FEFO/pickMethod suggestion of what to pick). It gated the suggestion off whenever a picking allocation merely existed (`shouldSuggestAllocation = … && !hasPickingAllocation`) and chose `seedAllocation = hasPickingAllocation ? pickedAllocation : suggestedAllocation`.
+
+**Problem:** `hasPickingAllocation` was true when `quantityToPick > 0` — i.e. the material is ON a picking list — but `pickedAllocation` is only non-empty once something is physically PICKED (pickingListLineTrackedEntity rows are written at pick time, never at allocation). For a material on an In-Progress list that hasn't been picked yet (common in a multi-line list where other lines were picked first), the primary branch was selected but resolved empty, the suggestion was gated off, and the seed effect bailed → operator got the default first lot instead of the recommendation. The two conditions "should we prefer picked lots" and "do picked lots exist" were conflated.
+
+**Rule:** When one data source is the preferred seed and another is the fallback, branch on whether the preferred source actually HAS data (`primary.length ? primary : fallback`), and load the fallback unconditionally — do not gate the fallback off on a proxy signal (here `hasPickingAllocation`) that can be true while the primary is still empty. Verify the "primary exists but is empty" state explicitly, since it's the one static reading and happy-path testing both miss.
+
+**Applies to:** `apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx` (picked vs suggested allocation seeding); any picking-list-aware UI that distinguishes allocated-but-not-picked from picked (`pickingListLineTrackedEntity.quantityPicked > 0`).
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index dee42c22c9..1971d81532 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -13,6 +13,7 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
- **Warehouse Transfer** — moves inventory between locations (inter-location).
- **Picking List** — generated pick instructions with FEFO/FIFO ordering and tracked entity allocation.
- **Kanban** — pull-based replenishment signal between storage units.
+- **Inventory Count** — physical/cycle count. Created with an optional scope (`storageUnitIds` + `itemType`) recorded in the header's `scope` JSONB (written at create; not yet read back). `generateInventoryCountLines` snapshots on-hand into `inventoryCountLine` rows, **excluding Rejected AND Consumed tracked lots**. The count **detail** table filters lines by item type / storage unit / storage type / tags / material attributes via the `inventoryCountLines` **view** (line → item → subtype tables → storageUnit, flattened) — the same generic column-filter set the quantities screen uses. There is no material-attribute scope at create time.
## Safety
@@ -67,6 +68,7 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",
- `generatePickingList` / `getPickingListAvailability` / `getPickingSchedule` — picking operations
- `getDefaultStorageUnitOrStorageUnitWithHighestQuantity` — picking defaults
- `getTrackedEntities` / `getTrackedEntityExpirations` / `getShelfLifeForItems` — tracking and expiry
+- `generateInventoryCountLines` — Kysely; aggregates `itemLedger` on-hand into `inventoryCountLine` rows, scoped by the optional `storageUnitIds` + `itemType`. Excludes `Rejected` and `Consumed` tracked lots (status-aware, matching `quantityOnHand`); non-tracked rows (NULL status) always included. `getInventoryCountLines` reads the `inventoryCountLines` view (joins item + subtype tables on `id = item."readableId"` — the same predicate `get_inventory_quantities` uses, all LEFT — + `storageUnit`) so the detail table can apply generic column filters on flat columns.
## Key Exports
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 514c523aab..279c0464e9 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1628,14 +1628,12 @@ export async function getInventoryCountLines(
companyId: string,
args: GenericQueryFilters & { search: string | null }
) {
+ // Read from the `inventoryCountLines` view: it flattens item + material +
+ // storage-unit attributes as top-level columns so the count detail table can
+ // apply the same generic column filters the quantities screen does.
let query = client
- .from("inventoryCountLine")
- .select(
- "*, item!inner(name, readableIdWithRevision, type, itemTrackingType, unitOfMeasureCode, thumbnailPath)",
- {
- count: "exact"
- }
- )
+ .from("inventoryCountLines")
+ .select("*", { count: "exact" })
.eq("inventoryCountId", inventoryCountId)
.eq("companyId", companyId);
@@ -1646,8 +1644,7 @@ export async function getInventoryCountLines(
// Search the item's identity (part number / name); the line's own readableId
// is only the batch/serial and is null for most rows.
query = query.or(
- `name.ilike.%${search}%,readableIdWithRevision.ilike.%${search}%`,
- { foreignTable: "item" }
+ `itemName.ilike.%${search}%,itemReadableIdWithRevision.ilike.%${search}%`
);
}
@@ -1655,7 +1652,7 @@ export async function getInventoryCountLines(
// number for a readable count sheet and fall back to the line id for a stable,
// deterministic order.
query = setGenericQueryFilters(query, args, [
- { column: "readableIdWithRevision", ascending: true, foreignTable: "item" },
+ { column: "itemReadableIdWithRevision", ascending: true },
{ column: "id", ascending: true }
]);
return query;
@@ -1776,14 +1773,16 @@ export async function generateInventoryCountLines(
.select((eb) => eb.fn.sum<number>("itemLedger.quantity").as("quantity"))
.where("itemLedger.companyId", "=", companyId)
.where("itemLedger.locationId", "=", locationId)
- // Status-aware on-hand: exclude Rejected stock so `systemQuantity` matches
- // the `get_inventory_quantities` definition of quantityOnHand (which is
- // `SUM(quantity) WHERE trackedEntityStatus IS NULL OR != 'Rejected'`) used
- // everywhere else in the app. Non-tracked rows have a NULL status.
+ // Status-aware on-hand: exclude Rejected and Consumed lots so a count
+ // never lists stock that's been used up or scrapped. Non-tracked rows
+ // have a NULL status and are always included.
.where((eb) =>
eb.or([
eb("itemLedger.trackedEntityStatus", "is", null),
- eb("itemLedger.trackedEntityStatus", "!=", "Rejected")
+ eb("itemLedger.trackedEntityStatus", "not in", [
+ "Rejected",
+ "Consumed"
+ ])
])
)
.groupBy([
@@ -1906,7 +1905,7 @@ async function resnapshotInventoryCountLinesInTrx(
.execute();
// Fresh status-aware on-hand for the location, grouped by bucket (matches
- // `generateInventoryCountLines` / `get_inventory_quantities`).
+ // `generateInventoryCountLines`): exclude Rejected and Consumed lots.
const onHandRows = await trx
.selectFrom("itemLedger")
.select(["itemId", "storageUnitId", "trackedEntityId"])
@@ -1916,7 +1915,7 @@ async function resnapshotInventoryCountLinesInTrx(
.where((eb) =>
eb.or([
eb("trackedEntityStatus", "is", null),
- eb("trackedEntityStatus", "!=", "Rejected")
+ eb("trackedEntityStatus", "not in", ["Rejected", "Consumed"])
])
)
.groupBy(["itemId", "storageUnitId", "trackedEntityId"])
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index dba3f1a2f8..dee39e5b3e 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -418,9 +418,11 @@ const InventoryTable = memo(
materialSubstanceId,
materialFormId
),
+ // The `materialType` column holds the type's name, not its id, so
+ // the filter value must be the name to match.
transform: (data: { id: string; name: string }[] | null) =>
- data?.map(({ id, name }) => ({
- value: id,
+ data?.map(({ name }) => ({
+ value: name,
label: name
})) ?? []
}
@@ -457,8 +459,7 @@ const InventoryTable = memo(
header: t`Tags`,
cell: ({ row }) => (
<HStack spacing={0} className="gap-1">
- {/* @ts-expect-error TS2339 */}
- {(row.original.tags || []).map((tag) => (
+ {(row.original.tags ?? []).map((tag) => (
<Badge key={tag} variant="secondary">
{tag}
</Badge>
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
index d535624495..ddae20f061 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
@@ -32,6 +32,7 @@ import {
InventoryCountLines,
InventoryCountStatus
} from "~/modules/inventory";
+import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import InventoryCountHistory from "./InventoryCountHistory";
@@ -42,6 +43,12 @@ type InventoryCountDetailsProps = {
summary: { uncounted: number; variances: number };
// Ledger adjustments this count has posted (empty for a never-posted Draft).
movements: StockMovement[];
+ // Option lists for the count-line column filters (same set as quantities).
+ forms: ListItem[];
+ substances: ListItem[];
+ tags: string[];
+ storageTypes: { id: string; name: string }[];
+ storageUnits: { id: string; name: string }[];
};
const InventoryCountDetails = ({
@@ -49,7 +56,12 @@ const InventoryCountDetails = ({
lines,
count,
summary,
- movements
+ movements,
+ forms,
+ substances,
+ tags,
+ storageTypes,
+ storageUnits
}: InventoryCountDetailsProps) => {
const { t } = useLingui();
const permissions = usePermissions();
@@ -188,6 +200,11 @@ const InventoryCountDetails = ({
titleBadge={<InventoryCountStatus status={status} />}
primaryAction={actions}
invalidLineIds={invalidLineIds}
+ forms={forms}
+ substances={substances}
+ tags={tags}
+ storageTypes={storageTypes}
+ storageUnits={storageUnits}
/>
</div>
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
index 699c110a79..10a897662c 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
@@ -2,13 +2,34 @@ import { Badge, HStack, Skeleton, toast, VStack } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import type { ColumnDef } from "@tanstack/react-table";
-import { type ReactNode, useCallback, useMemo } from "react";
-import { LuBox, LuCalculator, LuHash, LuPackage } from "react-icons/lu";
-import { Hyperlink, ItemThumbnail, Table } from "~/components";
+import { type ReactNode, useCallback, useEffect, useMemo, useRef } from "react";
+import {
+ LuBox,
+ LuCalculator,
+ LuExpand,
+ LuGlassWater,
+ LuHash,
+ LuPackage,
+ LuPaintBucket,
+ LuPuzzle,
+ LuShapes,
+ LuStar,
+ LuTag,
+ LuWarehouse
+} from "react-icons/lu";
+import {
+ Hyperlink,
+ ItemThumbnail,
+ MethodItemTypeIcon,
+ Table
+} from "~/components";
import { EditableNumber } from "~/components/Editable";
+import { Enumerable } from "~/components/Enumerable";
import { useStorageUnits } from "~/components/Form/StorageUnit";
+import { useFilters } from "~/components/Table/components/Filter/useFilters";
import type { InventoryCountLine } from "~/modules/inventory";
-import type { MethodItemType } from "~/modules/shared";
+import { inventoryItemTypes } from "~/modules/inventory";
+import type { ListItem } from "~/types";
import { path } from "~/utils/path";
type InventoryCountLinesProps = {
@@ -25,6 +46,12 @@ type InventoryCountLinesProps = {
// Line ids the last post attempt rejected (snapshot drift or invalid serial
// quantity) — highlighted red until fixed.
invalidLineIds?: string[];
+ // Option lists for the column filters (same set the quantities screen uses).
+ forms: ListItem[];
+ substances: ListItem[];
+ tags: string[];
+ storageTypes: { id: string; name: string }[];
+ storageUnits: { id: string; name: string }[];
};
const InventoryCountLines = ({
@@ -36,7 +63,12 @@ const InventoryCountLines = ({
title,
titleBadge,
primaryAction,
- invalidLineIds
+ invalidLineIds,
+ forms,
+ substances,
+ tags,
+ storageTypes,
+ storageUnits
}: InventoryCountLinesProps) => {
const { t } = useLingui();
@@ -47,24 +79,35 @@ const InventoryCountLines = ({
// Build the inventory query filter: scope to this count's location and search
// the quantities page for the item's readable id.
- const buildItemLink = useCallback((itemId: string, readableId?: string) => {
- const next = new URLSearchParams();
- next.set("search", readableId ?? "");
- return `${path.to.inventoryItem(itemId)}?${next.toString()}`;
- }, []);
+ const buildItemLink = useCallback(
+ (itemId: string | null, readableId?: string) => {
+ const next = new URLSearchParams();
+ next.set("search", readableId ?? "");
+ return `${path.to.inventoryItem(itemId ?? "")}?${next.toString()}`;
+ },
+ []
+ );
const hideSystem = hideSystemQuantity;
- const storageUnits = useStorageUnits(locationId);
+ const storageUnitsList = useStorageUnits(locationId);
// The options resolve asynchronously; until they do, render a loading
// placeholder instead of flashing the raw storage-unit id.
- const storageUnitsLoaded = !locationId || storageUnits.data !== undefined;
+ const storageUnitsLoaded = !locationId || storageUnitsList.data !== undefined;
const storageUnitLabel = useCallback(
(id: string | null | undefined) =>
- storageUnits.options?.find((s) => s.value === id)?.label ?? "—",
- [storageUnits.options]
+ storageUnitsList.options?.find((s) => s.value === id)?.label ?? "—",
+ [storageUnitsList.options]
);
+ // The dependent material filters (finish/grade/dimension/type) narrow by the
+ // currently-selected substance/shape — read straight back out of the URL.
+ const activeFilters = useFilters();
+ const materialSubstanceId = activeFilters.getFilter(
+ "materialSubstanceId"
+ )?.[0];
+ const materialFormId = activeFilters.getFilter("materialFormId")?.[0];
+
// Inline edits persist one line at a time through the `lines.update` route
// action, which enforces the Draft-only guard server-side and stamps the count
// audit fields. The returned `{ error }` shape lets the editable cell revert
@@ -103,33 +146,31 @@ const InventoryCountLines = ({
id: "item",
header: t`Item`,
cell: ({ row }) => {
- const item = (
- row.original as {
- item?: {
- name?: string;
- readableIdWithRevision?: string;
- type?: MethodItemType;
- thumbnailPath?: string | null;
- };
- }
- ).item;
+ const item = row.original;
return (
<HStack className="py-1 min-w-[200px] truncate" spacing={2}>
<ItemThumbnail
size="md"
- thumbnailPath={item?.thumbnailPath}
- type={item?.type}
+ thumbnailPath={item.itemThumbnailPath}
+ // The view's `type` union is broader than ItemThumbnail's — it
+ // also allows "Fixture", which the thumbnail can't render — so
+ // drop it rather than assert the type away.
+ type={
+ item.type == null || item.type === "Fixture"
+ ? undefined
+ : item.type
+ }
/>
<Hyperlink
to={buildItemLink(
- row.original.itemId,
- item?.readableIdWithRevision
+ item.itemId,
+ item.itemReadableIdWithRevision ?? undefined
)}
>
<VStack spacing={0}>
- {item?.readableIdWithRevision ?? row.original.itemId}
+ {item.itemReadableIdWithRevision ?? item.itemId}
<div className="w-full truncate text-muted-foreground text-xs">
- {item?.name}
+ {item.itemName}
</div>
</VStack>
</Hyperlink>
@@ -145,7 +186,37 @@ const InventoryCountLines = ({
meta: { icon: <LuHash /> }
},
{
- id: "storageUnit",
+ accessorKey: "type",
+ header: t`Item Type`,
+ cell: ({ row }) => {
+ const type = row.original.type;
+ return type ? (
+ <HStack spacing={2}>
+ <MethodItemTypeIcon type={type} />
+ <span>{type}</span>
+ </HStack>
+ ) : (
+ "—"
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: inventoryItemTypes.map((type) => ({
+ label: (
+ <HStack spacing={2}>
+ <MethodItemTypeIcon type={type} />
+ <span>{type}</span>
+ </HStack>
+ ),
+ value: type
+ }))
+ },
+ icon: <LuBox />
+ }
+ },
+ {
+ accessorKey: "storageUnitId",
header: t`Storage Unit`,
cell: ({ row }) => {
const id = row.original.storageUnitId;
@@ -153,7 +224,167 @@ const InventoryCountLines = ({
if (!storageUnitsLoaded) return <Skeleton className="h-4 w-24" />;
return storageUnitLabel(id);
},
- meta: { icon: <LuBox /> }
+ meta: {
+ filter: {
+ type: "static",
+ options: storageUnits.map((su) => ({
+ value: su.id,
+ label: <Enumerable value={su.name} />
+ }))
+ },
+ exportValue: (row) => storageUnitLabel(row.storageUnitId),
+ icon: <LuBox />
+ }
+ },
+ {
+ accessorKey: "storageTypeIds",
+ header: t`Storage Type`,
+ cell: ({ row }) => {
+ const ids = row.original.storageTypeIds ?? [];
+ return (
+ <HStack spacing={0} className="gap-1">
+ {ids.map((id) => {
+ const st = storageTypes.find((s) => s.id === id);
+ return <Enumerable key={id} value={st?.name ?? null} />;
+ })}
+ </HStack>
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: storageTypes.map((st) => ({
+ value: st.id,
+ label: <Enumerable value={st.name} />
+ })),
+ isArray: true
+ },
+ pluralHeader: t`Storage Types`,
+ icon: <LuWarehouse />
+ }
+ },
+ {
+ accessorKey: "materialSubstanceId",
+ header: t`Substance`,
+ cell: ({ row }) => {
+ const substance = substances.find(
+ (s) => s.id === row.original.materialSubstanceId
+ );
+ return <Enumerable value={substance?.name ?? null} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: substances.map((substance) => ({
+ label: <Enumerable value={substance.name ?? null} />,
+ value: substance.id
+ }))
+ },
+ icon: <LuGlassWater />
+ }
+ },
+ {
+ accessorKey: "materialFormId",
+ header: t`Shape`,
+ cell: ({ row }) => {
+ const form = forms.find((f) => f.id === row.original.materialFormId);
+ return <Enumerable value={form?.name ?? null} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: forms.map((form) => ({
+ label: <Enumerable value={form.name} />,
+ value: form.id
+ }))
+ },
+ icon: <LuShapes />
+ }
+ },
+ {
+ accessorKey: "finish",
+ header: t`Finish`,
+ cell: (item) => item.getValue() ?? "—",
+ meta: {
+ icon: <LuPaintBucket />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.materialFinishes(materialSubstanceId),
+ transform: (data: { id: string; name: string }[] | null) =>
+ data?.map(({ name }) => ({ value: name, label: name })) ?? []
+ }
+ }
+ },
+ {
+ accessorKey: "grade",
+ header: t`Grade`,
+ cell: (item) => item.getValue() ?? "—",
+ meta: {
+ icon: <LuStar />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.materialGrades(materialSubstanceId),
+ transform: (data: { id: string; name: string }[] | null) =>
+ data?.map(({ name }) => ({ value: name, label: name })) ?? []
+ }
+ }
+ },
+ {
+ accessorKey: "dimension",
+ header: t`Dimension`,
+ cell: (item) => item.getValue() ?? "—",
+ meta: {
+ icon: <LuExpand />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.materialDimensions(materialFormId),
+ transform: (data: { id: string; name: string }[] | null) =>
+ data?.map(({ name }) => ({ value: name, label: name })) ?? []
+ }
+ }
+ },
+ {
+ accessorKey: "materialType",
+ header: t`Material Type`,
+ cell: (item) => item.getValue() ?? "—",
+ meta: {
+ icon: <LuPuzzle />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.materialTypes(
+ materialSubstanceId,
+ materialFormId
+ ),
+ // The `materialType` column holds the type's name, so the filter
+ // value must be the name to match.
+ transform: (data: { id: string; name: string }[] | null) =>
+ data?.map(({ name }) => ({ value: name, label: name })) ?? []
+ }
+ }
+ },
+ {
+ accessorKey: "tags",
+ header: t`Tags`,
+ cell: ({ row }) => (
+ <HStack spacing={0} className="gap-1">
+ {(row.original.tags ?? []).map((tag) => (
+ <Badge key={tag} variant="secondary">
+ {tag}
+ </Badge>
+ ))}
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: tags?.map((tag) => ({
+ value: tag,
+ label: <Badge variant="secondary">{tag}</Badge>
+ })),
+ isArray: true
+ },
+ icon: <LuTag />
+ }
}
];
@@ -173,8 +404,12 @@ const InventoryCountLines = ({
header: t`Counted Qty`,
cell: (item) => {
const value = item.getValue<number | null>();
+ // Marked so the keyboard "Start counting" entry can locate the first
+ // editable cell and seed the table's selection (see below).
return (
- <span className="tabular-nums">{value === null ? "—" : value}</span>
+ <span data-counted-qty className="tabular-nums">
+ {value === null ? "—" : value}
+ </span>
);
},
meta: { icon: <LuCalculator /> }
@@ -201,7 +436,153 @@ const InventoryCountLines = ({
}
return cols;
- }, [buildItemLink, hideSystem, storageUnitLabel, storageUnitsLoaded, t]);
+ }, [
+ buildItemLink,
+ forms,
+ hideSystem,
+ materialFormId,
+ materialSubstanceId,
+ storageTypes,
+ storageUnitLabel,
+ storageUnits,
+ storageUnitsLoaded,
+ substances,
+ tags,
+ t
+ ]);
+
+ // The material attributes are filter-only — hidden by default (the item column
+ // already identifies the row) but available in the column picker.
+ const defaultColumnVisibility = {
+ type: false,
+ storageTypeIds: false,
+ materialSubstanceId: false,
+ materialFormId: false,
+ finish: false,
+ grade: false,
+ dimension: false,
+ materialType: false,
+ tags: false
+ };
+
+ const gridRef = useRef<HTMLDivElement>(null);
+
+ // Last-resolved Counted Qty column index, cached as a fallback. It's resolved
+ // live from the DOM on each keypress (below) so showing / hiding / reordering
+ // columns can never point navigation at the wrong cell.
+ const countedColumnRef = useRef<string | null>(null);
+
+ // Focus the first not-yet-edited Counted Qty cell. The shared Table only
+ // seeds its cell selection on a mouse click, so we click the cell to bootstrap
+ // its selection + edit; from there the counting keyboard flow below takes over.
+ // Scoped to this grid via the `data-counted-qty` marker.
+ const enterGrid = useCallback(() => {
+ (
+ gridRef.current?.querySelector("[data-counted-qty]") ??
+ document.querySelector("[data-counted-qty]")
+ )
+ ?.closest<HTMLElement>("[data-column]")
+ ?.click();
+ }, []);
+
+ // Take every focusable inside the grid lines out of the tab order — the only
+ // ones are the item name's link + its hover "Open" button (from the shared
+ // Hyperlink), which would otherwise capture Tab. This leaves the selected
+ // Counted Qty cell as the single line-level tab stop, so Tab drives counting.
+ // Runs each render since the Table re-mounts row cells; the Counted Qty editor
+ // is an <input>, not an <a>/<button>, so it's untouched.
+ useEffect(() => {
+ for (const el of gridRef.current?.querySelectorAll<HTMLElement>(
+ "[data-row] a, [data-row] button"
+ ) ?? []) {
+ el.tabIndex = -1;
+ }
+ });
+
+ // Land the counter in the first cell on open (Draft counts only), so the page
+ // is immediately keyboard-driveable without hunting for an entry point.
+ const hasAutoFocusedRef = useRef(false);
+ useEffect(() => {
+ if (isReadOnly || hasAutoFocusedRef.current || lines.length === 0) return;
+ hasAutoFocusedRef.current = true;
+ enterGrid();
+ }, [isReadOnly, lines.length, enterGrid]);
+
+ // Spreadsheet-style entry: Enter/Tab commit the current count and move to the
+ // NEXT line's Counted Qty cell; Shift+Tab moves to the PREVIOUS line. A keypress
+ // from any other cell jumps into the Counted Qty column instead of letting the
+ // shared Table wander sideways. At a boundary, Enter keeps focus on the cell
+ // while Tab is allowed to leave the grid (only the Table's own wrap is
+ // suppressed). Read-only counts are left entirely to the browser. Runs in the
+ // capture phase — this wrapper is an ancestor of the Table's own capture
+ // listener — so stopping propagation overrides it.
+ const onGridKeyDownCapture = useCallback(
+ (event: React.KeyboardEvent) => {
+ if (isReadOnly) return;
+ if (event.key !== "Enter" && event.key !== "Tab") return;
+ const cell = (event.target as HTMLElement).closest<HTMLElement>(
+ "[data-row][data-column]"
+ );
+ if (!cell || !gridRef.current?.contains(cell)) return;
+
+ // Resolve the Counted Qty column live: from the cell being edited (only the
+ // Counted Qty cell is editable) or, failing that, the `data-counted-qty`
+ // marker on any non-editing line. Falls back to the last-known index.
+ const active = document.activeElement as HTMLElement | null;
+ const editingColumn =
+ active?.tagName === "INPUT"
+ ? active
+ .closest<HTMLElement>("[data-column]")
+ ?.getAttribute("data-column")
+ : null;
+ const markerColumn = gridRef.current
+ ?.querySelector("[data-counted-qty]")
+ ?.closest<HTMLElement>("[data-column]")
+ ?.getAttribute("data-column");
+ const countedColumn =
+ editingColumn ?? markerColumn ?? countedColumnRef.current;
+ if (!countedColumn) return;
+ countedColumnRef.current = countedColumn;
+
+ const row = Number(cell.getAttribute("data-row"));
+
+ // From another column (e.g. a clicked Item cell), jump into this line's
+ // Counted Qty cell.
+ if (cell.getAttribute("data-column") !== countedColumn) {
+ event.preventDefault();
+ event.stopPropagation();
+ gridRef.current
+ ?.querySelector<HTMLElement>(
+ `[data-row="${row}"][data-column="${countedColumn}"]`
+ )
+ ?.click();
+ return;
+ }
+
+ const step = event.key === "Tab" && event.shiftKey ? -1 : 1;
+ const adjacent = gridRef.current?.querySelector<HTMLElement>(
+ `[data-row="${row + step}"][data-column="${countedColumn}"]`
+ );
+
+ // Let Tab exit the grid at the first/last line rather than trapping focus;
+ // only suppress the Table's own row-wrapping.
+ if (event.key === "Tab" && !adjacent) {
+ event.stopPropagation();
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ if (active?.tagName === "INPUT") active.blur(); // commit before moving
+ if (adjacent) {
+ adjacent.click(); // open the next line's cell for entry
+ } else {
+ // Enter at a boundary: keep focus on the cell rather than dropping out.
+ cell.focus();
+ }
+ },
+ [isReadOnly]
+ );
const editableComponents = useMemo(
() => ({
@@ -211,11 +592,7 @@ const InventoryCountLines = ({
// quantity at 1 (per row, since tracking type varies by line).
(row) => ({
minValue: 0,
- maxValue:
- (row as { item?: { itemTrackingType?: string } }).item
- ?.itemTrackingType === "Serial"
- ? 1
- : undefined
+ maxValue: row.itemTrackingType === "Serial" ? 1 : undefined
}),
{ clearable: true }
)
@@ -224,24 +601,43 @@ const InventoryCountLines = ({
);
return (
- <Table<InventoryCountLine>
- compact
- columns={columns}
- data={lines}
- count={count}
- editableComponents={editableComponents}
- getRowClassName={(row) =>
- invalidLineIdSet.has(row.id ?? "")
- ? "bg-destructive/30 hover:bg-destructive/40"
- : undefined
- }
- primaryAction={primaryAction}
- title={title ?? t`Lines`}
- titleBadge={titleBadge}
- withInlineEditing={!isReadOnly}
- // Draft counts are inherently editable — no Edit/Lock toggle, always on.
- forceEditMode={!isReadOnly}
- />
+ <div
+ ref={gridRef}
+ onKeyDownCapture={onGridKeyDownCapture}
+ className="flex h-full min-h-0 w-full flex-col"
+ >
+ {/* Keyboard skip-link into the grid: revealed on focus, activates the
+ first Counted Qty cell so counters can enter and drive the grid
+ without a mouse. */}
+ {!isReadOnly && lines.length > 0 && (
+ <button
+ type="button"
+ onClick={enterGrid}
+ className="sr-only focus:not-sr-only focus:absolute focus:z-10 focus:m-2 focus:rounded-md focus:bg-primary focus:px-3 focus:py-1.5 focus:text-sm focus:text-primary-foreground focus:shadow"
+ >
+ {t`Start counting`}
+ </button>
+ )}
+ <Table<InventoryCountLine>
+ compact
+ columns={columns}
+ data={lines}
+ count={count}
+ defaultColumnVisibility={defaultColumnVisibility}
+ editableComponents={editableComponents}
+ getRowClassName={(row) =>
+ invalidLineIdSet.has(row.id ?? "")
+ ? "bg-destructive/30 hover:bg-destructive/40"
+ : undefined
+ }
+ primaryAction={primaryAction}
+ title={title ?? t`Lines`}
+ titleBadge={titleBadge}
+ withInlineEditing={!isReadOnly}
+ // Draft counts are inherently editable — no Edit/Lock toggle, always on.
+ forceEditMode={!isReadOnly}
+ />
+ </div>
);
};
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 980ba5faad..d1b41e65e8 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-07-15T13:07:53.800Z",
+ "generated": "2026-07-16T13:34:05.765Z",
"totalTools": 1335,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/inventory+/quantities.tsx b/apps/erp/app/routes/x+/inventory+/quantities.tsx
index 4f26d349d8..c0417a7495 100644
--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx
+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx
@@ -101,7 +101,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
]);
if (inventoryItems.error) {
- redirect(
+ throw redirect(
path.to.authenticatedRoot,
await flash(
request,
diff --git a/apps/erp/app/routes/x+/inventory-count+/$id.tsx b/apps/erp/app/routes/x+/inventory-count+/$id.tsx
index d97a3d7973..ac3cc1430c 100644
--- a/apps/erp/app/routes/x+/inventory-count+/$id.tsx
+++ b/apps/erp/app/routes/x+/inventory-count+/$id.tsx
@@ -1,6 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { pluckUnique } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
@@ -9,8 +10,15 @@ import {
getInventoryCountLineSummary,
getInventoryCountLines,
getInventoryCountMovements,
+ getStorageTypesList,
+ getStorageUnitsListForLocation,
InventoryCountDetails
} from "~/modules/inventory";
+import {
+ getMaterialFormsList,
+ getMaterialSubstancesList
+} from "~/modules/items";
+import { getTagsList } from "~/modules/shared";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -47,7 +55,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [lines, summary, movements] = await Promise.all([
+ const [
+ lines,
+ summary,
+ movements,
+ forms,
+ substances,
+ tags,
+ storageTypes,
+ storageUnits
+ ] = await Promise.all([
getInventoryCountLines(client, id, companyId, {
search,
limit,
@@ -57,7 +74,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}),
getInventoryCountLineSummary(client, id, companyId),
// Adjustments this count has posted (empty for a never-posted Draft).
- getInventoryCountMovements(client, companyId, id)
+ getInventoryCountMovements(client, companyId, id),
+ // Option lists for the count-line column filters (same set the quantities
+ // screen loads).
+ getMaterialFormsList(client, companyId),
+ getMaterialSubstancesList(client, companyId),
+ getTagsList(client, companyId),
+ getStorageTypesList(client, companyId),
+ getStorageUnitsListForLocation(
+ client,
+ companyId,
+ inventoryCount.data.locationId
+ )
]);
// True blind counting: the system quantity (and the variance it can be derived
@@ -82,13 +110,28 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
lines: lineData,
count: lines.count ?? 0,
summary,
- movements: movements.data ?? []
+ movements: movements.data ?? [],
+ forms: forms.data ?? [],
+ substances: substances.data ?? [],
+ tags: pluckUnique(tags.data, (tag) => tag.name),
+ storageTypes: storageTypes.data ?? [],
+ storageUnits: storageUnits.data ?? []
};
}
export default function InventoryCountDetailRoute() {
- const { inventoryCount, lines, count, summary, movements } =
- useLoaderData<typeof loader>();
+ const {
+ inventoryCount,
+ lines,
+ count,
+ summary,
+ movements,
+ forms,
+ substances,
+ tags,
+ storageTypes,
+ storageUnits
+ } = useLoaderData<typeof loader>();
return (
<>
@@ -99,6 +142,11 @@ export default function InventoryCountDetailRoute() {
count={count}
summary={summary}
movements={movements}
+ forms={forms}
+ substances={substances}
+ tags={tags}
+ storageTypes={storageTypes}
+ storageUnits={storageUnits}
/>
</div>
<Outlet />
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index b4b7b91e95..d928672422 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -307,9 +307,18 @@ export function IssueMaterialModal({
// Tab state
const [activeTab, setActiveTab] = useState("scan");
- // When no picking list has allocated this tracked material, suggest the same
- // lots a picking list would (netting + the item's pickMethod sort) and pre-fill
- // the selection. The suggestion is a default only — fully editable below.
+ // Pre-fill the selection with the picking list's recommendation (a default
+ // only — fully editable below). Two sources feed it, in priority order:
+ // 1. the exact lots a picking list already PICKED for this material
+ // (`pickedAllocation`, from pickingListLineTrackedEntity), and
+ // 2. the on-the-fly pickMethod suggestion of what to pick
+ // (`suggestedAllocation`, netted + FEFO/FIFO sorted).
+ // A material can be on a picking list (quantityToPick > 0) with nothing picked
+ // yet — e.g. a multi-line list where other lines were picked first. In that
+ // state `pickedAllocation` is empty, so we must still surface the suggestion
+ // rather than leaving the operator with the default first lot. Hence the
+ // suggestion is ALWAYS loaded and used as the fallback, not gated off whenever
+ // a picking allocation merely exists.
const pickedOverlay = material as
| { quantityToPick?: number | null; quantityPicked?: number | null }
| undefined;
@@ -320,7 +329,6 @@ export function IssueMaterialModal({
!!material &&
!!selectedItemId &&
!!locationId &&
- !hasPickingAllocation &&
(trackingType === "Batch" || trackingType === "Serial");
const { data: suggestedAllocation } = useSuggestedAllocation(
shouldSuggestAllocation
@@ -331,20 +339,25 @@ export function IssueMaterialModal({
}
: undefined
);
- // When a picking list HAS allocated this material, seed the exact lots it
- // picked (from pickingListLineTrackedEntity) rather than a fresh suggestion.
const shouldLoadPickedAllocation =
!!material?.id &&
hasPickingAllocation &&
(trackingType === "Batch" || trackingType === "Serial");
- const { data: pickedAllocation } = usePickedAllocation(
- shouldLoadPickedAllocation ? (material?.id ?? undefined) : undefined
- );
- // One source feeds the seeding + add-row logic below: the picked lots when a
- // picking list exists, otherwise the on-the-fly suggestion.
- const seedAllocation = hasPickingAllocation
- ? pickedAllocation
- : suggestedAllocation;
+ const { data: pickedAllocation, resolved: pickedAllocationResolved } =
+ usePickedAllocation(
+ shouldLoadPickedAllocation ? (material?.id ?? undefined) : undefined
+ );
+ // Prefer the actual picks; fall back to the suggestion only when nothing's
+ // been picked yet (allocated-but-not-picked) or when there's no picking list.
+ // Wait for the picked-allocation request to resolve before falling back, so a
+ // faster suggestion response can't be seeded and then locked in ahead of the
+ // real picked lots.
+ const seedAllocation =
+ shouldLoadPickedAllocation && !pickedAllocationResolved
+ ? []
+ : pickedAllocation.length
+ ? pickedAllocation
+ : suggestedAllocation;
const hasSeededSuggestionRef = useRef(false);
useEffect(() => {
if (hasSeededSuggestionRef.current) return;
@@ -2048,5 +2061,11 @@ function usePickedAllocation(jobMaterialId?: string) {
}
}, [jobMaterialId]);
- return { data: fetcher.data?.data ?? [] };
+ return {
+ data: fetcher.data?.data ?? [],
+ // Has the request come back? An empty result only means "nothing picked"
+ // once this is true — before that it's still loading. Guards the seed from
+ // falling back to the suggestion before the picked lots have arrived.
+ resolved: fetcher.state === "idle" && fetcher.data !== undefined
+ };
}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index ca7e84f7c1..0fd47b11e7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -57166,6 +57166,303 @@ export type Database = {
}
Relationships: []
}
+ inventoryCountLines: {
+ Row: {
+ companyId: string | null
+ countedAt: string | null
+ countedBy: string | null
+ countedQuantity: number | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ dimension: string | null
+ dimensionId: string | null
+ finish: string | null
+ finishId: string | null
+ grade: string | null
+ gradeId: string | null
+ id: string | null
+ inventoryCountId: string | null
+ itemId: string | null
+ itemName: string | null
+ itemReadableIdWithRevision: string | null
+ itemThumbnailPath: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ locationId: string | null
+ materialFormId: string | null
+ materialSubstanceId: string | null
+ materialType: string | null
+ materialTypeId: string | null
+ postedItemLedgerId: string | null
+ readableId: string | null
+ storageTypeIds: string[] | null
+ storageUnitId: string | null
+ systemQuantity: number | null
+ tags: string[] | null
+ trackedEntityId: string | null
+ type: Database["public"]["Enums"]["itemType"] | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ variance: number | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_inventoryCountId_companyId_fkey"
+ columns: ["inventoryCountId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inventoryCount"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "material_dimensionId_fkey"
+ columns: ["dimensionId"]
+ isOneToOne: false
+ referencedRelation: "materialDimension"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_dimensionId_fkey"
+ columns: ["dimensionId"]
+ isOneToOne: false
+ referencedRelation: "materialDimensions"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_finishId_fkey"
+ columns: ["finishId"]
+ isOneToOne: false
+ referencedRelation: "materialFinish"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_finishId_fkey"
+ columns: ["finishId"]
+ isOneToOne: false
+ referencedRelation: "materialFinishes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_gradeId_fkey"
+ columns: ["gradeId"]
+ isOneToOne: false
+ referencedRelation: "materialGrade"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_gradeId_fkey"
+ columns: ["gradeId"]
+ isOneToOne: false
+ referencedRelation: "materialGrades"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialFormId_fkey"
+ columns: ["materialFormId"]
+ isOneToOne: false
+ referencedRelation: "materialForm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialSubstanceId_fkey"
+ columns: ["materialSubstanceId"]
+ isOneToOne: false
+ referencedRelation: "materialSubstance"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialTypeId_fkey"
+ columns: ["materialTypeId"]
+ isOneToOne: false
+ referencedRelation: "materialType"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialTypeId_fkey"
+ columns: ["materialTypeId"]
+ isOneToOne: false
+ referencedRelation: "materialTypes"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
issues: {
Row: {
approvalRequirements:
@@ -62501,6 +62798,8 @@ export type Database = {
| null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
+ receivableQuantity: number | null
+ receivedQuantity: number | null
revisionId: number | null
shippingMethodId: string | null
shippingTermId: string | null
@@ -65830,21 +66129,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70396,6 +70695,7 @@ export type Database = {
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
storageTypeIds: string[]
storageUnitIds: string[]
+ tags: string[]
thumbnailPath: string
type: Database["public"]["Enums"]["itemType"]
unitOfMeasureCode: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index ca7e84f7c1..0fd47b11e7 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -57166,6 +57166,303 @@ export type Database = {
}
Relationships: []
}
+ inventoryCountLines: {
+ Row: {
+ companyId: string | null
+ countedAt: string | null
+ countedBy: string | null
+ countedQuantity: number | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ dimension: string | null
+ dimensionId: string | null
+ finish: string | null
+ finishId: string | null
+ grade: string | null
+ gradeId: string | null
+ id: string | null
+ inventoryCountId: string | null
+ itemId: string | null
+ itemName: string | null
+ itemReadableIdWithRevision: string | null
+ itemThumbnailPath: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ locationId: string | null
+ materialFormId: string | null
+ materialSubstanceId: string | null
+ materialType: string | null
+ materialTypeId: string | null
+ postedItemLedgerId: string | null
+ readableId: string | null
+ storageTypeIds: string[] | null
+ storageUnitId: string | null
+ systemQuantity: number | null
+ tags: string[] | null
+ trackedEntityId: string | null
+ type: Database["public"]["Enums"]["itemType"] | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ variance: number | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_countedBy_fkey"
+ columns: ["countedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_inventoryCountId_companyId_fkey"
+ columns: ["inventoryCountId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "inventoryCount"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inventoryCountLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "material_dimensionId_fkey"
+ columns: ["dimensionId"]
+ isOneToOne: false
+ referencedRelation: "materialDimension"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_dimensionId_fkey"
+ columns: ["dimensionId"]
+ isOneToOne: false
+ referencedRelation: "materialDimensions"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_finishId_fkey"
+ columns: ["finishId"]
+ isOneToOne: false
+ referencedRelation: "materialFinish"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_finishId_fkey"
+ columns: ["finishId"]
+ isOneToOne: false
+ referencedRelation: "materialFinishes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_gradeId_fkey"
+ columns: ["gradeId"]
+ isOneToOne: false
+ referencedRelation: "materialGrade"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_gradeId_fkey"
+ columns: ["gradeId"]
+ isOneToOne: false
+ referencedRelation: "materialGrades"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialFormId_fkey"
+ columns: ["materialFormId"]
+ isOneToOne: false
+ referencedRelation: "materialForm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialSubstanceId_fkey"
+ columns: ["materialSubstanceId"]
+ isOneToOne: false
+ referencedRelation: "materialSubstance"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialTypeId_fkey"
+ columns: ["materialTypeId"]
+ isOneToOne: false
+ referencedRelation: "materialType"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "material_materialTypeId_fkey"
+ columns: ["materialTypeId"]
+ isOneToOne: false
+ referencedRelation: "materialTypes"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
issues: {
Row: {
approvalRequirements:
@@ -62501,6 +62798,8 @@ export type Database = {
| null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
+ receivableQuantity: number | null
+ receivedQuantity: number | null
revisionId: number | null
shippingMethodId: string | null
shippingTermId: string | null
@@ -65830,21 +66129,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70396,6 +70695,7 @@ export type Database = {
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
storageTypeIds: string[]
storageUnitIds: string[]
+ tags: string[]
thumbnailPath: string
type: Database["public"]["Enums"]["itemType"]
unitOfMeasureCode: string
diff --git a/packages/database/supabase/migrations/20260716142907_restore-inventory-quantities-tags.sql b/packages/database/supabase/migrations/20260716142907_restore-inventory-quantities-tags.sql
new file mode 100644
index 0000000000..95671c056e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260716142907_restore-inventory-quantities-tags.sql
@@ -0,0 +1,373 @@
+-- ============================================================
+-- Restore the "tags" output to get_inventory_quantities.
+--
+-- 20260113122437_inventory-tags-filter.sql added a "tags" column sourced from
+-- all four item subtype tables. 20260713235406_item-ledger-snapshot.sql then
+-- rewrote the function for the snapshot+delta read path and dropped "tags" from
+-- both RETURNS TABLE and the SELECT. That regressed the inventory Tags column
+-- (always empty) and the Tags filter (PostgREST 42703 against a column that no
+-- longer exists).
+--
+-- This restores "tags" onto the snapshot+delta definition. Everything else is
+-- carried over from 20260713235406 unchanged — the snapshot/delta arms, the
+-- status-aware sums, and every other output column.
+--
+-- "tags" is never a column on "item"; it lives on the subtype tables
+-- (material/part/tool/consumable), keyed id = item."readableId". An item is
+-- exactly one subtype, so COALESCE picks the single non-null array.
+--
+-- RETURNS TABLE changes, so the function must be dropped before recreation.
+-- ============================================================
+
+DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT);
+DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT, TEXT);
+
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "dimensionId" TEXT,
+ "dimension" TEXT,
+ "finishId" TEXT,
+ "finish" TEXT,
+ "gradeId" TEXT,
+ "grade" TEXT,
+ "materialType" TEXT,
+ "materialTypeId" TEXT,
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "maximumInventoryQuantity" NUMERIC,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "quantityOnHold" NUMERIC,
+ "quantityRejected" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC,
+ "demandForecast" NUMERIC,
+ "usageLast30Days" NUMERIC,
+ "usageLast90Days" NUMERIC,
+ "daysRemaining" NUMERIC,
+ "storageTypeIds" TEXT[],
+ "storageUnitIds" TEXT[],
+ "tags" TEXT[]
+ ) AS $$
+ DECLARE
+ v_cutoff TIMESTAMPTZ;
+ BEGIN
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND (item_id IS NULL OR pol."itemId" = item_id)
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ AND (item_id IS NULL OR sol."itemId" = item_id)
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR jm."itemId" = item_id)
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR j."itemId" = item_id)
+ GROUP BY j."itemId"
+ ),
+ -- Snapshot (immutable untracked rows) + live tracked rows + live untracked
+ -- rows past the snapshot cutoff. With no snapshot (v_cutoff NULL) the third
+ -- arm is the full untracked history — the pre-snapshot behavior.
+ item_ledgers AS (
+ SELECT
+ combined."itemId",
+ SUM(combined."quantityOnHand") AS "quantityOnHand",
+ SUM(combined."quantityOnHold") AS "quantityOnHold",
+ SUM(combined."quantityRejected") AS "quantityRejected",
+ SUM(combined."consumed30") / 30 AS "usageLast30Days",
+ SUM(combined."consumed90") / 90 AS "usageLast90Days"
+ FROM (
+ SELECT
+ s."itemId",
+ s."quantity" AS "quantityOnHand",
+ 0::NUMERIC AS "quantityOnHold",
+ 0::NUMERIC AS "quantityRejected",
+ s."consumed30",
+ s."consumed90"
+ FROM "itemLedgerSnapshot" s
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) combined
+ GROUP BY combined."itemId"
+ ),
+ -- Distinct storage units the item is stocked in: snapshot arrays plus the
+ -- same live arms. NULL storageUnitId rows are excluded.
+ item_storage_units AS (
+ SELECT
+ u."itemId",
+ ARRAY_AGG(DISTINCT u."storageUnitId") AS "storageUnitIds"
+ FROM (
+ SELECT s."itemId", su_id AS "storageUnitId"
+ FROM "itemLedgerSnapshot" s
+ CROSS JOIN LATERAL unnest(s."storageUnitIds") AS su_id
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) u
+ GROUP BY u."itemId"
+ ),
+ -- Distinct storage types, derived from the merged storage-unit ids.
+ item_storage_types AS (
+ SELECT
+ isu."itemId",
+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"
+ FROM item_storage_units isu
+ INNER JOIN "storageUnit" su
+ ON su."id" = ANY(isu."storageUnitIds")
+ AND su."companyId" = company_id
+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t
+ GROUP BY isu."itemId"
+ ),
+ demand_forecast AS (
+ SELECT combined."itemId", SUM(qty) AS "demandForecast"
+ FROM (
+ SELECT da."itemId", da."actualQuantity" AS qty
+ FROM "demandActual" da
+ WHERE da."companyId" = company_id AND da."locationId" = location_id
+ AND (item_id IS NULL OR da."itemId" = item_id)
+ UNION ALL
+ SELECT df."itemId", df."forecastQuantity" AS qty
+ FROM "demandForecast" df
+ WHERE df."companyId" = company_id AND df."locationId" = location_id
+ AND (item_id IS NULL OR df."itemId" = item_id)
+ ) combined
+ GROUP BY combined."itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."dimensionId",
+ md."name" AS "dimension",
+ m."finishId",
+ mf."name" AS "finish",
+ m."gradeId",
+ mg."name" AS "grade",
+ mt."name" AS "materialType",
+ m."materialTypeId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."maximumInventoryQuantity",
+ ip."orderMultiple",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",
+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",
+ COALESCE(df."demandForecast", 0) AS "demandForecast",
+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",
+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",
+ CASE
+ WHEN COALESCE(il."usageLast30Days", 0) > 0
+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)
+ ELSE NULL
+ END AS "daysRemaining",
+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",
+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds",
+ COALESCE(m."tags", p."tags", t."tags", c."tags") AS "tags"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"
+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id
+ LEFT JOIN part p ON i."readableId" = p."id" AND p."companyId" = company_id
+ LEFT JOIN tool t ON i."readableId" = t."id" AND t."companyId" = company_id
+ LEFT JOIN consumable c ON i."readableId" = c."id" AND c."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id
+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id
+ AND (item_id IS NULL OR i."id" = item_id);
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260716153000_inventory-count-lines-view.sql b/packages/database/supabase/migrations/20260716153000_inventory-count-lines-view.sql
new file mode 100644
index 0000000000..3cb0a92bfc
--- /dev/null
+++ b/packages/database/supabase/migrations/20260716153000_inventory-count-lines-view.sql
@@ -0,0 +1,55 @@
+-- ============================================================
+-- inventoryCountLines view: count lines with item + material + storage-unit
+-- attributes flattened as top-level columns, so the count detail table can
+-- offer the same generic column filters the inventory quantities screen does
+-- (item type, storage type, tags, material substance/shape/finish/grade/
+-- dimension/type).
+--
+-- The base inventoryCountLine only carries itemId / storageUnitId / readableId /
+-- quantities. Material attributes live on the item SUBTYPE tables
+-- (material/part/tool/consumable), keyed by item."readableId" - the same join
+-- get_inventory_quantities uses (NOT material.itemId) - and storage types live
+-- on storageUnit. Every attribute join is LEFT: Parts/Tools/Consumables have no
+-- material row, and a line's storageUnit may be null.
+--
+-- SECURITY_INVOKER so the querying user's RLS on each underlying table applies.
+-- ============================================================
+
+CREATE OR REPLACE VIEW "inventoryCountLines" WITH (SECURITY_INVOKER = true) AS
+SELECT
+ icl.*,
+ i."name" AS "itemName",
+ i."readableIdWithRevision" AS "itemReadableIdWithRevision",
+ i."type" AS "type",
+ i."itemTrackingType" AS "itemTrackingType",
+ i."thumbnailPath" AS "itemThumbnailPath",
+ i."unitOfMeasureCode" AS "unitOfMeasureCode",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."dimensionId",
+ md."name" AS "dimension",
+ m."finishId",
+ mf."name" AS "finish",
+ m."gradeId",
+ mg."name" AS "grade",
+ m."materialTypeId",
+ mt."name" AS "materialType",
+ COALESCE(m."tags", p."tags", t."tags", c."tags") AS "tags",
+ COALESCE(su."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds"
+FROM "inventoryCountLine" icl
+ INNER JOIN "item" i
+ ON i."id" = icl."itemId" AND i."companyId" = icl."companyId"
+ LEFT JOIN "material" m
+ ON m."id" = i."readableId" AND m."companyId" = icl."companyId"
+ LEFT JOIN "part" p
+ ON p."id" = i."readableId" AND p."companyId" = icl."companyId"
+ LEFT JOIN "tool" t
+ ON t."id" = i."readableId" AND t."companyId" = icl."companyId"
+ LEFT JOIN "consumable" c
+ ON c."id" = i."readableId" AND c."companyId" = icl."companyId"
+ LEFT JOIN "storageUnit" su
+ ON su."id" = icl."storageUnitId" AND su."companyId" = icl."companyId"
+ LEFT JOIN "materialDimension" md ON md."id" = m."dimensionId"
+ LEFT JOIN "materialFinish" mf ON mf."id" = m."finishId"
+ LEFT JOIN "materialGrade" mg ON mg."id" = m."gradeId"
+ LEFT JOIN "materialType" mt ON mt."id" = m."materialTypeId";
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 573b4d8390..52dd180b58 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Starten"
msgid "Start {0} Day Free Trial"
msgstr "Starten Sie die {0}-tägige kostenlose Testversion"
+msgid "Start counting"
+msgstr "Zählung starten"
+
msgid "Start Date"
msgstr "Startdatum"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index c1522fccb2..357dafd6bc 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Start"
msgid "Start {0} Day Free Trial"
msgstr "Start {0} Day Free Trial"
+msgid "Start counting"
+msgstr "Start counting"
+
msgid "Start Date"
msgstr "Start Date"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 53e65ca21f..7b0894a31e 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Iniciar"
msgid "Start {0} Day Free Trial"
msgstr "Iniciar prueba gratuita de {0} días"
+msgid "Start counting"
+msgstr "Iniciar conteo"
+
msgid "Start Date"
msgstr "Fecha de Inicio"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 4b0c10a1bc..b78a2b2f43 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Démarrer"
msgid "Start {0} Day Free Trial"
msgstr "Commencer l'essai gratuit de {0} jours"
+msgid "Start counting"
+msgstr "Commencer le comptage"
+
msgid "Start Date"
msgstr "Date de début"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index dfe806731f..22474f5b47 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -11129,6 +11129,9 @@ msgstr "शुरू करें"
msgid "Start {0} Day Free Trial"
msgstr "{0} दिन की निःशुल्क परीक्षण शुरू करें"
+msgid "Start counting"
+msgstr "गिनती शुरू करें"
+
msgid "Start Date"
msgstr "शुरुआत तारीख"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index eb7e33adab..faa76e79f5 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Avvia"
msgid "Start {0} Day Free Trial"
msgstr "Inizia la prova gratuita di {0} giorni"
+msgid "Start counting"
+msgstr "Inizia il conteggio"
+
msgid "Start Date"
msgstr "Data di inizio"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 36cb146f28..5eb9cf8b38 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -11129,6 +11129,9 @@ msgstr "開始"
msgid "Start {0} Day Free Trial"
msgstr "{0}日間の無料トライアルを開始"
+msgid "Start counting"
+msgstr "カウントを開始"
+
msgid "Start Date"
msgstr "開始日"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index ad68dfefb6..1e55dcc22b 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -11129,6 +11129,9 @@ msgstr "시작"
msgid "Start {0} Day Free Trial"
msgstr "{0}일 무료 체험 시작"
+msgid "Start counting"
+msgstr "실사 시작"
+
msgid "Start Date"
msgstr "시작일"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 05840a68aa..2dc845f809 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Rozpocznij"
msgid "Start {0} Day Free Trial"
msgstr "Rozpocznij {0}-dniowy bezpłatny okres próbny"
+msgid "Start counting"
+msgstr "Rozpocznij liczenie"
+
msgid "Start Date"
msgstr "Data początkowa"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 7345e2d522..48a5751b6c 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Iniciar"
msgid "Start {0} Day Free Trial"
msgstr "Iniciar Teste Gratuito de {0} Dias"
+msgid "Start counting"
+msgstr "Iniciar contagem"
+
msgid "Start Date"
msgstr "Data de Início"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 201e5968d7..a64a0e057b 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Начать"
msgid "Start {0} Day Free Trial"
msgstr "Начать {0}-дневный бесплатный пробный период"
+msgid "Start counting"
+msgstr "Начать подсчёт"
+
msgid "Start Date"
msgstr "Дата начала"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 809b026032..c07602d193 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -11129,6 +11129,9 @@ msgstr "Başlat"
msgid "Start {0} Day Free Trial"
msgstr "{0} Gün Ücretsiz Deneme Başlat"
+msgid "Start counting"
+msgstr "Saymaya başla"
+
msgid "Start Date"
msgstr "Başlangıç Tarihi"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index db863cea90..1ed2d44733 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -11129,6 +11129,9 @@ msgstr "开始"
msgid "Start {0} Day Free Trial"
msgstr "开始 {0} 天免费试用"
+msgid "Start counting"
+msgstr "开始盘点"
+
msgid "Start Date"
msgstr "开始日期"