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: default to fifo costing

Brad Barbine5079efc652e
diff --git a/apps/carbon/app/jobs/post-transaction.server.ts b/apps/carbon/app/jobs/post-transaction.server.ts
index 9e81392e86..8aecf77b7a 100644
--- a/apps/carbon/app/jobs/post-transaction.server.ts
+++ b/apps/carbon/app/jobs/post-transaction.server.ts
@@ -28,9 +28,7 @@ const job = triggerClient.defineJob({
switch (payload.type) {
case "receipt":
- await io.logger.info(
- `📫 Posting receipt for receipt ${payload.documentId}`
- );
+ await io.logger.info(`📫 Posting receipt ${payload.documentId}`);
const postReceipt = await supabaseClient.functions.invoke(
"post-receipt",
{
@@ -48,7 +46,7 @@ const job = triggerClient.defineJob({
break;
case "purchase-invoice":
await io.logger.info(
- `📫 Posting receipt for purchase invoice ${payload.documentId}`
+ `📫 Posting purchase invoice ${payload.documentId}`
);
const postPurchaseInvoice = await supabaseClient.functions.invoke(
"post-purchase-invoice",
@@ -64,6 +62,25 @@ const job = triggerClient.defineJob({
message: postPurchaseInvoice.error?.message,
};
+ if (result.success) {
+ await io.logger.info(
+ `💵 Updating pricing from invoice ${payload.documentId}`
+ );
+ const priceUpdate = await supabaseClient.functions.invoke(
+ "update-purchased-prices",
+ {
+ body: {
+ invoiceId: payload.documentId,
+ },
+ }
+ );
+
+ result = {
+ success: priceUpdate.error === null ? true : false,
+ message: priceUpdate.error?.message,
+ };
+ }
+
break;
default:
result = {
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx
index f6aee8cadc..4192615777 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartCostingForm.tsx
@@ -6,6 +6,7 @@ import {
CardTitle,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useState } from "react";
import type { z } from "zod";
import {
Boolean,
@@ -26,6 +27,9 @@ const currency = "USD"; // TODO: get from settings
const PartCostingForm = ({ initialValues }: PartCostingFormProps) => {
const permissions = usePermissions();
+ const [partCostingMethod, setPartCostingMethod] = useState<string>(
+ initialValues.costingMethod
+ );
const partCostingMethodOptions = partCostingMethods.map(
(partCostingMethod) => ({
@@ -51,6 +55,9 @@ const PartCostingForm = ({ initialValues }: PartCostingFormProps) => {
name="costingMethod"
label="Part Costing Method"
options={partCostingMethodOptions}
+ onChange={(newValue) => {
+ if (newValue) setPartCostingMethod(newValue.value);
+ }}
/>
<Number
name="standardCost"
@@ -59,6 +66,7 @@ const PartCostingForm = ({ initialValues }: PartCostingFormProps) => {
style: "currency",
currency,
}}
+ isReadOnly={partCostingMethod !== "Standard"}
/>
<Number
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
index 67e8328a5a..ecebec18d5 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
@@ -87,6 +87,10 @@ const useNextPartIdShortcut = () => {
return { partId, onPartIdChange, loading };
};
+function startsWithLetter(value: string) {
+ return /^[A-Za-z]/.test(value);
+}
+
const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
@@ -153,7 +157,11 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
<InputControlled
name="id"
label="Part ID"
- helperText="Use ... to get the next part ID"
+ helperText={
+ startsWithLetter(partId)
+ ? "Use ... to get the next part ID"
+ : undefined
+ }
value={partId}
onChange={onPartIdChange}
isDisabled={loading}
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
new file mode 100644
index 0000000000..a34c6c5c44
--- /dev/null
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -0,0 +1,61 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ const { invoiceId } = await req.json();
+
+ try {
+ if (!invoiceId) throw new Error("Payload is missing invoiceId");
+
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+
+ const [purchaseInvoice, purchaseInvoiceLines] = await Promise.all([
+ client.from("purchaseInvoice").select("*").eq("id", invoiceId).single(),
+ client.from("purchaseInvoiceLine").select("*").eq("invoiceId", invoiceId),
+ ]);
+
+ if (purchaseInvoice.error)
+ throw new Error("Failed to fetch purchaseInvoice");
+ 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) => {});
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ } catch (err) {
+ console.error(err);
+
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/migrations/20240411035639_purchased-prices.sql b/packages/database/supabase/migrations/20240411035639_purchased-prices.sql
new file mode 100644
index 0000000000..b1df3b54de
--- /dev/null
+++ b/packages/database/supabase/migrations/20240411035639_purchased-prices.sql
@@ -0,0 +1,16 @@
+CREATE OR REPLACE FUNCTION public.create_part_related_records()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."partCost"("partId", "costingMethod", "createdBy")
+ VALUES (new.id, 'FIFO', new."createdBy");
+
+ INSERT INTO public."partReplenishment"("partId", "createdBy")
+ VALUES (new.id, new."createdBy");
+
+ INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")
+ -- TODO: get default currency
+ VALUES (new.id, 'USD', new."createdBy");
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
\ No newline at end of file