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: update average cost and supplier price on invoice
Brad Barbin95d4b942786e
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsxindex 4192615777..e2b8950b73 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx@@ -71,7 +71,7 @@ const PartCostingForm = ({ initialValues }: PartCostingFormProps) => {<Numbername="unitCost"- label="Unit Cost"+ label="Average Cost"formatOptions={{style: "currency",currency,diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.tsindex a34c6c5c44..222afdcbbf 100644--- a/packages/database/supabase/functions/update-purchased-prices/index.ts+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts@@ -1,8 +1,10 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { corsHeaders } from "../lib/headers.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { Database } from "../lib/types.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -29,18 +31,119 @@ serve(async (req: Request) => {if (purchaseInvoiceLines.error)throw new Error("Failed to fetch receipt lines");- const partSuppliers = await client- .from("partSupplier")- .select("*")- .eq("supplierId", purchaseInvoice.data?.supplierId ?? "")- .in(- "partId",- purchaseInvoiceLines.data- .filter((line) => Boolean(line.partId))- .map((line) => line.partId)- );-- await db.transaction().execute(async (trx) => {});+ const partIds = purchaseInvoiceLines.data+ .filter((line) => Boolean(line.partId))+ .map((line) => line.partId);++ const dateOneYearAgo = format(+ new Date(new Date().setFullYear(new Date().getFullYear() - 1)),+ "yyyy-MM-dd"+ );++ const [costLedgers, partSuppliers] = await Promise.all([+ client+ .from("costLedger")+ .select("*")+ .in("partId", partIds)+ .gte("postingDate", dateOneYearAgo),+ client+ .from("partSupplier")+ .select("*")+ .eq("supplierId", purchaseInvoice.data?.supplierId ?? "")+ .in("partId", partIds),+ ]);++ const partCostUpdates: Database["public"]["Tables"]["partCost"]["Update"][] =+ [];+ const partSupplierInserts: Database["public"]["Tables"]["partSupplier"]["Insert"][] =+ [];+ const partSupplierUpdates: Database["public"]["Tables"]["partSupplier"]["Update"][] =+ [];++ const historicalPartCosts: Record<+ string,+ { quantity: number; cost: number }+ > = {};++ costLedgers.data?.forEach((ledger) => {+ if (ledger.partId) {+ if (!historicalPartCosts[ledger.partId]) {+ historicalPartCosts[ledger.partId] = {+ quantity: 0,+ cost: 0,+ };+ }++ historicalPartCosts[ledger.partId].quantity += ledger.quantity;+ historicalPartCosts[ledger.partId].cost += ledger.cost;+ }+ });++ purchaseInvoiceLines.data.forEach((line) => {+ if (line.partId && historicalPartCosts[line.partId]) {+ partCostUpdates.push({+ partId: line.partId,+ unitCost:+ historicalPartCosts[line.partId].cost /+ historicalPartCosts[line.partId].quantity,+ updatedBy: "system",+ });++ const partSupplier = partSuppliers.data?.find(+ (partSupplier) =>+ partSupplier.partId === line.partId &&+ partSupplier.supplierId === purchaseInvoice.data?.supplierId+ );++ if (partSupplier && partSupplier.id) {+ partSupplierUpdates.push({+ id: partSupplier.id,+ unitPrice: line.unitPrice,+ conversionFactor: line.conversionFactor ?? 1,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ updatedBy: "system",+ });+ } else {+ partSupplierInserts.push({+ partId: line.partId,+ supplierId: purchaseInvoice.data?.supplierId!,+ unitPrice: line.unitPrice,+ conversionFactor: line.conversionFactor ?? 1,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ createdBy: "system",+ });+ }+ }+ });++ await db.transaction().execute(async (trx) => {+ if (partCostUpdates.length > 0) {+ for await (const partCostUpdate of partCostUpdates) {+ await trx+ .updateTable("partCost")+ .set(partCostUpdate)+ .where("partId", "=", partCostUpdate.partId!)+ .execute();+ }+ }++ if (partSupplierInserts.length > 0) {+ await trx+ .insertInto("partSupplier")+ .values(partSupplierInserts)+ .execute();+ }++ if (partSupplierUpdates.length > 0) {+ for await (const partSupplierUpdate of partSupplierUpdates) {+ await trx+ .updateTable("partSupplier")+ .set(partSupplierUpdate)+ .where("id", "=", partSupplierUpdate.id!)+ .execute();+ }+ }+ });return new Response(JSON.stringify({diff --git a/packages/database/supabase/migrations/20240411035639_purchased-prices.sql b/packages/database/supabase/migrations/20240411035639_purchased-prices.sqlindex b1df3b54de..a0873d8f5f 100644--- a/packages/database/supabase/migrations/20240411035639_purchased-prices.sql+++ b/packages/database/supabase/migrations/20240411035639_purchased-prices.sql@@ -13,4 +13,7 @@ BEGINRETURN new;END;-$$ LANGUAGE plpgsql SECURITY DEFINER;\ No newline at end of file+$$ LANGUAGE plpgsql SECURITY DEFINER;+++CREATE INDEX "costLedger_partId_idx" ON "costLedger" ("partId");\ No newline at end of file