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.

- comment fixes

Gaurav Bhatt01701eb96bc4
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsx
index 76cb6d3c55..f360c66495 100644
--- a/apps/erp/app/components/RealtimeDataProvider.tsx
+++ b/apps/erp/app/components/RealtimeDataProvider.tsx
@@ -2,7 +2,7 @@
import { useCarbon } from "@carbon/auth";
import { fetchAllFromTable } from "@carbon/database";
-import { useRealtimeChannel } from "@carbon/react";
+import { useInterval, useRealtimeChannel } from "@carbon/react";
import { useEffect } from "react";
import { useUser } from "~/hooks";
import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
@@ -31,24 +31,39 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
const fetchQuantities = async () => {
if (!carbon || !companyId) return;
- const { data, error } = await carbon
- .from("itemStockQuantities")
- .select("itemId, quantityOnHand")
- .eq("companyId", companyId);
+ const { data, error } = await fetchAllFromTable<{
+ itemId: string;
+ locationId: string;
+ quantityOnHand: number;
+ }>(
+ carbon,
+ // @ts-ignore -- itemStockQuantities is a materialized view
+ "itemStockQuantities",
+ "itemId, locationId, quantityOnHand",
+ (query) => query.eq("companyId", companyId)
+ );
if (error || !data) return;
- const quantityMap = new Map<string, number>();
+ const totalMap = new Map<string, number>();
+ const locationMap = new Map<string, Record<string, number>>();
+
for (const row of data) {
- if (row.itemId) {
- quantityMap.set(row.itemId, Number(row.quantityOnHand) ?? 0);
- }
+ if (!row.itemId) continue;
+ const qty = Number(row.quantityOnHand) || 0;
+ const locId = row.locationId || "";
+
+ totalMap.set(row.itemId, (totalMap.get(row.itemId) ?? 0) + qty);
+
+ if (!locationMap.has(row.itemId)) locationMap.set(row.itemId, {});
+ if (locId) locationMap.get(row.itemId)![locId] = qty;
}
setItems((currentItems) =>
currentItems.map((item) => ({
...item,
- quantityOnHand: quantityMap.get(item.id) ?? 0
+ quantityOnHand: totalMap.get(item.id) ?? 0,
+ quantityByLocation: locationMap.get(item.id) ?? {}
}))
);
};
@@ -157,12 +172,7 @@ 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]);
+ useInterval(fetchQuantities, companyId ? 10 * 60 * 1000 : null);
useRealtimeChannel({
topic: `realtime:core`,
diff --git a/apps/erp/app/stores/items.ts b/apps/erp/app/stores/items.ts
index 94d787ba6c..3ff9bb91e8 100644
--- a/apps/erp/app/stores/items.ts
+++ b/apps/erp/app/stores/items.ts
@@ -12,6 +12,7 @@ export type Item = ListItem & {
type: Database["public"]["Enums"]["itemType"];
active: boolean;
quantityOnHand?: number;
+ quantityByLocation?: Record<string, number>;
};
const $itemsStore = atom<Item[]>([]);
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index ac829c608d..5b472a0d0c 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -17979,6 +17979,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemStockQuantities.companyId",
},
+ {
+ $ref: "#/parameters/rowFilter.itemStockQuantities.locationId",
+ },
{
$ref: "#/parameters/rowFilter.itemStockQuantities.quantityOnHand",
},
@@ -65533,34 +65536,6 @@ 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: [
@@ -76230,6 +76205,10 @@ export default {
format: "text",
type: "string",
},
+ locationId: {
+ format: "text",
+ type: "string",
+ },
quantityOnHand: {
format: "numeric",
type: "number",
@@ -107337,6 +107316,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.itemStockQuantities.locationId": {
+ name: "locationId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.itemStockQuantities.quantityOnHand": {
name: "quantityOnHand",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 11dc4ef9e7..ede5b19080 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -44601,6 +44601,7 @@ export type Database = {
Row: {
companyId: string | null
itemId: string | null
+ locationId: string | null
quantityOnHand: number | null
}
Relationships: [
@@ -56959,7 +56960,6 @@ 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: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b36a977a8f..4e031be3a0 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -44601,6 +44601,7 @@ export type Database = {
Row: {
companyId: string | null
itemId: string | null
+ locationId: string | null
quantityOnHand: number | null
}
Relationships: [
@@ -51887,14 +51888,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -56959,7 +56960,6 @@ 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: string
diff --git a/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql b/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql
index ec6e4dfbb6..f9e0e81c91 100644
--- a/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql
+++ b/packages/database/supabase/migrations/20260210052714_item-stock-quantities-materialized-view.sql
@@ -2,23 +2,23 @@ CREATE MATERIALIZED VIEW "itemStockQuantities" AS
SELECT
"itemId",
"companyId",
+ COALESCE("locationId", '') AS "locationId",
SUM("quantity") AS "quantityOnHand"
FROM "itemLedger"
-GROUP BY "itemId", "companyId";
+GROUP BY "itemId", "companyId", COALESCE("locationId", '');
-CREATE UNIQUE INDEX "itemStockQuantities_itemId_companyId_idx"
- ON "itemStockQuantities" ("itemId", "companyId");
+CREATE UNIQUE INDEX "itemStockQuantities_itemId_companyId_locationId_idx"
+ ON "itemStockQuantities" ("itemId", "companyId", "locationId");
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;
-$$;
+-- Refresh every 30 minutes via pg_cron (extension already created in embeddings migration)
+SELECT
+ cron.schedule(
+ 'refresh-item-stock-quantities',
+ '*/30 * * * *',
+ $$
+ REFRESH MATERIALIZED VIEW CONCURRENTLY "itemStockQuantities";
+ $$
+ );
diff --git a/packages/jobs/trigger/refresh-item-stock-quantities.ts b/packages/jobs/trigger/refresh-item-stock-quantities.ts
deleted file mode 100644
index addcebc8e3..0000000000
--- a/packages/jobs/trigger/refresh-item-stock-quantities.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-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.tsx
index 0005132b25..1cda716c8b 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -243,7 +243,11 @@ function VirtualizedCommand({
<p className="line-clamp-1 w-full">{item.label}</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>
+ {item.helperRight && (
+ <span className="flex-shrink-0">
+ {item.helperRight}
+ </span>
+ )}
</div>
</div>
) : (
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index 9566c38026..251a8e0056 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -299,9 +299,11 @@ function VirtualizedCommand({
<p className="truncate">{item.label}</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>
+ {item.helperRight && (
+ <span className="flex-shrink-0">
+ {item.helperRight}
+ </span>
+ )}
</div>
</div>
) : (