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
- email changes
Gaurav Bhattfafab04d2118
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsxnew file mode 100644index 0000000000..585e5b4ec4--- /dev/null+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx@@ -0,0 +1,109 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack,+} from "@carbon/react";+import type { FetcherWithComponents } from "@remix-run/react";+import { useState } from "react";+import { SelectControlled, SupplierContact } from "~/components/Form";+import { useIntegrations } from "~/hooks/useIntegrations";+import { supplierQuoteFinalizeValidator } from "../../purchasing.models";+import type { SupplierQuote } from "../../types";++type SupplierQuoteFinalizeModalProps = {+ onClose: () => void;+ quote?: SupplierQuote;+ fetcher: FetcherWithComponents<{}>;+ action: string;+};++const SupplierQuoteFinalizeModal = ({+ quote,+ onClose,+ fetcher,+ action,+}: SupplierQuoteFinalizeModalProps) => {+ const integrations = useIntegrations();+ const canEmail = integrations.has("resend");++ const [notificationType, setNotificationType] = useState(+ canEmail ? "Email" : "None"+ );++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <ModalContent>+ <ValidatedForm+ method="post"+ validator={supplierQuoteFinalizeValidator}+ action={action}+ onSubmit={onClose}+ defaultValues={{+ notification: notificationType as "Email" | "None",+ supplierContact: quote?.supplierContactId ?? undefined,+ }}+ fetcher={fetcher}+ >+ <ModalHeader>+ <ModalTitle>Send {quote?.supplierQuoteId}</ModalTitle>+ <ModalDescription>+ Send the supplier quote to the supplier via email.+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ {canEmail && (+ <SelectControlled+ label="Send Via"+ name="notification"+ options={[+ {+ label: "None",+ value: "None",+ },+ {+ label: "Email",+ value: "Email",+ },+ ]}+ value={notificationType}+ onChange={(t) => {+ if (t) setNotificationType(t.value);+ }}+ />+ )}+ {notificationType === "Email" && (+ <SupplierContact+ name="supplierContact"+ supplier={quote?.supplierId ?? undefined}+ />+ )}+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={onClose}>+ Cancel+ </Button>+ <Button type="submit">Send</Button>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ );+};++export default SupplierQuoteFinalizeModal;diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsxindex 6be3c1b62a..3b45fee6f8 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx@@ -88,44 +88,18 @@ const SupplierQuoteHeader = () => {const finalizeFetcher = useFetcher<{}>();const sendFetcher = useFetcher<{}>();const statusFetcher = useFetcher<{}>();- const canShare =- routeData?.quote.externalLinkId &&- ["Draft", "Active"].includes(routeData?.quote?.status ?? "");const hasLines = routeData?.lines && routeData.lines.length > 0;+ const quoteStatus = routeData?.quote?.status ?? "";+ const editableStatuses = ["Draft", "Active", "Declined"];+ const isEditableStatus = editableStatuses.includes(quoteStatus);- // Validation logic for missing prices and leadtimes- const lines = routeData?.lines ?? [];- const prices = routeData?.prices ?? [];+ const canShare = routeData?.quote.externalLinkId && isEditableStatus;- const linesMissingQuoteLinePrices = lines- .filter((line) => {- if (!line.quantity || !Array.isArray(line.quantity)) return false;- return line.quantity.some(- (qty) =>- !prices.some(- (price) =>- price.supplierQuoteLineId === line.id && price.quantity === qty- )- );- })- .map((line) => line.itemReadableId)- .filter((id): id is string => id !== undefined);-- const linesWithZeroPriceOrLeadTime = prices- .filter((price) => price.supplierUnitPrice === 0 || price.leadTime === 0)- .map((price) => {- const line = lines.find((line) => line.id === price.supplierQuoteLineId);- return line?.itemReadableId;- })- .filter((id): id is string => id !== undefined);+ const canSend =+ isEditableStatus && permissions.can("update", "purchasing") && hasLines;- const warningLineReadableIds = [- ...new Set([- ...linesMissingQuoteLinePrices,- ...linesWithZeroPriceOrLeadTime,- ]),- ];+ const canFinalize = ["Draft", "Declined"].includes(quoteStatus);return (<>@@ -212,7 +186,7 @@ const SupplierQuoteHeader = () => {</DropdownMenu>)}- {routeData?.quote?.status === "Draft" && (+ {canSend && (<ButtononClick={sendModal.onOpen}isLoading={sendFetcher.state !== "idle"}@@ -228,7 +202,7 @@ const SupplierQuoteHeader = () => {</Button>)}- {routeData?.quote?.status === "Draft" && (+ {canFinalize && (<ButtononClick={finalizeModal.onOpen}isLoading={finalizeFetcher.state !== "idle"}@@ -337,9 +311,10 @@ const SupplierQuoteHeader = () => {{finalizeModal.isOpen && (<SupplierQuoteFinalizeModalquote={routeData?.quote}+ lines={routeData?.lines ?? []}+ prices={routeData?.prices ?? []}onClose={finalizeModal.onClose}fetcher={finalizeFetcher}- warningLineReadableIds={warningLineReadableIds}/>)}{sendModal.isOpen && (@@ -349,14 +324,6 @@ const SupplierQuoteHeader = () => {fetcher={sendFetcher}/>)}- {finalizeModal.isOpen && (- <SupplierQuoteFinalizeModal- quote={routeData?.quote}- onClose={finalizeModal.onClose}- fetcher={sendFetcher}- warningLineReadableIds={warningLineReadableIds}- />- )}<ShareQuoteModalid={id}externalLinkId={(routeData?.quote as any)?.externalLinkId}@@ -369,18 +336,45 @@ const SupplierQuoteHeader = () => {function SupplierQuoteFinalizeModal({quote,+ lines,+ prices,onClose,fetcher,- warningLineReadableIds,}: {quote?: SupplierQuote;+ lines: SupplierQuoteLine[];+ prices: SupplierQuoteLinePrice[];onClose: () => void;fetcher: FetcherWithComponents<{}>;- warningLineReadableIds: string[];}) {const { id } = useParams();if (!id) throw new Error("id not found");+ // Validation logic: A line is valid if at least ONE quantity has both price and lead time+ // (not all quantities need them)+ const warningLineReadableIds = lines+ .filter((line) => {+ if (!line.id) return true; // Missing line ID is an error++ const linePrices = prices.filter(+ (price) => price.supplierQuoteLineId === line.id+ );++ // Check if at least one quantity has both valid price and lead time+ const hasValidPriceAndLeadTime = linePrices.some(+ (price) =>+ price.supplierUnitPrice !== null &&+ price.supplierUnitPrice !== 0 &&+ price.leadTime !== null &&+ price.leadTime !== 0+ );++ // If no valid price/lead time found, this line has a warning+ return !hasValidPriceAndLeadTime;+ })+ .map((line) => line.itemReadableId)+ .filter((id): id is string => id !== undefined);+const hasErrors = warningLineReadableIds.length > 0;return (diff --git a/apps/erp/app/routes/share+/supplier-quote.$id.tsx b/apps/erp/app/routes/share+/supplier-quote.$id.tsxindex 89d1fe69f6..f4eccd0ebf 100644--- a/apps/erp/app/routes/share+/supplier-quote.$id.tsx+++ b/apps/erp/app/routes/share+/supplier-quote.$id.tsx@@ -345,13 +345,9 @@ const LinePricing = ({? pricingOptions.map((opt) => opt.quantity): [1]; // Default to showing at least one row with quantity 1- const isDisabled = [- "Ordered",- "Partial",- "Expired",- "Cancelled",- "Declined",- ].includes(quoteStatus || "");+ const isDisabled = ["Expired", "Cancelled", "Declined"].includes(+ quoteStatus || ""+ );const formatter = new Intl.NumberFormat(locale, {style: "currency",@@ -553,95 +549,106 @@ const LinePricing = ({</label></Td><Td className=" bg-muted/30">{qty}</Td>- <Td className="">- <NumberField- value={unitPrice}- formatOptions={{- style: "currency",- currency: currencyCode,- }}- isDisabled={isDisabled || !isSelected}- minValue={0}- onChange={(value) => {- if (Number.isFinite(value) && value !== unitPrice) {- updatePricing(qty, "supplierUnitPrice", value);- }- }}- >- <NumberInput- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"- size="sm"- min={0}- />- </NumberField>- </Td>- <Td className="w-[150px]">- <NumberField- value={leadTime}- formatOptions={{- style: "unit",- unit: "day",- unitDisplay: "long",- }}- minValue={0}- isDisabled={isDisabled || !isSelected}- onChange={(value) => {- if (Number.isFinite(value) && value !== leadTime) {- updatePricing(qty, "leadTime", value);- }- }}- >- <NumberInput- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"- size="sm"- min={0}- />- </NumberField>- </Td>- <Td className="w-[150px]">- <NumberField- value={shippingCost}- formatOptions={{- style: "currency",- currency: currencyCode,- }}- isDisabled={isDisabled || !isSelected}- minValue={0}- onChange={(value) => {- if (Number.isFinite(value) && value !== shippingCost) {- updatePricing(qty, "supplierShippingCost", value);- }- }}- >- <NumberInput- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"- size="sm"- min={0}- />- </NumberField>- </Td>- <Td className="w-[120px]">- <NumberField- value={taxAmount}- formatOptions={{- style: "currency",- currency: currencyCode,- }}- isDisabled={isDisabled || !isSelected}- minValue={0}- onChange={(value) => {- if (Number.isFinite(value) && value !== taxAmount) {- updatePricing(qty, "supplierTaxAmount", value);- }- }}- >- <NumberInput- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"- size="sm"- min={0}- />- </NumberField>- </Td>+ {isSelected ? (+ <>+ <Td className="">+ <NumberField+ value={unitPrice}+ formatOptions={{+ style: "currency",+ currency: currencyCode,+ }}+ isDisabled={isDisabled || !isSelected}+ minValue={0}+ onChange={(value) => {+ if (Number.isFinite(value) && value !== unitPrice) {+ updatePricing(qty, "supplierUnitPrice", value);+ }+ }}+ >+ <NumberInput+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"+ size="sm"+ min={0}+ />+ </NumberField>+ </Td>+ <Td className="w-[150px]">+ <NumberField+ value={leadTime}+ formatOptions={{+ style: "unit",+ unit: "day",+ unitDisplay: "long",+ }}+ minValue={0}+ isDisabled={isDisabled || !isSelected}+ onChange={(value) => {+ if (Number.isFinite(value) && value !== leadTime) {+ updatePricing(qty, "leadTime", value);+ }+ }}+ >+ <NumberInput+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"+ size="sm"+ min={0}+ />+ </NumberField>+ </Td>+ <Td className="w-[150px]">+ <NumberField+ value={shippingCost}+ formatOptions={{+ style: "currency",+ currency: currencyCode,+ }}+ isDisabled={isDisabled || !isSelected}+ minValue={0}+ onChange={(value) => {+ if (+ Number.isFinite(value) &&+ value !== shippingCost+ ) {+ updatePricing(qty, "supplierShippingCost", value);+ }+ }}+ >+ <NumberInput+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"+ size="sm"+ min={0}+ />+ </NumberField>+ </Td>+ <Td className="w-[120px]">+ <NumberField+ value={taxAmount}+ formatOptions={{+ style: "currency",+ currency: currencyCode,+ }}+ isDisabled={isDisabled || !isSelected}+ minValue={0}+ onChange={(value) => {+ if (Number.isFinite(value) && value !== taxAmount) {+ updatePricing(qty, "supplierTaxAmount", value);+ }+ }}+ >+ <NumberInput+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"+ size="sm"+ min={0}+ />+ </NumberField>+ </Td>+ </>+ ) : (+ <Td colSpan={4} className="text-muted-foreground">+ Select to provide pricing+ </Td>+ )}<Td className="w-[150px] bg-muted/30">{isSelected && total > 0 ? formatter.format(total) : "—"}</Td>diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsxindex a7ea50baf9..bb4d134855 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx@@ -1,21 +1,14 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { validationError, validator } from "@carbon/form";-import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";-import { tasks } from "@trigger.dev/sdk";import { redirect, type ActionFunctionArgs } from "@vercel/remix";import {finalizeSupplierQuote,- getSupplierContact,getSupplierQuote,getSupplierQuoteLines,getSupplierQuoteLinePricesByQuoteId,- supplierQuoteFinalizeValidator,} from "~/modules/purchasing";-import { getCompany, getCompanySettings } from "~/modules/settings";import { upsertExternalLink } from "~/modules/shared";-import { getUser } from "~/modules/users/users.server";import { path } from "~/utils/path";export async function action(args: ActionFunctionArgs) {@@ -56,6 +49,7 @@ export async function action(args: ActionFunctionArgs) {.from("supplierQuote").update({externalLinkId: externalLink.data.id,+ status: "Active",}).eq("id", id);}@@ -87,18 +81,24 @@ export async function action(args: ActionFunctionArgs) {}// Check that each line has at least one quantity with price and lead time+ // (not all quantities need them, just at least one per line)const lines = quoteLines.data ?? [];const prices = quoteLinePrices.data ?? [];for (const line of lines) {if (!line.id) continue;const linePrices = prices.filter((p) => p.supplierQuoteLineId === line.id);- const quantities =- Array.isArray(line.quantity) && line.quantity.length > 0- ? line.quantity- : linePrices.map((p) => p.quantity);- if (quantities.length === 0) {+ // Check if at least one quantity has both valid price and lead time+ const hasValidPriceAndLeadTime = linePrices.some(+ (price) =>+ price.supplierUnitPrice !== null &&+ price.supplierUnitPrice !== 0 &&+ price.leadTime !== null &&+ price.leadTime !== 0+ );++ if (!hasValidPriceAndLeadTime) {throw redirect(path.to.supplierQuote(id),await flash(@@ -110,30 +110,6 @@ export async function action(args: ActionFunctionArgs) {));}-- for (const qty of quantities) {- const price = linePrices.find(- (p) => p.supplierQuoteLineId === line.id && p.quantity === qty- );- if (- !price ||- price.supplierUnitPrice === 0 ||- price.leadTime === 0 ||- price.supplierUnitPrice === null ||- price.leadTime === null- ) {- throw redirect(- path.to.supplierQuote(id),- await flash(- request,- error(- null,- `Line ${line.itemReadableId} quantity ${qty} must have price and lead time`- )- )- );- }- }}// TODO: Add PDF generation for supplier quotes when available@@ -157,75 +133,6 @@ export async function action(args: ActionFunctionArgs) {);}- const validation = await validator(supplierQuoteFinalizeValidator).validate(- await request.formData()- );-- if (validation.error) {- return validationError(validation.error);- }-- const { notification, supplierContact: supplierContactId } = validation.data;-- switch (notification) {- case "Email":- try {- if (!supplierContactId) throw new Error("Supplier contact is required");-- const [company, companySettings, supplierContact, supplierQuote, user] =- await Promise.all([- getCompany(client, companyId),- getCompanySettings(client, companyId),- getSupplierContact(client, supplierContactId),- getSupplierQuote(client, id),- getUser(client, userId),- ]);-- if (!company.data) throw new Error("Failed to get company");- if (!companySettings.data)- throw new Error("Failed to get company settings");- if (!supplierContact?.data?.contact)- throw new Error("Failed to get supplier contact");- if (!supplierQuote.data)- throw new Error("Failed to get supplier quote");- if (!user.data) throw new Error("Failed to get user");-- // For now, we'll send a simple email without PDF attachment- // TODO: Add PDF generation for supplier quotes when available- const requestUrl = new URL(request.url);- const baseUrl = `${requestUrl.protocol}//${requestUrl.host}`;- const externalQuoteUrl = `${baseUrl}${path.to.externalSupplierQuote(- externalLink.data?.id ?? ""- )}`;-- const emailSubject = `Supplier Quote ${supplierQuote.data.supplierQuoteId} from ${company.data.name}`;- const emailBody = `This link is for supplier quote ${supplierQuote.data.supplierQuoteId}. Please go to the link below to fill out the supplier code.`;-- const emailBodyHtml = `This link is for supplier quote ${supplierQuote.data.supplierQuoteId}. Please go to the link below to fill out the supplier code.<br><br><a href="${externalQuoteUrl}">${externalQuoteUrl}</a>`;-- await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {- to: [user.data.email, supplierContact.data.contact.email],- from: user.data.email,- subject: emailSubject,- html: emailBodyHtml,- text: `${emailBody}\n\n${externalQuoteUrl}`,- companyId,- });- } catch (err) {- throw redirect(- path.to.supplierQuote(id),- await flash(request, error(err, "Failed to send email"))- );- }-- break;- case undefined:- case "None":- break;- default:- throw new Error("Invalid notification type");- }-throw redirect(path.to.supplierQuote(id),await flash(request, success("Supplier quote finalized successfully"))diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsxindex d41c896ac7..bc63495f8b 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx@@ -114,16 +114,17 @@ export async function action(args: ActionFunctionArgs) {)}`;const emailSubject = `Supplier Quote ${supplierQuote.data.supplierQuoteId} from ${company.data.name}`;- const emailBody = `This link is for supplier quote ${supplierQuote.data.supplierQuoteId}. Please go to the link below to fill out the supplier code.`;- const emailBodyHtml = `This link is for supplier quote ${supplierQuote.data.supplierQuoteId}. Please go to the link below to fill out the supplier code.<br><br><a href="${externalQuoteUrl}">${externalQuoteUrl}</a>`;+ // Hey there,+ // \n\nHere is the link to the supplier quote form. We’d appreciate it if you could provide your quote for the listed items. Please go ahead and fill out the form.+ const emailMessage = `Hey there,\n\nHere is the link to the supplier quote ${supplierQuote.data.supplierQuoteId}. We’d appreciate it if you could provide your quote for the listed items. Please go ahead and fill out the form.`;await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {to: [user.data.email, supplierContact.data.contact.email],from: user.data.email,subject: emailSubject,- html: emailBodyHtml,- text: `${emailBody}\n\n${externalQuoteUrl}`,+ html: `${emailMessage}<br><br><a href="${externalQuoteUrl}">${externalQuoteUrl}</a>`,+ text: `${emailMessage}\n\n${externalQuoteUrl}`,companyId,});} catch (err) {