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: handle error states

Brad Barbineead7a540b3f
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index f5b6bbe9ad..8f6c79c505 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -679,10 +679,9 @@ export async function getQuoteByExternalId(
externalId: string
) {
return client
- .from("externalLink")
+ .from("quote")
.select("*")
- .eq("externalId", externalId)
- .eq("documentType", "Quote")
+ .eq("externalLinkId", externalId)
.single();
}
diff --git a/apps/carbon/app/modules/shared/shared.service.ts b/apps/carbon/app/modules/shared/shared.service.ts
index 1a437a2dda..0574de3a9a 100644
--- a/apps/carbon/app/modules/shared/shared.service.ts
+++ b/apps/carbon/app/modules/shared/shared.service.ts
@@ -71,6 +71,21 @@ export async function insertNote(
return client.from("note").insert([note]).select("*").single();
}
+export async function upsertExternalLink(
+ client: SupabaseClient<Database>,
+ externalLink: Database["public"]["Tables"]["externalLink"]["Insert"]
+) {
+ if ("id" in externalLink && externalLink.id) {
+ return client
+ .from("externalLink")
+ .update(externalLink)
+ .eq("id", externalLink.id)
+ .select("id")
+ .single();
+ }
+ return client.from("externalLink").insert(externalLink).select("id").single();
+}
+
export async function updateNote(
client: SupabaseClient<Database>,
id: string,
diff --git a/apps/carbon/app/routes/external+/quote.$id.tsx b/apps/carbon/app/routes/external+/quote.$id.tsx
index d128a08bf6..1f3ebb4a2b 100644
--- a/apps/carbon/app/routes/external+/quote.$id.tsx
+++ b/apps/carbon/app/routes/external+/quote.$id.tsx
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
// import { getCarbonServiceRole, notFound } from "@carbon/auth";
import {
Avatar,
@@ -10,23 +11,54 @@ import {
RadioGroup,
RadioGroupItem,
} from "@carbon/react";
+import { useLoaderData } from "@remix-run/react";
import { json, type LoaderFunctionArgs } from "@vercel/remix";
import { motion } from "framer-motion";
import { useState } from "react";
import { LuChevronDown, LuChevronUp } from "react-icons/lu";
-// import { getQuoteByExternalId } from "~/modules/sales";
+import { getQuoteByExternalId } from "~/modules/sales";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- // const { id } = params;
- // if (!id) throw notFound("Quote not found");
+enum QuoteState {
+ Valid,
+ Expired,
+ NotFound,
+}
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { id } = params;
+ if (!id) {
+ return json({
+ state: QuoteState.NotFound,
+ data: null,
+ });
+ }
+
+ const serviceRole = getCarbonServiceRole();
+ const quote = await getQuoteByExternalId(serviceRole, id);
+
+ if (quote.error) {
+ return json({
+ state: QuoteState.NotFound,
+ data: null,
+ });
+ }
- // const serviceRole = getCarbonServiceRole();
- // const document = await getQuoteByExternalId(serviceRole, id);
- // if (!document.data || !document.data.documentId)
- // throw notFound("Quote not found");
- // const quoteId = document.data.documentId;
+ if (
+ quote.data.expirationDate &&
+ new Date(quote.data.expirationDate) < new Date()
+ ) {
+ return json({
+ state: QuoteState.Expired,
+ data: null,
+ });
+ }
- return json({});
+ return json({
+ state: QuoteState.Valid,
+ data: {
+ quote: quote.data,
+ },
+ });
}
type OptionType = {
@@ -200,7 +232,7 @@ const LineItems = ({
};
// Main Quote Component
-export default function Quote({
+const Quote = ({
companyName = "Acme Inc.",
companyLogo = "/placeholder.svg?height=50&width=50",
customerName = "John Doe",
@@ -231,7 +263,7 @@ export default function Quote({
],
},
],
-}: QuoteProps) {
+}: QuoteProps) => {
const [selectedOptions, setSelectedOptions] = useState<
Record<number, number>
>(() =>
@@ -289,4 +321,129 @@ export default function Quote({
</CardContent>
</Card>
);
+};
+
+const ErrorMessage = ({
+ title,
+ message,
+}: {
+ title: string;
+ message: string;
+}) => {
+ const containerVariants = {
+ hidden: { opacity: 0 },
+ visible: {
+ opacity: 1,
+ transition: {
+ delay: 0.3,
+ when: "beforeChildren",
+ staggerChildren: 0.2,
+ },
+ },
+ };
+
+ const itemVariants = {
+ hidden: { y: 20, opacity: 0 },
+ visible: {
+ y: 0,
+ opacity: 1,
+ },
+ };
+
+ return (
+ <motion.div
+ className="flex min-h-screen flex-col items-center justify-center p-4 text-center"
+ initial="hidden"
+ animate="visible"
+ variants={containerVariants}
+ >
+ <motion.div
+ className="w-full max-w-md space-y-8"
+ variants={containerVariants}
+ >
+ <motion.div
+ className="relative mx-auto h-24 w-24"
+ variants={itemVariants}
+ >
+ <svg
+ className="absolute inset-0"
+ viewBox="0 0 100 100"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <motion.circle
+ cx="50"
+ cy="50"
+ r="45"
+ stroke="hsl(var(--muted))"
+ strokeWidth="10"
+ initial={{ pathLength: 0 }}
+ animate={{ pathLength: 1 }}
+ transition={{ duration: 2, ease: "easeInOut" }}
+ />
+ <motion.path
+ d="M50 5 A45 45 0 0 1 95 50"
+ stroke="hsl(var(--primary))"
+ strokeWidth="10"
+ strokeLinecap="round"
+ initial={{ pathLength: 0 }}
+ animate={{ pathLength: 1 }}
+ transition={{
+ duration: 2,
+ ease: "easeInOut",
+ }}
+ />
+ </svg>
+ <motion.div
+ className="absolute inset-0 flex items-center justify-center"
+ initial={{ scale: 0 }}
+ animate={{ scale: 1 }}
+ transition={{
+ delay: 0.5,
+ type: "spring",
+ stiffness: 200,
+ damping: 10,
+ }}
+ >
+ <span className="text-2xl font-bold text-muted-foreground">!</span>
+ </motion.div>
+ </motion.div>
+ <motion.h1
+ className="text-3xl font-bold tracking-tight text-foreground sm:text-4xl"
+ variants={itemVariants}
+ >
+ {title}
+ </motion.h1>
+ <motion.p
+ className="text-lg text-muted-foreground"
+ variants={itemVariants}
+ >
+ {message}
+ </motion.p>
+ </motion.div>
+ </motion.div>
+ );
+};
+
+export default function ExternalQuote() {
+ const { state, data } = useLoaderData<typeof loader>();
+
+ switch (state) {
+ case QuoteState.Valid:
+ return <pre>{JSON.stringify(data, null, 2)}</pre>;
+ case QuoteState.Expired:
+ return (
+ <ErrorMessage
+ title="Quote expired"
+ message="Oops! The link you're trying to access has expired or is no longer valid."
+ />
+ );
+ case QuoteState.NotFound:
+ return (
+ <ErrorMessage
+ title="Quote not found"
+ message="Oops! The link you're trying to access is not valid."
+ />
+ );
+ }
}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
index 39c5732650..cd384616a9 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -16,6 +16,7 @@ import {
quoteFinalizeValidator,
} from "~/modules/sales";
import { getCompany } from "~/modules/settings";
+import { upsertExternalLink } from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have this task defined
@@ -59,6 +60,22 @@ export async function action(args: ActionFunctionArgs) {
);
}
+ const externalLink = await upsertExternalLink(client, {
+ id: quote.data.externalLinkId ?? undefined, // TODO
+ documentType: "Quote",
+ documentId: quoteId,
+ customerId: quote.data.customerId,
+ expiresAt: quote.data.expirationDate,
+ companyId,
+ });
+
+ if (externalLink.data && quote.data.externalLinkId !== externalLink.data.id) {
+ await client
+ .from("quote")
+ .update({ externalLinkId: externalLink.data.id })
+ .eq("id", quoteId);
+ }
+
try {
const pdf = await pdfLoader({ ...args, params: { id: quoteId } });
if (pdf.headers.get("content-type") !== "application/pdf")
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 40d85eb992..88f5b986cf 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8625,8 +8625,8 @@ export type Database = {
grade: string | null
id: string
itemId: string | null
- materialFormId: string
- materialSubstanceId: string
+ materialFormId: string | null
+ materialSubstanceId: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -8643,8 +8643,8 @@ export type Database = {
grade?: string | null
id: string
itemId?: string | null
- materialFormId: string
- materialSubstanceId: string
+ materialFormId?: string | null
+ materialSubstanceId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8661,8 +8661,8 @@ export type Database = {
grade?: string | null
id?: string
itemId?: string | null
- materialFormId?: string
- materialSubstanceId?: string
+ materialFormId?: string | null
+ materialSubstanceId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -14138,6 +14138,7 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
+ externalLinkId: string | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -14165,6 +14166,7 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
+ externalLinkId?: string | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -14192,6 +14194,7 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
+ externalLinkId?: string | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -14379,6 +14382,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quote_externalLinkId_fkey"
+ columns: ["externalLinkId"]
+ isOneToOne: false
+ referencedRelation: "externalLink"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -26862,6 +26872,7 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
+ externalLinkId: string | null
externalNotes: Json | null
favorite: boolean | null
id: string | null
@@ -27089,6 +27100,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quote_externalLinkId_fkey"
+ columns: ["externalLinkId"]
+ isOneToOne: false
+ referencedRelation: "externalLink"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 40d85eb992..88f5b986cf 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -8625,8 +8625,8 @@ export type Database = {
grade: string | null
id: string
itemId: string | null
- materialFormId: string
- materialSubstanceId: string
+ materialFormId: string | null
+ materialSubstanceId: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -8643,8 +8643,8 @@ export type Database = {
grade?: string | null
id: string
itemId?: string | null
- materialFormId: string
- materialSubstanceId: string
+ materialFormId?: string | null
+ materialSubstanceId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8661,8 +8661,8 @@ export type Database = {
grade?: string | null
id?: string
itemId?: string | null
- materialFormId?: string
- materialSubstanceId?: string
+ materialFormId?: string | null
+ materialSubstanceId?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -14138,6 +14138,7 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
+ externalLinkId: string | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -14165,6 +14166,7 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
+ externalLinkId?: string | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -14192,6 +14194,7 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
+ externalLinkId?: string | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -14379,6 +14382,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quote_externalLinkId_fkey"
+ columns: ["externalLinkId"]
+ isOneToOne: false
+ referencedRelation: "externalLink"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
@@ -26862,6 +26872,7 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
+ externalLinkId: string | null
externalNotes: Json | null
favorite: boolean | null
id: string | null
@@ -27089,6 +27100,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quote_externalLinkId_fkey"
+ columns: ["externalLinkId"]
+ isOneToOne: false
+ referencedRelation: "externalLink"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quote_locationId_fkey"
columns: ["locationId"]
diff --git a/packages/database/supabase/migrations/20241030005037_external-links.sql b/packages/database/supabase/migrations/20241030005037_external-links.sql
index 137a394b60..c534119143 100644
--- a/packages/database/supabase/migrations/20241030005037_external-links.sql
+++ b/packages/database/supabase/migrations/20241030005037_external-links.sql
@@ -83,3 +83,28 @@ CREATE POLICY "Employees can delete external link messages" ON "externalLinkMess
USING (
has_role('employee', "companyId")
);
+
+ALTER TABLE "quote" ADD COLUMN "externalLinkId" uuid REFERENCES "externalLink"("id") ON DELETE SET NULL;
+DROP VIEW IF EXISTS "quotes";
+CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ q.*,
+ l."name" AS "locationName",
+ ql."lines",
+ ql."completedLines",
+ EXISTS(SELECT 1 FROM "quoteFavorite" pf WHERE pf."quoteId" = q.id AND pf."userId" = auth.uid()::text) AS favorite,
+ opp."salesRfqId",
+ opp."salesOrderId"
+ FROM "quote" q
+ LEFT JOIN (
+ SELECT
+ "quoteId",
+ COUNT("id") FILTER (WHERE "status" != 'No Quote') AS "lines",
+ COUNT("id") FILTER (WHERE "status" = 'Complete') AS "completedLines"
+ FROM "quoteLine"
+ GROUP BY "quoteId"
+ ) ql ON ql."quoteId" = q.id
+ LEFT JOIN "location" l
+ ON l.id = q."locationId"
+ LEFT JOIN "opportunity" opp
+ ON opp."quoteId" = q.id;
\ No newline at end of file