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.

- new changes in regards to status and UI

Gaurav Bhatt796b5e0a953a
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index b84fbbbb70..17be2e278f 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -323,11 +323,8 @@ export const supplierStatusValidator = z.object({
});
export const supplierQuoteStatusType = [
+ "Draft",
"Active",
- "Sent",
- "Submitted",
- "Partial",
- "Ordered",
"Expired",
"Declined",
"Cancelled",
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index fce1db6c71..d77fedf1e7 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -77,7 +77,28 @@ export async function finalizeSupplierQuote(
const quoteUpdate = await client
.from("supplierQuote")
.update({
- status: "Sent",
+ status: "Active",
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", supplierQuoteId);
+
+ if (quoteUpdate.error) {
+ return quoteUpdate;
+ }
+
+ return { data: null, error: null };
+}
+
+export async function sendSupplierQuote(
+ client: SupabaseClient<Database>,
+ supplierQuoteId: string,
+ userId: string
+) {
+ // Send keeps status as Draft, just updates timestamp
+ const quoteUpdate = await client
+ .from("supplierQuote")
+ .update({
updatedAt: today(getLocalTimeZone()).toString(),
updatedBy: userId,
})
@@ -1481,10 +1502,11 @@ export async function upsertSupplierQuote(
.insert([
{
...supplierQuote,
+ status: supplierQuote.status ?? "Draft",
supplierInteractionId: supplierInteraction.data?.id,
},
])
- .select("id, supplierQuoteId")
+ .select("id, supplierQuoteId, externalLinkId")
.single();
if (insert.error) {
@@ -1494,19 +1516,22 @@ export async function upsertSupplierQuote(
const supplierQuoteId = insert.data?.id;
if (!supplierQuoteId) return insert;
- const externalLink = await upsertExternalLink(client, {
- documentType: "SupplierQuote",
- documentId: supplierQuoteId,
- supplierId: supplierQuote.supplierId,
- expiresAt: supplierQuote.expirationDate,
- companyId: supplierQuote.companyId,
- });
-
- if (externalLink.data) {
- await client
- .from("supplierQuote")
- .update({ externalLinkId: externalLink.data.id })
- .eq("id", supplierQuoteId);
+ // Only create external link if one doesn't exist
+ if (!insert.data.externalLinkId) {
+ const externalLink = await upsertExternalLink(client, {
+ documentType: "SupplierQuote",
+ documentId: supplierQuoteId,
+ supplierId: supplierQuote.supplierId,
+ expiresAt: supplierQuote.expirationDate,
+ companyId: supplierQuote.companyId,
+ });
+
+ if (externalLink.data) {
+ await client
+ .from("supplierQuote")
+ .update({ externalLinkId: externalLink.data.id })
+ .eq("id", supplierQuoteId);
+ }
}
return insert;
@@ -1548,7 +1573,7 @@ export async function upsertSupplierQuote(
supplierQuote.expirationDate &&
today(getLocalTimeZone()).toString() > supplierQuote.expirationDate
? "Expired"
- : supplierQuote.status ?? existingStatus ?? "Active",
+ : supplierQuote.status ?? existingStatus ?? "Draft",
updatedAt: today(getLocalTimeZone()).toString(),
})
.eq("id", supplierQuote.id);
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx
index 51da796a89..5d5777264e 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteFinalizeModal.tsx
@@ -39,6 +39,7 @@ type SupplierQuoteFinalizeModalProps = {
lines: SupplierQuoteLine[];
pricing: SupplierQuoteLinePrice[];
fetcher: FetcherWithComponents<{}>;
+ action?: string;
};
const SupplierQuoteFinalizeModal = ({
@@ -46,6 +47,7 @@ const SupplierQuoteFinalizeModal = ({
onClose,
fetcher,
pricing,
+ action,
}: SupplierQuoteFinalizeModalProps) => {
const { id } = useParams();
if (!id) throw new Error("id not found");
@@ -121,7 +123,7 @@ const SupplierQuoteFinalizeModal = ({
<ValidatedForm
method="post"
validator={supplierQuoteFinalizeValidator}
- action={path.to.supplierQuoteFinalize(id)}
+ action={action ?? path.to.supplierQuoteFinalize(id)}
onSubmit={onClose}
defaultValues={{
notification: notificationType as "Email" | "None",
@@ -130,9 +132,15 @@ const SupplierQuoteFinalizeModal = ({
fetcher={fetcher}
>
<ModalHeader>
- <ModalTitle>{`Finalize ${quote?.supplierQuoteId}`}</ModalTitle>
+ <ModalTitle>
+ {action === path.to.supplierQuoteSend(id)
+ ? `Send ${quote?.supplierQuoteId}`
+ : `Finalize ${quote?.supplierQuoteId}`}
+ </ModalTitle>
<ModalDescription>
- Are you sure you want to finalize the supplier quote?
+ {action === path.to.supplierQuoteSend(id)
+ ? "Send the supplier quote to the supplier via email."
+ : "Are you sure you want to finalize the supplier quote?"}
</ModalDescription>
</ModalHeader>
<ModalBody>
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
index d68a048acc..0e7c58b577 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
@@ -37,8 +37,6 @@ import {
LuCheckCheck,
LuCircleStop,
LuLoaderCircle,
- LuCircleCheck,
- LuCircleX,
} from "react-icons/lu";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
@@ -78,8 +76,10 @@ const SupplierQuoteHeader = () => {
const deleteModal = useDisclosure();
const shareModal = useDisclosure();
const finalizeModal = useDisclosure();
+ const sendModal = useDisclosure();
const finalizeFetcher = useFetcher<{}>();
+ const sendFetcher = useFetcher<{}>();
const statusFetcher = useFetcher<{}>();
const hasLines = routeData?.lines && routeData.lines.length > 0;
@@ -132,133 +132,78 @@ const SupplierQuoteHeader = () => {
)}
</HStack>
<HStack>
- {routeData?.quote?.status === "Sent" &&
- (routeData?.quote as any)?.externalLinkId ? (
- <Button
- onClick={shareModal.onOpen}
- leftIcon={<LuShare />}
- variant="secondary"
- >
- Share
- </Button>
- ) : (
- (routeData?.quote as any)?.externalLinkId && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- leftIcon={<LuEye />}
- variant="secondary"
- rightIcon={<LuChevronDown />}
+ {(routeData?.quote as any)?.externalLinkId && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuEye />}
+ variant="secondary"
+ rightIcon={<LuChevronDown />}
+ >
+ Preview
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <a
+ target="_blank"
+ href={path.to.externalSupplierQuote(
+ (routeData?.quote as any).externalLinkId
+ )}
+ rel="noreferrer"
>
- Preview
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem asChild>
- <a
- target="_blank"
- href={path.to.externalSupplierQuote(
- (routeData?.quote as any).externalLinkId
- )}
- rel="noreferrer"
- >
- <DropdownMenuIcon icon={<LuExternalLink />} />
- Digital Quote
- </a>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )
+ <DropdownMenuIcon icon={<LuExternalLink />} />
+ Digital Quote
+ </a>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
)}
- <Button
- onClick={finalizeModal.onOpen}
- isLoading={finalizeFetcher.state !== "idle"}
- isDisabled={
- routeData?.quote?.status !== "Active" ||
- finalizeFetcher.state !== "idle" ||
- !permissions.can("update", "purchasing") ||
- !hasLines
- }
- variant={
- routeData?.quote?.status === "Active" ? "primary" : "secondary"
- }
- leftIcon={<LuCheckCheck />}
- >
- Finalize
- </Button>
-
- <statusFetcher.Form
- id="submit-form"
- method="post"
- action={path.to.supplierQuoteStatus(id)}
- >
- <input type="hidden" name="status" value="Submitted" />
+ {routeData?.quote?.status === "Draft" && (
<Button
+ onClick={sendModal.onOpen}
+ isLoading={sendFetcher.state !== "idle"}
isDisabled={
- routeData?.quote?.status !== "Sent" ||
- statusFetcher.state !== "idle" ||
- !permissions.can("update", "purchasing")
+ sendFetcher.state !== "idle" ||
+ !permissions.can("update", "purchasing") ||
+ !hasLines
}
- isLoading={
- statusFetcher.state !== "idle" &&
- statusFetcher.formData?.get("status") === "Submitted"
- }
- variant={
- routeData?.quote?.status === "Sent" ? "primary" : "secondary"
- }
- leftIcon={<LuCircleCheck />}
- type="submit"
+ variant="primary"
+ leftIcon={<LuShare />}
>
- Submit
+ Send
</Button>
- </statusFetcher.Form>
+ )}
- <statusFetcher.Form
- id="decline-form"
- method="post"
- action={path.to.supplierQuoteStatus(id)}
- >
- <input type="hidden" name="status" value="Declined" />
+ {routeData?.quote?.status === "Draft" && (
<Button
+ onClick={finalizeModal.onOpen}
+ isLoading={finalizeFetcher.state !== "idle"}
isDisabled={
- routeData?.quote?.status !== "Sent" ||
- statusFetcher.state !== "idle" ||
- !permissions.can("update", "purchasing")
- }
- isLoading={
- statusFetcher.state !== "idle" &&
- statusFetcher.formData?.get("status") === "Declined"
+ finalizeFetcher.state !== "idle" ||
+ !permissions.can("update", "purchasing") ||
+ !hasLines
}
- variant={
- routeData?.quote?.status === "Sent"
- ? "destructive"
- : "secondary"
- }
- leftIcon={<LuCircleX />}
- type="submit"
+ variant="secondary"
+ leftIcon={<LuCheckCheck />}
>
- Decline
+ Finalize
</Button>
- </statusFetcher.Form>
+ )}
- <Button
- isDisabled={
- routeData?.quote?.status !== "Submitted" ||
- !permissions.can("update", "purchasing")
- }
- variant={
- routeData?.quote?.status === "Submitted"
- ? "primary"
- : "secondary"
- }
- leftIcon={<LuShoppingCart />}
- onClick={convertToOrderModal.onOpen}
- >
- Order
- </Button>
+ {routeData?.quote?.status === "Active" && (
+ <Button
+ isDisabled={!permissions.can("update", "purchasing")}
+ variant="primary"
+ leftIcon={<LuShoppingCart />}
+ onClick={convertToOrderModal.onOpen}
+ >
+ Order
+ </Button>
+ )}
- {routeData?.quote?.status === "Active" ? (
+ {routeData?.quote?.status === "Active" && (
<statusFetcher.Form
method="post"
action={path.to.supplierQuoteStatus(id)}
@@ -280,31 +225,33 @@ const SupplierQuoteHeader = () => {
Cancel
</Button>
</statusFetcher.Form>
- ) : (
- <statusFetcher.Form
- method="post"
- action={path.to.supplierQuoteStatus(id)}
- >
- <input type="hidden" name="status" value="Active" />
- <Button
- isDisabled={
- statusFetcher.state !== "idle" ||
- !permissions.can("update", "purchasing") ||
- routeData?.quote?.status === "Ordered"
- }
- isLoading={
- statusFetcher.state !== "idle" &&
- statusFetcher.formData?.get("status") === "Active"
- }
- leftIcon={<LuLoaderCircle />}
- type="submit"
- variant="secondary"
- >
- Reopen
- </Button>
- </statusFetcher.Form>
)}
+ {routeData?.quote?.status !== "Draft" &&
+ routeData?.quote?.status !== "Active" && (
+ <statusFetcher.Form
+ method="post"
+ action={path.to.supplierQuoteStatus(id)}
+ >
+ <input type="hidden" name="status" value="Draft" />
+ <Button
+ isDisabled={
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "purchasing")
+ }
+ isLoading={
+ statusFetcher.state !== "idle" &&
+ statusFetcher.formData?.get("status") === "Draft"
+ }
+ leftIcon={<LuLoaderCircle />}
+ type="submit"
+ variant="secondary"
+ >
+ Reopen
+ </Button>
+ </statusFetcher.Form>
+ )}
+
<IconButton
aria-label="Toggle Properties"
icon={<LuPanelRight />}
@@ -345,6 +292,16 @@ const SupplierQuoteHeader = () => {
fetcher={finalizeFetcher}
/>
)}
+ {sendModal.isOpen && (
+ <SupplierQuoteFinalizeModal
+ quote={routeData?.quote}
+ lines={routeData?.lines ?? []}
+ pricing={routeData?.prices ?? []}
+ onClose={sendModal.onClose}
+ fetcher={sendFetcher}
+ action={path.to.supplierQuoteSend(id)}
+ />
+ )}
<ShareQuoteModal
id={id}
externalLinkId={(routeData?.quote as any)?.externalLinkId}
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteStatus.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteStatus.tsx
index 71f84c9124..c05c823067 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteStatus.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteStatus.tsx
@@ -8,15 +8,13 @@ type SupplierQuoteStatusProps = {
const SupplierQuoteStatus = ({ status }: SupplierQuoteStatusProps) => {
switch (status) {
case "Active":
- case "Partial":
- case "Ordered":
return <Status color="green">{status}</Status>;
- case "Sent":
- case "Submitted":
- return <Status color="yellow">{status}</Status>;
- case "Declined":
+ case "Draft":
return <Status color="gray">{status}</Status>;
+ case "Declined":
+ return <Status color="orange">{status}</Status>;
case "Expired":
+ case "Cancelled":
return <Status color="red">{status}</Status>;
default:
return null;
diff --git a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
index ed47639a1b..6f49ec17e2 100644
--- a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
@@ -7,9 +7,7 @@ import {
externalSupplierQuoteValidator,
selectedLineSchema,
} from "~/modules/purchasing/purchasing.models";
-import {
- getSupplierQuoteByExternalId,
-} from "~/modules/purchasing/purchasing.service";
+import { getSupplierQuoteByExternalId } from "~/modules/purchasing/purchasing.service";
import { getCompanySettings } from "~/modules/settings";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -113,7 +111,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
try {
parsedData = JSON.parse(selectedLinesRaw);
} catch (e) {
- return json({ success: false, message: "Invalid JSON in selected lines data" });
+ return json({
+ success: false,
+ message: "Invalid JSON in selected lines data",
+ });
}
// selectedLines is Record<string, Record<number, SelectedLine>>
@@ -143,7 +144,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
for (const [lineId, lineSelections] of Object.entries(selectedLines)) {
// lineSelections is Record<number, SelectedLine>
- for (const [quantityStr, selectedLine] of Object.entries(lineSelections)) {
+ for (const [quantityStr, selectedLine] of Object.entries(
+ lineSelections
+ )) {
const quantity = Number(quantityStr);
// Only process if quantity > 0 (line is selected)
@@ -183,10 +186,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
serviceRole
.from("supplierQuoteLinePrice")
.update({
- supplierUnitPrice: selectedLine.supplierUnitPrice,
- leadTime: selectedLine.leadTime,
- supplierShippingCost: selectedLine.supplierShippingCost,
- supplierTaxAmount: selectedLine.supplierTaxAmount,
+ supplierUnitPrice: selectedLine.supplierUnitPrice ?? 0,
+ leadTime: selectedLine.leadTime ?? 0,
+ supplierShippingCost: selectedLine.supplierShippingCost ?? 0,
+ supplierTaxAmount: selectedLine.supplierTaxAmount ?? 0,
updatedAt: new Date().toISOString(),
updatedBy: quote.data.createdBy,
})
@@ -199,10 +202,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
supplierQuoteId: quote.data.id,
supplierQuoteLineId: lineId,
quantity: quantity,
- supplierUnitPrice: selectedLine.supplierUnitPrice,
- leadTime: selectedLine.leadTime,
- supplierShippingCost: selectedLine.supplierShippingCost,
- supplierTaxAmount: selectedLine.supplierTaxAmount,
+ supplierUnitPrice: selectedLine.supplierUnitPrice ?? 0,
+ leadTime: selectedLine.leadTime ?? 0,
+ supplierShippingCost: selectedLine.supplierShippingCost ?? 0,
+ supplierTaxAmount: selectedLine.supplierTaxAmount ?? 0,
exchangeRate: quote.data.exchangeRate ?? 1,
createdBy: quote.data.createdBy,
});
@@ -219,11 +222,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const now = new Date().toISOString();
- // Update quote status to Submitted
+ // Update quote status to Active (submit moves from Draft to Active)
await serviceRole
.from("supplierQuote")
.update({
- status: "Submitted",
+ status: "Active",
updatedAt: now,
externalNotes: {
...((quote.data.externalNotes as Record<string, unknown>) || {}),
diff --git a/apps/erp/app/routes/share+/supplier-quote.$id.tsx b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
index 1a688ccc34..0c118fb240 100644
--- a/apps/erp/app/routes/share+/supplier-quote.$id.tsx
+++ b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
@@ -112,7 +112,7 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
if (
quote.data.expirationDate &&
new Date(quote.data.expirationDate) < new Date() &&
- quote.data.status === "Sent"
+ quote.data.status === "Draft"
) {
return json({
state: QuoteState.Expired,
@@ -201,8 +201,8 @@ const Header = ({ company, quote }: { company: any; quote: any }) => (
</div>
<span className="text-base font-semibold text-blue-900 dark:text-blue-100">
- Please fill the columns marked with the <EditableBadge /> icon to update
- pricing
+ Please fill the columns marked with the <EditableBadge /> icon to
+ provide pricing
</span>
</VStack>
</CardHeader>
@@ -274,31 +274,30 @@ const LineItems = ({
<HStack spacing={4}>
{(() => {
const lineSelections = selectedLines[line.id!] || {};
- const total = Object.values(lineSelections).reduce(
- (acc, sel) => {
- if (sel.quantity > 0) {
- return (
- acc +
- sel.supplierUnitPrice * sel.quantity +
- sel.supplierShippingCost +
- sel.supplierTaxAmount
- );
- }
- return acc;
- },
- 0
- );
- return total > 0 ? (
- <MotionNumber
- className="font-bold text-xl"
- value={total}
- format={{
- style: "currency",
- currency: currencyCode,
- }}
- locales={locale}
- />
- ) : null;
+ const selectedCount =
+ Object.keys(lineSelections).length;
+ // Only show sum if there's a single quantity selected
+ if (selectedCount === 1) {
+ const sel = Object.values(lineSelections)[0];
+ if (sel && sel.quantity > 0) {
+ const total =
+ sel.supplierUnitPrice * sel.quantity +
+ sel.supplierShippingCost +
+ sel.supplierTaxAmount;
+ return total > 0 ? (
+ <MotionNumber
+ className="font-bold text-xl"
+ value={total}
+ format={{
+ style: "currency",
+ currency: currencyCode,
+ }}
+ locales={locale}
+ />
+ ) : null;
+ }
+ }
+ return null;
})()}
<motion.div
animate={{
@@ -503,7 +502,7 @@ const LinePricing = ({
storedPricing?.supplierTaxAmount ??
pricing?.supplierTaxAmount ??
0,
- },
+ } as SelectedLine,
},
}));
} else {
@@ -591,112 +590,99 @@ const LinePricing = ({
{qty}
</label>
</Td>
- {!isSelected ? (
- <Td
- colSpan={6}
- className="bg-muted/20 text-center text-muted-foreground"
+ <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);
+ }
+ }}
>
- No item selected
- </Td>
- ) : (
- <>
- <Td className=" bg-muted/30">{qty}</Td>
- <Td className="">
- <NumberField
- value={unitPrice}
- formatOptions={{
- style: "currency",
- currency: currencyCode,
- }}
- isDisabled={isDisabled}
- 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}
- 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}
- 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}
- 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 className="w-[150px] bg-muted/30">
- {total > 0 ? formatter.format(total) : "—"}
- </Td>
- </>
- )}
+ <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 className="w-[150px] bg-muted/30">
+ {isSelected && total > 0 ? formatter.format(total) : "—"}
+ </Td>
</Tr>
);
})}
@@ -716,7 +702,7 @@ const Quote = ({
quoteLinePrices: SupplierQuoteLinePrice[];
};
}) => {
- const { company, quote, quoteLines, quoteLinePrices } = data;
+ const { company, quote, quoteLinePrices } = data;
const { locale } = useLocale();
const { id } = useParams();
if (!id) throw new Error("Could not find external quote id");
@@ -736,53 +722,11 @@ const Quote = ({
}
}, [fetcher.state, submitModal, declineModal]);
- // Initialize selected lines from loaded prices - select all quantities by default
+ // Initialize selected lines - don't select by default
const [selectedLines, setSelectedLines] = useState<
Record<string, Record<number, SelectedLine>>
>(() => {
- return (
- quoteLines?.reduce<Record<string, Record<number, SelectedLine>>>(
- (acc, line: SupplierQuoteLine) => {
- if (!line.id) {
- return acc;
- }
-
- // Get all quantities for this line
- const quantities =
- Array.isArray(line.quantity) && line.quantity.length > 0
- ? line.quantity
- : quoteLinePrices
- ?.filter(
- (p: SupplierQuoteLinePrice) =>
- p.supplierQuoteLineId === line.id
- )
- .map((p) => p.quantity) ?? [1];
-
- // Select all quantities by default
- const lineSelections: Record<number, SelectedLine> = {};
- quantities.forEach((qty) => {
- const price = quoteLinePrices?.find(
- (p: SupplierQuoteLinePrice) =>
- p.supplierQuoteLineId === line.id && p.quantity === qty
- );
-
- lineSelections[qty] = {
- quantity: qty,
- supplierUnitPrice: price?.supplierUnitPrice ?? 0,
- unitPrice: price?.unitPrice ?? 0,
- leadTime: price?.leadTime ?? 0,
- shippingCost: price?.shippingCost ?? 0,
- supplierShippingCost: price?.supplierShippingCost ?? 0,
- supplierTaxAmount: price?.supplierTaxAmount ?? 0,
- };
- });
-
- acc[line.id] = lineSelections;
- return acc;
- },
- {}
- ) ?? {}
- );
+ return {};
});
// Calculate grand total for display (all selected quantities across all lines)
@@ -815,22 +759,8 @@ const Quote = ({
)}
<Card className="w-full max-w-5xl mx-auto">
<div className="w-full text-center">
- {quote?.status !== "Sent" && quote?.status && (
- <Status
- color={
- quote.status === "Expired" || quote.status === "Cancelled"
- ? "orange"
- : quote.status === "Declined"
- ? "red"
- : quote.status === "Ordered" ||
- quote.status === "Partial" ||
- quote.status === "Submitted"
- ? "green"
- : quote.status === "Active"
- ? "blue"
- : "gray"
- }
- >
+ {quote?.status && (quote?.status as string) !== "Draft" && (
+ <Status color={quote.status === "Active" ? "green" : "gray"}>
{quote.status}
</Status>
)}
@@ -846,7 +776,7 @@ const Quote = ({
quoteLinePrices={quoteLinePrices}
/>
- <div className="mt-8 border-t pt-4">
+ {/* <div className="mt-8 border-t pt-4">
<HStack className="justify-between text-xl font-bold w-full">
<span>Estimated Total:</span>
<MotionNumber
@@ -858,10 +788,10 @@ const Quote = ({
locales={locale}
/>
</HStack>
- </div>
+ </div> */}
<div className="flex flex-col gap-2">
- {quote?.status === "Sent" && (
+ {(quote?.status as string) === "Draft" && (
<VStack className="w-full mt-8 gap-4">
<Button
onClick={submitModal.onOpen}
@@ -871,7 +801,7 @@ const Quote = ({
className="w-full text-lg"
>
Submit Quote
- </Button>{" "}
+ </Button>
<Button
onClick={declineModal.onOpen}
size="lg"
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
index 62b30fa283..82fc8042bd 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
@@ -3,13 +3,14 @@ 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 { getLocalTimeZone, now } from "@internationalized/date";
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";
@@ -38,6 +39,7 @@ export async function action(args: ActionFunctionArgs) {
);
}
+ // Reuse existing external link or create one if it doesn't exist
const [externalLink] = await Promise.all([
upsertExternalLink(client, {
id: quote.data.externalLinkId ?? undefined,
@@ -54,11 +56,86 @@ export async function action(args: ActionFunctionArgs) {
.from("supplierQuote")
.update({
externalLinkId: externalLink.data.id,
- completedDate: now(getLocalTimeZone()).toAbsoluteString(),
})
.eq("id", id);
}
+ // Validate that all quantities have price and lead time
+ const [quoteLines, quoteLinePrices] = await Promise.all([
+ getSupplierQuoteLines(client, id),
+ getSupplierQuoteLinePricesByQuoteId(client, id),
+ ]);
+
+ if (quoteLines.error) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(
+ request,
+ error(quoteLines.error, "Failed to get supplier quote lines")
+ )
+ );
+ }
+
+ if (quoteLinePrices.error) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(
+ request,
+ error(quoteLinePrices.error, "Failed to get supplier quote line prices")
+ )
+ );
+ }
+
+ // Check that each line has at least one quantity with price and lead time
+ 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) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(
+ request,
+ error(
+ null,
+ `Line ${line.itemReadableId} must have at least one quantity with price and lead time`
+ )
+ )
+ );
+ }
+
+ 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
// TODO: Add document creation for supplier quotes when PDF is available
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
new file mode 100644
index 0000000000..af978fbd3b
--- /dev/null
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
@@ -0,0 +1,163 @@
+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 {
+ getSupplierContact,
+ getSupplierQuote,
+ sendSupplierQuote,
+ 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) {
+ const { request, params } = args;
+ assertIsPost(request);
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ role: "employee",
+ bypassRls: true,
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find supplier quote id");
+
+ const [quote] = await Promise.all([getSupplierQuote(client, id)]);
+ if (quote.error) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(request, error(quote.error, "Failed to get supplier quote"))
+ );
+ }
+
+ // Reuse existing external link or create one if it doesn't exist
+ const [externalLink] = await Promise.all([
+ upsertExternalLink(client, {
+ id: quote.data.externalLinkId ?? undefined,
+ documentType: "SupplierQuote",
+ documentId: id,
+ supplierId: quote.data.supplierId,
+ expiresAt: quote.data.expirationDate,
+ companyId,
+ }),
+ ]);
+
+ if (externalLink.data && quote.data.externalLinkId !== externalLink.data.id) {
+ await client
+ .from("supplierQuote")
+ .update({
+ externalLinkId: externalLink.data.id,
+ })
+ .eq("id", id);
+ }
+
+ // Send keeps status as Draft
+ try {
+ const send = await sendSupplierQuote(client, id, userId);
+ if (send.error) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(request, error(send.error, "Failed to send supplier quote"))
+ );
+ }
+ } catch (err) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(request, error(err, "Failed to send supplier quote"))
+ );
+ }
+
+ 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");
+
+ 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 = `
+ Hi ${supplierContact.data.contact.firstName ?? ""},
+
+ Please review the supplier quote ${
+ supplierQuote.data.supplierQuoteId
+ }.
+
+ You can view and respond to this quote at: ${externalQuoteUrl}
+
+ ${
+ quote.data.expirationDate
+ ? `This quote expires on ${quote.data.expirationDate}.`
+ : ""
+ }
+
+ Best regards,
+ ${user.data.firstName} ${user.data.lastName}
+ `;
+
+ await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
+ to: [user.data.email, supplierContact.data.contact.email],
+ from: user.data.email,
+ subject: emailSubject,
+ html: emailBody.replace(/\n/g, "<br>"),
+ text: emailBody,
+ 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 sent successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/supplier-quote+/new.tsx b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
index b428af415b..004fb25b46 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/new.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
@@ -91,7 +91,7 @@ export default function SupplierQuoteNewRoute() {
expirationDate: "",
quotedDate: today(getLocalTimeZone()).toString(),
supplierQuoteId: undefined,
- status: "Active" as const,
+ status: "Draft" as const,
currencyCode: company.baseCurrencyCode,
exchangeRate: undefined,
exchangeRateUpdatedAt: "",
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 4569b8376f..3cedd79b3a 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1390,6 +1390,8 @@ export const path = {
generatePath(`${x}/supplier-quote/${id}/${lineId}/details`),
supplierQuoteFinalize: (id: string) =>
generatePath(`${x}/supplier-quote/${id}/finalize`),
+ supplierQuoteSend: (id: string) =>
+ generatePath(`${x}/supplier-quote/${id}/send`),
supplierQuoteStatus: (id: string) =>
generatePath(`${x}/supplier-quote/${id}/status`),
supplierRoot: `${x}/supplier`,
diff --git a/packages/database/supabase/migrations/20251127000000_supplier_quote_updates.sql b/packages/database/supabase/migrations/20251127000000_supplier_quote_updates.sql
index d6355da1e4..f9f2441219 100644
--- a/packages/database/supabase/migrations/20251127000000_supplier_quote_updates.sql
+++ b/packages/database/supabase/migrations/20251127000000_supplier_quote_updates.sql
@@ -1,10 +1,7 @@
-- Add new status values to supplierQuoteStatus enum
-ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Sent';
-ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Ordered';
-ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Partial';
+ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Draft';
ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Declined';
ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Cancelled';
-ALTER TYPE "supplierQuoteStatus" ADD VALUE IF NOT EXISTS 'Submitted';
-- Add externalLinkId column to supplierQuote table