Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
[FEAT] Add item stock quantities
Gaurav Bhattb71dd94fcc1e
diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsxindex 4f7229cb60..6e3b081ff7 100644--- a/apps/erp/app/components/Form/Item.tsx+++ b/apps/erp/app/components/Form/Item.tsx@@ -106,7 +106,11 @@ const Item = ({.map((item) => ({value: item.id,label: item.readableIdWithRevision,- helper: item.name+ helper: item.name,+ helperRight:+ item.quantityOnHand !== undefined+ ? `${item.quantityOnHand} ${item.unitOfMeasureCode}`+ : undefined}));if (props.whitelist) {diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 586b60a1d3..76cb6d3c55 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -28,6 +28,31 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {const [, setCustomers] = useCustomers();const [, setPeople] = usePeople();+ const fetchQuantities = async () => {+ if (!carbon || !companyId) return;++ const { data, error } = await carbon+ .from("itemStockQuantities")+ .select("itemId, quantityOnHand")+ .eq("companyId", companyId);++ if (error || !data) return;++ const quantityMap = new Map<string, number>();+ for (const row of data) {+ if (row.itemId) {+ quantityMap.set(row.itemId, Number(row.quantityOnHand) ?? 0);+ }+ }++ setItems((currentItems) =>+ currentItems.map((item) => ({+ ...item,+ quantityOnHand: quantityMap.get(item.id) ?? 0+ }))+ );+ };+const hydrate = async () => {const idb = (await import("localforage")).default;if (!hydratedFromIdb) {@@ -122,6 +147,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {idb.setItem("suppliers", suppliers.data);idb.setItem("customers", customers.data);idb.setItem("people", people.data);++ fetchQuantities();};// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration@@ -130,6 +157,13 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {hydrate();}, [companyId]);+ // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ useEffect(() => {+ if (!companyId) return;+ const interval = setInterval(fetchQuantities, 10 * 60 * 1000);+ return () => clearInterval(interval);+ }, [companyId]);+useRealtimeChannel({topic: `realtime:core`,dependencies: [companyId],diff --git a/apps/erp/app/stores/items.ts b/apps/erp/app/stores/items.tsindex 45b20f9e2a..94d787ba6c 100644--- a/apps/erp/app/stores/items.ts+++ b/apps/erp/app/stores/items.ts@@ -11,6 +11,7 @@ export type Item = ListItem & {unitOfMeasureCode: string;type: Database["public"]["Enums"]["itemType"];active: boolean;+ quantityOnHand?: number;};const $itemsStore = atom<Item[]>([]);diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex a4b99b1648..ac829c608d 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -17970,6 +17970,57 @@ export default {tags: ["purchasingRfqSupplier"],},},+ "/itemStockQuantities": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.itemStockQuantities.itemId",+ },+ {+ $ref: "#/parameters/rowFilter.itemStockQuantities.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.itemStockQuantities.quantityOnHand",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/itemStockQuantities",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["itemStockQuantities"],+ },+ },"/demandActual": {get: {parameters: [@@ -65482,6 +65533,34 @@ export default {tags: ["(rpc) uuid_to_base58"],},},+ "/rpc/refresh_item_stock_quantities": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) refresh_item_stock_quantities"],+ },+ },"/rpc/get_assigned_job_operations": {post: {parameters: [@@ -76137,6 +76216,27 @@ export default {},type: "object",},+ itemStockQuantities: {+ properties: {+ itemId: {+ description:+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string",+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ quantityOnHand: {+ format: "numeric",+ type: "number",+ },+ },+ type: "object",+ },demandActual: {required: ["itemId",@@ -107216,6 +107316,33 @@ export default {in: "query",type: "string",},+ "body.itemStockQuantities": {+ name: "itemStockQuantities",+ description: "itemStockQuantities",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/itemStockQuantities",+ },+ },+ "rowFilter.itemStockQuantities.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.itemStockQuantities.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.itemStockQuantities.quantityOnHand": {+ name: "quantityOnHand",+ required: false,+ in: "query",+ type: "string",+ },"body.demandActual": {name: "demandActual",description: "demandActual",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex c85942b4d4..11dc4ef9e7 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -44597,6 +44597,85 @@ export type Database = {},]}+ itemStockQuantities: {+ Row: {+ companyId: string | null+ itemId: string | null+ quantityOnHand: number | null+ }+ Relationships: [+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }jobMaterialWithMakeMethodId: {Row: {companyId: string | null@@ -56880,6 +56959,7 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ refresh_item_stock_quantities: { Args: never; Returns: undefined }search_company_index: {Args: {p_company_id: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex a03a071f2f..b36a977a8f 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -44597,6 +44597,85 @@ export type Database = {},]}+ itemStockQuantities: {+ Row: {+ companyId: string | null+ itemId: string | null+ quantityOnHand: number | null+ }+ Relationships: [+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemLedger_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "partLeger_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }jobMaterialWithMakeMethodId: {Row: {companyId: string | null@@ -51808,14 +51887,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56880,6 +56959,7 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ refresh_item_stock_quantities: { Args: never; Returns: undefined }search_company_index: {Args: {p_company_id: stringdiff --git a/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql b/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sqlnew file mode 100644index 0000000000..ec6e4dfbb6--- /dev/null+++ b/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql@@ -0,0 +1,24 @@+CREATE MATERIALIZED VIEW "itemStockQuantities" AS+SELECT+ "itemId",+ "companyId",+ SUM("quantity") AS "quantityOnHand"+FROM "itemLedger"+GROUP BY "itemId", "companyId";++CREATE UNIQUE INDEX "itemStockQuantities_itemId_companyId_idx"+ ON "itemStockQuantities" ("itemId", "companyId");++CREATE INDEX "itemStockQuantities_companyId_idx"+ ON "itemStockQuantities" ("companyId");++-- RPC function for Trigger.dev to call (REFRESH is DDL, can't go through PostgREST)+CREATE OR REPLACE FUNCTION refresh_item_stock_quantities()+RETURNS void+LANGUAGE plpgsql+SECURITY DEFINER+AS $$+BEGIN+ REFRESH MATERIALIZED VIEW CONCURRENTLY "itemStockQuantities";+END;+$$;diff --git a/packages/jobs/trigger/refresh-item-stock-quantities.ts b/packages/jobs/trigger/refresh-item-stock-quantities.tsnew file mode 100644index 0000000000..addcebc8e3--- /dev/null+++ b/packages/jobs/trigger/refresh-item-stock-quantities.ts@@ -0,0 +1,27 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { schedules } from "@trigger.dev/sdk";++const serviceRole = getCarbonServiceRole();++export const refreshItemStockQuantities = schedules.task({+ id: "refresh-item-stock-quantities",+ cron: "*/30 * * * *",+ run: async () => {+ console.log(+ `📦 Refreshing item stock quantities: ${new Date().toISOString()}`+ );++ const { error } = await serviceRole.rpc(+ "refresh_item_stock_quantities"+ );++ if (error) {+ console.error(+ `❌ Failed to refresh item stock quantities: ${JSON.stringify(error)}`+ );+ return;+ }++ console.log(`✅ Item stock quantities refreshed successfully`);+ },+});diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsxindex c849e2f675..0005132b25 100644--- a/packages/react/src/Combobox.tsx+++ b/packages/react/src/Combobox.tsx@@ -27,6 +27,7 @@ export type ComboboxProps = Omit<label: string | JSX.Element;value: string;helper?: string;+ helperRight?: string;}[];isClearable?: boolean;isLoading?: boolean;@@ -233,11 +234,17 @@ function VirtualizedCommand({}}>{item.helper ? (- <div className="flex flex-col pr-2">+ <div+ className={cn(+ "flex flex-col min-w-0 flex-1",+ itemValue === value && "pr-2"+ )}+ ><p className="line-clamp-1 w-full">{item.label}</p>- <p className="text-xs text-muted-foreground line-clamp-1">- {item.helper}- </p>+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">+ <span className="truncate flex-1">{item.helper}</span>+ <span className="flex-shrink-0">{item.helperRight}</span>+ </div></div>) : (<span className="line-clamp-1 w-full pr-2">{item.label}</span>@@ -245,7 +252,7 @@ function VirtualizedCommand({<LuCheckclassName={cn("ml-auto h-4 w-4",- itemValue === value ? "opacity-100" : "opacity-0"+ itemValue === value ? "opacity-100" : "opacity-0 hidden")}/></CommandItem>diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsxindex c743e75b7f..9566c38026 100644--- a/packages/react/src/CreateableCombobox.tsx+++ b/packages/react/src/CreateableCombobox.tsx@@ -25,6 +25,7 @@ export type CreatableComboboxProps = Omit<label: string | JSX.Element;value: string;helper?: string;+ helperRight?: string;}[];selected?: string[];isClearable?: boolean;@@ -289,11 +290,19 @@ function VirtualizedCommand({</span></div>) : item.helper ? (- <div className="flex flex-col min-w-0 flex-1">+ <div+ className={cn(+ "flex flex-col min-w-0 flex-1",+ isSelected || (item.value === value && "pr-2")+ )}+ ><p className="truncate">{item.label}</p>- <p className="text-xs text-muted-foreground truncate">- {item.helper}- </p>+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">+ <span className="truncate flex-1">{item.helper}</span>+ <span className="flex-shrink-0">+ {item.helperRight}+ </span>+ </div></div>) : (<span className="truncate flex-1">{item.label}</span>@@ -304,7 +313,7 @@ function VirtualizedCommand({"ml-auto h-4 w-4 flex-shrink-0",isSelected || item.value === value? "opacity-100"- : "opacity-0"+ : "opacity-0 hidden")}/>)}