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: update costs when line quantity updates

Brad Barbin5eca929364e6
diff --git a/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsx b/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsx
new file mode 100644
index 0000000000..d88d3c1c95
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsx
@@ -0,0 +1,85 @@
+/* eslint-disable react/display-name */
+import type { Database } from "@carbon/database";
+import { Input, NumberField } from "@carbon/react";
+import type {
+ PostgrestSingleResponse,
+ SupabaseClient,
+} from "@supabase/supabase-js";
+import type { FocusEvent, KeyboardEvent } from "react";
+
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+import type { QuotationLineQuantity } from "~/modules/sales";
+import { getLinePriceUpdate } from "~/modules/sales";
+import { type LinePriceEffects } from "~/modules/sales/ui/Quotation/useQuotation";
+
+const EditableQuotationLineQuantity =
+ (
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: QuotationLineQuantity
+ ) => Promise<PostgrestSingleResponse<unknown>>,
+ options: {
+ client?: SupabaseClient<Database>;
+ effects: LinePriceEffects;
+ }
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<QuotationLineQuantity>) => {
+ const updateNumber = async (newValue: string) => {
+ const quantity = Number(newValue);
+ const { client, effects } = options;
+
+ const update = getLinePriceUpdate(quantity, effects);
+
+ console.log({ quantity, effects, update });
+ // this is the optimistic update on the FE
+ onUpdate({ quantity, ...update });
+
+ const mutation = await client
+ ?.from("quoteLineQuantity")
+ .update({ quantity, ...update })
+ .eq("id", row.id!);
+
+ if (!mutation || mutation.error) {
+ onError();
+ onUpdate({ ...row });
+ }
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ // only run the update if they click enter
+ if (event.key === "Enter" || event.key === "Tab") {
+ if (event.currentTarget.value !== value) {
+ updateNumber(event.currentTarget.value);
+ }
+ }
+ };
+
+ // run update if focus is lost
+ const onBlur = (event: FocusEvent<HTMLInputElement>) => {
+ if (event.currentTarget.value !== value) {
+ updateNumber(event.currentTarget.value);
+ }
+ };
+
+ return (
+ <NumberField defaultValue={value as number}>
+ <Input
+ size="sm"
+ className="w-full rounded-none ring-offset-0"
+ autoFocus
+ onKeyDown={onKeyDown}
+ onBlur={onBlur}
+ />
+ </NumberField>
+ );
+ };
+
+EditableQuotationLineQuantity.displayName = "EditableQuotationLineQuantity";
+export default EditableQuotationLineQuantity;
diff --git a/apps/carbon/app/components/Editable/index.ts b/apps/carbon/app/components/Editable/index.ts
index cf9535b570..d819db2aff 100644
--- a/apps/carbon/app/components/Editable/index.ts
+++ b/apps/carbon/app/components/Editable/index.ts
@@ -2,6 +2,7 @@ import EditableList from "./EditableList";
import EditableNumber from "./EditableNumber";
import EditablePurchaseInvoiceLineNumber from "./EditablePurchaseInvoiceLineNumber";
import EditablePurchaseOrderLineNumber from "./EditablePurchaseOrderLineNumber";
+import EditableQuotationLineQuantity from "./EditableQuotationLineQuantity";
import EditableQuotationMaterial from "./EditableQuotationMaterial";
import EditableText from "./EditableText";
@@ -11,6 +12,7 @@ export {
EditableNumber,
EditablePurchaseInvoiceLineNumber,
EditablePurchaseOrderLineNumber,
+ EditableQuotationLineQuantity,
EditableQuotationMaterial,
EditableText,
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx
index b54530b6aa..72b20dc20d 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx
@@ -16,12 +16,16 @@ import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useMemo, useRef } from "react";
import { IoMdTrash } from "react-icons/io";
import { MdMoreHoriz } from "react-icons/md";
-import { EditableNumber } from "~/components/Editable";
+import {
+ EditableNumber,
+ EditableQuotationLineQuantity,
+} from "~/components/Editable";
import Grid from "~/components/Grid";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import {
useQuotation,
+ useQuotationLinePriceEffects,
type QuotationLine,
type QuotationLineQuantity,
} from "~/modules/sales";
@@ -43,6 +47,8 @@ const QuotationLineQuantities = ({
const navigate = useNavigate();
const [quotation] = useQuotation();
+ const linePriceEffects = useQuotationLinePriceEffects();
+ console.log("linePriceEffects", linePriceEffects);
// TODO: use the currency of the quote
const formatter = new Intl.NumberFormat("en-US", {
@@ -160,11 +166,6 @@ const QuotationLineQuantities = ({
if (isMade) {
_columns.push(
- {
- accessorKey: "scrapPercentage",
- header: "Scrap Percentage",
- cell: (item) => item.getValue() + "%",
- },
{
accessorKey: "setupHours",
header: "Setup Hours",
@@ -187,14 +188,11 @@ const QuotationLineQuantities = ({
if (isMade) {
_columns.push(
{
- accessorKey: "laborCost",
- header: "Labor Cost",
- cell: (item) => formatter.format(item.getValue<number>()),
- },
- {
- accessorKey: "overheadCost",
- header: "Overhead Cost",
- cell: (item) => formatter.format(item.getValue<number>()),
+ header: "Labor + Overhead Cost",
+ cell: ({ row }) =>
+ formatter.format(
+ row.original.laborCost + row.original.overheadCost
+ ),
},
{
accessorKey: "additionalCost",
@@ -210,23 +208,17 @@ const QuotationLineQuantities = ({
const editableComponents = useMemo(
() => ({
- quantity: EditableNumber(onCellEdit),
- scrapPercentage: EditableNumber(onCellEdit, {
- minValue: 0,
- maxValue: 1,
+ quantity: EditableQuotationLineQuantity(onCellEdit, {
+ client: supabase,
+ effects: linePriceEffects.effects[lineId],
}),
- setupHours: EditableNumber(onCellEdit, { minValue: 0 }),
- productionHours: EditableNumber(onCellEdit, { minValue: 0 }),
- materialCost: EditableNumber(onCellEdit, { minValue: 0 }),
- laborCost: EditableNumber(onCellEdit, { minValue: 0 }),
- overheadCost: EditableNumber(onCellEdit, { minValue: 0 }),
additionalCost: EditableNumber(onCellEdit, { minValue: 0 }),
discountPercentage: EditableNumber(onCellEdit, { minValue: 0 }),
markupPercentage: EditableNumber(onCellEdit, { minValue: 0 }),
unitTaxAmount: EditableNumber(onCellEdit, { minValue: 0 }),
leadTime: EditableNumber(onCellEdit, { minValue: 0 }),
}),
- [onCellEdit]
+ [lineId, linePriceEffects.effects, onCellEdit, supabase]
);
const newRowButtonRef = useRef<HTMLButtonElement>(null);
@@ -267,11 +259,12 @@ const QuotationLineQuantities = ({
export default QuotationLineQuantities;
-function getUnitCost(quantity: QuotationLineQuantity) {
+function getUnitCost(line: QuotationLineQuantity) {
return (
- quantity.materialCost +
- quantity.laborCost +
- quantity.overheadCost +
- quantity.additionalCost
+ (line.materialCost +
+ line.laborCost +
+ line.overheadCost +
+ line.additionalCost) /
+ line.quantity
);
}
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
index 6d3ab6d004..565ec53f00 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
@@ -9,7 +9,12 @@ import QuotationMaterialForm from "./QuotationMaterialForm";
import QuotationMaterialLines from "./QuotationMaterialLines";
import QuotationOperationForm from "./QuotationOperationForm";
import QuotationStatus from "./QuotationStatus";
-import { useQuotation, useQuotationLinePriceEffects } from "./useQuotation";
+import {
+ getLinePriceUpdate,
+ useQuotation,
+ useQuotationLinePriceEffects,
+ useQuotationLinePriceEffectsUpdate,
+} from "./useQuotation";
export {
QuotationAssemblyForm,
QuotationDocuments,
@@ -22,6 +27,8 @@ export {
QuotationMaterialLines,
QuotationOperationForm,
QuotationStatus,
+ getLinePriceUpdate,
useQuotation,
useQuotationLinePriceEffects,
+ useQuotationLinePriceEffectsUpdate,
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx b/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx
index 293f85308a..e3612b6910 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx
@@ -23,7 +23,7 @@ type QuoteStore = {
type Effect = (quantity: number) => number;
-type LinePriceEffects = {
+export type LinePriceEffects = {
materialCost: Effect[];
laborCost: Effect[];
overheadCost: Effect[];
@@ -42,286 +42,310 @@ const $quotationStore = atom<QuoteStore>({
const defaultLinePriceEffectsResult = {} as Record<string, LinePriceEffects>;
-const $quotationLinePriceEffects = computed($quotationStore, (store) =>
- task(async () => {
- if (!store.quote?.id || !store.client) return defaultLinePriceEffectsResult;
-
- const quoteLineQuantities = await store.client
- .from("quoteLineQuantity")
- .select("*")
- .eq("quoteId", store.quote.id);
-
- console.log("quoteLineQuantities", quoteLineQuantities);
-
- if (quoteLineQuantities.error) {
- logger.error(quoteLineQuantities.error);
- return defaultLinePriceEffectsResult;
+const $quotationLinePriceEffects = computed($quotationStore, (store) => {
+ const assembliesByLineId = store.assemblies?.reduce<
+ Record<string, QuotationAssembly[]>
+ >((acc, assembly) => {
+ if (!acc[assembly.quoteLineId]) {
+ acc[assembly.quoteLineId] = [];
}
-
- if (!quoteLineQuantities.data || !quoteLineQuantities.data.length) {
- return defaultLinePriceEffectsResult;
+ acc[assembly.quoteLineId].push(assembly);
+ return acc;
+ }, {});
+
+ const operationsByLineId = store.operations?.reduce<
+ Record<string, QuotationOperation[]>
+ >((acc, operation) => {
+ if (!acc[operation.quoteLineId]) {
+ acc[operation.quoteLineId] = [];
}
-
- const assembliesByLineId = store.assemblies?.reduce<
- Record<string, QuotationAssembly[]>
+ acc[operation.quoteLineId].push(operation);
+ return acc;
+ }, {});
+
+ let materialsByOperationId = store.materials?.reduce<
+ Record<string, QuotationMaterial[]>
+ >((acc, material) => {
+ if (!acc[material.quoteOperationId]) {
+ acc[material.quoteOperationId] = [];
+ }
+ acc[material.quoteOperationId].push(material);
+ return acc;
+ }, {});
+
+ const linePriceEffects = store?.lines?.reduce<
+ Record<string, LinePriceEffects>
+ >((effects, line) => {
+ effects[line.id] = {
+ materialCost: [],
+ laborCost: [],
+ overheadCost: [],
+ setupHours: [],
+ productionHours: [],
+ };
+
+ let assembliesById = assembliesByLineId[line.id]?.reduce<
+ Record<string, QuotationAssembly>
>((acc, assembly) => {
- if (!acc[assembly.quoteLineId]) {
- acc[assembly.quoteLineId] = [];
- }
- acc[assembly.quoteLineId].push(assembly);
+ acc[assembly.id] = assembly;
return acc;
}, {});
- const operationsByLineId = store.operations?.reduce<
- Record<string, QuotationOperation[]>
- >((acc, operation) => {
- if (!acc[operation.quoteLineId]) {
- acc[operation.quoteLineId] = [];
- }
- acc[operation.quoteLineId].push(operation);
- return acc;
- }, {});
+ const extendedQuantitiesPerAssembly = assembliesByLineId[line.id]?.reduce<
+ Record<string, number>
+ >((acc, assembly: QuotationAssembly) => {
+ let quantity = assembly.quantityPerParent ?? 1;
+ let asm = assembliesById[assembly.id];
+ while (asm.parentAssemblyId) {
+ // memoize the results
+ if (acc[asm.parentAssemblyId]) {
+ quantity *= acc[asm.parentAssemblyId];
+ break;
+ }
- let materialsByOperationId = store.materials?.reduce<
- Record<string, QuotationMaterial[]>
- >((acc, material) => {
- if (!acc[material.quoteOperationId]) {
- acc[material.quoteOperationId] = [];
+ let parent = assembliesById[asm.parentAssemblyId];
+ quantity *= parent.quantityPerParent ?? 1;
+ asm = parent;
}
- acc[material.quoteOperationId].push(material);
+
+ acc[assembly.id] = quantity;
return acc;
}, {});
- const linePriceEffects = store?.lines?.reduce<
- Record<string, LinePriceEffects>
- >((effects, line) => {
- effects[line.id] = {
- materialCost: [],
- laborCost: [],
- overheadCost: [],
- setupHours: [],
- productionHours: [],
- };
-
- let assembliesById = assembliesByLineId[line.id]?.reduce<
- Record<string, QuotationAssembly>
- >((acc, assembly) => {
- acc[assembly.id] = assembly;
- return acc;
- }, {});
-
- const extendedQuantitiesPerAssembly = assembliesByLineId[line.id]?.reduce<
- Record<string, number>
- >((acc, assembly: QuotationAssembly) => {
- let quantity = assembly.quantityPerParent ?? 1;
- let asm = assembliesById[assembly.id];
- while (asm.parentAssemblyId) {
- // memoize the results
- if (acc[asm.parentAssemblyId]) {
- quantity *= acc[asm.parentAssemblyId];
- break;
- }
+ operationsByLineId[line.id]?.forEach((operation: QuotationOperation) => {
+ let materials = materialsByOperationId[operation.id] ?? [];
+ let extendedQuantityPerAssembly = operation.quoteAssemblyId
+ ? extendedQuantitiesPerAssembly[operation.quoteAssemblyId] ?? 1
+ : 1;
- let parent = assembliesById[asm.parentAssemblyId];
- quantity *= parent.quantityPerParent ?? 1;
- asm = parent;
- }
+ let materialCost = materials.reduce(
+ (acc, material: QuotationMaterial) => {
+ return acc + (material.quantity ?? 0) * (material.unitCost ?? 0);
+ },
+ 0
+ );
- acc[assembly.id] = quantity;
- return acc;
- }, {});
-
- operationsByLineId[line.id]?.forEach((operation: QuotationOperation) => {
- let materials = materialsByOperationId[operation.id] ?? [];
- let extendedQuantityPerAssembly = operation.quoteAssemblyId
- ? extendedQuantitiesPerAssembly[operation.quoteAssemblyId] ?? 1
- : 1;
-
- let materialCost = materials.reduce(
- (acc, material: QuotationMaterial) => {
- return acc + (material.quantity ?? 0) * (material.unitCost ?? 0);
- },
- 0
- );
-
- effects[line.id].materialCost.push((quantity) => {
- return materialCost * quantity * extendedQuantityPerAssembly;
+ effects[line.id].materialCost.push((quantity) => {
+ return materialCost * quantity * extendedQuantityPerAssembly;
+ });
+
+ if (operation.setupHours) {
+ effects[line.id].setupHours.push((_quantity) => {
+ return operation.setupHours;
});
+ if (operation.quotingRate) {
+ effects[line.id].overheadCost.push((_quantity) => {
+ return operation.setupHours * (operation.quotingRate ?? 0);
+ });
+ } else {
+ effects[line.id].laborCost.push((_quantity) => {
+ return operation.setupHours * (operation.laborRate ?? 0);
+ });
+ effects[line.id].overheadCost.push((_quantity) => {
+ return operation.setupHours * (operation.overheadRate ?? 0);
+ });
+ }
+ }
+
+ if (operation.productionStandard) {
+ let hoursPerProductionStandard = 0;
+ switch (operation.standardFactor) {
+ case "Hours/Piece":
+ hoursPerProductionStandard = operation.productionStandard;
+ break;
+ case "Hours/100 Pieces":
+ hoursPerProductionStandard = operation.productionStandard / 100;
+ break;
+ case "Hours/1000 Pieces":
+ hoursPerProductionStandard = operation.productionStandard / 1000;
+ break;
+ case "Minutes/Piece":
+ hoursPerProductionStandard = operation.productionStandard / 60;
+ break;
+ case "Minutes/100 Pieces":
+ hoursPerProductionStandard =
+ operation.productionStandard / 100 / 60;
+ break;
+ case "Minutes/1000 Pieces":
+ hoursPerProductionStandard =
+ operation.productionStandard / 1000 / 60;
+ break;
+ case "Pieces/Hour":
+ hoursPerProductionStandard = 1 / operation.productionStandard;
+ break;
+ case "Pieces/Minute":
+ hoursPerProductionStandard =
+ 1 / (operation.productionStandard / 60);
+ break;
+ case "Seconds/Piece":
+ hoursPerProductionStandard = operation.productionStandard / 3600;
+ break;
+ case "Total Hours":
+ hoursPerProductionStandard = operation.productionStandard;
+ break;
+ case "Total Minutes":
+ hoursPerProductionStandard = operation.productionStandard / 60;
+ break;
+ default:
+ break;
+ }
- if (operation.setupHours) {
- effects[line.id].setupHours.push((_quantity) => {
- return operation.setupHours;
+ if (
+ ["Total Hours", "Total Minutes"].includes(operation.standardFactor)
+ ) {
+ effects[line.id].productionHours.push((quantity) => {
+ return quantity * hoursPerProductionStandard;
});
if (operation.quotingRate) {
- effects[line.id].overheadCost.push((_quantity) => {
- return operation.setupHours * (operation.quotingRate ?? 0);
+ effects[line.id].overheadCost.push((quantity) => {
+ return (
+ quantity *
+ hoursPerProductionStandard *
+ (operation.quotingRate ?? 0)
+ );
});
} else {
- effects[line.id].laborCost.push((_quantity) => {
- return operation.setupHours * (operation.laborRate ?? 0);
+ effects[line.id].laborCost.push((quantity) => {
+ return (
+ quantity *
+ hoursPerProductionStandard *
+ (operation.laborRate ?? 0)
+ );
});
- effects[line.id].overheadCost.push((_quantity) => {
- return operation.setupHours * (operation.overheadRate ?? 0);
+ effects[line.id].overheadCost.push((quantity) => {
+ return (
+ quantity *
+ hoursPerProductionStandard *
+ (operation.overheadRate ?? 0)
+ );
});
}
- }
-
- if (operation.productionStandard) {
- let hoursPerProductionStandard = 0;
- switch (operation.standardFactor) {
- case "Hours/Piece":
- hoursPerProductionStandard = operation.productionStandard;
- break;
- case "Hours/100 Pieces":
- hoursPerProductionStandard = operation.productionStandard / 100;
- break;
- case "Hours/1000 Pieces":
- hoursPerProductionStandard = operation.productionStandard / 1000;
- break;
- case "Minutes/Piece":
- hoursPerProductionStandard = operation.productionStandard / 60;
- break;
- case "Minutes/100 Pieces":
- hoursPerProductionStandard =
- operation.productionStandard / 100 / 60;
- break;
- case "Minutes/1000 Pieces":
- hoursPerProductionStandard =
- operation.productionStandard / 1000 / 60;
- break;
- case "Pieces/Hour":
- hoursPerProductionStandard = 1 / operation.productionStandard;
- break;
- case "Pieces/Minute":
- hoursPerProductionStandard =
- 1 / (operation.productionStandard / 60);
- break;
- case "Seconds/Piece":
- hoursPerProductionStandard = operation.productionStandard / 3600;
- break;
- case "Total Hours":
- hoursPerProductionStandard = operation.productionStandard;
- break;
- case "Total Minutes":
- hoursPerProductionStandard = operation.productionStandard / 60;
- break;
- default:
- break;
- }
-
- if (
- ["Total Hours", "Total Minutes"].includes(operation.standardFactor)
- ) {
- effects[line.id].productionHours.push((_quantity) => {
- return hoursPerProductionStandard;
+ } else {
+ effects[line.id].productionHours.push((quantity) => {
+ return (
+ hoursPerProductionStandard *
+ quantity *
+ extendedQuantityPerAssembly
+ );
+ });
+ if (operation.quotingRate) {
+ effects[line.id].overheadCost.push((quantity) => {
+ return (
+ hoursPerProductionStandard *
+ quantity *
+ extendedQuantityPerAssembly *
+ (operation.quotingRate ?? 0)
+ );
});
- if (operation.quotingRate) {
- effects[line.id].overheadCost.push((_quantity) => {
- return (
- hoursPerProductionStandard * (operation.quotingRate ?? 0)
- );
- });
- } else {
- effects[line.id].laborCost.push((_quantity) => {
- return hoursPerProductionStandard * (operation.laborRate ?? 0);
- });
- effects[line.id].overheadCost.push((_quantity) => {
- return (
- hoursPerProductionStandard * (operation.overheadRate ?? 0)
- );
- });
- }
} else {
- effects[line.id].productionHours.push((quantity) => {
+ effects[line.id].laborCost.push((quantity) => {
return (
hoursPerProductionStandard *
quantity *
- extendedQuantityPerAssembly
+ extendedQuantityPerAssembly *
+ (operation.laborRate ?? 0)
+ );
+ });
+ effects[line.id].overheadCost.push((quantity) => {
+ return (
+ hoursPerProductionStandard *
+ quantity *
+ extendedQuantityPerAssembly *
+ (operation.overheadRate ?? 0)
);
});
- if (operation.quotingRate) {
- effects[line.id].overheadCost.push((quantity) => {
- return (
- hoursPerProductionStandard *
- quantity *
- extendedQuantityPerAssembly *
- (operation.quotingRate ?? 0)
- );
- });
- } else {
- effects[line.id].laborCost.push((quantity) => {
- return (
- hoursPerProductionStandard *
- quantity *
- extendedQuantityPerAssembly *
- (operation.laborRate ?? 0)
- );
- });
- effects[line.id].overheadCost.push((quantity) => {
- return (
- hoursPerProductionStandard *
- quantity *
- extendedQuantityPerAssembly *
- (operation.overheadRate ?? 0)
- );
- });
- }
}
}
- });
- return effects;
- }, {});
+ }
+ });
+ return effects;
+ }, {});
+
+ return {
+ client: store.client,
+ quoteId: store.quote?.id ?? "",
+ effects: linePriceEffects,
+ };
+});
- console.log("linePriceEffects", linePriceEffects);
- for await (const lineQuantity of quoteLineQuantities.data) {
- const quantity = lineQuantity.quantity ?? 0;
- const effects = linePriceEffects[lineQuantity.quoteLineId];
+const $quotationLinePriceEffectsUpdate = computed(
+ $quotationLinePriceEffects,
+ (store) =>
+ task(async () => {
+ if (!store.quoteId || !store.client) return defaultLinePriceEffectsResult;
- const materialCost = effects?.materialCost.reduce(
- (acc, effect) => acc + effect(quantity),
- 0
- );
+ const quoteLineQuantities = await store.client
+ .from("quoteLineQuantity")
+ .select("*")
+ .eq("quoteId", store.quoteId);
- const laborCost = effects?.laborCost.reduce(
- (acc, effect) => acc + effect(quantity),
- 0
- );
+ if (quoteLineQuantities.error) {
+ logger.error(quoteLineQuantities.error);
+ return defaultLinePriceEffectsResult;
+ }
- const overheadCost = effects?.overheadCost.reduce(
- (acc, effect) => acc + effect(quantity),
- 0
- );
+ if (!quoteLineQuantities.data || !quoteLineQuantities.data.length) {
+ return defaultLinePriceEffectsResult;
+ }
- const setupHours = effects?.setupHours.reduce(
- (acc, effect) => acc + effect(quantity),
- 0
- );
+ for await (const lineQuantity of quoteLineQuantities.data) {
+ const quantity = lineQuantity.quantity ?? 0;
+ const effects = store.effects[lineQuantity.quoteLineId];
- const productionHours = effects?.productionHours.reduce(
- (acc, effect) => acc + effect(quantity),
- 0
- );
+ const update = getLinePriceUpdate(quantity, effects);
- const update = await store.client
- .from("quoteLineQuantity")
- .update({
- materialCost,
- laborCost,
- overheadCost,
- setupHours,
- productionHours,
- })
- .eq("id", lineQuantity.id);
-
- if (update.error) {
- logger.error(update.error);
- }
- }
+ const { error } = await store.client
+ .from("quoteLineQuantity")
+ .update(update)
+ .eq("id", lineQuantity.id);
- return linePriceEffects;
- })
+ if (error) {
+ logger.error(error);
+ }
+ }
+ })
);
+export function getLinePriceUpdate(
+ quantity: number,
+ effects: LinePriceEffects
+) {
+ const materialCost = effects?.materialCost.reduce(
+ (acc, effect) => acc + effect(quantity),
+ 0
+ );
+
+ const laborCost = effects?.laborCost.reduce(
+ (acc, effect) => acc + effect(quantity),
+ 0
+ );
+
+ const overheadCost = effects?.overheadCost.reduce(
+ (acc, effect) => acc + effect(quantity),
+ 0
+ );
+
+ const setupHours = effects?.setupHours.reduce(
+ (acc, effect) => acc + effect(quantity),
+ 0
+ );
+
+ const productionHours = effects?.productionHours.reduce(
+ (acc, effect) => acc + effect(quantity),
+ 0
+ );
+
+ return {
+ materialCost,
+ laborCost,
+ overheadCost,
+ setupHours,
+ productionHours,
+ };
+}
+
export const useQuotation = () => useNanoStore<QuoteStore>($quotationStore);
export const useQuotationLinePriceEffects = () =>
useValue($quotationLinePriceEffects);
+export const useQuotationLinePriceEffectsUpdate = () =>
+ useValue($quotationLinePriceEffectsUpdate);
diff --git a/apps/carbon/app/routes/x+/quote+/$id.tsx b/apps/carbon/app/routes/x+/quote+/$id.tsx
index fe90a41993..cd5019ee63 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.tsx
@@ -34,7 +34,7 @@ import {
getQuoteMaterials,
getQuoteOperations,
useQuotation,
- useQuotationLinePriceEffects,
+ useQuotationLinePriceEffectsUpdate,
} from "~/modules/sales";
import { requirePermissions } from "~/services/auth";
@@ -113,7 +113,7 @@ export default function QuotationRoute() {
} = useLoaderData<typeof loader>();
const [quote, setQuote] = useQuotation();
- useQuotationLinePriceEffects();
+ useQuotationLinePriceEffectsUpdate();
useEffect(() => {
setQuote({