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: convert rfq to quote

Brad Barbinf1db89461a39
diff --git a/apps/carbon/app/components/SortableList.tsx b/apps/carbon/app/components/SortableList.tsx
index a34a3bc0e3..18859541f6 100644
--- a/apps/carbon/app/components/SortableList.tsx
+++ b/apps/carbon/app/components/SortableList.tsx
@@ -1,6 +1,6 @@
"use client";
-import { LayoutGroup, Reorder, useDragControls } from "framer-motion";
+import { LayoutGroup, Reorder, motion, useDragControls } from "framer-motion";
import type { ReactNode } from "react";
import { useState } from "react";
@@ -91,7 +91,10 @@ function SortableListItem<T>({
whileDrag={{ zIndex: 9999 }}
>
<div className={cn(isExpanded ? "w-full" : "", "z-20 ")}>
- <div className="grid items-center justify-between grid-cols-[1fr_auto] w-full gap-2 py-1">
+ <motion.div
+ className="grid items-center justify-between grid-cols-[1fr_auto] w-full gap-2 py-1"
+ layout="position"
+ >
{!isExpanded ? (
<div className="flex w-full items-center gap-x-2 truncate">
{/* List Remove Actions */}
@@ -138,7 +141,7 @@ function SortableListItem<T>({
{/* List Item Children */}
{renderExtra && renderExtra(item)}
- </div>
+ </motion.div>
</div>
<div
onPointerDown={isDraggable ? handleDragStart : undefined}
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
index 0bbaa120f4..ac22b8ecab 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
@@ -4,7 +4,13 @@ import { Link, useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { LuPencil } from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import {
+ EmployeeAvatar,
+ Hyperlink,
+ New,
+ SupplierAvatar,
+ Table,
+} from "~/components";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type {
@@ -36,7 +42,7 @@ const SuppliersTable = memo(
header: "Name",
cell: ({ row }) => (
<Hyperlink to={path.to.supplierDetails(row.original.id!)}>
- {row.original.name}
+ <SupplierAvatar supplierId={row.original.id!} />
</Hyperlink>
),
},
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 9f9b7b59b0..561eceeb44 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -434,8 +434,8 @@ export const salesRfqValidator = z.object({
export const salesRfqLineValidator = z.object({
id: z.string().min(1, { message: "ID is required" }),
salesRfqId: z.string().min(20, { message: "RFQ is required" }),
- customerPartNumber: z.string().min(1, { message: "Part Number is required" }),
- customerRevisionId: zfd.text(z.string().optional()),
+ customerPartId: z.string().min(1, { message: "Part Number is required" }),
+ customerPartRevision: zfd.text(z.string().optional()),
itemId: zfd.text(z.string().optional()),
description: zfd.text(z.string().optional()),
quantity: z.array(
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 8574aff467..c39394bb10 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -27,6 +27,7 @@ import type {
salesOrderShipmentValidator,
salesOrderValidator,
salesRfqLineValidator,
+ salesRFQStatusType,
salesRfqValidator,
} from "./sales.models";
@@ -47,6 +48,22 @@ export async function closeSalesOrder(
.single();
}
+export async function convertSalesRfqToQuote(
+ client: SupabaseClient<Database>,
+ payload: {
+ id: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("convert", {
+ body: {
+ type: "salesRfqToQuote",
+ ...payload,
+ },
+ });
+}
+
export async function convertQuoteToOrder(
client: SupabaseClient<Database>,
quoteId: string,
@@ -1261,6 +1278,18 @@ export async function updateQuoteFavorite(
}
}
+export async function updateSalesRFQStatus(
+ client: SupabaseClient<Database>,
+ update: {
+ id: string;
+ status: (typeof salesRFQStatusType)[number];
+ assignee: null | undefined;
+ updatedBy: string;
+ }
+) {
+ return client.from("salesRfq").update(update).eq("id", update.id);
+}
+
export async function updateQuoteMaterialOrder(
client: SupabaseClient<Database>,
updates: {
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index e21d76da71..ab6d765639 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -1,5 +1,9 @@
import type { Database } from "@carbon/database";
+import type { JSONContent } from "@carbon/react";
+import type { z } from "zod";
+import type { ModelUpload } from "../items/types";
import type { QuantityEffect } from "../shared";
+import type { salesRfqLineValidator } from "./sales.models";
import type {
getCustomer,
getCustomerContacts,
@@ -131,4 +135,9 @@ export type SalesRFQ = NonNullable<
Awaited<ReturnType<typeof getSalesRFQs>>["data"]
>[number];
+export type SalesRFQLine = z.infer<typeof salesRfqLineValidator> & {
+ internalNotes: JSONContent;
+ externalNotes: JSONContent;
+} & ModelUpload;
+
export type SalesRFQStatus = Database["public"]["Enums"]["salesRfqStatus"];
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
index 1a926c07f2..d929f2a9cb 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
@@ -4,7 +4,13 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { LuPencil } from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import {
+ CustomerAvatar,
+ EmployeeAvatar,
+ Hyperlink,
+ New,
+ Table,
+} from "~/components";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { Customer, CustomerStatus, CustomerType } from "~/modules/sales";
@@ -32,7 +38,7 @@ const CustomersTable = memo(
header: "Name",
cell: ({ row }) => (
<Hyperlink to={path.to.customerDetails(row.original.id!)}>
- {row.original.name}
+ <CustomerAvatar customerId={row.original.id!} />
</Hyperlink>
),
},
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 7f48be2f4d..0d8bc29170 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -15,6 +15,7 @@ import {
CustomFormFields,
Customer,
CustomerContact,
+ CustomerLocation,
DatePicker,
Employee,
Hidden,
@@ -77,6 +78,11 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
setCustomer(newValue?.value as string | undefined)
}
/>
+ <CustomerLocation
+ name="customerLocationId"
+ label="Customer Location"
+ customer={customer}
+ />
<CustomerContact
name="customerContactId"
label="Customer Contact"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
index 9325e4e1d3..3deed7edb0 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx
@@ -105,7 +105,7 @@ export function useLineCosts({
}
}
- data.operations?.forEach((operation) => {
+ data.operations?.forEach((operation: QuotationOperation) => {
if (operation.setupHours) {
// setupHours don't depend on quantity
effects.setupHours.push((quantity) => {
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
index 0d7869f2e5..9c1af54727 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
@@ -15,6 +15,7 @@ import {
CustomFormFields,
Customer,
CustomerContact,
+ CustomerLocation,
DatePicker,
Hidden,
Input,
@@ -38,6 +39,7 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
);
const isEditing = initialValues.id !== undefined;
const isCustomer = permissions.is("customer");
+ const isDraft = initialValues.status === "Draft";
const statusOptions = salesRFQStatusType.map((status) => ({
label: status,
@@ -77,6 +79,11 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
setCustomer(newValue?.value as string | undefined)
}
/>
+ <CustomerLocation
+ name="customerLocationId"
+ label="Customer Location"
+ customer={customer}
+ />
<Input name="customerReference" label="Customer Ref. Number" />
{isEditing && permissions.can("delete", "sales") && (
<Select
@@ -104,7 +111,7 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
label="Expiration Date"
isDisabled={isCustomer}
/>
- <Location name="locationId" label="Location" />
+ <Location name="locationId" label="RFQ Location" />
<CustomFormFields table="salesRfq" />
</div>
</VStack>
@@ -112,9 +119,10 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
<CardFooter>
<Submit
isDisabled={
- isEditing
+ !isDraft ||
+ (isEditing
? !permissions.can("update", "sales")
- : !permissions.can("create", "sales")
+ : !permissions.can("create", "sales"))
}
>
Save
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
index 827ad5f3bf..bc366d2384 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx
@@ -1,31 +1,236 @@
-import { Badge, HStack, Heading, VStack } from "@carbon/react";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Badge,
+ Button,
+ HStack,
+ Heading,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ useDisclosure,
+} from "@carbon/react";
-import { useParams } from "@remix-run/react";
-import { RiProgress2Line } from "react-icons/ri";
-import { useRouteData } from "~/hooks";
-import type { SalesRFQ } from "~/modules/sales";
+import { Form, Link, useFetcher, useParams } from "@remix-run/react";
+import { useEffect } from "react";
+import {
+ LuAlertTriangle,
+ LuRefreshCw,
+ LuSend,
+ LuXCircle,
+} from "react-icons/lu";
+import { RiProgress2Line, RiProgress4Line } from "react-icons/ri";
+import { Assignee, useOptimisticAssignment } from "~/components";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { SalesRFQ, SalesRFQLine } from "~/modules/sales";
import { path } from "~/utils/path";
const SalesRFQHeader = () => {
const { rfqId } = useParams();
if (!rfqId) throw new Error("rfqId not found");
- const routeData = useRouteData<{ rfqSummary: SalesRFQ }>(
- path.to.salesRfq(rfqId)
- );
+ const convertToQuoteModal = useDisclosure();
+ const permissions = usePermissions();
+
+ const routeData = useRouteData<{
+ rfqSummary: SalesRFQ;
+ lines: SalesRFQLine[];
+ }>(path.to.salesRfq(rfqId));
+
+ const optimisticAssignment = useOptimisticAssignment({
+ id: rfqId,
+ table: "salesRfq",
+ });
+ const assignee =
+ optimisticAssignment !== undefined
+ ? optimisticAssignment
+ : routeData?.rfqSummary?.assignee;
+
+ const status = routeData?.rfqSummary?.status ?? "Draft";
return (
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border">
- <VStack spacing={0} className="flex-grow">
+ <HStack className="w-full justify-between">
<HStack>
<Heading size="h2">{routeData?.rfqSummary?.rfqId}</Heading>
<Badge variant="secondary">
<RiProgress2Line />
</Badge>
</HStack>
- </VStack>
+ <HStack>
+ <Assignee
+ id={rfqId}
+ table="salesRfq"
+ value={assignee ?? ""}
+ className="h-8"
+ isReadOnly={!permissions.can("update", "sales")}
+ />
+
+ {status === "Draft" ? (
+ <>
+ <Form method="post" action={path.to.salesRfqStatus(rfqId)}>
+ <input type="hidden" name="status" value="Closed" />
+ <Button
+ isDisabled={
+ status !== "Draft" || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuXCircle />}
+ type="submit"
+ variant="destructive"
+ >
+ Close
+ </Button>
+ </Form>
+ <Button
+ isDisabled={
+ routeData?.lines?.length === 0 ||
+ !permissions.can("create", "sales")
+ }
+ leftIcon={<RiProgress4Line />}
+ type="submit"
+ variant="primary"
+ onClick={convertToQuoteModal.onOpen}
+ >
+ Quote
+ </Button>
+ </>
+ ) : status === "Ready for Quote" ? (
+ <Button
+ isDisabled={!routeData?.rfqSummary.quoteId}
+ leftIcon={<LuSend />}
+ variant="primary"
+ asChild
+ >
+ <Link
+ to={path.to.quoteDetails(routeData?.rfqSummary.quoteId!)}
+ prefetch="intent"
+ >
+ View Quote
+ </Link>
+ </Button>
+ ) : status === "Closed" ? (
+ <>
+ <Button isDisabled leftIcon={<LuXCircle />} variant="destructive">
+ Close
+ </Button>
+ <Form method="post" action={path.to.salesRfqStatus(rfqId)}>
+ <input type="hidden" name="status" value="Draft" />
+ <Button
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuRefreshCw />}
+ type="submit"
+ variant="secondary"
+ >
+ Reopen
+ </Button>
+ </Form>
+ </>
+ ) : null}
+
+ {/* <IconButton
+ aria-label="Previous"
+ icon={<LuMoveLeft />}
+ variant="secondary"
+ />
+ <IconButton
+ aria-label="Next"
+ icon={<LuMoveRight />}
+ variant="secondary"
+ /> */}
+ </HStack>
+ </HStack>
+ {convertToQuoteModal.isOpen && (
+ <ConvertToQuoteModal
+ lines={routeData?.lines ?? []}
+ rfqId={rfqId}
+ onClose={convertToQuoteModal.onClose}
+ />
+ )}
</div>
);
};
export default SalesRFQHeader;
+
+function ConvertToQuoteModal({
+ lines,
+ rfqId,
+ onClose,
+}: {
+ lines: SalesRFQLine[];
+ rfqId: string;
+ onClose: () => void;
+}) {
+ const fetcher = useFetcher<{ error: string | null }>();
+ const isLoading = fetcher.state !== "idle";
+ const linesWithoutItems = lines.filter((line) => !line.itemId);
+ const requiresPartNumbers = linesWithoutItems.length > 0;
+
+ useEffect(() => {
+ if (fetcher.state === "loading") {
+ onClose();
+ }
+ }, [fetcher.state, onClose]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Convert to Quote</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to convert the RFQ to a quote?
+ </ModalDescription>
+ </ModalHeader>
+
+ {requiresPartNumbers && (
+ <ModalBody>
+ <Alert variant="destructive">
+ <LuAlertTriangle className="h-4 w-4" />
+ <AlertTitle>Lines need internal part numbers</AlertTitle>
+ <AlertDescription>
+ In order to convert this RFQ to a quote, all lines must have an
+ internal part number.
+ <ul className="list-disc py-2 pl-4">
+ {linesWithoutItems.map((line) => (
+ <li key={line.id}>
+ {line.customerPartId}{" "}
+ {line.customerPartRevision &&
+ `Rev. ${line.customerPartRevision}`}
+ </li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ </ModalBody>
+ )}
+
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <fetcher.Form method="post" action={path.to.salesRfqConvert(rfqId)}>
+ <Button
+ isDisabled={isLoading || requiresPartNumbers}
+ type="submit"
+ isLoading={isLoading}
+ >
+ Convert
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
index 0cf68ef684..580049664e 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
@@ -10,23 +10,28 @@ import {
CardTitle,
Editor,
HStack,
+ Kbd,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
VStack,
cn,
generateHTML,
toast,
useDebounce,
+ useKeyboardShortcuts,
useMount,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
+import { prettifyKeyboardShortcut } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { useFetcher, useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { LuMove3D, LuPaperclip, LuSettings2, LuX } from "react-icons/lu";
-import type { z } from "zod";
import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";
import {
ArrayNumeric,
@@ -42,31 +47,26 @@ import type {
SortableItemRenderProps,
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
-import { usePermissions, useUser } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
-import type { ModelUpload } from "~/modules/items";
import { CadModel } from "~/modules/items";
import { path } from "~/utils/path";
import { salesRfqLineValidator } from "../../sales.models";
+import type { SalesRFQ, SalesRFQLine } from "../../types";
import SalesRFQLineDocuments from "./SalesRFQLineDocuments";
-type Line = z.infer<typeof salesRfqLineValidator> & {
- internalNotes: JSONContent;
- externalNotes: JSONContent;
-} & ModelUpload;
-
type ItemWithData = SortableItem & {
- data: Line;
+ data: SalesRFQLine;
files?: (FileObject & { salesRfqLineId: string | null })[];
};
type SalesRFQLinesProps = {
- lines: Line[];
+ lines: SalesRFQLine[];
files: (FileObject & { salesRfqLineId: string | null })[];
};
function makeItems(
- lines: Line[],
+ lines: SalesRFQLine[],
files: (FileObject & { salesRfqLineId: string | null })[]
): ItemWithData[] {
return lines.map((line) =>
@@ -80,7 +80,7 @@ function makeItems(
}
function makeItem(
- line: Line,
+ line: SalesRFQLine,
files?: (FileObject & { salesRfqLineId: string | null })[]
): ItemWithData {
return {
@@ -88,8 +88,10 @@ function makeItem(
title: (
<VStack spacing={0}>
<h4 className="font-mono">
- {line.customerPartNumber}{" "}
- {line.customerRevisionId && `(${line.customerRevisionId})`}
+ {line.customerPartId}{" "}
+ {line.customerPartRevision && (
+ <span className="text-muted-foreground">{`Rev. ${line.customerPartRevision}`}</span>
+ )}
</h4>
{line?.description && (
<span className="text-xs text-muted-foreground">
@@ -124,9 +126,9 @@ function makeItem(
};
}
-const initialLine: Omit<Line, "id" | "salesRfqId" | "order"> = {
- customerPartNumber: "",
- customerRevisionId: "",
+const initialLine: Omit<SalesRFQLine, "id" | "salesRfqId" | "order"> = {
+ customerPartId: "",
+ customerPartRevision: "",
itemId: "",
description: "",
quantity: [1],
@@ -154,18 +156,25 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
id: userId,
} = useUser();
+ const routeData = useRouteData<{ rfqSummary: SalesRFQ }>(
+ path.to.salesRfq(rfqId)
+ );
+ const isDraft = routeData?.rfqSummary.status === "Draft";
+
const [items, setItems] = useState<ItemWithData[]>(
makeItems(lines ?? [], files)
);
const [selectedLineId, setSelectedLineId] = useState<string | null>(null);
useEffect(() => {
- setItems(makeItems(lines, files));
+ const temporaryItem = items.find((item) => item.isTemporary);
+ const existingItems = makeItems(lines, files);
+ setItems([...existingItems, ...(temporaryItem ? [temporaryItem] : [])]);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [files]);
+ }, [files, selectedLineId]);
const onToggleItem = (id: string) => {
- if (permissions.can("delete", "sales")) {
+ if (permissions.can("delete", "sales") && isDraft) {
setItems((prevItems) =>
prevItems.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
@@ -209,6 +218,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
};
const onRemoveItem = async (id: string) => {
+ if (!permissions.can("delete", "sales") || !isDraft) return;
// get the item and it's order in the list
const itemIndex = items.findIndex((i) => i.id === id);
const item = items[itemIndex];
@@ -359,6 +369,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
item={item}
setItems={setItems}
setSelectedLineId={setSelectedLineId}
+ isDraft={isDraft}
/>
</motion.div>
</div>
@@ -387,6 +398,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
salesRfqLineId: item.id,
}}
modelPath={item.data.modelPath ?? null}
+ viewerClassName="min-h-[520px]"
uploadClassName="min-h-[300px]"
/>
</motion.div>
@@ -496,7 +508,7 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
];
return (
- <SortableListItem<Line>
+ <SortableListItem<SalesRFQLine>
item={item}
items={items}
order={order}
@@ -606,6 +618,14 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
);
};
+ const newLineRef = useRef<HTMLButtonElement>(null);
+ useKeyboardShortcuts({
+ "Command+Shift+l": (event: KeyboardEvent) => {
+ event.stopPropagation();
+ newLineRef.current?.click();
+ },
+ });
+
return (
<Card>
<HStack className="justify-between">
@@ -614,15 +634,25 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
</CardHeader>
<CardAction>
- <Button
- variant="secondary"
- isDisabled={
- !permissions.can("update", "sales") || selectedLineId !== null
- }
- onClick={onAddItem}
- >
- Add Line
- </Button>
+ <Tooltip>
+ <TooltipTrigger className="w-full">
+ <Button
+ ref={newLineRef}
+ variant="secondary"
+ isDisabled={
+ !isDraft ||
+ !permissions.can("update", "sales") ||
+ selectedLineId !== null
+ }
+ onClick={onAddItem}
+ >
+ Add Line
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <Kbd>{prettifyKeyboardShortcut("Command+Shift+l")}</Kbd>
+ </TooltipContent>
+ </Tooltip>
</CardAction>
</HStack>
<CardContent>
@@ -644,10 +674,12 @@ function SalesRFQLineForm({
item,
setItems,
setSelectedLineId,
+ isDraft,
}: {
item: ItemWithData;
setItems: Dispatch<SetStateAction<ItemWithData[]>>;
setSelectedLineId: Dispatch<SetStateAction<string | null>>;
+ isDraft: boolean;
}) {
const { supabase } = useSupabase();
const salesRfqLineFetcher = useFetcher<{ id: string }>();
@@ -722,6 +754,7 @@ function SalesRFQLineForm({
className="w-full"
fetcher={salesRfqLineFetcher}
onSubmit={(values) => {
+ setSelectedLineId(null);
setItems((prevItems) =>
prevItems.map((i) =>
i.id === item.id
@@ -749,11 +782,11 @@ function SalesRFQLineForm({
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<div className="col-span-2 grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-2 auto-rows-min">
<Input
- name="customerPartNumber"
+ name="customerPartId"
label="Customer Part Number"
autoFocus
/>
- <Input name="customerRevisionId" label="Customer Revision" />
+ <Input name="customerPartRevision" label="Customer Revision" />
<Item
name="itemId"
label="Part"
@@ -800,7 +833,9 @@ function SalesRFQLineForm({
}}
>
<motion.div layout className="ml-auto mr-1 pt-2">
- <Submit disabled={!permissions.can("update", "sales")}>Save</Submit>
+ <Submit disabled={!isDraft || !permissions.can("update", "sales")}>
+ Save
+ </Submit>
</motion.div>
</motion.div>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQStatus.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQStatus.tsx
index aab2e0a211..232e422fef 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQStatus.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQStatus.tsx
@@ -12,7 +12,7 @@ const SalesRFQStatus = ({ status }: SalesRFQStatusProps) => {
case "Ready for Quote":
return <Status color="green">{status}</Status>;
case "Closed":
- return <Status color="blue">{status}</Status>;
+ return <Status color="red">{status}</Status>;
default:
return null;
}
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
index 064ec73866..2c4951921b 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQs/SalesRFQsTable.tsx
@@ -175,7 +175,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
id: "createdBy",
header: "Created By",
cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.employeeId} />
+ <EmployeeAvatar employeeId={row.original.createdBy} />
),
meta: {
filter: {
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index c3e0c24099..94be927b73 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -51,7 +51,7 @@ export async function loader({ request }: ActionFunctionArgs) {
});
}
- return { company: company.data };
+ return json({ company: company.data });
}
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
new file mode 100644
index 0000000000..59ec502149
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
@@ -0,0 +1,38 @@
+import { type ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "remix-typedjson";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { convertSalesRfqToQuote } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+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({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { rfqId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const serviceRole = getSupabaseServiceRole();
+ const convert = await convertSalesRfqToQuote(serviceRole, {
+ id,
+ companyId,
+ userId,
+ });
+
+ if (convert.error) {
+ throw redirect(
+ path.to.salesRfq(id),
+ await flash(request, error(convert.error, "Failed to convert RFQ"))
+ );
+ }
+
+ throw redirect(
+ path.to.salesRfq(id),
+ await flash(request, success("Successfully converted RFQ to quote"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index 1a99501eef..9580be9af6 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -1,16 +1,14 @@
-import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import { validationError, validator } from "@carbon/remix-validated-form";
import { parseDate } from "@internationalized/date";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
-import { json, redirect } from "@remix-run/node";
-import { useLoaderData, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import { useRouteData } from "~/hooks";
-import type { SalesRFQ, SalesRFQStatus } from "~/modules/sales";
+import type { SalesRFQ, SalesRFQLine, SalesRFQStatus } from "~/modules/sales";
import {
SalesRFQForm,
- getSalesRFQLines,
salesRfqValidator,
upsertSalesRFQ,
} from "~/modules/sales";
@@ -22,38 +20,6 @@ import { assertIsPost } from "~/utils/http";
import { path } from "~/utils/path";
import { error, success } from "~/utils/result";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "sales",
- });
-
- const { rfqId } = params;
- if (!rfqId) throw new Error("Could not find rfqId");
-
- const lines = await getSalesRFQLines(client, rfqId);
- if (lines.error) {
- throw redirect(
- path.to.salesRfqs,
- await flash(request, error(lines.error, "Failed to load RFQ lines"))
- );
- }
-
- return json({
- lines: lines.data.map((line) => ({
- ...line,
- id: line.id ?? "",
- order: line.order ?? 0,
- unitOfMeasureCode: line.unitOfMeasureCode ?? "",
- customerRevisionId: line.customerRevisionId ?? "",
- description: line.description ?? "",
- externalNotes: (line.externalNotes ?? {}) as JSONContent,
- internalNotes: (line.internalNotes ?? {}) as JSONContent,
- itemId: line.itemId ?? "",
- quantity: line.quantity ?? [1],
- })) ?? [1],
- });
-}
-
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, userId } = await requirePermissions(request, {
@@ -97,10 +63,9 @@ export default function SalesRFQDetailsRoute() {
const { rfqId } = useParams();
if (!rfqId) throw new Error("Could not find rfqId");
- const { lines } = useLoaderData<typeof loader>();
-
const rfqData = useRouteData<{
rfqSummary: SalesRFQ;
+ lines: SalesRFQLine[];
files: (FileObject & { salesRfqLineId: string | null })[];
}>(path.to.salesRfq(rfqId));
@@ -125,10 +90,13 @@ export default function SalesRFQDetailsRoute() {
return (
<VStack spacing={2} className="p-2">
- <SalesRFQForm key={initialValues.id} initialValues={initialValues} />
+ <SalesRFQForm
+ key={`${initialValues.id}:${initialValues.status}`}
+ initialValues={initialValues}
+ />
<SalesRFQLines
- // @ts-ignore
- lines={lines}
+ key={initialValues.id}
+ lines={rfqData?.lines ?? []}
files={rfqData?.files ?? []}
/>
</VStack>
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.status.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.status.tsx
new file mode 100644
index 0000000000..17f1f30450
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.status.tsx
@@ -0,0 +1,46 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "remix-typedjson";
+import { salesRFQStatusType, updateSalesRFQStatus } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+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({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { rfqId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get("status") as (typeof salesRFQStatusType)[number];
+
+ if (!status || !salesRFQStatusType.includes(status)) {
+ throw redirect(
+ path.to.salesRfq(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await updateSalesRFQStatus(client, {
+ id,
+ status,
+ assignee: status === "Closed" ? null : undefined,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ path.to.salesRfq(id),
+ await flash(request, error(update.error, "Failed to update RFQ"))
+ );
+ }
+
+ throw redirect(
+ path.to.salesRfq(id),
+ await flash(request, success("Updated RFQ"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
index 5fea4f4db5..bf42f30912 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -1,3 +1,4 @@
+import type { JSONContent } from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
@@ -6,6 +7,7 @@ import {
SalesRFQProperties,
getFilesByRfqId,
getSalesRFQ,
+ getSalesRFQLines,
} from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -26,14 +28,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { rfqId } = params;
if (!rfqId) throw new Error("Could not find rfqId");
- const [rfqSummary, files] = await Promise.all([
+ const [rfqSummary, lines, files] = await Promise.all([
getSalesRFQ(client, rfqId),
+ getSalesRFQLines(client, rfqId),
getFilesByRfqId(client, rfqId, companyId),
]);
if (rfqSummary.error) {
throw redirect(
- path.to.sales,
+ path.to.salesRfqs,
await flash(
request,
error(rfqSummary.error, "Failed to load part summary")
@@ -41,8 +44,29 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ if (lines.error) {
+ throw redirect(
+ path.to.salesRfqs,
+ await flash(request, error(lines.error, "Failed to load RFQ lines"))
+ );
+ }
+
return json({
rfqSummary: rfqSummary.data,
+ lines:
+ lines.data.map((line) => ({
+ ...line,
+ id: line.id ?? "",
+ order: line.order ?? 0,
+ unitOfMeasureCode: line.unitOfMeasureCode ?? "",
+ customerPartId: line.customerPartId ?? "",
+ customerPartRevision: line.customerPartRevision ?? "",
+ description: line.description ?? "",
+ externalNotes: (line.externalNotes ?? {}) as JSONContent,
+ internalNotes: (line.internalNotes ?? {}) as JSONContent,
+ itemId: line.itemId ?? "",
+ quantity: line.quantity ?? [1],
+ })) ?? [],
files: files.data?.files ?? [],
});
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index d119a2f584..bb5c67625a 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -629,8 +629,9 @@ export const path = {
salesOrderRelease: (id: string) =>
generatePath(`${x}/sales-order/${id}/release`),
salesOrders: `${x}/sales/orders`,
- salesRfqRoot: `${x}/sales-rfq`,
salesRfq: (id: string) => generatePath(`${x}/sales-rfq/${id}`),
+ salesRfqConvert: (id: string) =>
+ generatePath(`${x}/sales-rfq/${id}/convert`),
salesRfqDetails: (id: string) =>
generatePath(`${x}/sales-rfq/${id}/details`),
salesRfqFavorite: `${x}/sales/rfqs/favorite`,
@@ -638,6 +639,8 @@ export const path = {
generatePath(`${x}/sales-rfq/${id}/lines/${lineId}`),
salesRfqLinesOrder: (id: string) =>
generatePath(`${x}/sales-rfq/${id}/lines/order`),
+ salesRfqRoot: `${x}/sales-rfq`,
+ salesRfqStatus: (id: string) => generatePath(`${x}/sales-rfq/${id}/status`),
salesRfqs: `${x}/sales/rfqs`,
scheduling: `${x}/scheduling`,
service: (id: string) => generatePath(`${x}/service/${id}`),
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 4423a7c5dc..a90cd1d59e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3401,6 +3401,94 @@ export type Database = {
},
]
}
+ customerPartToItem: {
+ Row: {
+ companyId: string
+ customerId: string
+ customerPartId: string
+ customerPartRevision: string
+ itemId: string
+ }
+ Insert: {
+ companyId: string
+ customerId: string
+ customerPartId: string
+ customerPartRevision: string
+ itemId: string
+ }
+ Update: {
+ companyId?: string
+ customerId?: string
+ customerPartId?: string
+ customerPartRevision?: string
+ itemId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customer"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderCustomers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ ]
+ }
customerPayment: {
Row: {
companyId: string
@@ -15500,6 +15588,7 @@ export type Database = {
createdBy: string | null
customerContactId: string | null
customerId: string
+ customerLocationId: string | null
customerReference: string | null
customFields: Json | null
employeeId: string | null
@@ -15522,6 +15611,7 @@ export type Database = {
createdBy?: string | null
customerContactId?: string | null
customerId: string
+ customerLocationId?: string | null
customerReference?: string | null
customFields?: Json | null
employeeId?: string | null
@@ -15544,6 +15634,7 @@ export type Database = {
createdBy?: string | null
customerContactId?: string | null
customerId?: string
+ customerLocationId?: string | null
customerReference?: string | null
customFields?: Json | null
employeeId?: string | null
@@ -15686,6 +15777,13 @@ export type Database = {
referencedRelation: "salesOrderCustomers"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfq_customerLocationId_fkey"
+ columns: ["customerLocationId"]
+ isOneToOne: false
+ referencedRelation: "customerLocation"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_employeeId_fkey"
columns: ["employeeId"]
@@ -15856,8 +15954,8 @@ export type Database = {
companyId: string
createdAt: string | null
createdBy: string
- customerPartNumber: string
- customerRevisionId: string | null
+ customerPartId: string
+ customerPartRevision: string | null
customFields: Json | null
description: string | null
externalNotes: Json | null
@@ -15876,8 +15974,8 @@ export type Database = {
companyId: string
createdAt?: string | null
createdBy: string
- customerPartNumber: string
- customerRevisionId?: string | null
+ customerPartId: string
+ customerPartRevision?: string | null
customFields?: Json | null
description?: string | null
externalNotes?: Json | null
@@ -15896,8 +15994,8 @@ export type Database = {
companyId?: string
createdAt?: string | null
createdBy?: string
- customerPartNumber?: string
- customerRevisionId?: string | null
+ customerPartId?: string
+ customerPartRevision?: string | null
customFields?: Json | null
description?: string | null
externalNotes?: Json | null
@@ -16048,6 +16146,88 @@ export type Database = {
},
]
}
+ salesRfqToQuote: {
+ Row: {
+ companyId: string
+ quoteId: string
+ salesRfqId: string
+ }
+ Insert: {
+ companyId: string
+ quoteId: string
+ salesRfqId: string
+ }
+ Update: {
+ companyId?: string
+ quoteId?: string
+ salesRfqId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
search: {
Row: {
companyId: string | null
@@ -24547,8 +24727,8 @@ export type Database = {
companyId: string | null
createdAt: string | null
createdBy: string | null
- customerPartNumber: string | null
- customerRevisionId: string | null
+ customerPartId: string | null
+ customerPartRevision: string | null
customFields: Json | null
description: string | null
externalNotes: Json | null
@@ -24556,6 +24736,9 @@ export type Database = {
internalNotes: Json | null
itemId: string | null
itemName: string | null
+ itemReadableId: string | null
+ itemType: Database["public"]["Enums"]["itemType"] | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
modelId: string | null
modelName: string | null
modelPath: string | null
@@ -24713,6 +24896,7 @@ export type Database = {
createdBy: string | null
customerContactId: string | null
customerId: string | null
+ customerLocationId: string | null
customerReference: string | null
customFields: Json | null
employeeId: string | null
@@ -24723,6 +24907,7 @@ export type Database = {
internalNotes: string | null
locationId: string | null
locationName: string | null
+ quoteId: string | null
revisionId: number | null
rfqDate: string | null
rfqId: string | null
@@ -24857,6 +25042,13 @@ export type Database = {
referencedRelation: "salesOrderCustomers"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfq_customerLocationId_fkey"
+ columns: ["customerLocationId"]
+ isOneToOne: false
+ referencedRelation: "customerLocation"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_employeeId_fkey"
columns: ["employeeId"]
@@ -24955,6 +25147,27 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
]
}
services: {
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
new file mode 100644
index 0000000000..374cf1bb8d
--- /dev/null
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -0,0 +1,200 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { z } from "https://deno.land/x/[email protected]/mod.ts";
+
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+import { Database } from "../lib/types.ts";
+import { getNextSequence } from "../shared/get-next-sequence.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.object({
+ type: z.enum(["salesRfqToQuote"]),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+});
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const payload = await req.json();
+
+ try {
+ const { type, id, companyId, userId } = payloadValidator.parse(payload);
+
+ console.log({
+ function: "convert",
+ type,
+ id,
+ companyId,
+ userId,
+ });
+
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+
+ switch (type) {
+ case "salesRfqToQuote": {
+ const [salesRfq, salesRfqLines] = await Promise.all([
+ client.from("salesRfq").select("*").eq("id", id).single(),
+ client.from("salesRfqLines").select("*").eq("salesRfqId", id),
+ ]);
+
+ if (salesRfq.error)
+ throw new Error(`Sales RFQ with id ${id} not found`);
+ if (salesRfq.data?.status !== "Draft")
+ throw new Error(`Sales RFQ with id ${id} is not in Draft status`);
+
+ if (salesRfqLines.error) {
+ throw new Error(`Sales RFQ Lines with id ${id} not found`);
+ }
+
+ const validLines = salesRfqLines.data?.filter(
+ (line) =>
+ line.itemId &&
+ line.itemType &&
+ line.methodType &&
+ line.quantity &&
+ line.unitOfMeasureCode
+ );
+
+ let insertedQuoteId = "";
+ let insertedQuoteLines: {
+ id?: string;
+ itemId?: string;
+ methodType?: "Buy" | "Make" | "Pick";
+ }[] = [];
+ await db.transaction().execute(async (trx) => {
+ const quoteId = await getNextSequence(trx, "quote", companyId);
+ const quote = await trx
+ .insertInto("quote")
+ .values([
+ {
+ quoteId,
+ customerId: salesRfq.data?.customerId,
+ customerContactId: salesRfq.data?.customerContactId,
+ customerLocationId: salesRfq.data?.customerLocationId,
+ customerReference: salesRfq.data?.customerReference,
+ locationId: salesRfq.data?.locationId,
+ expirationDate: salesRfq.data?.expirationDate,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ },
+ ])
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (!quote.id) {
+ throw new Error("Failed to insert quote");
+ }
+
+ const quoteLineInserts: Database["public"]["Tables"]["quoteLine"]["Insert"][] =
+ validLines.map((line) => ({
+ quoteId: quote.id!,
+ itemId: line.itemId!,
+ itemReadableId: line.itemReadableId!,
+ customerPartId: line.customerPartId,
+ customerPartRevision: line.customerPartRevision,
+ description: line.description ?? line.itemName ?? "",
+ itemType: line.itemType!,
+ methodType: line.methodType!,
+ modelUploadId: line.modelUploadId,
+ notes: line.internalNotes,
+ quantity: line.quantity,
+ status: "Draft",
+ unitOfMeasureCode: line.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ }));
+
+ if (quoteLineInserts.length > 0) {
+ insertedQuoteLines = await trx
+ .insertInto("quoteLine")
+ .values(quoteLineInserts)
+ .returning(["id", "itemId", "methodType"])
+ .execute();
+ }
+
+ // update salesRfq status
+ await trx
+ .updateTable("salesRfq")
+ .set({ status: "Ready for Quote" })
+ .where("id", "=", id)
+ .execute();
+
+ await trx
+ .insertInto("salesRfqToQuote")
+ .values([
+ {
+ salesRfqId: id,
+ quoteId: quote.id!,
+ companyId,
+ },
+ ])
+ .execute();
+
+ const customerPartToItemInserts = validLines
+ .map((line) => ({
+ companyId,
+ customerId: salesRfq.data?.customerId!,
+ customerPartId: line.customerPartId!,
+ customerPartRevision: line.customerPartRevision,
+ itemId: line.itemId!,
+ }))
+ .filter((line) => !!line.itemId && !!line.customerPartId);
+ if (customerPartToItemInserts.length > 0) {
+ await trx
+ .insertInto("customerPartToItem")
+ // @ts-ignore ..
+ .values(customerPartToItemInserts)
+ .execute();
+ }
+
+ insertedQuoteId = quote.id!;
+ });
+
+ // get method for each make line
+ await Promise.all(
+ insertedQuoteLines
+ .filter((line) => line.methodType === "Make")
+ .map((line) =>
+ client.functions.invoke("get-method", {
+ body: {
+ type: "itemToQuoteLine",
+ sourceId: line.itemId,
+ targetId: `${insertedQuoteId}:${line.id}`,
+ companyId: companyId,
+ userId: userId,
+ },
+ })
+ )
+ );
+ break;
+ }
+
+ default:
+ throw new Error(`Invalid type ${type}`);
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 4423a7c5dc..a90cd1d59e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -3401,6 +3401,94 @@ export type Database = {
},
]
}
+ customerPartToItem: {
+ Row: {
+ companyId: string
+ customerId: string
+ customerPartId: string
+ customerPartRevision: string
+ itemId: string
+ }
+ Insert: {
+ companyId: string
+ customerId: string
+ customerPartId: string
+ customerPartRevision: string
+ itemId: string
+ }
+ Update: {
+ companyId?: string
+ customerId?: string
+ customerPartId?: string
+ customerPartRevision?: string
+ itemId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customer"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderCustomers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ ]
+ }
customerPayment: {
Row: {
companyId: string
@@ -15500,6 +15588,7 @@ export type Database = {
createdBy: string | null
customerContactId: string | null
customerId: string
+ customerLocationId: string | null
customerReference: string | null
customFields: Json | null
employeeId: string | null
@@ -15522,6 +15611,7 @@ export type Database = {
createdBy?: string | null
customerContactId?: string | null
customerId: string
+ customerLocationId?: string | null
customerReference?: string | null
customFields?: Json | null
employeeId?: string | null
@@ -15544,6 +15634,7 @@ export type Database = {
createdBy?: string | null
customerContactId?: string | null
customerId?: string
+ customerLocationId?: string | null
customerReference?: string | null
customFields?: Json | null
employeeId?: string | null
@@ -15686,6 +15777,13 @@ export type Database = {
referencedRelation: "salesOrderCustomers"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfq_customerLocationId_fkey"
+ columns: ["customerLocationId"]
+ isOneToOne: false
+ referencedRelation: "customerLocation"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_employeeId_fkey"
columns: ["employeeId"]
@@ -15856,8 +15954,8 @@ export type Database = {
companyId: string
createdAt: string | null
createdBy: string
- customerPartNumber: string
- customerRevisionId: string | null
+ customerPartId: string
+ customerPartRevision: string | null
customFields: Json | null
description: string | null
externalNotes: Json | null
@@ -15876,8 +15974,8 @@ export type Database = {
companyId: string
createdAt?: string | null
createdBy: string
- customerPartNumber: string
- customerRevisionId?: string | null
+ customerPartId: string
+ customerPartRevision?: string | null
customFields?: Json | null
description?: string | null
externalNotes?: Json | null
@@ -15896,8 +15994,8 @@ export type Database = {
companyId?: string
createdAt?: string | null
createdBy?: string
- customerPartNumber?: string
- customerRevisionId?: string | null
+ customerPartId?: string
+ customerPartRevision?: string | null
customFields?: Json | null
description?: string | null
externalNotes?: Json | null
@@ -16048,6 +16146,88 @@ export type Database = {
},
]
}
+ salesRfqToQuote: {
+ Row: {
+ companyId: string
+ quoteId: string
+ salesRfqId: string
+ }
+ Insert: {
+ companyId: string
+ quoteId: string
+ salesRfqId: string
+ }
+ Update: {
+ companyId?: string
+ quoteId?: string
+ salesRfqId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfq"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_salesRfqId_fkey"
+ columns: ["salesRfqId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqs"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
search: {
Row: {
companyId: string | null
@@ -24547,8 +24727,8 @@ export type Database = {
companyId: string | null
createdAt: string | null
createdBy: string | null
- customerPartNumber: string | null
- customerRevisionId: string | null
+ customerPartId: string | null
+ customerPartRevision: string | null
customFields: Json | null
description: string | null
externalNotes: Json | null
@@ -24556,6 +24736,9 @@ export type Database = {
internalNotes: Json | null
itemId: string | null
itemName: string | null
+ itemReadableId: string | null
+ itemType: Database["public"]["Enums"]["itemType"] | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
modelId: string | null
modelName: string | null
modelPath: string | null
@@ -24713,6 +24896,7 @@ export type Database = {
createdBy: string | null
customerContactId: string | null
customerId: string | null
+ customerLocationId: string | null
customerReference: string | null
customFields: Json | null
employeeId: string | null
@@ -24723,6 +24907,7 @@ export type Database = {
internalNotes: string | null
locationId: string | null
locationName: string | null
+ quoteId: string | null
revisionId: number | null
rfqDate: string | null
rfqId: string | null
@@ -24857,6 +25042,13 @@ export type Database = {
referencedRelation: "salesOrderCustomers"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfq_customerLocationId_fkey"
+ columns: ["customerLocationId"]
+ isOneToOne: false
+ referencedRelation: "customerLocation"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfq_employeeId_fkey"
columns: ["employeeId"]
@@ -24955,6 +25147,27 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quote"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quoteCustomerDetails"
+ referencedColumns: ["quoteId"]
+ },
+ {
+ foreignKeyName: "salesRfqToQuote_quoteId_fkey"
+ columns: ["quoteId"]
+ isOneToOne: false
+ referencedRelation: "quotes"
+ referencedColumns: ["id"]
+ },
]
}
services: {
diff --git a/packages/database/supabase/migrations/20240704105128_rfq.sql b/packages/database/supabase/migrations/20240704105128_rfq.sql
index 7e8e9752f3..8dd71b1ca0 100644
--- a/packages/database/supabase/migrations/20240704105128_rfq.sql
+++ b/packages/database/supabase/migrations/20240704105128_rfq.sql
@@ -47,7 +47,7 @@ CREATE TABLE "salesRfqLine" (
"id" TEXT NOT NULL DEFAULT xid(),
"salesRfqId" TEXT NOT NULL,
"customerPartNumber" TEXT NOT NULL,
- "customerRevisionId" TEXT,
+ "customerPartRevision" TEXT,
"itemId" TEXT,
"description" TEXT,
"quantity" NUMERIC(20, 2)[] DEFAULT ARRAY[]::NUMERIC(20, 2)[],
diff --git a/packages/database/supabase/migrations/20240811231527_convert-rfq.sql b/packages/database/supabase/migrations/20240811231527_convert-rfq.sql
new file mode 100644
index 0000000000..2d8f1bfeea
--- /dev/null
+++ b/packages/database/supabase/migrations/20240811231527_convert-rfq.sql
@@ -0,0 +1,127 @@
+CREATE TABLE "salesRfqToQuote" (
+ "salesRfqId" TEXT NOT NULL,
+ "quoteId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+
+ PRIMARY KEY ("salesRfqId", "quoteId"),
+ FOREIGN KEY ("salesRfqId") REFERENCES "salesRfq" ("id") ON DELETE CASCADE,
+ FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE,
+ FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "salesRfqToQuote_companyId_idx" ON "salesRfqToQuote" ("companyId");
+
+ALTER TABLE "salesRfqToQuote" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with sales_view can view salesRfqToQuote" ON "salesRfqToQuote" FOR SELECT USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_create can insert salesRfqToQuote" ON "salesRfqToQuote" FOR INSERT WITH CHECK (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE TABLE "customerPartToItem" (
+ "customerId" TEXT NOT NULL,
+ "customerPartId" TEXT NOT NULL,
+ "customerPartRevision" TEXT,
+ "itemId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+
+ PRIMARY KEY ("customerId", "customerPartId", "customerPartRevision"),
+ FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE,
+ FOREIGN KEY ("itemId") REFERENCES "item" ("id") ON DELETE CASCADE,
+ FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "customerPartToItem_companyId_idx" ON "customerPartToItem" ("companyId");
+CREATE INDEX "customerPartToItem_customerPartId_idx" ON "customerPartToItem" ("customerPartId", "customerPartRevision");
+
+ALTER TABLE "customerPartToItem" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with sales_view can view customer part to item" ON "customerPartToItem" FOR SELECT USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_create can insert customer part to item" ON "customerPartToItem" FOR INSERT WITH CHECK (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_delete can delete customer part to item" ON "customerPartToItem" FOR SELECT USING (
+ has_company_permission('sales_delete', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+ALTER TABLE "salesRfq"
+ ADD COLUMN "customerLocationId" TEXT,
+ ADD CONSTRAINT "salesRfq_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation" ("id") ON DELETE SET NULL;
+
+ALTER TABLE "salesRfqLine" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with sales_view can view salesRfqLine" ON "salesRfqLine" FOR SELECT USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_create can insert salesRfqLine" ON "salesRfqLine" FOR INSERT WITH CHECK (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_update can update salesRfqLine" ON "salesRfqLine" FOR UPDATE USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+CREATE POLICY "Employees with sales_delete can delete salesRfqLine" ON "salesRfqLine" FOR DELETE USING (
+ has_company_permission('sales_view', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+DROP VIEW "salesRfqs";
+DROP VIEW "salesRfqLines";
+
+ALTER TABLE "salesRfqLine"
+ DROP COLUMN "customerPartNumber",
+ DROP COLUMN "customerPartRevision";
+
+COMMIT;
+
+ALTER TABLE "salesRfqLine"
+ ADD COLUMN "customerPartId" TEXT NOT NULL,
+ ADD COLUMN "customerPartRevision" TEXT;
+
+CREATE OR REPLACE VIEW "salesRfqs" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ rfq.*,
+ l."name" AS "locationName",
+ srtq."quoteId",
+ EXISTS(SELECT 1 FROM "salesRfqFavorite" rf WHERE rf."rfqId" = rfq.id AND rf."userId" = auth.uid()::text) AS favorite
+ FROM "salesRfq" rfq
+ LEFT JOIN "location" l
+ ON l.id = rfq."locationId"
+ LEFT JOIN "salesRfqToQuote" srtq
+ ON srtq."salesRfqId" = rfq.id;
+
+
+CREATE OR REPLACE VIEW "salesRfqLines" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ srl.*,
+ mu.id as "modelId",
+ mu."autodeskUrn",
+ mu."modelPath",
+ mu."thumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."name" as "itemName",
+ i."defaultMethodType" AS "methodType",
+ i."readableId" AS "itemReadableId",
+ i."type" AS "itemType"
+ FROM "salesRfqLine" srl
+ LEFT JOIN "item" i ON i.id = srl."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = srl."modelUploadId";
+