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.

feat: add filters to inventory table

Brad Barbin9203a68cc5c0
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 97113bc7e7..c7cb585915 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -16,12 +16,16 @@ import {
LuBox,
LuCheck,
LuCirclePlay,
+ LuExpand,
LuGlassWater,
LuMoveDown,
LuMoveUp,
LuPackage,
+ LuPaintBucket,
+ LuPuzzle,
LuRuler,
LuShapes,
+ LuStar,
} from "react-icons/lu";
import {
Hyperlink,
@@ -32,6 +36,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
+import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { useUrlParams } from "~/hooks";
import type { action as mrpAction } from "~/routes/api+/mrp";
import type { ListItem } from "~/types";
@@ -54,6 +59,10 @@ const InventoryTable = memo(
const locations = useLocations();
const unitOfMeasures = useUnitOfMeasure();
+ const filters = useFilters();
+ const materialSubstanceId = filters.getFilter("materialSubstanceId")?.[0];
+ const materialFormId = filters.getFilter("materialFormId")?.[0];
+
const columns = useMemo<ColumnDef<InventoryItem>[]>(() => {
return [
{
@@ -184,8 +193,79 @@ const InventoryTable = memo(
},
},
{
- accessorKey: "type",
+ accessorKey: "finish",
+ header: "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: "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: "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: "Type",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuPuzzle />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.materialTypes(
+ materialSubstanceId,
+ materialFormId
+ ),
+ transform: (data: { id: string; name: string }[] | null) =>
+ data?.map(({ id, name }) => ({
+ value: id,
+ label: name,
+ })) ?? [],
+ },
+ },
+ },
+ {
+ accessorKey: "type",
+ header: "Item Type",
cell: ({ row }) =>
row.original.type && (
<HStack>
@@ -226,11 +306,22 @@ const InventoryTable = memo(
},
},
];
- }, [forms, params, substances, unitOfMeasures]);
+ }, [
+ forms,
+ materialFormId,
+ materialSubstanceId,
+ params,
+ substances,
+ unitOfMeasures,
+ ]);
const defaultColumnVisibility = {
active: false,
type: false,
+ finish: false,
+ grade: false,
+ dimension: false,
+ materialType: false,
};
const defaultColumnPinning = {
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 6c381b7ac3..7c46aacf21 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -2129,7 +2129,9 @@ export async function upsertPickMethod(
})
) {
if ("createdBy" in pickMethod) {
- return client.from("pickMethod").insert(pickMethod);
+ return client.from("pickMethod").upsert(pickMethod, {
+ onConflict: "itemId,locationId",
+ });
}
return client
diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
index 640157c7a1..1d6c5c793a 100644
--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
@@ -57,39 +57,35 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- let [pickMethod] = await Promise.all([
- getPickMethod(client, itemId, companyId, locationId),
- ]);
-
- if (pickMethod.error || !pickMethod.data) {
- const insertPickMethod = await upsertPickMethod(client, {
- itemId,
- companyId,
- locationId,
- customFields: {},
- createdBy: userId,
- });
+ // Ensure pick method exists for this item/location combination
+ const ensurePickMethod = await upsertPickMethod(client, {
+ itemId,
+ companyId,
+ locationId,
+ customFields: {},
+ createdBy: userId,
+ });
- if (insertPickMethod.error) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(insertPickMethod.error, "Failed to insert part inventory")
- )
- );
- }
+ if (ensurePickMethod.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(ensurePickMethod.error, "Failed to ensure pick method exists")
+ )
+ );
+ }
- pickMethod = await getPickMethod(client, itemId, companyId, locationId);
- if (pickMethod.error || !pickMethod.data) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(pickMethod.error, "Failed to load part inventory")
- )
- );
- }
+ // Now get the pick method (it should definitely exist)
+ const pickMethod = await getPickMethod(client, itemId, companyId, locationId);
+ if (pickMethod.error || !pickMethod.data) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(pickMethod.error, "Failed to load pick method")
+ )
+ );
}
const item = await getItem(client, itemId);
diff --git a/llm/cache/inventory-system.md b/llm/cache/inventory-system.md
new file mode 100644
index 0000000000..924354759c
--- /dev/null
+++ b/llm/cache/inventory-system.md
@@ -0,0 +1,72 @@
+# Inventory System
+
+## Overview
+
+Carbon's inventory system tracks material and item quantities across different locations and stages of the manufacturing process.
+
+## Key Functions
+
+### get_inventory_quantities
+
+The `get_inventory_quantities` function is a PostgreSQL function that returns inventory information for items at a specific location. It was last updated in migration `20250724195443_update-inventory-quantities-material-properties.sql`.
+
+**Parameters:**
+- `company_id`: TEXT - The company identifier
+- `location_id`: TEXT - The location identifier
+
+**Returns a table with the following columns:**
+- `id`: TEXT - Item ID
+- `readableId`: TEXT - Human-readable item ID
+- `readableIdWithRevision`: TEXT - Readable ID with revision
+- `name`: TEXT - Item name
+- `active`: BOOLEAN - Whether the item is active
+- `type`: itemType - Item type enum
+- `itemTrackingType`: itemTrackingType - Tracking type enum
+- `replenishmentSystem`: itemReplenishmentSystem - Replenishment system enum
+- `materialSubstanceId`: TEXT - Material substance ID (e.g., steel, aluminum)
+- `materialFormId`: TEXT - Material form ID (e.g., sheet, plate, round bar)
+- `dimensionId`: TEXT - Material dimension ID
+- `dimension`: TEXT - Dimension name
+- `finishId`: TEXT - Material finish ID
+- `finish`: TEXT - Finish name
+- `gradeId`: TEXT - Material grade ID
+- `grade`: TEXT - Grade name
+- `materialType`: TEXT - Material type name
+- `materialTypeId`: TEXT - Material type ID
+- `thumbnailPath`: TEXT - Path to thumbnail image
+- `unitOfMeasureCode`: TEXT - Unit of measure code
+- `quantityOnHand`: NUMERIC - Current inventory quantity
+- `quantityOnSalesOrder`: NUMERIC - Quantity committed to sales orders
+- `quantityOnPurchaseOrder`: NUMERIC - Quantity on purchase orders
+- `quantityOnProductionOrder`: NUMERIC - Quantity on production orders
+- `quantityOnProductionDemand`: NUMERIC - Quantity demanded for production
+
+The function aggregates quantities from:
+- Item ledger entries (for on-hand inventory)
+- Open sales orders (status: Confirmed, To Ship and Invoice, To Ship, To Invoice, In Progress)
+- Open purchase orders (status: Planned, To Receive, To Receive and Invoice)
+- Open production jobs (status: Planned, Ready, In Progress, Paused)
+- Open job material requirements
+
+The function excludes non-inventory items and includes material property information by joining with:
+- `material` table for base material information
+- `materialDimension` table for dimension names
+- `materialFinish` table for finish names
+- `materialGrade` table for grade names
+- `materialType` table for material type names
+
+## TypeScript Types
+
+The function's TypeScript types are defined in:
+- `/packages/database/src/types.ts`
+- `/packages/database/supabase/functions/lib/types.ts`
+
+Both files include the complete type definition for the function's arguments and return values in the `Database["public"]["Functions"]` interface.
+
+## Usage
+
+This function is primarily used by:
+- Inventory module (`/apps/erp/app/modules/inventory/inventory.service.ts`)
+- Items module (`/apps/erp/app/modules/items/items.service.ts`)
+
+It provides a comprehensive view of inventory levels and commitments for materials tracking.
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250724195443_update-inventory-quantities-material-properties.sql b/packages/database/supabase/migrations/20250724195443_update-inventory-quantities-material-properties.sql
new file mode 100644
index 0000000000..483d6fe409
--- /dev/null
+++ b/packages/database/supabase/migrations/20250724195443_update-inventory-quantities-material-properties.sql
@@ -0,0 +1,159 @@
+-- Update get_inventory_quantities function to include new material properties
+DROP FUNCTION IF EXISTS get_inventory_quantities;
+
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT)
+ 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,
+ "quantityOnHand" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC
+ ) AS $$
+ BEGIN
+ 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
+ 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
+ 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'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_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
+ GROUP BY j."itemId"
+ ),
+ item_ledgers AS (
+ SELECT "itemId", SUM("quantity") AS "quantityOnHand"
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ GROUP BY "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",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."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 material m ON i."readableId" = m."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"
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id;
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
\ No newline at end of file