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: quote parts that aren't made

Brad Barbincc6658befd81
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 3d790a9cc4..604c988368 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -966,6 +966,25 @@ export async function insertShelf(
.single();
}
+export async function updateItemCost(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ cost: {
+ unitCost: number;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("itemCost")
+ .update({
+ ...cost,
+ costIsAdjusted: true,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("itemId", itemId)
+ .single();
+}
+
export async function updateMaterialOrder(
client: SupabaseClient<Database>,
updates: {
diff --git a/apps/carbon/app/modules/items/ui/Consumables/useConsumableNavigation.tsx b/apps/carbon/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
index 112ed4cda5..5de95075a9 100644
--- a/apps/carbon/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Consumables/useConsumableNavigation.tsx
@@ -31,7 +31,7 @@ export function useConsumableNavigation() {
shortcut: "Command+Shift+p",
},
{
- name: "Accounting",
+ name: "Costing",
to: path.to.consumableCosting(itemId),
role: ["employee"],
icon: LuTags,
diff --git a/apps/carbon/app/modules/items/ui/Fixtures/useFixtureNavigation.tsx b/apps/carbon/app/modules/items/ui/Fixtures/useFixtureNavigation.tsx
index ebd960f1f2..f180851c8e 100644
--- a/apps/carbon/app/modules/items/ui/Fixtures/useFixtureNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Fixtures/useFixtureNavigation.tsx
@@ -44,7 +44,7 @@ export function useFixtureNavigation() {
shortcut: "Command+Shift+m",
},
{
- name: "Accounting",
+ name: "Costing",
to: path.to.fixtureCosting(itemId),
role: ["employee"],
icon: LuTags,
diff --git a/apps/carbon/app/modules/items/ui/Materials/useMaterialNavigation.tsx b/apps/carbon/app/modules/items/ui/Materials/useMaterialNavigation.tsx
index 445e629222..1cc03f27c1 100644
--- a/apps/carbon/app/modules/items/ui/Materials/useMaterialNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Materials/useMaterialNavigation.tsx
@@ -31,7 +31,7 @@ export function useMaterialNavigation() {
shortcut: "Command+Shift+p",
},
{
- name: "Accounting",
+ name: "Costing",
to: path.to.materialCosting(itemId),
role: ["employee"],
icon: LuTags,
diff --git a/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx b/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
index 558591b5e7..c63045dbc1 100644
--- a/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
@@ -58,7 +58,7 @@ export function usePartNavigation() {
shortcut: "Command+Shift+i",
},
{
- name: "Accounting",
+ name: "Costing",
to: path.to.partCosting(itemId),
role: ["employee"],
icon: LuTags,
diff --git a/apps/carbon/app/modules/items/ui/Tools/useToolNavigation.tsx b/apps/carbon/app/modules/items/ui/Tools/useToolNavigation.tsx
index e3286d8759..5ceb35b783 100644
--- a/apps/carbon/app/modules/items/ui/Tools/useToolNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Tools/useToolNavigation.tsx
@@ -31,7 +31,7 @@ export function useToolNavigation() {
shortcut: "Command+Shift+p",
},
{
- name: "Accounting",
+ name: "Costing",
to: path.to.toolCosting(itemId),
role: ["employee"],
icon: LuTags,
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index ed46e4fc58..bcf8b228fd 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -1,4 +1,3 @@
-import type { Json } from "@carbon/database";
import {
Button,
Card,
@@ -20,6 +19,7 @@ import {
Td,
Th,
Thead,
+ toast,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -41,21 +41,27 @@ import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
import { quoteLineAdditionalChargesValidator } from "../../sales.models";
-import type { Costs, Quotation, QuotationPrice } from "../../types";
+import type {
+ Costs,
+ Quotation,
+ QuotationLine,
+ QuotationPrice,
+} from "../../types";
const QuoteLinePricing = ({
- quantities,
- additionalCharges: additionalChargesJson,
+ line,
pricesByQuantity,
getLineCosts,
}: {
- quantities: number[];
- additionalCharges?: Json;
+ line: QuotationLine;
pricesByQuantity: Record<number, QuotationPrice>;
getLineCosts: (quantity: number) => Costs;
}) => {
const permissions = usePermissions();
+ const isMade = line.methodType === "Make";
+ const quantities = line.quantity ?? [1];
+
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
@@ -73,7 +79,24 @@ const QuoteLinePricing = ({
["Draft"].includes(routeData?.quote?.status ?? "");
const { supabase } = useSupabase();
- const fetcher = useFetcher<{ id: string }>();
+ const fetcher = useFetcher<{ id?: string; error: string | null }>();
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error);
+ }
+ }, [fetcher.data]);
+
+ const optimisticUnitCost = useMemo<number>(() => {
+ if (!line.itemId) return line.unitCost ?? 0;
+ if (fetcher.formAction === path.to.itemCostUpdate(line.itemId)) {
+ const submitted = fetcher.formData?.get("unitCost");
+ if (submitted) {
+ return Number(submitted);
+ }
+ }
+ return line.unitCost ?? 0;
+ }, [line.itemId, line.unitCost, fetcher.formAction, fetcher.formData]);
+
const { id: userId } = useUser();
const { locale } = useLocale();
@@ -91,16 +114,10 @@ const QuoteLinePricing = ({
) as z.infer<typeof quoteLineAdditionalChargesValidator>;
}
const parsedAdditionalCharges =
- quoteLineAdditionalChargesValidator.safeParse(additionalChargesJson);
+ quoteLineAdditionalChargesValidator.safeParse(line.additionalCharges);
return parsedAdditionalCharges.success ? parsedAdditionalCharges.data : {};
- }, [
- additionalChargesJson,
- fetcher.formAction,
- fetcher.formData,
- lineId,
- quoteId,
- ]);
+ }, [line, fetcher.formAction, fetcher.formData, lineId, quoteId]);
const additionalChargesByQuantity = quantities.map((quantity) => {
const charges = Object.values(additionalCharges).reduce((acc, charge) => {
@@ -188,6 +205,16 @@ const QuoteLinePricing = ({
});
};
+ const onUpdateCost = async (value: number) => {
+ if (!line.itemId) return;
+ const formData = new FormData();
+ formData.append("unitCost", value.toString());
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.itemCostUpdate(line.itemId),
+ });
+ };
+
const onUpdatePrice = async (
key: "leadTime" | "unitPrice" | "discountPercent",
quantity: number,
@@ -309,7 +336,6 @@ const QuoteLinePricing = ({
>
<NumberField
value={leadTime}
- isReadOnly={!isEditable}
formatOptions={{
style: "unit",
unit: "day",
@@ -324,7 +350,7 @@ const QuoteLinePricing = ({
>
<NumberInput
className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
- isReadOnly={!isEditable}
+ isDisabled={!isEditable}
size="sm"
min={0}
/>
@@ -333,19 +359,43 @@ const QuoteLinePricing = ({
);
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
+ <Tr className={cn(isMade && "[&>td]:bg-muted/60")}>
<Td className="border-r border-border group-hover:bg-muted/50">
<HStack className="w-full justify-between ">
<span>Unit Cost</span>
</HStack>
</Td>
+
{unitCostsByQuantity.map((cost, index) => {
- return (
+ return isMade ? (
<Td key={index} className="group-hover:bg-muted/50">
<VStack spacing={0}>
- <span>{formatter.format(cost ?? 0)}</span>
+ <span>{formatter.format(optimisticUnitCost)}</span>
</VStack>
</Td>
+ ) : (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <NumberField
+ value={cost}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ minValue={0}
+ onChange={(value) => {
+ if (Number.isFinite(value) && value !== cost) {
+ onUpdateCost(value);
+ }
+ }}
+ >
+ <NumberInput
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!isEditable}
+ size="sm"
+ min={0}
+ />
+ </NumberField>
+ </Td>
);
})}
</Tr>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
index 3deed7edb0..2e4b1b8998 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
@@ -26,9 +26,11 @@ type EnhancedTree = Tree<QuoteMethod & { operations?: QuotationOperation[] }>;
export function useLineCosts({
methodTree: originalMethodTree,
operations,
+ unitCost = 0,
}: {
methodTree?: Tree<QuoteMethod>;
operations: QuotationOperation[];
+ unitCost?: number;
}): (quantity: number) => Costs {
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
@@ -37,12 +39,13 @@ export function useLineCosts({
// TODO: instead of walking the tree twice (once for the quantities/operations and once for the effects)
// we could do it all in one pass
- const methodTree = useMemo<EnhancedTree>(() => {
+ const methodTree = useMemo<EnhancedTree | undefined>(() => {
if (!originalMethodTree || !originalMethodTree.id) {
- return {} as Tree<QuoteMethod>;
+ return undefined;
}
const tree = structuredClone(originalMethodTree);
+
function walkTree(tree: EnhancedTree, parentQuantity: number) {
// multiply quantity by parent quantity
tree.data.quantity = tree.data.quantity * parentQuantity;
@@ -205,10 +208,14 @@ export function useLineCosts({
}
}
- walkTree(methodTree);
+ if (methodTree) {
+ walkTree(methodTree);
+ } else {
+ effects.materialCost.push((quantity) => unitCost * quantity);
+ }
return effects;
- }, [methodTree]);
+ }, [methodTree, unitCost]);
const getCosts = useCallback(
(quantity: number) => {
diff --git a/apps/carbon/app/routes/x+/items+/cost.$itemId.tsx b/apps/carbon/app/routes/x+/items+/cost.$itemId.tsx
new file mode 100644
index 0000000000..457c2ae964
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/cost.$itemId.tsx
@@ -0,0 +1,33 @@
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import logger from "~/lib/logger";
+import { updateItemCost } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { assertIsPost } from "~/utils/http";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const formData = await request.formData();
+ const unitCost = parseInt(formData.get("unitCost") as string);
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const deletion = await updateItemCost(client, itemId, {
+ unitCost,
+ updatedBy: userId,
+ });
+ if (deletion.error) {
+ logger.error("Failed to update item cost", deletion.error);
+ return json({
+ error: "Failed to update item cost",
+ });
+ }
+
+ return json({
+ error: null,
+ });
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index d45b5e2834..0f964c2906 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -128,6 +128,7 @@ export default function QuoteLine() {
const getLineCosts = useLineCosts({
methodTree,
operations,
+ unitCost: line.unitCost ?? 0,
});
const initialValues = {
@@ -177,8 +178,7 @@ export default function QuoteLine() {
/>
)}
<QuoteLinePricing
- quantities={line.quantity ?? [1]}
- additionalCharges={line.additionalCharges ?? {}}
+ line={line}
pricesByQuantity={pricesByQuantity}
getLineCosts={getLineCosts}
/>
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.delete.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.delete.tsx
index faf1a394e3..94d465da50 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.delete.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.delete.tsx
@@ -22,10 +22,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (quoteDelete.error) {
return json(
path.to.quotes,
- await flash(
- request,
- error(quoteDelete.error, "Failed to delete quote line")
- )
+ await flash(request, error(quoteDelete.error, "Failed to delete quote"))
);
}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
index 23e27109b5..a01dcbb1dd 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.status.tsx
@@ -4,7 +4,7 @@ import { quoteStatusType, updateQuoteStatus } from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
import { error, success } from "~/utils/result";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -34,13 +34,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (update.error) {
throw redirect(
- path.to.quote(id),
+ requestReferrer(request) ?? path.to.quote(id),
await flash(request, error(update.error, "Failed to update RFQ status"))
);
}
throw redirect(
- path.to.quote(id),
+ requestReferrer(request) ?? path.to.quote(id),
await flash(request, success("Updated RFQ status"))
);
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx
index 708019228b..b61a45354a 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx
@@ -17,17 +17,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { rfqId } = params;
if (!rfqId) throw new Error("Could not find rfqId");
- const quoteDelete = await deleteSalesRFQ(client, rfqId);
+ const salesRfqDelete = await deleteSalesRFQ(client, rfqId);
- if (quoteDelete.error) {
+ if (salesRfqDelete.error) {
return json(
- path.to.quotes,
- await flash(
- request,
- error(quoteDelete.error, "Failed to delete quote line")
- )
+ path.to.salesRfqs,
+ await flash(request, error(salesRfqDelete.error, "Failed to delete RFQ"))
);
}
- throw redirect(path.to.quotes);
+ throw redirect(path.to.salesRfqs);
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index d1dc8dd019..d5f55d8b1b 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -248,7 +248,7 @@ export const path = {
generatePath(`${x}/sales-order/delete/${id}`),
deleteSalesOrderLine: (orderId: string, lineId: string) =>
generatePath(`${x}/sales-order/${orderId}/lines/delete/${lineId}`),
- deleteSalesRfq: (id: string) => generatePath(`${x}/sales-rfq/delete/${id}`),
+ deleteSalesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}/delete`),
deleteSalesRfqLine: (id: string, lineId: string) =>
generatePath(`${x}/sales-rfq/${id}/${lineId}/delete`),
deleteShift: (id: string) =>
@@ -338,6 +338,7 @@ export const path = {
inventory: `${x}/inventory`,
invoicing: `${x}/invoicing`,
items: `${x}/items`,
+ itemCostUpdate: (id: string) => generatePath(`${x}/items/cost/${id}`),
itemPostingGroup: (id: string) => generatePath(`${x}/items/groups/${id}`),
itemPostingGroups: `${x}/items/groups`,
jobs: `${x}/jobs`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5d926d1515..49bc370530 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -23111,6 +23111,7 @@ export type Database = {
quoteRevisionId: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
thumbnailPath: string | null
+ unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index feeac76f50..6ee6c98920 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -68,6 +68,7 @@ serve(async (req: Request) => {
itemId?: string;
methodType?: "Buy" | "Make" | "Pick";
}[] = [];
+
await db.transaction().execute(async (trx) => {
const quoteId = await getNextSequence(trx, "quote", companyId);
const quote = await trx
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5d926d1515..49bc370530 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -23111,6 +23111,7 @@ export type Database = {
quoteRevisionId: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
thumbnailPath: string | null
+ unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
diff --git a/packages/database/supabase/migrations/20240816102540_quote-line-cost.sql b/packages/database/supabase/migrations/20240816102540_quote-line-cost.sql
new file mode 100644
index 0000000000..ec3681af5c
--- /dev/null
+++ b/packages/database/supabase/migrations/20240816102540_quote-line-cost.sql
@@ -0,0 +1,17 @@
+DROP VIEW "quoteLines";
+CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."thumbnailPath", imu."thumbnailPath") as "thumbnailPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost"
+ FROM "quoteLine" ql
+ LEFT JOIN "modelUpload" mu ON ql."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+);
\ No newline at end of file