Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add quote list view and form
Brad Barbinf807e0a38148
diff --git a/apps/carbon/app/components/Layout/Topbar/useCreate.tsx b/apps/carbon/app/components/Layout/Topbar/useCreate.tsxindex 125b5c2371..fe8a13f2cf 100644--- a/apps/carbon/app/components/Layout/Topbar/useCreate.tsx+++ b/apps/carbon/app/components/Layout/Topbar/useCreate.tsx@@ -1,6 +1,6 @@import { useMemo } from "react";import { AiOutlinePartition } from "react-icons/ai";-import { BsCartDash, BsShieldLock } from "react-icons/bs";+import { BsCartDash, BsCartPlus, BsShieldLock } from "react-icons/bs";import { IoMdPeople } from "react-icons/io";import { PiShareNetworkFill } from "react-icons/pi";import { usePermissions } from "~/hooks";@@ -8,7 +8,7 @@ import { usePermissions } from "~/hooks";import type { Route } from "~/types";import { path } from "~/utils/path";-export default function useNewMenu(): Route[] {+export default function useCreate(): Route[] {const permissions = usePermissions();const result = useMemo(() => {@@ -43,6 +43,11 @@ export default function useNewMenu(): Route[] {to: path.to.newCustomer,icon: <IoMdPeople />,});+ links.push({+ name: "Quotation",+ to: path.to.newQuote,+ icon: <BsCartPlus />,+ });}if (permissions.can("create", "users")) {diff --git a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsxindex e6500cde95..c1b91093dd 100644--- a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx+++ b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx@@ -10,10 +10,10 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [name: "Receipts",to: path.to.receipts,},- {- name: "Shipments",- to: path.to.shipments,- },+ // {+ // name: "Shipments",+ // to: path.to.shipments,+ // },],},{diff --git a/apps/carbon/app/modules/invoicing/ui/useInvoicingSubmodules.tsx b/apps/carbon/app/modules/invoicing/ui/useInvoicingSubmodules.tsxindex 02d8145acd..b96c46290c 100644--- a/apps/carbon/app/modules/invoicing/ui/useInvoicingSubmodules.tsx+++ b/apps/carbon/app/modules/invoicing/ui/useInvoicingSubmodules.tsx@@ -1,4 +1,4 @@-import { BsCartDash, BsCartPlus } from "react-icons/bs";+import { BsCartDash } from "react-icons/bs";import { usePermissions } from "~/hooks";import type { AuthenticatedRouteGroup } from "~/types";import { path } from "~/utils/path";@@ -13,12 +13,12 @@ const invoicingRoutes: AuthenticatedRouteGroup[] = [role: "employee",icon: <BsCartDash />,},- {- name: "Sales",- to: path.to.salesInvoices,- role: "employee",- icon: <BsCartPlus />,- },+ // {+ // name: "Sales",+ // to: path.to.salesInvoices,+ // role: "employee",+ // icon: <BsCartPlus />,+ // },],},];diff --git a/apps/carbon/app/modules/parts/ui/Part/PartPreview.tsx b/apps/carbon/app/modules/parts/ui/Part/PartPreview.tsxindex dd0a7a1bd5..2faeb9dc07 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartPreview.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartPreview.tsx@@ -1,5 +1,4 @@import {- Button,Card,CardAction,CardAttribute,@@ -14,7 +13,6 @@ import {} from "@carbon/react";import { useParams } from "@remix-run/react";-import { FaHistory } from "react-icons/fa";import { useRouteData } from "~/hooks";import type { PartSummary } from "~/modules/parts";import { path } from "~/utils/path";@@ -35,13 +33,13 @@ const PartPreview = () => {<CardDescription>{routeData?.partSummary?.name}</CardDescription></CardHeader><CardAction>- <Button+ {/* <Buttonvariant="secondary"onClick={() => alert("TODO")}leftIcon={<FaHistory />}>View History- </Button>+ </Button> */}</CardAction></HStack><CardContent>diff --git a/apps/carbon/app/modules/parts/ui/Service/ServicePreview.tsx b/apps/carbon/app/modules/parts/ui/Service/ServicePreview.tsxindex bb7138076c..11d8d30a32 100644--- a/apps/carbon/app/modules/parts/ui/Service/ServicePreview.tsx+++ b/apps/carbon/app/modules/parts/ui/Service/ServicePreview.tsx@@ -1,5 +1,4 @@import {- Button,Card,CardAction,CardAttribute,@@ -13,7 +12,6 @@ import {HStack,} from "@carbon/react";import { useParams } from "@remix-run/react";-import { FaHistory } from "react-icons/fa";import { useRouteData } from "~/hooks";import type { Service } from "~/modules/parts";import { path } from "~/utils/path";@@ -34,13 +32,13 @@ const ServicePreview = () => {<CardDescription>{routeData?.service?.description}</CardDescription></CardHeader><CardAction>- <Button+ {/* <Buttonvariant="secondary"onClick={() => alert("TODO")}leftIcon={<FaHistory />}>View History- </Button>+ </Button> */}</CardAction></HStack><CardContent>diff --git a/apps/carbon/app/modules/parts/ui/usePartsSubmodules.tsx b/apps/carbon/app/modules/parts/ui/usePartsSubmodules.tsxindex d7fb8c564c..b024422162 100644--- a/apps/carbon/app/modules/parts/ui/usePartsSubmodules.tsx+++ b/apps/carbon/app/modules/parts/ui/usePartsSubmodules.tsx@@ -14,11 +14,11 @@ const partsRoutes: AuthenticatedRouteGroup[] = [name: "Services",to: path.to.services,},- {- name: "Routing",- to: path.to.routings,- role: "employee",- },+ // {+ // name: "Routing",+ // to: path.to.routings,+ // role: "employee",+ // },],},{diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.tsindex 54cd6c221a..1f0368b1e8 100644--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts@@ -229,7 +229,7 @@ export async function getRequestsForQuotes(if (args.search) {query = query.or(- `id.ilike.%${args.search}%,requestForQuoteId.ilike.%${args.search}%,description.ilike.%${args.search}%`+ `id.ilike.%${args.search}%,requestForQuoteId.ilike.%${args.search}%,name.ilike.%${args.search}%`);}diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsxindex ff0a2b2730..59b246ee73 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx@@ -1,5 +1,4 @@import {- Button,Card,CardAction,CardAttribute,@@ -18,7 +17,6 @@ import {} from "@carbon/react";import { useParams } from "@remix-run/react";import { useMemo } from "react";-import { FaHistory } from "react-icons/fa";import { usePermissions, useRouteData } from "~/hooks";import type { PurchaseOrder } from "~/modules/purchasing";import { PurchasingStatus, usePurchaseOrderTotals } from "~/modules/purchasing";@@ -107,13 +105,13 @@ const PurchaseOrderHeader = () => {</CardDescription></CardHeader><CardAction>- <Button+ {/* <Buttonvariant="secondary"onClick={() => alert("TODO")}leftIcon={<FaHistory />}>Supplier Details- </Button>+ </Button> */}</CardAction></HStack><CardContent>diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsxindex 84b405ffc4..573f65937e 100644--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx+++ b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx@@ -100,8 +100,8 @@ const RequestForQuotesTable = memo(),},{- accessorKey: "description",- header: "Description",+ accessorKey: "name",+ header: "Name",cell: (item) => {if (item.getValue<string>()) {return item.getValue<string>().substring(0, 50);diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsxindex 64c359cc65..2475e04450 100644--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx@@ -1,5 +1,4 @@import {- Button,Card,CardAction,CardAttribute,@@ -13,7 +12,6 @@ import {VStack,} from "@carbon/react";import { useParams } from "@remix-run/react";-import { FaHistory } from "react-icons/fa";import { useRouteData } from "~/hooks";import type {SupplierDetail,@@ -44,13 +42,13 @@ const SupplierHeader = () => {<CardTitle>{routeData?.supplier?.name}</CardTitle></CardHeader><CardAction>- <Button+ {/* <Buttonvariant="secondary"onClick={() => alert("TODO")}leftIcon={<FaHistory />}>Supplier Details- </Button>+ </Button> */}</CardAction></HStack><CardContent>diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 17279e9194..032969c514 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -58,3 +58,29 @@ export const customerTypeValidator = withZod(color: z.string(),}));++export const quoteStatusType = [+ "Draft",+ "Open",+ "Replied",+ "Ordered",+ "Partially Ordered",+ "Lost",+ "Cancelled",+ "Expired",+] as const;++export const quotationValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+ customerId: z.string().min(36, { message: "Customer is required" }),+ customerLocationId: zfd.text(z.string().optional()),+ customerContactId: zfd.text(z.string().optional()),+ customerReference: zfd.text(z.string().optional()),+ locationId: zfd.text(z.string().optional()),+ ownerId: z.string().min(36, { message: "Owner is required" }),+ notes: zfd.text(z.string().optional()),+ expirationDate: zfd.text(z.string().optional()),+ })+);diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex 1501eab77d..e3cfe00dc6 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -10,6 +10,7 @@ import type {customerShippingValidator,customerTypeValidator,customerValidator,+ quotationValidator,} from "./sales.models";export async function deleteCustomerContact(@@ -43,6 +44,13 @@ export async function deleteCustomerType(return client.from("customerType").delete().eq("id", customerTypeId);}+export async function deleteQuote(+ client: SupabaseClient<Database>,+ quoteId: string+) {+ return client.from("quote").delete().eq("id", quoteId);+}+export async function getCustomer(client: SupabaseClient<Database>,customerId: string@@ -207,6 +215,39 @@ export async function getCustomerTypesList(client: SupabaseClient<Database>) {return client.from("customerType").select("id, name").order("name");}+export async function getQuotes(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ search: string | null;+ status: string | null;+ customerId: string | null;+ partId: string | null;+ }+) {+ let query = client.from("quotes").select("*", { count: "exact" });++ if (args.search) {+ query = query.or(+ `id.ilike.%${args.search}%,quoteId.ilike.%${args.search}%,name.ilike.%${args.search}%`+ );+ }++ if (args.status) {+ query = query.eq("status", args.status);+ }++ if (args.customerId) {+ query = query.eq("customerId", args.customerId);+ }++ if (args.partId) {+ query = query.contains("partIds", [args.partId]);+ }++ query = setGenericQueryFilters(query, args, "id", false);+ return query;+}+export async function insertCustomer(client: SupabaseClient<Database>,customer:@@ -406,3 +447,43 @@ export async function upsertCustomerType(.eq("id", customerType.id);}}++export async function updateQuoteFavorite(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ favorite: boolean;+ userId: string;+ }+) {+ const { id, favorite, userId } = args;+ if (!favorite) {+ return client+ .from("quoteFavorite")+ .delete()+ .eq("quoteId", id)+ .eq("userId", userId);+ } else {+ return client.from("quoteFavorite").insert({ quoteId: id, userId: userId });+ }+}++export async function upsertQuote(+ client: SupabaseClient<Database>,+ quote:+ | (Omit<TypeOfValidator<typeof quotationValidator>, "id" | "quoteId"> & {+ quoteId: string;+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof quotationValidator>, "id" | "quoteId"> & {+ id: string;+ quoteId: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in quote) {+ return client.from("quote").insert([quote]).select("id, quoteId");+ } else {+ return client.from("quote").update(sanitize(quote)).eq("id", quote.id);+ }+}diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.tsindex e787cd08d2..a2a89fa0d4 100644--- a/apps/carbon/app/modules/sales/types.ts+++ b/apps/carbon/app/modules/sales/types.ts@@ -1,3 +1,4 @@+import type { Database } from "@carbon/database";import type {getCustomer,getCustomerContacts,@@ -5,6 +6,7 @@ import type {getCustomers,getCustomerStatuses,getCustomerTypes,+ getQuotes,} from "./sales.service";export type Customer = NonNullable<@@ -30,3 +32,9 @@ export type CustomerStatus = NonNullable<export type CustomerType = NonNullable<Awaited<ReturnType<typeof getCustomerTypes>>["data"]>[number];++export type Quotation = NonNullable<+ Awaited<ReturnType<typeof getQuotes>>["data"]+>[number];++export type QuotationStatus = Database["public"]["Enums"]["quoteStatus"];diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsxindex 75419e5a84..b3b7cf2eb1 100644--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx@@ -1,5 +1,4 @@import {- Button,Card,CardAction,CardAttribute,@@ -14,7 +13,6 @@ import {} from "@carbon/react";import { useParams } from "@remix-run/react";-import { FaHistory } from "react-icons/fa";import { useRouteData } from "~/hooks";import type {CustomerDetail,@@ -44,9 +42,9 @@ const CustomerHeader = () => {<CardTitle>{routeData?.customer?.name}</CardTitle></CardHeader><CardAction>- <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>+ {/* <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>Customer Details- </Button>+ </Button> */}</CardAction></HStack><CardContent>diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsxnew file mode 100644index 0000000000..bbda5dc022--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx@@ -0,0 +1,118 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ VStack,+ cn,+} from "@carbon/react";+import { useState } from "react";+import { ValidatedForm } from "remix-validated-form";+import {+ Customer,+ CustomerContact,+ CustomerLocation,+ DatePicker,+ Employee,+ Hidden,+ Input,+ Location,+ Submit,+ TextArea,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import { quotationValidator } from "~/modules/sales";+import type { TypeOfValidator } from "~/types/validators";++type QuotationFormValues = TypeOfValidator<typeof quotationValidator>;++type QuotationFormProps = {+ initialValues: QuotationFormValues;+};++const QuotationForm = ({ initialValues }: QuotationFormProps) => {+ const permissions = usePermissions();+ const [customer, setCustomer] = useState<string | undefined>(+ initialValues.customerId+ );++ const isEditing = initialValues.id !== undefined;++ return (+ <ValidatedForm+ method="post"+ validator={quotationValidator}+ defaultValues={initialValues}+ >+ <Card>+ <CardHeader>+ <CardTitle>{isEditing ? "Quote" : "New Quote"}</CardTitle>+ {!isEditing && (+ <CardDescription>+ A quote is a document that provides a potential customer with a+ price for a product or service.+ </CardDescription>+ )}+ </CardHeader>+ <CardContent>+ <Hidden name="quotationId" />+ <VStack>+ <div+ className={cn(+ "grid w-full gap-x-8 gap-y-2",+ isEditing ? "grid-cols-1 md:grid-cols-3" : "grid-cols-1"+ )}+ >+ <VStack>+ <Input name="name" label="Name" />+ <Employee name="ownerId" label="Quoter" />+ <Location name="locationId" label="Location" />+ </VStack>+ <VStack>+ <Customer+ name="customerId"+ label="Customer"+ onChange={(value) => setCustomer(value?.value as string)}+ />+ <CustomerLocation+ name="customerLocationId"+ label="Customer Location"+ customer={customer}+ />+ <CustomerContact+ name="customerContactId"+ label="Customer Contact"+ customer={customer}+ />+ </VStack>+ <VStack>+ {isEditing && (+ <>+ <DatePicker name="expirationDate" label="Expiration Date" />++ <TextArea name="notes" label="Notes" />+ </>+ )}+ </VStack>+ </div>+ </VStack>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={+ isEditing+ ? !permissions.can("update", "sales")+ : !permissions.can("create", "sales")+ }+ >+ Save+ </Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default QuotationForm;diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationStatus.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationStatus.tsxnew file mode 100644index 0000000000..4abed87060--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationStatus.tsx@@ -0,0 +1,27 @@+import { Status } from "@carbon/react";+import type { quoteStatusType } from "~/modules/sales";++type QuotationStatusProps = {+ status?: (typeof quoteStatusType)[number] | null;+};++const QuotationStatus = ({ status }: QuotationStatusProps) => {+ switch (status) {+ case "Draft":+ return <Status color="gray">{status}</Status>;+ case "Open":+ case "Replied":+ return <Status color="orange">{status}</Status>;+ case "Ordered":+ case "Partially Ordered":+ return <Status color="green">{status}</Status>;+ case "Lost":+ case "Cancelled":+ case "Expired":+ return <Status color="red">{status}</Status>;+ default:+ return null;+ }+};++export default QuotationStatus;diff --git a/apps/carbon/app/modules/sales/ui/Quotation/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/index.tsnew file mode 100644index 0000000000..d2b6a36d57--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotation/index.ts@@ -0,0 +1,4 @@+import QuotationForm from "./QuotationForm";+import QuotationStatus from "./QuotationStatus";++export { QuotationForm, QuotationStatus };diff --git a/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsxnew file mode 100644index 0000000000..ad1d222b8c--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx@@ -0,0 +1,260 @@+import {+ HStack,+ Hyperlink,+ MenuIcon,+ MenuItem,+ useDisclosure,+} from "@carbon/react";+import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useMemo, useState } from "react";+import { BsFillPenFill, BsStar, BsStarFill } from "react-icons/bs";+import { IoMdTrash } from "react-icons/io";+import { Avatar, Table } from "~/components";+import { ConfirmDelete } from "~/components/Modals";+import { usePermissions } from "~/hooks";+import { type Quotation, type quoteStatusType } from "~/modules/sales";+import { favoriteSchema } from "~/types/validators";+import { path } from "~/utils/path";+import { QuotationStatus } from "../Quotation";+// import { QuotationStatus } from "~/modules/purchasing";++type QuotationsTableProps = {+ data: Quotation[];+ count: number;+};++const QuotationsTable = memo(({ data, count }: QuotationsTableProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const fetcher = useFetcher();+ const optimisticFavorite = useOptimisticFavorite();++ const rows = useMemo<Quotation[]>(+ () =>+ data.map((d) =>+ d.id === optimisticFavorite?.id+ ? {+ ...d,+ favorite: optimisticFavorite?.favorite+ ? optimisticFavorite.favorite === "favorite"+ : d.favorite,+ }+ : d+ ),+ [data, optimisticFavorite]+ );++ const [selectedQuotation, setSelectedQuotation] = useState<Quotation | null>(+ null+ );+ const deleteQuotationModal = useDisclosure();++ const columns = useMemo<ColumnDef<Quotation>[]>(() => {+ return [+ {+ accessorKey: "quoteId",+ header: "Quote Number",+ cell: ({ row }) => (+ <HStack>+ {row.original.favorite ? (+ <fetcher.Form method="post" action={path.to.quoteFavorite}>+ <input type="hidden" name="id" value={row.original.id!} />+ <input type="hidden" name="favorite" value="unfavorite" />+ <button type="submit">+ <BsStarFill+ className="text-yellow-400 cursor-pointer h-4 w-4"+ type="submit"+ />+ </button>+ </fetcher.Form>+ ) : (+ <fetcher.Form method="post" action={path.to.quoteFavorite}>+ <input type="hidden" name="id" value={row.original.id!} />+ <input type="hidden" name="favorite" value="favorite" />+ <button type="submit">+ <BsStar+ className="text-yellow-400 cursor-pointer h-4 w-4"+ type="submit"+ />+ </button>+ </fetcher.Form>+ )}+ <Hyperlink+ onClick={() => navigate(path.to.quote(row.original.id!))}+ >+ {row.original.quoteId}+ </Hyperlink>+ </HStack>+ ),+ },+ {+ accessorKey: "customerName",+ header: "Customer",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "name",+ header: "Name",+ cell: (item) => {+ if (item.getValue<string>()) {+ return item.getValue<string>().substring(0, 50);+ }+ return null;+ },+ },+ {+ accessorKey: "partIds",+ header: "Parts",+ cell: (item) => item.getValue<string[]>()?.filter(Boolean)?.length ?? 0,+ },+ {+ accessorKey: "status",+ header: "Status",+ cell: (item) => {+ const status = item.getValue<(typeof quoteStatusType)[number]>();+ return <QuotationStatus status={status} />;+ },+ },+ {+ accessorKey: "quoteDate",+ header: "Quote Date",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "expirationDate",+ header: "Expiration Date",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "locationName",+ header: "Location",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "customerReference",+ header: "Customer Reference",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "createdByFullName",+ header: "Created By",+ cell: ({ row }) => {+ return (+ <HStack>+ <Avatar size="sm" path={row.original.createdByAvatar} />+ <p>{row.original.createdByFullName}</p>+ </HStack>+ );+ },+ },+ {+ accessorKey: "createdAt",+ header: "Created At",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "updatedByFullName",+ header: "Updated By",+ cell: ({ row }) => {+ return row.original.updatedByFullName ? (+ <HStack>+ <Avatar size="sm" path={row.original.updatedByAvatar ?? null} />+ <p>{row.original.updatedByFullName}</p>+ </HStack>+ ) : null;+ },+ },+ {+ accessorKey: "updatedAt",+ header: "Updated At",+ cell: (item) => item.getValue(),+ },+ ];+ }, [fetcher, navigate]);++ const defaultColumnVisibility = {+ expirationDate: false,+ quoteDate: false,+ customerReference: false,+ locationName: false,+ createdAt: false,+ createdByFullName: false,+ updatedAt: false,+ updatedByFullName: false,+ };++ const renderContextMenu = useMemo(() => {+ // eslint-disable-next-line react/display-name+ return (row: Quotation) => (+ <>+ <MenuItem onClick={() => navigate(path.to.quote(row.id!))}>+ <MenuIcon icon={<BsFillPenFill />} />+ Edit+ </MenuItem>+ <MenuItem+ disabled={!permissions.can("delete", "purchasing")}+ onClick={() => {+ setSelectedQuotation(row);+ deleteQuotationModal.onOpen();+ }}+ >+ <MenuIcon icon={<IoMdTrash />} />+ Delete+ </MenuItem>+ </>+ );+ }, [deleteQuotationModal, navigate, permissions]);++ return (+ <>+ <Table<Quotation>+ count={count}+ columns={columns}+ data={rows}+ defaultColumnVisibility={defaultColumnVisibility}+ withColumnOrdering+ withFilters+ withPagination+ withSimpleSorting+ renderContextMenu={renderContextMenu}+ />+ {selectedQuotation && selectedQuotation.id && (+ <ConfirmDelete+ action={path.to.deleteQuote(selectedQuotation.id)}+ isOpen={deleteQuotationModal.isOpen}+ name={selectedQuotation.quoteId!}+ text={`Are you sure you want to delete ${selectedQuotation.quoteId!}? This cannot be undone.`}+ onCancel={() => {+ deleteQuotationModal.onClose();+ setSelectedQuotation(null);+ }}+ onSubmit={() => {+ deleteQuotationModal.onClose();+ setSelectedQuotation(null);+ }}+ />+ )}+ </>+ );+});++QuotationsTable.displayName = "QuotationsTable";++export default QuotationsTable;++function useOptimisticFavorite() {+ const fetchers = useFetchers();+ const favoriteFetcher = fetchers.find(+ (f) => f.formAction === path.to.quoteFavorite+ );++ if (favoriteFetcher && favoriteFetcher.formData) {+ const id = favoriteFetcher.formData.get("id");+ const favorite = favoriteFetcher.formData.get("favorite") ?? "off";+ const submission = favoriteSchema.safeParse({ id, favorite });+ if (submission.success) {+ return submission.data;+ }+ }+}diff --git a/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTableFilters.tsx b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTableFilters.tsxnew file mode 100644index 0000000000..29239cee18--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTableFilters.tsx@@ -0,0 +1,86 @@+import { Button, HStack } from "@carbon/react";+import { Link } from "@remix-run/react";+import { IoMdAdd } from "react-icons/io";+import { Combobox, Select } from "~/components";+import { TableFilters } from "~/components/Layout";+import { DebouncedInput } from "~/components/Search";+import { usePermissions, useUrlParams } from "~/hooks";+import { quoteStatusType } from "~/modules/sales";+import { useCustomers, useParts } from "~/stores";+import { path } from "~/utils/path";++const QuotesTableFilters = () => {+ const [customers] = useCustomers();+ const [parts] = useParts();+ const [params, setParams] = useUrlParams();+ const permissions = usePermissions();++ const customerOptions = customers+ .filter((customer) => customer.id && customer.name)+ .map((customer) => ({+ label: customer.name,+ value: customer.id,+ }));++ const partOptions = parts+ .filter((part) => part.id && part.name)+ .map((part) => ({+ label: part.name,+ value: part.id,+ }));++ const quoteStatusOptions = quoteStatusType.map((status) => ({+ label: status,+ value: status,+ }));++ return (+ <TableFilters>+ <HStack>+ <DebouncedInput param="search" size="sm" placeholder="Search" />+ <Select+ size="sm"+ value={params.get("status") ?? ""}+ isClearable+ options={quoteStatusOptions}+ onChange={(selected) => {+ setParams({ status: selected });+ }}+ aria-label="Status"+ placeholder="Status"+ />+ <Combobox+ size="sm"+ value={params.get("customerId") ?? ""}+ isClearable+ options={customerOptions}+ onChange={(selected) => {+ setParams({ customerId: selected });+ }}+ aria-label="Customer"+ placeholder="Customer"+ />+ <Combobox+ size="sm"+ value={params.get("partId") ?? ""}+ isClearable+ options={partOptions}+ onChange={(selected) => {+ setParams({ partId: selected });+ }}+ aria-label="Part"+ placeholder="Part"+ />+ </HStack>+ <HStack>+ {permissions.can("create", "sales") && (+ <Button asChild leftIcon={<IoMdAdd />}>+ <Link to={path.to.newQuote}>New Quote</Link>+ </Button>+ )}+ </HStack>+ </TableFilters>+ );+};++export default QuotesTableFilters;diff --git a/apps/carbon/app/modules/sales/ui/Quotations/index.ts b/apps/carbon/app/modules/sales/ui/Quotations/index.tsnew file mode 100644index 0000000000..ea15c99ff9--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotations/index.ts@@ -0,0 +1,4 @@+import QuotationsTable from "./QuotationsTable";+import QuotationsTableFilters from "./QuotationsTableFilters";++export { QuotationsTable, QuotationsTableFilters };diff --git a/apps/carbon/app/modules/sales/ui/index.ts b/apps/carbon/app/modules/sales/ui/index.tsindex ec7c041598..6a2223cd42 100644--- a/apps/carbon/app/modules/sales/ui/index.ts+++ b/apps/carbon/app/modules/sales/ui/index.ts@@ -2,4 +2,6 @@ import useSalesSubmodules from "./useSalesSubmodules";export * from "./Customer";export * from "./CustomerTypes";export * from "./Customers";+export * from "./Quotation";+export * from "./Quotations";export { useSalesSubmodules };diff --git a/apps/carbon/app/routes/x+/quote+/$id.tsx b/apps/carbon/app/routes/x+/quote+/$id.tsxnew file mode 100644index 0000000000..ca73fb467f--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/$id.tsx@@ -0,0 +1,9 @@+import { VStack } from "@carbon/react";++export default function RequestForQuoteRoute() {+ return (+ <VStack spacing={4} className="h-full p-4">+ <pre>TODO</pre>+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/quote+/_layout.tsx b/apps/carbon/app/routes/x+/quote+/_layout.tsxnew file mode 100644index 0000000000..a858b9c21f--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/_layout.tsx@@ -0,0 +1,23 @@+import { VStack } from "@carbon/react";+import type { MetaFunction } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Quotation" }];+};++export const handle: Handle = {+ breadcrumb: "Sales",+ to: path.to.sales,+ module: "sales",+};++export default function QuotationRoute() {+ return (+ <VStack spacing={4} className="h-full p-4">+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/quote+/delete.$id.tsx b/apps/carbon/app/routes/x+/quote+/delete.$id.tsxnew file mode 100644index 0000000000..159ad5e54d--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/delete.$id.tsx@@ -0,0 +1,29 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { deleteQuote } from "~/modules/sales";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session.server";+import { assertIsPost, notFound } from "~/utils/http";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "sales",+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const remove = await deleteQuote(client, id);++ if (remove.error) {+ return redirect(+ path.to.quotes,+ await flash(request, error(remove.error, "Failed to delete quote"))+ );+ }++ return redirect(path.to.quotes);+}diff --git a/apps/carbon/app/routes/x+/quote+/new.tsx b/apps/carbon/app/routes/x+/quote+/new.tsxnew file mode 100644index 0000000000..b8a1a1fa23--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/new.tsx@@ -0,0 +1,81 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import { useUser } from "~/hooks";+import type { QuotationStatus } from "~/modules/sales";+import {+ QuotationForm,+ quotationValidator,+ upsertQuote,+} from "~/modules/sales";+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session.server";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "sales",+ });++ const validation = await quotationValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const nextSequence = await getNextSequence(client, "quote", userId);+ if (nextSequence.error) {+ return redirect(+ path.to.newQuote,+ await flash(+ request,+ error(nextSequence.error, "Failed to get next sequence")+ )+ );+ }++ const createQuotation = await upsertQuote(client, {+ ...validation.data,+ quoteId: nextSequence.data,+ createdBy: userId,+ });++ if (createQuotation.error || !createQuotation.data?.[0]) {+ // TODO: this should be done as a transaction+ await rollbackNextSequence(client, "quote", userId);+ return redirect(+ path.to.quotes,+ await flash(+ request,+ error(createQuotation.error, "Failed to insert quotation")+ )+ );+ }++ const order = createQuotation.data?.[0];++ return redirect(path.to.quote(order.id!));+}++export default function QuotationNewRoute() {+ const user = useUser();+ const initialValues = {+ ownerId: user.id,+ locationId: user.defaults.locationId,+ description: "",+ status: "Draft" as QuotationStatus,+ };++ return (+ <div className="w-1/2 max-w-[720px] min-w-[420px] mx-auto">+ {/* @ts-expect-error */}+ <QuotationForm initialValues={initialValues} />+ </div>+ );+}diff --git a/apps/carbon/app/routes/x+/rfq+/new.tsx b/apps/carbon/app/routes/x+/rfq+/new.tsxindex 33c8f7a495..a3cdcbed90 100644--- a/apps/carbon/app/routes/x+/rfq+/new.tsx+++ b/apps/carbon/app/routes/x+/rfq+/new.tsx@@ -52,7 +52,7 @@ export async function action({ request }: ActionFunctionArgs) {path.to.requestForQuotes,await flash(request,- error(createRequestForQuote.error, "Failed to insert purchase order")+ error(createRequestForQuote.error, "Failed to insert request for quote")));}diff --git a/apps/carbon/app/routes/x+/sales+/quotes.favorite.tsx b/apps/carbon/app/routes/x+/sales+/quotes.favorite.tsxnew file mode 100644index 0000000000..ea4fb496e1--- /dev/null+++ b/apps/carbon/app/routes/x+/sales+/quotes.favorite.tsx@@ -0,0 +1,38 @@+import { json, type ActionFunctionArgs } from "@remix-run/node";+import { withZod } from "@remix-validated-form/with-zod";+import { validationError } from "remix-validated-form";+import { updateQuoteFavorite } from "~/modules/sales";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session.server";+import { favoriteSchema } from "~/types/validators";+import { error } from "~/utils/result";++export async function action({ request }: ActionFunctionArgs) {+ const { client, userId } = await requirePermissions(request, {+ view: "purchasing",+ });++ const validation = await withZod(favoriteSchema).validate(+ await request.formData()+ );+ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, favorite } = validation.data;++ const result = await updateQuoteFavorite(client, {+ id,+ favorite: favorite === "favorite",+ userId,+ });++ if (result.error) {+ return json(+ {},+ await flash(request, error(result, "Failed to favorite Quote"))+ );+ }++ return json({});+}diff --git a/apps/carbon/app/routes/x+/sales+/quotes.tsx b/apps/carbon/app/routes/x+/sales+/quotes.tsxnew file mode 100644index 0000000000..b5e408fdcc--- /dev/null+++ b/apps/carbon/app/routes/x+/sales+/quotes.tsx@@ -0,0 +1,73 @@+import { VStack } from "@carbon/react";+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import {+ QuotationsTable,+ QuotationsTableFilters,+ getQuotes,+} from "~/modules/sales";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session.server";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export const handle: Handle = {+ breadcrumb: "Requests for Quotes",+ to: path.to.quotes,+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "purchasing",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const status = searchParams.get("status");+ const customerId = searchParams.get("customerId");+ const partId = searchParams.get("partId");++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const [quotes] = await Promise.all([+ getQuotes(client, {+ search,+ status,+ partId,+ customerId,+ limit,+ offset,+ sorts,+ filters,+ }),+ ]);++ if (quotes.error) {+ redirect(+ path.to.authenticatedRoot,+ await flash(request, error(quotes.error, "Failed to fetch quotes"))+ );+ }++ return json({+ count: quotes.count ?? 0,+ quotes: quotes.data ?? [],+ });+}++export default function QuotesRoute() {+ const { count, quotes } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <QuotationsTableFilters />+ <QuotationsTable data={quotes} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.tsindex c73e0a31d5..6b658d018e 100644--- a/apps/carbon/app/services/session.server.ts+++ b/apps/carbon/app/services/session.server.ts@@ -6,7 +6,6 @@ import {makeRedirectToFromHere,safeRedirect,} from "~/utils/http";-import { error } from "~/utils/result";import {NODE_ENV,@@ -30,8 +29,7 @@ async function assertAuthSession(if (!authSession?.accessToken || !authSession?.refreshToken) {throw redirect(- `${onFailRedirectTo || path.to.login}?${makeRedirectToFromHere(request)}`,- await flash(request, error("No user session found"))+ `${onFailRedirectTo || path.to.login}?${makeRedirectToFromHere(request)}`);}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex fae25336bc..6c4d784bc2 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -166,6 +166,7 @@ export const path = {generatePath(`${x}/purchase-order/delete/${id}`),deletePurchaseOrderLine: (orderId: string, lineId: string) =>generatePath(`${x}/purchase-order/${orderId}/lines/delete/${lineId}`),+ deleteQuote: (id: string) => generatePath(`${x}/quote/delete/${id}`),deleteReceipt: (id: string) =>generatePath(`${x}/inventory/receipts/delete/${id}`),deleteRequestForQuote: (id: string) =>@@ -271,6 +272,7 @@ export const path = {newPurchaseOrder: `${x}/purchase-order/new`,newPurchaseOrderLine: (id: string) =>generatePath(`${x}/purchase-order/${id}/lines/new`),+ newQuote: `${x}/quote/new`,newReceipt: `${x}/inventory/receipts/new`,newRequestForQuote: `${x}/rfq/new`,newShift: `${x}/resources/shifts/new`,@@ -353,7 +355,9 @@ export const path = {generatePath(`${x}/purchase-order/${id}/release`),purchaseOrders: `${x}/purchasing/orders`,purchasing: `${x}/purchasing`,+ quote: (id: string) => generatePath(`${x}/quote/${id}`),quotes: `${x}/sales/quotes`,+ quoteFavorite: `${x}/sales/quotes/favorite`,receipt: (id: string) => generatePath(`${x}/inventory/receipts/${id}`),receipts: `${x}/inventory/receipts`,receiptInvoice: (id: string) => generatePath(`${x}/receipt/${id}/invoice`),diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex ac735229a4..8929213a8d 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6712,54 +6712,799 @@ export interface Database {customerId: string;customerLocationId: string | null;customerReference: string | null;+ expirationDate: string | null;+ id: string;+ locationId: string | null;+ name: string;+ notes: string | null;+ ownerId: string;+ quoteDate: string | null;+ quoteId: string;+ revisionId: number;+ status: Database["public"]["Enums"]["quoteStatus"];+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Insert: {+ createdAt?: string;+ createdBy: string;+ customerContactId?: string | null;+ customerId: string;+ customerLocationId?: string | null;+ customerReference?: string | null;+ expirationDate?: string | null;+ id?: string;+ locationId?: string | null;+ name: string;+ notes?: string | null;+ ownerId: string;+ quoteDate?: string | null;+ quoteId: string;+ revisionId?: number;+ status?: Database["public"]["Enums"]["quoteStatus"];+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Update: {+ createdAt?: string;+ createdBy?: string;+ customerContactId?: string | null;+ customerId?: string;+ customerLocationId?: string | null;+ customerReference?: string | null;+ expirationDate?: string | null;+ id?: string;+ locationId?: string | null;+ name?: string;+ notes?: string | null;+ ownerId?: string;+ quoteDate?: string | null;+ quoteId?: string;+ revisionId?: number;+ status?: Database["public"]["Enums"]["quoteStatus"];+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quote_customerContactId_fkey";+ columns: ["customerContactId"];+ referencedRelation: "contact";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerLocationId_fkey";+ columns: ["customerLocationId"];+ referencedRelation: "location";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerLocationId_fkey";+ columns: ["customerLocationId"];+ referencedRelation: "partQuantities";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_customerLocationId_fkey";+ columns: ["customerLocationId"];+ referencedRelation: "purchaseOrders";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "location";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "partQuantities";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "purchaseOrders";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quote_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteFavorite: {+ Row: {+ quoteId: string;+ userId: string;+ };+ Insert: {+ quoteId: string;+ userId: string;+ };+ Update: {+ quoteId?: string;+ userId?: string;+ };+ Relationships: [+ {+ foreignKeyName: "quoteFavorites_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteFavorites_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteFavorites_userId_fkey";+ columns: ["userId"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteFavorites_userId_fkey";+ columns: ["userId"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteFavorites_userId_fkey";+ columns: ["userId"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteLine: {+ Row: {+ createdBy: string;+ customerPartId: string | null;+ description: string;+ id: string;+ partId: string;+ quantity: number;+ quoteId: string;+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Insert: {+ createdBy: string;+ customerPartId?: string | null;+ description: string;+ id?: string;+ partId: string;+ quantity?: number;+ quoteId: string;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Update: {+ createdBy?: string;+ customerPartId?: string | null;+ description?: string;+ id?: string;+ partId?: string;+ quantity?: number;+ quoteId?: string;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLine_partId_fkey";+ columns: ["partId"];+ referencedRelation: "part";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_partId_fkey";+ columns: ["partId"];+ referencedRelation: "partQuantities";+ referencedColumns: ["partId"];+ },+ {+ foreignKeyName: "quoteLine_partId_fkey";+ columns: ["partId"];+ referencedRelation: "parts";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteLineQuantities: {+ Row: {+ additionalCost: number;+ createdAt: string;+ createdBy: string;+ discountPercentage: number;+ extendedCost: number;+ id: string;+ laborCost: number;+ leadTime: number;+ markupPercentage: number;+ materialCost: number;+ overheadCost: number;+ productionHours: number;+ quantity: number;+ quoteLineId: string;+ scrapPercentage: number;+ setupHours: number;+ unitCostBase: number;+ unitTaxAmount: number;+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Insert: {+ additionalCost?: number;+ createdAt?: string;+ createdBy: string;+ discountPercentage?: number;+ extendedCost?: number;+ id?: string;+ laborCost?: number;+ leadTime?: number;+ markupPercentage?: number;+ materialCost?: number;+ overheadCost?: number;+ productionHours?: number;+ quantity?: number;+ quoteLineId: string;+ scrapPercentage?: number;+ setupHours?: number;+ unitCostBase?: number;+ unitTaxAmount?: number;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Update: {+ additionalCost?: number;+ createdAt?: string;+ createdBy?: string;+ discountPercentage?: number;+ extendedCost?: number;+ id?: string;+ laborCost?: number;+ leadTime?: number;+ markupPercentage?: number;+ materialCost?: number;+ overheadCost?: number;+ productionHours?: number;+ quantity?: number;+ quoteLineId?: string;+ scrapPercentage?: number;+ setupHours?: number;+ unitCostBase?: number;+ unitTaxAmount?: number;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quoteLineQuantities_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLineQuantities_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLineQuantities_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLineQuantities_quoteLineId_fkey";+ columns: ["quoteLineId"];+ referencedRelation: "quoteLine";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLineQuantities_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLineQuantities_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLineQuantities_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteMaterial: {+ Row: {+ createdAt: string;+ createdBy: string;+ description: string;+ id: string;+ partId: string;+ quantity: number;+ quoteId: string;+ quoteLineId: string;+ quoteProcessId: string;+ unitCost: number;+ unitOfMeasureCode: string | null;+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Insert: {+ createdAt?: string;+ createdBy: string;+ description: string;+ id?: string;+ partId: string;+ quantity?: number;+ quoteId: string;+ quoteLineId: string;+ quoteProcessId: string;+ unitCost?: number;+ unitOfMeasureCode?: string | null;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Update: {+ createdAt?: string;+ createdBy?: string;+ description?: string;+ id?: string;+ partId?: string;+ quantity?: number;+ quoteId?: string;+ quoteLineId?: string;+ quoteProcessId?: string;+ unitCost?: number;+ unitOfMeasureCode?: string | null;+ updatedAt?: string | null;+ updatedBy?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quoteMaterial_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteMaterial_partId_fkey";+ columns: ["partId"];+ referencedRelation: "part";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_partId_fkey";+ columns: ["partId"];+ referencedRelation: "partQuantities";+ referencedColumns: ["partId"];+ },+ {+ foreignKeyName: "quoteMaterial_partId_fkey";+ columns: ["partId"];+ referencedRelation: "parts";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_quoteLineId_fkey";+ columns: ["quoteLineId"];+ referencedRelation: "quoteLine";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_quoteProcessId_fkey";+ columns: ["quoteProcessId"];+ referencedRelation: "quoteProcess";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteMaterial_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteModule: {+ Row: {+ createdAt: string;+ createdBy: string;+ description: string | null;id: string;- name: string;- notes: string | null;- ownerId: string;- quoteDate: string;+ parentModuleId: string | null;+ partId: string;+ quantityPerParent: number;quoteId: string;- revisionId: number;- status: Database["public"]["Enums"]["quoteStatus"];+ quoteLineId: string;+ quoteModuleId: string;+ unitOfMeasureCode: string | null;updatedAt: string | null;updatedBy: string | null;};Insert: {createdAt?: string;createdBy: string;- customerContactId?: string | null;- customerId: string;- customerLocationId?: string | null;- customerReference?: string | null;+ description?: string | null;id?: string;- name: string;- notes?: string | null;- ownerId: string;- quoteDate?: string;+ parentModuleId?: string | null;+ partId: string;+ quantityPerParent?: number;quoteId: string;- revisionId?: number;- status?: Database["public"]["Enums"]["quoteStatus"];+ quoteLineId: string;+ quoteModuleId?: string;+ unitOfMeasureCode?: string | null;updatedAt?: string | null;updatedBy?: string | null;};Update: {createdAt?: string;createdBy?: string;- customerContactId?: string | null;- customerId?: string;- customerLocationId?: string | null;- customerReference?: string | null;+ description?: string | null;id?: string;- name?: string;- notes?: string | null;- ownerId?: string;- quoteDate?: string;+ parentModuleId?: string | null;+ partId?: string;+ quantityPerParent?: number;quoteId?: string;- revisionId?: number;- status?: Database["public"]["Enums"]["quoteStatus"];+ quoteLineId?: string;+ quoteModuleId?: string;+ unitOfMeasureCode?: string | null;updatedAt?: string | null;updatedBy?: string | null;};- Relationships: [];+ Relationships: [+ {+ foreignKeyName: "quoteModule_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteModule_parentModuleId_fkey";+ columns: ["parentModuleId"];+ referencedRelation: "quoteModule";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_quoteLineId_fkey";+ columns: ["quoteLineId"];+ referencedRelation: "quoteLine";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteModule_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };+ quoteProcess: {+ Row: {+ createdAt: string;+ createdBy: string;+ description: string;+ equipmentTypeId: string | null;+ id: string;+ laborRate: number;+ overheadRate: number;+ productionStandard: number;+ quoteId: string;+ quoteLineId: string;+ quoteModuleId: string;+ quotingRate: number;+ setupHours: number;+ standardFactor: Database["public"]["Enums"]["factor"];+ updatedAt: string | null;+ updatedBy: string | null;+ workCellTypeId: string;+ };+ Insert: {+ createdAt?: string;+ createdBy: string;+ description: string;+ equipmentTypeId?: string | null;+ id?: string;+ laborRate?: number;+ overheadRate?: number;+ productionStandard?: number;+ quoteId: string;+ quoteLineId: string;+ quoteModuleId: string;+ quotingRate?: number;+ setupHours?: number;+ standardFactor?: Database["public"]["Enums"]["factor"];+ updatedAt?: string | null;+ updatedBy?: string | null;+ workCellTypeId: string;+ };+ Update: {+ createdAt?: string;+ createdBy?: string;+ description?: string;+ equipmentTypeId?: string | null;+ id?: string;+ laborRate?: number;+ overheadRate?: number;+ productionStandard?: number;+ quoteId?: string;+ quoteLineId?: string;+ quoteModuleId?: string;+ quotingRate?: number;+ setupHours?: number;+ standardFactor?: Database["public"]["Enums"]["factor"];+ updatedAt?: string | null;+ updatedBy?: string | null;+ workCellTypeId?: string;+ };+ Relationships: [+ {+ foreignKeyName: "quoteProcess_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteProcess_equipmentTypeId_fkey";+ columns: ["equipmentTypeId"];+ referencedRelation: "equipmentType";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_quoteId_fkey";+ columns: ["quoteId"];+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_quoteLineId_fkey";+ columns: ["quoteLineId"];+ referencedRelation: "quoteLine";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_quoteModuleId_fkey";+ columns: ["quoteModuleId"];+ referencedRelation: "quoteModule";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteProcess_updatedBy_fkey";+ columns: ["updatedBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteProcess_workCellTypeId_fkey";+ columns: ["workCellTypeId"];+ referencedRelation: "workCellType";+ referencedColumns: ["id"];+ }+ ];};receipt: {Row: {@@ -10669,6 +11414,101 @@ export interface Database {};Relationships: [];};+ quotes: {+ Row: {+ createdAt: string | null;+ createdBy: string | null;+ createdByAvatar: string | null;+ createdByFullName: string | null;+ customerId: string | null;+ customerName: string | null;+ customerReference: string | null;+ expirationDate: string | null;+ favorite: boolean | null;+ id: string | null;+ locationId: string | null;+ locationName: string | null;+ name: string | null;+ notes: string | null;+ ownerAvatar: string | null;+ ownerFullName: string | null;+ ownerId: string | null;+ partIds: string[] | null;+ quoteDate: string | null;+ quoteId: string | null;+ status: Database["public"]["Enums"]["quoteStatus"] | null;+ updatedByAvatar: string | null;+ updatedByFullName: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_createdBy_fkey";+ columns: ["createdBy"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "location";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "partQuantities";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_locationId_fkey";+ columns: ["locationId"];+ referencedRelation: "purchaseOrders";+ referencedColumns: ["locationId"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_ownerId_fkey";+ columns: ["ownerId"];+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };receiptsPostedNotInvoiced: {Row: {estimatedCost: number | null;@@ -11133,7 +11973,8 @@ export interface Database {| "Replied"| "Ordered"| "Partially Ordered"- | "LostCancelled"+ | "Lost"+ | "Cancelled"| "Expired";receiptSourceDocument:| "Sales Order"diff --git a/packages/database/supabase/migrations/20240206224405_quotes.sql b/packages/database/supabase/migrations/20240206224405_quotes.sqlindex 799000142c..0740bd7c08 100644--- a/packages/database/supabase/migrations/20240206224405_quotes.sql+++ b/packages/database/supabase/migrations/20240206224405_quotes.sql@@ -1,10 +1,12 @@++CREATE TYPE "quoteStatus" AS ENUM ('Draft','Open','Replied','Ordered','Partially Ordered',- 'Lost'+ 'Lost','Cancelled','Expired');@@ -16,14 +18,250 @@ CREATE TABLE "quote" ("ownerId" TEXT NOT NULL,"name" TEXT NOT NULL,"status" "quoteStatus" NOT NULL DEFAULT 'Draft',- "quoteDate" DATE NOT NULL DEFAULT CURRENT_DATE,+ "quoteDate" DATE,+ "expirationDate" DATE,"notes" TEXT,"customerId" TEXT NOT NULL,"customerLocationId" TEXT,"customerContactId" TEXT,"customerReference" TEXT,+ "locationId" TEXT,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quote_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quote_quoteId_key" UNIQUE ("quoteId"),+ CONSTRAINT "quote_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quote_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quote_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "location" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quote_customerContactId_fkey" FOREIGN KEY ("customerContactId") REFERENCES "contact" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quote_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quote_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quote_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE TABLE "quoteLine" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteId" TEXT NOT NULL,+ -- "quoteRevisionId" INTEGER NOT NULL DEFAULT 0,+ "partId" TEXT NOT NULL,+ "customerPartId" TEXT,+ "description" TEXT NOT NULL,+ "quantity" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quoteLine_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteLine_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "quoteLine_quoteId_idx" ON "quoteLine" ("quoteId");++CREATE TABLE "quoteLineQuantities" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteLineId" TEXT NOT NULL,+ "quantity" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "scrapPercentage" NUMERIC(5, 2) NOT NULL DEFAULT 0,+ "setupHours" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "productionHours" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "materialCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "laborCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "overheadCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "additionalCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "discountPercentage" NUMERIC(5, 2) NOT NULL DEFAULT 0,+ "markupPercentage" NUMERIC(5, 2) NOT NULL DEFAULT 0,+ "unitCostBase" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "unitTaxAmount" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "extendedCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "leadTime" INTEGER NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quoteLineQuantities_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteLineQuantities_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteLineQuantities_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteLineQuantities_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "quoteLineQuantities_quoteLineId_idx" ON "quoteLineQuantities" ("quoteLineId");++CREATE TABLE "quoteModule" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteId" TEXT NOT NULL,+ "quoteLineId" TEXT NOT NULL,+ "quoteModuleId" TEXT NOT NULL DEFAULT xid(),+ "parentModuleId" TEXT,+ "partId" TEXT NOT NULL,+ "description" TEXT,+ "unitOfMeasureCode" TEXT,+ "quantityPerParent" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quoteModule_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteModule_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteModule_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteModule_parentModuleId_fkey" FOREIGN KEY ("parentModuleId") REFERENCES "quoteModule" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteModule_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteModule_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "quoteModule_quoteId_idx" ON "quoteModule" ("quoteId");+CREATE INDEX "quoteModule_quoteLineId_idx" ON "quoteModule" ("quoteLineId");+CREATE INDEX "quoteModule_parentModuleId_idx" ON "quoteModule" ("parentModuleId");++CREATE TABLE "quoteProcess" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteId" TEXT NOT NULL,+ "quoteLineId" TEXT NOT NULL,+ "quoteModuleId" TEXT NOT NULL,+ "workCellTypeId" TEXT NOT NULL,+ "equipmentTypeId" TEXT,+ "description" TEXT NOT NULL,+ "setupHours" NUMERIC(10,2) NOT NULL DEFAULT 0,+ "standardFactor" factor NOT NULL DEFAULT 'Hours/Piece',+ "productionStandard" NUMERIC(10,4) NOT NULL DEFAULT 0,+ "quotingRate" NUMERIC(10,4) NOT NULL DEFAULT 0,+ "laborRate" NUMERIC(10,4) NOT NULL DEFAULT 0,+ "overheadRate" NUMERIC(10,4) NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quoteProcess_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteProcess_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_quoteModuleId_fkey" FOREIGN KEY ("quoteModuleId") REFERENCES "quoteModule" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_workCellTypeId_fkey" FOREIGN KEY ("workCellTypeId") REFERENCES "workCellType" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_equipmentTypeId_fkey" FOREIGN KEY ("equipmentTypeId") REFERENCES "equipmentType" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteProcess_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "quoteProcess_quoteId_idx" ON "quoteProcess" ("quoteId");+CREATE INDEX "quoteProcess_quoteLineId_idx" ON "quoteProcess" ("quoteLineId");+CREATE INDEX "quoteProcess_quoteModuleId_idx" ON "quoteProcess" ("quoteModuleId");++CREATE TABLE "quoteMaterial" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteId" TEXT NOT NULL,+ "quoteLineId" TEXT NOT NULL,+ "quoteProcessId" TEXT NOT NULL,+ "partId" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "quantity" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "unitOfMeasureCode" TEXT,+ "unitCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,"updatedAt" TIMESTAMP WITH TIME ZONE,- "updatedBy" TEXT-);\ No newline at end of file+ "updatedBy" TEXT,++ CONSTRAINT "quoteMaterial_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteMaterial_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteMaterial_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteMaterial_quoteProcessId_fkey" FOREIGN KEY ("quoteProcessId") REFERENCES "quoteProcess" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteMaterial_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteMaterial_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteMaterial_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE TABLE "quoteFavorite" (+ "quoteId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,++ CONSTRAINT "quoteFavorites_pkey" PRIMARY KEY ("quoteId", "userId"),+ CONSTRAINT "quoteFavorites_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote"("id") ON DELETE CASCADE,+ CONSTRAINT "quoteFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "quoteFavorites_userId_idx" ON "quoteFavorite" ("userId");+CREATE INDEX "quoteFavorites_quoteId_idx" ON "quoteFavorite" ("quoteId");++ALTER TABLE "quoteFavorite" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own quote favorites" ON "quoteFavorite"+ FOR SELECT USING (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can create their own quote favorites" ON "quoteFavorite"+ FOR INSERT WITH CHECK (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can delete their own quote favorites" ON "quoteFavorite"+ FOR DELETE USING (+ auth.uid()::text = "userId"+ );++CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS+ SELECT+ q."id",+ q."quoteId",+ q."customerId",+ q."name",+ q."status",+ q."notes",+ q."quoteDate",+ q."expirationDate",+ q."customerReference",+ q."locationId",+ q."createdAt",+ q."createdBy",+ q."ownerId",+ uo."fullName" AS "ownerFullName",+ uo."avatarUrl" AS "ownerAvatar",+ c."name" AS "customerName",+ uc."fullName" AS "createdByFullName",+ uc."avatarUrl" AS "createdByAvatar",+ uu."fullName" AS "updatedByFullName",+ uu."avatarUrl" AS "updatedByAvatar",+ l."name" AS "locationName",+ array_agg(ql."partId") AS "partIds",+ EXISTS(SELECT 1 FROM "quoteFavorite" pf WHERE pf."quoteId" = q.id AND pf."userId" = auth.uid()::text) AS favorite+FROM "quote" q+LEFT JOIN "customer" c+ ON c.id = q."customerId"+LEFT JOIN "location" l+ ON l.id = q."locationId"+LEFT JOIN "quoteLine" ql+ ON ql."quoteId" = q.id+LEFT JOIN "user" uo+ ON uo.id = q."ownerId"+LEFT JOIN "user" uc+ ON uc.id = q."createdBy"+LEFT JOIN "user" uu+ ON uu.id = q."updatedBy"+GROUP BY+ q."id",+ q."quoteId",+ q."customerId",+ q."name",+ q."status",+ q."notes",+ q."quoteDate",+ q."expirationDate",+ q."customerReference",+ q."locationId",+ q."createdAt",+ q."createdBy",+ c."name",+ uo."fullName",+ uo."avatarUrl",+ uc."fullName",+ uc."avatarUrl",+ uu."fullName",+ uu."avatarUrl",+ l."name";\ No newline at end of filediff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sqlindex e589977292..b81283c965 100644--- a/packages/database/supabase/seed.sql+++ b/packages/database/supabase/seed.sql@@ -181,11 +181,11 @@ VALUESINSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")VALUES- ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 6, 1),- ('purchaseInvoice', 'Purchase Invoice', 'AP', NULL, 0, 6, 1),- ('receipt', 'Receipt', 'RE', NULL, 0, 6, 1),- ('requestForQuote', 'Request For Quote', 'RFQ', NULL, 0, 6, 1),- ('quote', 'Quote', 'QUO', NULL, 0, 6, 1);+ ('purchaseOrder', 'Purchase Order', 'PO-', NULL, 0, 6, 1),+ ('purchaseInvoice', 'Purchase Invoice', 'AP-', NULL, 0, 6, 1),+ ('receipt', 'Receipt', 'RE-', NULL, 0, 6, 1),+ ('requestForQuote', 'Request For Quote', 'RFQ-', NULL, 0, 6, 1),+ ('quote', 'Quote', 'QUO-', NULL, 0, 6, 1);-- account categories