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.

docs: add script for getting inventory value by location

Brad Barbinb4c4bddc9606
diff --git a/packages/database/supabase/migrations/20260325031223_inventory-value-report.sql b/packages/database/supabase/migrations/20260325031223_inventory-value-report.sql
new file mode 100644
index 0000000000..faaa5f8255
--- /dev/null
+++ b/packages/database/supabase/migrations/20260325031223_inventory-value-report.sql
@@ -0,0 +1,41 @@
+DROP FUNCTION IF EXISTS get_inventory_value_by_location;
+CREATE OR REPLACE FUNCTION get_inventory_value_by_location(company_id TEXT)
+RETURNS TABLE (
+ "locationName" TEXT,
+ "itemReadableId" TEXT,
+ "itemName" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHand" NUMERIC,
+ "unitCost" NUMERIC,
+ "totalValue" NUMERIC
+) AS $$
+BEGIN
+ RETURN QUERY
+ WITH item_ledgers AS (
+ SELECT
+ il."itemId",
+ il."locationId",
+ SUM(il."quantity") AS "quantityOnHand"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ GROUP BY il."itemId", il."locationId"
+ HAVING SUM(il."quantity") <> 0
+ )
+ SELECT
+ l."name" AS "locationName",
+ i."readableIdWithRevision" AS "itemReadableId",
+ i."name" AS "itemName",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ il."quantityOnHand",
+ COALESCE(ic."unitCost", 0) AS "unitCost",
+ il."quantityOnHand" * COALESCE(ic."unitCost", 0) AS "totalValue"
+ FROM item_ledgers il
+ INNER JOIN "item" i ON il."itemId" = i."id"
+ INNER JOIN "location" l ON il."locationId" = l."id"
+ LEFT JOIN "itemCost" ic ON i."id" = ic."itemId"
+ WHERE i."companyId" = company_id
+ ORDER BY l."name", i."readableId";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/scripts/inventory-value.ts b/scripts/inventory-value.ts
new file mode 100644
index 0000000000..b6cbba4f56
--- /dev/null
+++ b/scripts/inventory-value.ts
@@ -0,0 +1,34 @@
+import { createClient } from "@supabase/supabase-js";
+import { config } from "dotenv";
+import { writeFileSync } from "fs";
+
+config();
+
+const apiUrl = "https://rest.carbon.ms";
+const apiKey = "crbn_*****************";
+
+
+const carbon = createClient(apiUrl, apiKey);
+
+(async () => {
+ const company = await carbon.from("company").select("id").single();
+ const companyId = company.data?.id;
+ if (!companyId) {
+ console.error("Company not found");
+ return;
+ }
+
+ const inventoryValue = await carbon.rpc("get_inventory_value_by_location", {
+ company_id: companyId,
+ }).csv();
+
+ if (inventoryValue.error) {
+ console.error("Error fetching inventory value:", inventoryValue.error);
+ return;
+ }
+
+ const date = new Date().toISOString().split("T")[0];
+ const filename = `inventory-value-${date}.csv`;
+ writeFileSync(filename, inventoryValue.data);
+ console.log(`Saved to ${filename}`);
+})();