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.

wip

neilk17d415f11eae15
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index c2370bc81a..6fa2ce09de 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -16,6 +16,7 @@ import type {
quotationOperationValidator,
quotationValidator,
} from "./sales.models";
+import { getLocalTimeZone, today } from "@internationalized/date";
export async function deleteCustomerContact(
client: SupabaseClient<Database>,
@@ -549,6 +550,21 @@ export async function insertQuoteLineQuantity(
]);
}
+export async function releaseQuote(
+ client: SupabaseClient<Database>,
+ quoteId: string,
+ usedId: string
+) {
+ return client
+ .from("quote")
+ .update({
+ status: "Open",
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: usedId,
+ })
+ .eq("id", quoteId);
+}
+
export async function updateCustomer(
client: SupabaseClient<Database>,
customer: Omit<z.infer<typeof customerValidator>, "id"> & {
diff --git a/apps/carbon/app/routes/x+/quote+/$id.release.tsx b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
new file mode 100644
index 0000000000..12ce9d1f6f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
@@ -0,0 +1,198 @@
+import { QuoteEmail } from "@carbon/documents";
+import { validationError, validator } from "@carbon/remix-validated-form";
+import { renderAsync } from "@react-email/components";
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { triggerClient } from "~/lib/trigger.server";
+// import {
+// getPurchaseOrder,
+// getPurchaseOrderLines,
+// getPurchaseOrderLocations,
+// getSupplierContact,
+// } from "~/modules/purchasing";
+import {
+ getQuote,
+ releaseQuote,
+ quotationReleaseValidator,
+ getCustomer,
+} from "~/modules/sales";
+import { getCompany } from "~/modules/settings";
+// import { getUser } from "~/modules/users/users.server";
+// import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$id[.]pdf";
+import { loader as pdfLoader } from "~/routes/file+/quote+/$quoteId[.]pdf";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action(args: ActionFunctionArgs) {
+ const { request, params } = args;
+ assertIsPost(request);
+
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ role: "employee",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ let file: ArrayBuffer;
+ let bucketName = id;
+ let fileName: string;
+
+ const release = await releaseQuote(client, id, userId);
+ if (release.error) {
+ return redirect(
+ path.to.quote(id),
+ await flash(request, error(release.error, "Failed to release quote"))
+ );
+ }
+
+ const quote = await getQuote(client, id);
+ if (quote.error) {
+ return redirect(
+ path.to.quote(id),
+ await flash(request, error(quote.error, "Failed to get quote"))
+ );
+ }
+
+ try {
+ const pdf = await pdfLoader(args);
+ if (pdf.headers.get("content-type") !== "application/pdf")
+ throw new Error("Failed to generate PDF");
+
+ file = await pdf.arrayBuffer();
+ fileName = `${quote.data.quoteId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`;
+
+ const fileUpload = await client.storage
+ .from("purchasing-external")
+ .upload(`${bucketName}/${fileName}`, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ });
+
+ if (fileUpload.error) {
+ return redirect(
+ path.to.purchaseOrder(id),
+ await flash(request, error(fileUpload.error, "Failed to upload file"))
+ );
+ }
+ } catch (err) {
+ return redirect(
+ path.to.purchaseOrder(id),
+ await flash(request, error(err, "Failed to generate PDF"))
+ );
+ }
+
+ const validation = await validator(quotationReleaseValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { notification, customerContact } = validation.data;
+
+ switch (notification) {
+ case "Email":
+ try {
+ if (!customerContact) throw new Error("Customer contact is required");
+
+ const [
+ company,
+ customer,
+ // supplier,
+ // purchaseOrder,
+ // purchaseOrderLines,
+ // purchaseOrderLocations,
+ // buyer,
+ ] = await Promise.all([
+ getCompany(client),
+ getCustomer(client, quote.data.customerId),
+ // getSupplierContact(client, customerContact),
+ // getPurchaseOrder(client, id),
+ // getPurchaseOrderLines(client, id),
+ // getPurchaseOrderLocations(client, id),
+ // getUser(client, userId),
+ ]);
+
+ // if (!supplier?.data?.contact) throw new Error("Failed to get supplier contact");
+ if (!company.data) throw new Error("Failed to get company");
+ // if (!buyer.data) throw new Error("Failed to get user");
+ // if (!purchaseOrder.data) throw new Error("Failed to get purchase order");
+ // if (!purchaseOrderLocations.data) throw new Error("Failed to get purchase order locations");
+
+ // const emailTemplate = PurchaseOrderEmail({
+ // company: company.data,
+ // purchaseOrder: purchaseOrder.data,
+ // purchaseOrderLines: purchaseOrderLines.data ?? [],
+ // purchaseOrderLocations: purchaseOrderLocations.data,
+ // recipient: {
+ // email: supplier.data.contact.email,
+ // firstName: supplier.data.contact.firstName,
+ // lastName: supplier.data.contact.lastName,
+ // },
+ // sender: {
+ // email: buyer.data.email,
+ // firstName: buyer.data.firstName,
+ // lastName: buyer.data.lastName,
+ // },
+ // });
+
+ // TODO: Update sender email
+ const emailTemplate = QuoteEmail({
+ company: company.data,
+ quote: quote.data,
+ recipient: {
+ email: customerContact,
+ firstName: "Customer",
+ lastName: "",
+ },
+ sender: {
+ email: "[email protected]",
+ firstName: "Neil",
+ lastName: "Kanakia",
+ },
+ });
+
+ await triggerClient.sendEvent({
+ name: "resend.email",
+ payload: {
+ to: [customer.data.contact.email],
+ // TODO: Update from email
+ subject: `${quote.data.quoteId} from ${company.data.name}`,
+ html: await renderAsync(emailTemplate),
+ text: await renderAsync(emailTemplate, { plainText: true }),
+ attachments: [
+ {
+ content: Buffer.from(file),
+ filename: fileName,
+ },
+ ],
+ },
+ });
+ } catch (err) {
+ return redirect(
+ path.to.purchaseOrder(id),
+ await flash(request, error(err, "Failed to send email"))
+ );
+ }
+
+ break;
+ case undefined:
+ case "None":
+ break;
+ default:
+ throw new Error("Invalid notification type");
+ }
+
+ return redirect(
+ path.to.purchaseOrderExternalDocuments(id),
+ await flash(request, success("Purchase order released"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$id.tsx b/apps/carbon/app/routes/x+/quote+/$id.tsx
index 476c4b79af..1f90620f75 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.tsx
@@ -10,6 +10,7 @@ import {
TooltipContent,
TooltipTrigger,
VStack,
+ useDisclosure,
useKeyboardShortcuts,
} from "@carbon/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
@@ -39,6 +40,7 @@ import {
useQuotation,
useQuotationLinePriceEffectsUpdate,
} from "~/modules/sales";
+import QuotationReleaseModal from "~/modules/sales/ui/Quotation/QuotationReleaseModal";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session.server";
@@ -128,6 +130,7 @@ export default function QuotationRoute() {
quotationMaterials,
quotationOperations,
} = useLoaderData<typeof loader>();
+ const releaseDisclosure = useDisclosure();
const [quote, setQuote] = useQuotation();
useQuotationLinePriceEffectsUpdate();
@@ -202,11 +205,22 @@ export default function QuotationRoute() {
Preview
</a>
</MenubarItem>
- <MenubarItem isDisabled>Release</MenubarItem>
+ <MenubarItem
+ onClick={releaseDisclosure.onOpen}
+ // isDisabled={isReleased}
+ >
+ Release
+ </MenubarItem>
</Menubar>
<Outlet />
</VStack>
+ {releaseDisclosure.isOpen && (
+ <QuotationReleaseModal
+ quotation={quotation}
+ onClose={releaseDisclosure.onClose}
+ />
+ )}
</div>
);
}
diff --git a/packages/documents/src/email/QuoteEmail.tsx b/packages/documents/src/email/QuoteEmail.tsx
new file mode 100644
index 0000000000..9057509b95
--- /dev/null
+++ b/packages/documents/src/email/QuoteEmail.tsx
@@ -0,0 +1,376 @@
+import type { Database } from "@carbon/database";
+import {
+ Body,
+ Column,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Text,
+} from "@react-email/components";
+import type { Email } from "../types";
+// import {
+// getLineDescription,
+// getLineDescriptionDetails,
+// getTotal,
+// } from "../utils/purchase-order";
+// import { formatAddress } from "../utils/shared";
+
+interface QuoteEmailProps extends Email {
+ quote: Database["public"]["Tables"]["quote"]["Row"];
+}
+
+const QuoteEmail = ({ company, quote, recipient, sender }: QuoteEmailProps) => {
+ const reSubject = `Re: ${quote.quoteId} from ${company.name}`;
+
+ return (
+ <Html lang="en">
+ <Head />
+ <Preview>{`${quote.quoteId} from ${company.name}`}</Preview>
+
+ <Body style={main}>
+ <Container style={container}>
+ <Section>
+ <Row>
+ <Column>
+ {company.logo ? (
+ <Img
+ src={company.logo}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text style={logoText}>{company.name}</Text>
+ )}
+ </Column>
+
+ <Column align="right" style={tableCell}>
+ <Text style={heading}>Purchase Order</Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ <Text style={subtleText}>
+ Hi {recipient.firstName}, please see the attached purchase order
+ and let me know if you have any questions.
+ </Text>
+ </Section>
+ <Section style={informationTable}>
+ <Row style={informationTableRow}>
+ <Column colSpan={2}>
+ <Section>
+ <Row>
+ <Column style={informationTableColumn}>
+ <Text style={informationTableLabel}>Buyer</Text>
+ <Link
+ style={{
+ ...informationTableValue,
+ color: "#15c",
+ textDecoration: "underline",
+ }}
+ href={`mailto:${sender.email}?subject=${reSubject}`}
+ >
+ {`${sender.firstName} ${sender.lastName}`}
+ </Link>
+ </Column>
+ </Row>
+
+ <Row>
+ <Column style={informationTableColumn}>
+ <Text style={informationTableLabel}>Payment Terms</Text>
+ {/* <Text style={informationTableValue}>
+ {quote.paymentTermName ?? "--"}
+ </Text> */}
+ </Column>
+ </Row>
+
+ <Row>
+ <Column style={informationTableColumn}>
+ <Text style={informationTableLabel}>Order ID</Text>
+ <Text style={informationTableValue}>{quote.quoteId}</Text>
+ </Column>
+ <Column style={informationTableColumn}>
+ <Text style={informationTableLabel}>Requested Date</Text>
+ {/* <Text style={informationTableValue}>
+ {quote.receiptRequestedDate ?? "--"}
+ </Text> */}
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ {/* <Column style={informationTableColumn} colSpan={2}>
+ <Text style={informationTableLabel}>Ship To</Text>
+ {dropShipment ? (
+ <>
+ <Text style={informationTableValue}>{customerName}</Text>
+ {customerAddressLine1 && (
+ <Text style={informationTableValue}>
+ {customerAddressLine1}
+ </Text>
+ )}
+ {customerAddressLine2 && (
+ <Text style={informationTableValue}>
+ {customerAddressLine2}
+ </Text>
+ )}
+ <Text style={informationTableValue}>
+ {formatAddress(
+ customerCity,
+ customerState,
+ customerPostalCode
+ )}
+ </Text>
+ <Text style={informationTableValue}>
+ {customerCountryCode}
+ </Text>
+ </>
+ ) : (
+ <>
+ <Text style={informationTableValue}>{company.name}</Text>
+ <Text style={informationTableValue}>{deliveryName}</Text>
+ {deliveryAddressLine1 && (
+ <Text style={informationTableValue}>
+ {deliveryAddressLine1}
+ </Text>
+ )}
+ {deliveryAddressLine2 && (
+ <Text style={informationTableValue}>
+ {deliveryAddressLine2}
+ </Text>
+ )}
+ <Text style={informationTableValue}>
+ {formatAddress(
+ deliveryCity,
+ deliveryState,
+ deliveryPostalCode
+ )}
+ </Text>
+ <Text>{deliveryCountryCode}</Text>
+ </>
+ )}
+ </Column> */}
+ </Row>
+ </Section>
+ <Section style={linesHeader}>
+ <Text style={{ ...informationTableLabel, paddingLeft: "20px" }}>
+ Purchase Order Lines
+ </Text>
+ </Section>
+ {/* <Section>
+ {purchaseOrderLines.map((line) => (
+ <Row key={line.id} style={lineRow}>
+ <Column
+ style={{
+ paddingLeft: "5px",
+ }}
+ >
+ <Text style={lineTitle}>{getLineDescription(line)}</Text>
+ {getLineDescriptionDetails(line)
+ ?.split("\n")
+ .map((l, i) => (
+ <Text key={i} style={lineDescription}>
+ {l}
+ </Text>
+ ))}
+ </Column>
+ <Column style={lineValueWrapper} align="right">
+ <Text style={lineValue}>
+ {line.purchaseOrderLineType === "Comment"
+ ? ""
+ : `(${line.purchaseQuantity})`}
+ </Text>
+ </Column>
+ <Column style={lineValueWrapper} align="right">
+ <Text style={lineValue}>
+ {line.purchaseOrderLineType === "Comment"
+ ? "--"
+ : line.unitPrice
+ ? `$${line.unitPrice.toFixed(2)}`
+ : "--"}
+ </Text>
+ </Column>
+ </Row>
+ ))}
+ </Section> */}
+ <Hr style={priceLine} />
+ <Section align="right">
+ <Row>
+ <Column style={tableCell} align="right">
+ <Text style={priceTotal}>TOTAL</Text>
+ </Column>
+ <Column style={priceVerticalLine}></Column>
+ <Column style={priceLargeWrapper}>
+ {/* <Text style={priceLarge}>
+ {`$${getTotal(purchaseOrderLines)}`}
+ </Text> */}
+ </Column>
+ </Row>
+ </Section>
+ <Hr style={priceLineBottom} />
+ <Section>
+ <Row>
+ <Column align="center" style={block}>
+ {company.logo ? (
+ <Img
+ src={company.logo}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text style={logoText}>{company.name}</Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </Html>
+ );
+};
+
+export default QuoteEmail;
+
+const main = {
+ fontFamily: '"Helvetica Neue",Helvetica,Arial,sans-serif',
+ backgroundColor: "#ffffff",
+};
+
+const resetText = {
+ margin: "0",
+ padding: "0",
+ lineHeight: 1.4,
+};
+
+const container = {
+ margin: "0 auto",
+ padding: "20px 0 48px",
+ width: "660px",
+ maxWidth: "100%",
+};
+
+const tableCell = { display: "table-cell" };
+
+const logoText = {
+ fontSize: "32px",
+ fontWeight: "700",
+ color: "#111111",
+};
+
+const heading = {
+ fontSize: "32px",
+ fontWeight: "300",
+ color: "#888888",
+};
+
+const subtleText = {
+ textAlign: "left" as const,
+ margin: "36px 0 40px 0",
+ fontSize: "14px",
+ fontWeight: "500",
+ color: "#111111",
+};
+
+const informationTable = {
+ borderCollapse: "collapse" as const,
+ borderSpacing: "0px",
+ color: "rgb(51,51,51)",
+ backgroundColor: "rgb(250,250,250)",
+ borderRadius: "6px",
+ fontSize: "12px",
+};
+
+const informationTableRow = {
+ height: "46px",
+};
+
+const informationTableColumn = {
+ paddingLeft: "20px",
+ borderStyle: "solid",
+ borderColor: "white",
+ borderWidth: "0px 1px 1px 0px",
+ height: "44px",
+};
+
+const informationTableLabel = {
+ ...resetText,
+ color: "rgb(102,102,102)",
+ fontSize: "10px",
+ textTransform: "uppercase" as const,
+};
+
+const informationTableValue = {
+ fontSize: "12px",
+ margin: "0",
+ padding: "0",
+ lineHeight: 1.4,
+};
+
+const linesHeader = {
+ ...informationTable,
+ margin: "30px 0 15px 0",
+ height: "24px",
+};
+
+// const lineTitle = { fontSize: "12px", fontWeight: "600", ...resetText };
+
+// const lineDescription = {
+// fontSize: "12px",
+// color: "rgb(102,102,102)",
+// ...resetText,
+// };
+
+// const lineRow = {
+// marginBottom: "10px",
+// paddingLeft: "20px",
+// };
+
+const priceTotal = {
+ margin: "0",
+ color: "rgb(102,102,102)",
+ fontSize: "10px",
+ fontWeight: "600",
+ padding: "0px 30px 0px 0px",
+ textAlign: "right" as const,
+};
+
+// const lineValue = {
+// fontSize: "12px",
+// fontWeight: "600",
+// margin: "0",
+// };
+
+// const priceLarge = {
+// margin: "0px 20px 0px 0px",
+// fontSize: "16px",
+// fontWeight: "600",
+// whiteSpace: "nowrap" as const,
+// textAlign: "right" as const,
+// };
+
+// const lineValueWrapper = {
+// display: "table-cell",
+// padding: "0px 20px 0px 0px",
+// width: "100px",
+// verticalAlign: "top",
+// };
+
+const priceLine = { margin: "30px 0 0 0" };
+
+const priceVerticalLine = {
+ height: "48px",
+ borderLeft: "1px solid",
+ borderColor: "rgb(238,238,238)",
+};
+
+const priceLargeWrapper = { display: "table-cell", width: "90px" };
+
+const priceLineBottom = { margin: "0 0 75px 0" };
+
+const block = { display: "block" };
diff --git a/packages/documents/src/email/index.ts b/packages/documents/src/email/index.ts
index b655ce277d..261bed01ec 100644
--- a/packages/documents/src/email/index.ts
+++ b/packages/documents/src/email/index.ts
@@ -1,3 +1,4 @@
import PurchaseOrderEmail from "./PurchaseOrderEmail";
+import QuoteEmail from "./QuoteEmail";
-export { PurchaseOrderEmail };
+export { PurchaseOrderEmail, QuoteEmail };