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
feat: add the ability to reject digital quote
Brad Barbin9480ccb45f05
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex dc3f4417b2..9705d5cf46 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -99,12 +99,22 @@ export const customerTypeValidator = z.object({name: z.string().min(1, { message: "Name is required" }),});-export const externalQuoteValidator = z.object({- digitalQuoteAcceptedBy: z.string().min(1, { message: "Name is required" }),- digitalQuoteAcceptedByEmail: z- .string()- .email({ message: "Email is invalid" }),-});+export const externalQuoteValidator = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("accept"),+ digitalQuoteAcceptedBy: z.string().min(1, { message: "Name is required" }),+ digitalQuoteAcceptedByEmail: z+ .string()+ .email({ message: "Email is invalid" }),+ }),+ z.object({+ type: z.literal("reject"),+ digitalQuoteRejectedBy: z.string().min(1, { message: "Name is required" }),+ digitalQuoteRejectedByEmail: z+ .string()+ .email({ message: "Email is invalid" }),+ }),+]);export const getLineMethodValidator = z.object({type: z.enum(["line"]),diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsxindex f7039b5d2a..e2fd839eb9 100644--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx@@ -23,27 +23,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!id) throw notFound("id not found");const formData = await request.formData();- const selectedLinesRaw = formData.get("selectedLines") ?? "{}";- const digitalQuoteAcceptedBy = String(formData.get("digitalQuoteAcceptedBy"));- const digitalQuoteAcceptedByEmail = String(- formData.get("digitalQuoteAcceptedByEmail")- );- const file = formData.get("file");-- if (typeof selectedLinesRaw !== "string") {- return json({ success: false, message: "Invalid selected lines data" });- }-- const parseResult = selectedLinesValidator.safeParse(- JSON.parse(selectedLinesRaw)- );-- if (!parseResult.success) {- console.error("Validation error:", parseResult.error);- return json({ success: false, message: "Invalid selected lines data" });- }-- const selectedLines = parseResult.data;+ const type = String(formData.get("type"));const serviceRole = getCarbonServiceRole();const quote = await getQuoteByExternalId(serviceRole, id);@@ -55,92 +35,157 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Quote not found",});}- const [convert, companySettings, opportunity] = await Promise.all([- convertQuoteToOrder(serviceRole, {- id: quote.data.id,- companyId: quote.data.companyId,- userId: quote.data.createdBy,- selectedLines,- digitalQuoteAcceptedBy,- digitalQuoteAcceptedByEmail,- }),- getCompanySettings(serviceRole, quote.data.companyId),- getOpportunityByQuote(serviceRole, quote.data.id),- ]);-- if (convert.error) {- console.error("Failed to convert quote to order", convert.error);- return json({- success: false,- message: "Failed to convert quote to order",- });- }- if (companySettings.error) {- console.error("Failed to get company settings", companySettings.error);- return json({- success: false,- message: "Failed to send notification",- });- }-- if (opportunity.error) {- console.error("Failed to get opportunity", opportunity.error);- return json({- success: false,- message: "Failed to send notification",- });- }+ switch (type) {+ case "accept":+ const digitalQuoteAcceptedBy = String(+ formData.get("digitalQuoteAcceptedBy")+ );+ const digitalQuoteAcceptedByEmail = String(+ formData.get("digitalQuoteAcceptedByEmail")+ );+ const selectedLinesRaw = formData.get("selectedLines") ?? "{}";+ const file = formData.get("file");++ if (typeof selectedLinesRaw !== "string") {+ return json({ success: false, message: "Invalid selected lines data" });+ }++ const parseResult = selectedLinesValidator.safeParse(+ JSON.parse(selectedLinesRaw)+ );++ if (!parseResult.success) {+ console.error("Validation error:", parseResult.error);+ return json({ success: false, message: "Invalid selected lines data" });+ }++ const selectedLines = parseResult.data;++ const [convert, companySettings, opportunity] = await Promise.all([+ convertQuoteToOrder(serviceRole, {+ id: quote.data.id,+ companyId: quote.data.companyId,+ userId: quote.data.createdBy,+ selectedLines,+ digitalQuoteAcceptedBy,+ digitalQuoteAcceptedByEmail,+ }),+ getCompanySettings(serviceRole, quote.data.companyId),+ getOpportunityByQuote(serviceRole, quote.data.id),+ ]);++ if (convert.error) {+ console.error("Failed to convert quote to order", convert.error);+ return json({+ success: false,+ message: "Failed to convert quote to order",+ });+ }++ if (companySettings.error) {+ console.error("Failed to get company settings", companySettings.error);+ return json({+ success: false,+ message: "Failed to send notification",+ });+ }++ if (opportunity.error) {+ console.error("Failed to get opportunity", opportunity.error);+ return json({+ success: false,+ message: "Failed to send notification",+ });+ }++ if (companySettings.data?.digitalQuoteNotificationGroup?.length) {+ try {+ await tasks.trigger<typeof notifyTask>("notify", {+ companyId: companySettings.data.id,+ documentId: quote.data.id,+ event: NotificationEvent.DigitalQuoteResponse,+ recipient: {+ type: "group",+ groupIds:+ companySettings.data?.digitalQuoteNotificationGroup ?? [],+ },+ });+ } catch (err) {+ console.error("Failed to trigger notification", err);+ return json({+ success: false,+ message: "Failed to send notification",+ });+ }+ }++ if (file && file instanceof File) {+ const purchaseOrderDocumentPath = `${companySettings.data.id}/opportunity/${opportunity.data.id}/${file.name}`;++ const fileUpload = await serviceRole.storage+ .from("private")+ .upload(purchaseOrderDocumentPath, file);++ if (fileUpload.error) {+ console.error("Failed to upload file", fileUpload.error);+ return json({+ success: false,+ message: "Failed to upload file",+ });+ }++ const updateOpportunity = await serviceRole+ .from("opportunity")+ .update({+ purchaseOrderDocumentPath,+ })+ .eq("id", opportunity.data?.id!);++ if (updateOpportunity.error) {+ console.error(+ "Failed to update opportunity",+ updateOpportunity.error+ );+ }+ }- if (companySettings.data?.digitalQuoteNotificationGroup?.length) {- try {- await tasks.trigger<typeof notifyTask>("notify", {- companyId: companySettings.data.id,- documentId: quote.data.id,- event: NotificationEvent.DigitalQuoteResponse,- recipient: {- type: "group",- groupIds: companySettings.data?.digitalQuoteNotificationGroup ?? [],- },- });- } catch (err) {- console.error("Failed to trigger notification", err);return json({- success: false,- message: "Failed to send notification",+ success: true,+ message: "Quote accepted!",});- }- }-- if (file && file instanceof File) {- const purchaseOrderDocumentPath = `${companySettings.data.id}/opportunity/${opportunity.data.id}/${file.name}`;- const fileUpload = await serviceRole.storage- .from("private")- .upload(purchaseOrderDocumentPath, file);+ case "reject":+ const digitalQuoteRejectedBy = String(+ formData.get("digitalQuoteRejectedBy")+ );+ const digitalQuoteRejectedByEmail = String(+ formData.get("digitalQuoteRejectedByEmail")+ );++ const rejectQuote = await serviceRole+ .from("quote")+ .update({+ status: "Lost",+ digitalQuoteRejectedBy,+ digitalQuoteRejectedByEmail,+ })+ .eq("id", quote.data.id);++ if (rejectQuote.error) {+ console.error("Failed to reject quote", rejectQuote.error);+ return json({+ success: false,+ message: "Failed to reject quote",+ });+ }- if (fileUpload.error) {- console.error("Failed to upload file", fileUpload.error);return json({- success: false,- message: "Failed to upload file",+ success: true,+ message: "Quote rejected!",});- }-- const updateOpportunity = await serviceRole- .from("opportunity")- .update({- purchaseOrderDocumentPath,- })- .eq("id", opportunity.data?.id!);-- if (updateOpportunity.error) {- console.error("Failed to update opportunity", updateOpportunity.error);- }- }- return json({- success: true,- message: "Quote accepted!",- });+ default:+ return json({ success: false, message: "Invalid type" });+ }}diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsxindex 944c47c4d7..e147bdffe5 100644--- a/apps/erp/app/routes/share+/quote.$id.tsx+++ b/apps/erp/app/routes/share+/quote.$id.tsx@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth";import { Input, ValidatedForm } from "@carbon/form";import type { JSONContent } from "@carbon/react";import {+ Badge,Button,Card,CardContent,@@ -92,11 +93,16 @@ const translations = {en: {"Accept Quote": "Accept Quote","Add-Ons": "Add-Ons",+ "Are you sure you want to accept this quote?": (+ id: string,+ amount: string+ ) => `Are you sure you want to accept quote ${id} for ${amount}?`,+ "Are you sure you want to reject this quote?":+ "Are you sure you want to reject this quote?",Cancel: "Cancel",Change: "Change",days: "days","Digital Quote": "Digital Quote",- "Don't Buy": "Don't Buy","Drag and drop a Purchase Order PDF here, or click to select a file":"Drag and drop a Purchase Order PDF here, or click to select a file",Expires: "Expires",@@ -113,6 +119,8 @@ const translations = {Quantity: "Quantity","Quote expired": "Quote expired","Quote not found": "Quote not found",+ "Reject Quote": "Reject Quote",+ Remove: "Remove","Shipping Method": "Shipping Method",Shipping: "Shipping",Subtotal: "Subtotal",@@ -120,15 +128,23 @@ const translations = {Total: "Total","Unit Price": "Unit Price","Yes, Accept": "Yes, Accept",+ "Yes, Reject": "Yes, Reject",},es: {"Accept Quote": "Aceptar Cotización","Add-Ons": "Complementos",+ "Are you sure you want to accept this quote?": (+ id: string,+ amount: string+ ) =>+ `¿Estás seguro de que quieres aceptar la cotización ${id} por ${amount}?`,+ "Are you sure you want to reject this quote?":+ "¿Estás seguro de que quieres rechazar esta cotización?",Cancel: "Cancelar",Change: "Cambiar",days: "días","Digital Quote": "Cotización Digital",- "Don't Buy": "No Comprar",+"Drag and drop a Purchase Order PDF here, or click to select a file":"Arrastre y suelte un PDF de Orden de Compra aquí, o haga clic para seleccionar un archivo",Expires: "Expira",@@ -146,6 +162,8 @@ const translations = {Quantity: "Cantidad","Quote expired": "Cotización expirada","Quote not found": "Cotización no encontrada",+ "Reject Quote": "Rechazar Cotización",+ Remove: "Eliminar","Shipping Method": "Método de Envío",Shipping: "Envío",Subtotal: "Subtotal",@@ -153,15 +171,22 @@ const translations = {Total: "Total","Unit Price": "Precio Unitario","Yes, Accept": "Sí, Aceptar",+ "Yes, Reject": "Sí, Rechazar",},de: {"Accept Quote": "Angebot Annehmen","Add-Ons": "Zusätze",+ "Are you sure you want to accept this quote?": (+ id: string,+ amount: string+ ) =>+ `Sind Sie sicher, dass Sie das Angebot ${id} für ${amount} annehmen möchten?`,+ "Are you sure you want to reject this quote?":+ "Sind Sie sicher, dass Sie dieses Angebot ablehnen möchten?",Cancel: "Abbrechen",Change: "Ändern",days: "Tage","Digital Quote": "Digitales Angebot",- "Don't Buy": "Nicht Kaufen","Drag and drop a Purchase Order PDF here, or click to select a file":"Ziehen Sie eine Bestellung als PDF hierher oder klicken Sie zum Auswählen",Expires: "Läuft ab",@@ -179,6 +204,8 @@ const translations = {Quantity: "Menge","Quote expired": "Angebot abgelaufen","Quote not found": "Angebot nicht gefunden",+ "Reject Quote": "Angebot ablehnen",+ Remove: "Entfernen","Shipping Method": "Versandart",Shipping: "Versand",Subtotal: "Zwischensumme",@@ -186,6 +213,7 @@ const translations = {Total: "Gesamt","Unit Price": "Stückpreis","Yes, Accept": "Ja, Annehmen",+ "Yes, Reject": "Ja, Ablehnen",},};@@ -874,7 +902,7 @@ const LinePricingOptions = ({{selectedLine.quantity !== 0 && !hasSalesOrder && (<HStack spacing={2} className="w-full justify-end items-center"><Button- variant="primary"+ variant="secondary"leftIcon={<LuCircleX />}onClick={() => {setSelectedValue("0");@@ -884,7 +912,7 @@ const LinePricingOptions = ({}));}}>- {strings["Don't Buy"]}+ {strings.Remove}</Button></HStack>)}@@ -924,7 +952,10 @@ const Quote = ({const { id } = useParams();if (!id) throw new Error("Could not find external quote id");+const confirmQuoteModal = useDisclosure();+ const rejectQuoteModal = useDisclosure();+const fetcher = useFetcher<typeof action>();const submitted = useRef<boolean>(false);const mode = useMode();@@ -1060,7 +1091,10 @@ const Quote = ({)}<Card className="w-full max-w-5xl mx-auto"><div className="w-full text-center">- {quote?.status !== "Sent" && <QuoteStatus status={quote.status} />}+ {!["Sent", "Lost"].includes(quote.status) && (+ <QuoteStatus status={quote.status} />+ )}+ {quote?.status === "Lost" && <Badge variant="red">Rejected</Badge>}</div><Headercompany={company}@@ -1125,16 +1159,29 @@ const Quote = ({/></HStack></VStack>- {companySettings?.digitalQuoteEnabled && quote?.status === "Sent" && (- <Button- onClick={confirmQuoteModal.onOpen}- size="lg"- isDisabled={total === 0}- className="w-full mt-8 text-lg"- >- {strings["Accept Quote"]}- </Button>- )}+ <div className="flex flex-col gap-2">+ {companySettings?.digitalQuoteEnabled &&+ quote?.status === "Sent" && (+ <>+ <Button+ onClick={confirmQuoteModal.onOpen}+ size="lg"+ variant="primary"+ isDisabled={total === 0}+ className="w-full mt-8 text-lg"+ >+ {strings["Accept Quote"]}+ </Button>+ <Button+ onClick={rejectQuoteModal.onOpen}+ size="lg"+ variant="link"+ >+ {strings["Reject Quote"]}+ </Button>+ </>+ )}+ </div></CardContent></Card>{termsHTML && (@@ -1174,6 +1221,7 @@ const Quote = ({{!companySettings?.digitalQuoteIncludesPurchaseOrders && (<input type="hidden" name="file" />)}+ <input type="hidden" name="type" value="accept" /><div className="space-y-4 py-4"><Inputname="digitalQuoteAcceptedBy"@@ -1241,6 +1289,62 @@ const Quote = ({</ModalContent></Modal>)}++ {rejectQuoteModal.isOpen && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) rejectQuoteModal.onClose();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ValidatedForm+ action={path.to.api.digitalQuote(id)}+ validator={externalQuoteValidator}+ method="post"+ fetcher={fetcher}+ onSubmit={() => {+ submitted.current = true;+ }}+ >+ <ModalHeader>+ <ModalTitle>{strings["Reject Quote"]}</ModalTitle>+ <ModalDescription>+ {strings["Are you sure you want to reject this quote?"]}+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <input type="hidden" name="type" value="reject" />+ <div className="space-y-4 py-4">+ <Input+ name="digitalQuoteRejectedBy"+ label="Please enter your name"+ />+ <Input+ name="digitalQuoteRejectedByEmail"+ label="Please enter your email address"+ />+ </div>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={rejectQuoteModal.onClose}>+ {strings.Cancel}+ </Button>++ <Button+ isLoading={fetcher.state !== "idle"}+ isDisabled={fetcher.state !== "idle"}+ variant="destructive"+ type="submit"+ >+ {strings["Yes, Reject"]}+ </Button>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ )}</VStack>);};@@ -1357,6 +1461,7 @@ export default function ExternalQuote() {switch (state) {case QuoteState.Valid:if (data) {+ // @ts-ignorereturn <Quote data={data as QuoteData} strings={strings} />;}return (diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 8fe3ea20c5..9a0a8c2dc3 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -15514,6 +15514,8 @@ export type Database = {customFields: Json | nulldigitalQuoteAcceptedBy: string | nulldigitalQuoteAcceptedByEmail: string | null+ digitalQuoteRejectedBy: string | null+ digitalQuoteRejectedByEmail: string | nulldueDate: string | nullestimatorId: string | nullexchangeRate: number | null@@ -15545,6 +15547,8 @@ export type Database = {customFields?: Json | nulldigitalQuoteAcceptedBy?: string | nulldigitalQuoteAcceptedByEmail?: string | null+ digitalQuoteRejectedBy?: string | null+ digitalQuoteRejectedByEmail?: string | nulldueDate?: string | nullestimatorId?: string | nullexchangeRate?: number | null@@ -15576,6 +15580,8 @@ export type Database = {customFields?: Json | nulldigitalQuoteAcceptedBy?: string | nulldigitalQuoteAcceptedByEmail?: string | null+ digitalQuoteRejectedBy?: string | null+ digitalQuoteRejectedByEmail?: string | nulldueDate?: string | nullestimatorId?: string | nullexchangeRate?: number | nulldiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 8fe3ea20c5..9a0a8c2dc3 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -15514,6 +15514,8 @@ export type Database = {customFields: Json | nulldigitalQuoteAcceptedBy: string | nulldigitalQuoteAcceptedByEmail: string | null+ digitalQuoteRejectedBy: string | null+ digitalQuoteRejectedByEmail: string | nulldueDate: string | nullestimatorId: string | nullexchangeRate: number | null@@ -15545,6 +15547,8 @@ export type Database = {customFields?: Json | nulldigitalQuoteAcceptedBy?: string | nulldigitalQuoteAcceptedByEmail?: string | null+ digitalQuoteRejectedBy?: string | null+ digitalQuoteRejectedByEmail?: string | nulldueDate?: string | nullestimatorId?: string | nullexchangeRate?: number | null@@ -15576,6 +15580,8 @@ export type Database = {customFields?: Json | nulldigitalQuoteAcceptedBy?: string | nulldigitalQuoteAcceptedByEmail?: string | null+ digitalQuoteRejectedBy?: string | null+ digitalQuoteRejectedByEmail?: string | nulldueDate?: string | nullestimatorId?: string | nullexchangeRate?: number | nulldiff --git a/packages/database/supabase/migrations/20250120133507_reject-digital-quote.sql b/packages/database/supabase/migrations/20250120133507_reject-digital-quote.sqlnew file mode 100644index 0000000000..f59408dfe2--- /dev/null+++ b/packages/database/supabase/migrations/20250120133507_reject-digital-quote.sql@@ -0,0 +1,2 @@+ALTER TABLE "quote" ADD COLUMN "digitalQuoteRejectedBy" TEXT;+ALTER TABLE "quote" ADD COLUMN "digitalQuoteRejectedByEmail" TEXT;\ No newline at end of filediff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsxindex 76dbea7dfc..636ce34282 100644--- a/packages/react/src/Button.tsx+++ b/packages/react/src/Button.tsx@@ -25,7 +25,7 @@ export const buttonVariants = cva(solid:"bg-accent text-accent-foreground hover:bg-accent/90 shadow-button-base",destructive:- "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-button-danger",+ "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)]",ghost:"bg-transparent hover:bg-primary/10 text-accent-foreground hover:text-accent-foreground/90",link: "text-foreground hover:text-foreground underline-offset-4 hover:underline px-0 py-0",