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: add and delete supplier quotes

Brad Barbin0a6ecae01f08
diff --git a/apps/carbon/app/components/Documents.tsx b/apps/carbon/app/components/Documents.tsx
index f132c48320..6b3caffafc 100644
--- a/apps/carbon/app/components/Documents.tsx
+++ b/apps/carbon/app/components/Documents.tsx
@@ -24,8 +24,7 @@ import { convertKbToString } from "@carbon/utils";
import { Link, useFetchers, useRevalidator, useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
-import { LuAxis3D, LuUpload } from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
+import { LuAxis3D, LuMoreVertical, LuUpload } from "react-icons/lu";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { usePermissions, useUser } from "~/hooks";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
@@ -277,7 +276,7 @@ const Documents = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
@@ -343,7 +342,7 @@ const Documents = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
index efd19db62f..34692bd069 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -21,8 +21,7 @@ import {
Tr,
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
-import { LuAxis3D, LuUpload } from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
+import { LuAxis3D, LuMoreVertical, LuUpload } from "react-icons/lu";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile } from "~/modules/items";
@@ -128,7 +127,7 @@ const ItemDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
@@ -190,7 +189,7 @@ const ItemDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/carbon/app/modules/purchasing/purchasing.models.ts b/apps/carbon/app/modules/purchasing/purchasing.models.ts
index ce98b94e25..aaffe47276 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.models.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.models.ts
@@ -236,3 +236,19 @@ export const supplierQuoteStatusType = [
"Accepted",
"Rejected",
] as const;
+
+export const supplierQuoteValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ supplierQuoteId: zfd.text(z.string().optional()),
+ supplierId: z.string().min(36, { message: "Customer is required" }),
+ supplierLocationId: zfd.text(z.string().optional()),
+ supplierContactId: zfd.text(z.string().optional()),
+ supplierReference: zfd.text(z.string().optional()),
+ status: z.enum(supplierQuoteStatusType).optional(),
+ notes: z.any().optional(),
+ dueDate: zfd.text(z.string().optional()),
+ expirationDate: zfd.text(z.string().optional()),
+ currencyCode: zfd.text(z.string().optional()),
+ exchangeRate: zfd.numeric(z.number().optional()),
+ exchangeRateUpdatedAt: zfd.text(z.string().optional()),
+});
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index fa9787c161..230c88fced 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -6,6 +6,7 @@ import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
+import { getCurrencyByCode } from "../accounting/accounting.service";
import type {
purchaseOrderDeliveryValidator,
purchaseOrderLineValidator,
@@ -15,6 +16,7 @@ import type {
supplierContactValidator,
supplierPaymentValidator,
supplierProcessValidator,
+ supplierQuoteValidator,
supplierShippingValidator,
supplierStatusValidator,
supplierTypeValidator,
@@ -120,6 +122,27 @@ export async function deleteSupplierProcess(
.single();
}
+export async function deleteSupplierQuote(
+ client: SupabaseClient<Database>,
+ supplierQuoteId: string
+) {
+ const [quote, interaction] = await Promise.all([
+ client.from("supplierQuote").delete().eq("id", supplierQuoteId),
+ client
+ .from("supplierInteraction")
+ .update({
+ supplierQuoteId: null,
+ })
+ .eq("supplierQuoteId", supplierQuoteId),
+ ]);
+
+ if (interaction.error) {
+ return interaction;
+ }
+
+ return quote;
+}
+
export async function deleteSupplierStatus(
client: SupabaseClient<Database>,
supplierStatusId: string
@@ -308,6 +331,57 @@ export async function getSupplierContacts(
.eq("supplierId", supplierId);
}
+export async function getSupplierInteractionByQuote(
+ client: SupabaseClient<Database>,
+ quoteId: string
+) {
+ return client
+ .from("supplierInteraction")
+ .select("*")
+ .eq("supplierQuoteId", quoteId)
+ .single();
+}
+
+export async function getSupplierInteractionByPurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client
+ .from("supplierInteraction")
+ .select("*")
+ .eq("purchaseOrderId", purchaseOrderId)
+ .single();
+}
+
+export async function getSupplierInteractionDocuments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ interactionId: string
+) {
+ const result = await client.storage
+ .from("private")
+ .list(`${companyId}/supplier-interaction/${interactionId}`);
+
+ return (
+ result.data?.map((f) => ({ ...f, bucket: "supplier-interaction" })) ?? []
+ );
+}
+
+export async function getSupplierInteractionLineDocuments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ lineId: string
+) {
+ const result = await client.storage
+ .from("private")
+ .list(`${companyId}/supplier-interaction-line/${lineId}`);
+
+ return (
+ result.data?.map((f) => ({ ...f, bucket: "supplier-interaction-line" })) ??
+ []
+ );
+}
+
export async function getSupplierLocations(
client: SupabaseClient<Database>,
supplierId: string
@@ -400,6 +474,27 @@ export async function getSupplierQuotes(
return query;
}
+export async function getSupplierQuoteLines(
+ client: SupabaseClient<Database>,
+ supplierQuoteId: string
+) {
+ return client
+ .from("supplierQuoteLine")
+ .select("*")
+ .eq("supplierQuoteId", supplierQuoteId);
+}
+
+export async function getSupplierQuoteLinePricesByQuoteId(
+ client: SupabaseClient<Database>,
+ supplierQuoteId: string
+) {
+ return client
+ .from("supplierQuoteLinePrice")
+ .select("*")
+ .eq("supplierQuoteId", supplierQuoteId)
+ .order("supplierQuoteLineId", { ascending: true });
+}
+
export async function getSupplierQuotesList(
client: SupabaseClient<Database>,
companyId: string
@@ -693,63 +788,6 @@ export async function updatePurchaseOrderFavorite(
}
}
-export async function upsertSupplier(
- client: SupabaseClient<Database>,
- supplier:
- | (Omit<z.infer<typeof supplierValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })
- | (Omit<z.infer<typeof supplierValidator>, "id"> & {
- id: string;
- updatedBy: string;
- customFields?: Json;
- })
-) {
- if ("createdBy" in supplier) {
- return client.from("supplier").insert([supplier]).select("*").single();
- }
- return client
- .from("supplier")
- .update({
- ...sanitize(supplier),
- updatedAt: today(getLocalTimeZone()).toString(),
- })
- .eq("id", supplier.id)
- .select("id")
- .single();
-}
-
-export async function upsertSupplierProcess(
- client: SupabaseClient<Database>,
- supplierProcess:
- | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })
- | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
- id: string;
- updatedBy: string;
- customFields?: Json;
- })
-) {
- if ("createdBy" in supplierProcess) {
- return client
- .from("supplierProcess")
- .insert([supplierProcess])
- .select("id")
- .single();
- }
- return client
- .from("supplierProcess")
- .update(sanitize(supplierProcess))
- .eq("id", supplierProcess.id)
- .select("id")
- .single();
-}
-
export async function updateSupplierAccounting(
client: SupabaseClient<Database>,
supplierAccounting: z.infer<typeof supplierAccountingValidator> & {
@@ -1056,6 +1094,158 @@ export async function upsertPurchaseOrderPayment(
.single();
}
+export async function upsertSupplier(
+ client: SupabaseClient<Database>,
+ supplier:
+ | (Omit<z.infer<typeof supplierValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof supplierValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in supplier) {
+ return client.from("supplier").insert([supplier]).select("*").single();
+ }
+ return client
+ .from("supplier")
+ .update({
+ ...sanitize(supplier),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", supplier.id)
+ .select("id")
+ .single();
+}
+
+export async function upsertSupplierProcess(
+ client: SupabaseClient<Database>,
+ supplierProcess:
+ | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in supplierProcess) {
+ return client
+ .from("supplierProcess")
+ .insert([supplierProcess])
+ .select("id")
+ .single();
+ }
+ return client
+ .from("supplierProcess")
+ .update(sanitize(supplierProcess))
+ .eq("id", supplierProcess.id)
+ .select("id")
+ .single();
+}
+
+export async function upsertSupplierQuote(
+ client: SupabaseClient<Database>,
+ supplierQuote:
+ | (Omit<
+ z.infer<typeof supplierQuoteValidator>,
+ "id" | "supplierQuoteId"
+ > & {
+ supplierQuoteId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<
+ z.infer<typeof supplierQuoteValidator>,
+ "id" | "supplierQuoteId"
+ > & {
+ id: string;
+ supplierQuoteId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in supplierQuote) {
+ if (supplierQuote.currencyCode) {
+ const currency = await getCurrencyByCode(
+ client,
+ supplierQuote.companyId,
+ supplierQuote.currencyCode
+ );
+ if (currency.data) {
+ supplierQuote.exchangeRate = currency.data.exchangeRate ?? undefined;
+ supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+ } else {
+ supplierQuote.exchangeRate = 1;
+ supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+
+ const insert = await client
+ .from("supplierQuote")
+ .insert([supplierQuote])
+ .select("id, supplierQuoteId");
+ if (insert.error) {
+ return insert;
+ }
+
+ const supplierQuoteId = insert.data?.[0]?.id;
+ if (!supplierQuoteId) return insert;
+
+ const supplierInteraction = await client
+ .from("supplierInteraction")
+ .insert([{ supplierQuoteId, companyId: supplierQuote.companyId }]);
+
+ if (supplierInteraction.error) {
+ await deleteSupplierQuote(client, supplierQuoteId);
+ return supplierInteraction;
+ }
+
+ return insert;
+ } else {
+ // Only update the exchange rate if the currency code has changed
+ const existingQuote = await client
+ .from("quote")
+ .select("companyId, currencyCode")
+ .eq("id", supplierQuote.id)
+ .single();
+
+ if (existingQuote.error) return existingQuote;
+
+ const { companyId, currencyCode } = existingQuote.data;
+
+ if (
+ supplierQuote.currencyCode &&
+ currencyCode !== supplierQuote.currencyCode
+ ) {
+ const currency = await getCurrencyByCode(
+ client,
+ companyId,
+ supplierQuote.currencyCode
+ );
+ if (currency.data) {
+ supplierQuote.exchangeRate = currency.data.exchangeRate ?? undefined;
+ supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+ }
+ return client
+ .from("supplierQuote")
+ .update({
+ ...sanitize(supplierQuote),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", supplierQuote.id);
+ }
+}
+
export async function upsertSupplierStatus(
client: SupabaseClient<Database>,
supplierStatus:
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index 4a807ca836..f654b09c38 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -5,6 +5,7 @@ import type {
getPurchaseOrders,
getSupplier,
getSupplierContacts,
+ getSupplierInteractionByQuote,
getSupplierLocations,
getSupplierProcessesBySupplier,
getSupplierQuotes,
@@ -50,6 +51,10 @@ export type SupplierContact = NonNullable<
Awaited<ReturnType<typeof getSupplierContacts>>["data"]
>[number];
+export type SupplierInteraction = NonNullable<
+ Awaited<ReturnType<typeof getSupplierInteractionByQuote>>["data"]
+>;
+
export type SupplierLocation = NonNullable<
Awaited<ReturnType<typeof getSupplierLocations>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocuments.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocuments.tsx
index 775ae72172..4827a48fd5 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocuments.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocuments.tsx
@@ -20,7 +20,7 @@ import {
import { convertKbToString } from "@carbon/utils";
import { Await, Outlet } from "@remix-run/react";
import { Suspense } from "react";
-import { MdMoreVert } from "react-icons/md";
+import { LuMoreVertical } from "react-icons/lu";
import { DocumentPreview } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { PurchaseOrderAttachment } from "~/modules/purchasing";
@@ -127,7 +127,7 @@ const PurchaseOrderDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
new file mode 100644
index 0000000000..260a9469e6
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
@@ -0,0 +1,396 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Badge,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ File,
+ HStack,
+ IconButton,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+ toast,
+} from "@carbon/react";
+import { convertKbToString } from "@carbon/utils";
+import {
+ Outlet,
+ useFetchers,
+ useRevalidator,
+ useSubmit,
+} from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import type { ChangeEvent } from "react";
+import { useCallback } from "react";
+import {
+ LuMoreVertical,
+ LuRadioTower,
+ LuShoppingCart,
+ LuUpload,
+} from "react-icons/lu";
+import { DocumentPreview, FileDropzone } from "~/components";
+import { usePermissions, useUser } from "~/hooks";
+import { DocumentIcon, getDocumentType } from "~/modules/documents";
+import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
+import type { SupplierInteraction } from "../../types";
+
+type SupplierInteractionDocumentsProps = {
+ attachments: FileObject[];
+ interaction: SupplierInteraction;
+ id: string;
+ type: "Supplier Quote" | "Purchase Order";
+};
+
+const SupplierInteractionDocuments = ({
+ attachments,
+ interaction,
+ id,
+ type,
+}: SupplierInteractionDocumentsProps) => {
+ const { canDelete, download, deleteAttachment, getPath, upload } =
+ useSupplierInteractionDocuments({
+ interactionId: interaction.id,
+ id,
+ type,
+ });
+
+ const onDrop = useCallback(
+ (acceptedFiles: File[]) => {
+ upload(acceptedFiles);
+ },
+ [upload]
+ );
+
+ return (
+ <>
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <SupplierInteractionDocumentForm
+ interactionId={interaction.id}
+ id={id}
+ type={type}
+ />
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ <Th></Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {attachments.length ? (
+ attachments.map((attachment) => (
+ <Tr key={attachment.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={getDocumentType(attachment.name)} />
+ <span
+ className="font-medium"
+ onClick={() => download(attachment)}
+ >
+ {["PDF", "Image"].includes(
+ getDocumentType(attachment.name)
+ ) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={getDocumentType(attachment.name)}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </span>
+ {interaction?.salesOrderDocumentPath ===
+ getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuShoppingCart />
+ </Badge>
+ )}
+ {interaction?.quoteDocumentPath ===
+ getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuRadioTower />
+ </Badge>
+ )}
+ </HStack>
+ </Td>
+ <Td className="text-xs font-mono">
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<LuMoreVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() => download(attachment)}
+ >
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ onClick={() => deleteAttachment(attachment)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ ))
+ ) : (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ No files uploaded
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ <FileDropzone onDrop={onDrop} />
+ </CardContent>
+ </Card>
+
+ <Outlet />
+ </>
+ );
+};
+
+type SupplierInteractionDocumentFormProps = {
+ interactionId: string;
+ id: string;
+ type: "Supplier Quote" | "Purchase Order";
+};
+
+export const useSupplierInteractionDocuments = ({
+ id,
+ interactionId,
+ type,
+}: SupplierInteractionDocumentFormProps) => {
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { carbon } = useCarbon();
+ const revalidator = useRevalidator();
+ const submit = useSubmit();
+
+ const canDelete = permissions.can("delete", "sales"); // TODO: or is document owner
+
+ const getPath = useCallback(
+ (attachment: { name: string }) => {
+ return `${
+ company.id
+ }/supplier-interaction/${interactionId}/${stripSpecialCharacters(
+ attachment.name
+ )}`;
+ },
+ [company.id, interactionId]
+ );
+
+ const deleteAttachment = useCallback(
+ async (attachment: FileObject) => {
+ const result = await carbon?.storage
+ .from("private")
+ .remove([getPath(attachment)]);
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error deleting file");
+ return;
+ }
+
+ toast.success(`${attachment.name} deleted successfully`);
+ revalidator.revalidate();
+ },
+ [carbon?.storage, getPath, revalidator]
+ );
+
+ const download = useCallback(
+ async (attachment: FileObject) => {
+ const result = await carbon?.storage
+ .from("private")
+ .download(getPath(attachment));
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error downloading file");
+ return;
+ }
+
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ const url = window.URL.createObjectURL(result.data);
+ a.href = url;
+ a.download = attachment.name;
+ a.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }, 0);
+ },
+ [carbon?.storage, getPath]
+ );
+
+ const createDocumentRecord = useCallback(
+ ({
+ path: filePath,
+ name,
+ size,
+ }: {
+ path: string;
+ name: string;
+ size: number;
+ }) => {
+ const formData = new FormData();
+ formData.append("path", filePath);
+ formData.append("name", name);
+ formData.append("size", Math.round(size / 1024).toString());
+ formData.append("sourceDocument", type);
+ formData.append("sourceDocumentId", id);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `interaction:${name}`,
+ });
+ },
+ [id, submit, type]
+ );
+
+ const upload = useCallback(
+ async (files: File[]) => {
+ if (!carbon) {
+ toast.error("Carbon client not available");
+ return;
+ }
+
+ for (const file of files) {
+ const fileName = getPath(file);
+ toast.info(`Uploading ${file.name}`);
+
+ const fileUpload = await carbon.storage
+ .from("private")
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ toast.error(`Failed to upload file: ${file.name}`);
+ } else if (fileUpload.data?.path) {
+ toast.success(`Uploaded: ${file.name}`);
+ createDocumentRecord({
+ path: fileUpload.data.path,
+ name: file.name,
+ size: file.size,
+ });
+ }
+ }
+ revalidator.revalidate();
+ },
+ [getPath, createDocumentRecord, carbon, revalidator]
+ );
+
+ return {
+ canDelete,
+ deleteAttachment,
+ download,
+ upload,
+ getPath,
+ };
+};
+
+const SupplierInteractionDocumentForm = (
+ props: SupplierInteractionDocumentFormProps
+) => {
+ const { company } = useUser();
+ const { carbon } = useCarbon();
+ const permissions = usePermissions();
+
+ const { upload } = useSupplierInteractionDocuments(props);
+
+ const uploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files && carbon && company) {
+ upload(Array.from(e.target.files));
+ }
+ };
+
+ return (
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFiles}
+ multiple
+ >
+ New
+ </File>
+ );
+};
+
+export default SupplierInteractionDocuments;
+
+type OptimisticFileObject = Omit<
+ FileObject,
+ "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"
+>;
+export const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
new file mode 100644
index 0000000000..72a70149fa
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
@@ -0,0 +1,387 @@
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ File,
+ HStack,
+ IconButton,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+ toast,
+} from "@carbon/react";
+import { convertKbToString } from "@carbon/utils";
+import type { FileObject } from "@supabase/storage-js";
+import { LuMoreVertical, LuUpload } from "react-icons/lu";
+import { DocumentPreview, FileDropzone } from "~/components";
+import { DocumentIcon, getDocumentType } from "~/modules/documents";
+import type { ItemFile } from "~/modules/items";
+
+import { useFetchers, useRevalidator, useSubmit } from "@remix-run/react";
+import type { ChangeEvent } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { path } from "~/utils/path";
+
+import { useCarbon } from "@carbon/auth";
+import { useCallback } from "react";
+import type { OptimisticFileObject } from "~/modules/shared";
+import { stripSpecialCharacters } from "~/utils/string";
+
+const useSupplierInteractionLineDocuments = ({
+ id,
+ lineId,
+ type,
+}: {
+ id: string;
+ lineId: string;
+ type: "Supplier Quote" | "Purchase Order";
+}) => {
+ const permissions = usePermissions();
+ const revalidator = useRevalidator();
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const submit = useSubmit();
+
+ const canDelete = permissions.can("delete", "sales");
+ const canUpdate = permissions.can("update", "sales");
+
+ const getPath = useCallback(
+ (file: { name: string }) => {
+ return `${
+ company.id
+ }/supplier-interaction-line/${lineId}/${stripSpecialCharacters(
+ file.name
+ )}`;
+ },
+ [company.id, lineId]
+ );
+
+ const deleteFile = useCallback(
+ async (file: ItemFile) => {
+ const fileDelete = await carbon?.storage
+ .from("private")
+ .remove([getPath(file)]);
+
+ if (!fileDelete || fileDelete.error) {
+ toast.error(fileDelete?.error?.message || "Error deleting file");
+ return;
+ }
+
+ toast.success(`${file.name} deleted successfully`);
+ revalidator.revalidate();
+ },
+ [getPath, carbon?.storage, revalidator]
+ );
+
+ const download = useCallback(
+ async (file: ItemFile) => {
+ const result = await carbon?.storage
+ .from("private")
+ .download(getPath(file));
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error downloading file");
+ return;
+ }
+
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ const url = window.URL.createObjectURL(result.data);
+ a.href = url;
+ a.download = file.name;
+ a.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }, 0);
+ },
+ [carbon?.storage, getPath]
+ );
+
+ const createDocumentRecord = useCallback(
+ ({
+ path: filePath,
+ name,
+ size,
+ }: {
+ path: string;
+ name: string;
+ size: number;
+ }) => {
+ const formData = new FormData();
+ formData.append("path", filePath);
+ formData.append("name", name);
+ formData.append("size", Math.round(size / 1024).toString());
+ formData.append("sourceDocument", type);
+ formData.append("sourceDocumentId", id);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `supplier-interaction-line:${name}`,
+ });
+ },
+ [id, submit, type]
+ );
+
+ const upload = useCallback(
+ async (files: File[]) => {
+ if (!carbon) {
+ toast.error("Carbon client not available");
+ return;
+ }
+
+ for (const file of files) {
+ const fileName = getPath(file);
+
+ const fileUpload = await carbon.storage
+ .from("private")
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ toast.error(`Failed to upload file: ${file.name}`);
+ } else if (fileUpload.data?.path) {
+ createDocumentRecord({
+ path: fileUpload.data.path,
+ name: file.name,
+ size: file.size,
+ });
+ }
+ }
+ revalidator.revalidate();
+ },
+ [getPath, createDocumentRecord, carbon, revalidator]
+ );
+
+ return {
+ canDelete,
+ canUpdate,
+ deleteFile,
+ download,
+ getPath,
+
+ upload,
+ };
+};
+
+type SupplierInteractionLineDocumentsProps = {
+ files: FileObject[];
+ id: string;
+ lineId: string;
+ type: "Supplier Quote" | "Purchase Order";
+};
+
+const SupplierInteractionLineDocuments = ({
+ files,
+ id,
+ lineId,
+ type,
+}: SupplierInteractionLineDocumentsProps) => {
+ const { canDelete, download, deleteFile, getPath, upload } =
+ useSupplierInteractionLineDocuments({
+ id,
+ lineId,
+ type,
+ });
+
+ const onDrop = useCallback(
+ (acceptedFiles: File[]) => {
+ upload(acceptedFiles);
+ },
+ [upload]
+ );
+
+ const attachmentsByName = new Map<string, FileObject | OptimisticFileObject>(
+ files.map((file) => [file.name, file])
+ );
+ const pendingItems = usePendingItems();
+ for (let pendingItem of pendingItems) {
+ let item = attachmentsByName.get(pendingItem.name);
+ let merged = item ? { ...item, ...pendingItem } : pendingItem;
+ attachmentsByName.set(pendingItem.name, merged);
+ }
+
+ const allFiles = Array.from(attachmentsByName.values()).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ ) as FileObject[];
+
+ return (
+ <>
+ <Card className="flex-grow">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <SupplierInteractionLineDocumentForm
+ id={id}
+ type={type}
+ lineId={lineId}
+ />
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ <Th />
+ </Tr>
+ </Thead>
+ <Tbody>
+ {allFiles.map((file) => {
+ const type = getDocumentType(file.name);
+ return (
+ <Tr key={file.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <span
+ className="font-medium"
+ onClick={() => download(file)}
+ >
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(file)}
+ // @ts-ignore
+ type={type}
+ >
+ {file.name}
+ </DocumentPreview>
+ ) : (
+ file.name
+ )}
+ </span>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((file.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<LuMoreVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem onClick={() => download(file)}>
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ onClick={() => deleteFile(file)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ );
+ })}
+ {allFiles.length === 0 && (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ No files
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ <FileDropzone onDrop={onDrop} />
+ </CardContent>
+ </Card>
+ </>
+ );
+};
+
+export default SupplierInteractionLineDocuments;
+
+type SupplierInteractionLineDocumentFormProps = {
+ id: string;
+ lineId: string;
+ type: "Supplier Quote" | "Purchase Order";
+};
+
+const SupplierInteractionLineDocumentForm = ({
+ id,
+ lineId,
+ type,
+}: SupplierInteractionLineDocumentFormProps) => {
+ const permissions = usePermissions();
+ const { upload } = useSupplierInteractionLineDocuments({ id, lineId, type });
+
+ const uploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files) {
+ upload(Array.from(e.target.files));
+ }
+ };
+
+ return (
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFiles}
+ multiple
+ >
+ New
+ </File>
+ );
+};
+
+const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ bucket: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx
new file mode 100644
index 0000000000..76b1ff2e06
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx
@@ -0,0 +1,109 @@
+import { useCarbon } from "@carbon/auth";
+import type { JSONContent } from "@carbon/react";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Editor,
+ generateHTML,
+ toast,
+ useDebounce,
+} from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { nanoid } from "nanoid";
+import { useState } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl } from "~/utils/path";
+
+const SupplierInteractionLineNotes = ({
+ id,
+ table,
+ title,
+ subTitle,
+ notes: initialNotes,
+}: {
+ id: string | null;
+ table: "supplierQuoteLine" | "purchaseOrderLine";
+ title: string;
+ subTitle: string;
+ notes?: JSONContent;
+}) => {
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+ const { carbon } = useCarbon();
+ const permissions = usePermissions();
+
+ const [notes, setInternalNotes] = useState(initialNotes ?? {});
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/supplier-interaction-line/${id}/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ const onUpdateInternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ notes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
+
+ if (!id) return null;
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <CardDescription>{subTitle}</CardDescription>
+ </CardHeader>
+
+ <CardContent>
+ {permissions.can("update", "sales") ? (
+ <Editor
+ initialValue={(notes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setInternalNotes(value);
+ onUpdateInternalNotes(value);
+ }}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(notes as JSONContent),
+ }}
+ />
+ )}
+ </CardContent>
+ </Card>
+ </>
+ );
+};
+
+export default SupplierInteractionLineNotes;
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx
new file mode 100644
index 0000000000..5233c87db1
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx
@@ -0,0 +1,167 @@
+import { useCarbon } from "@carbon/auth";
+import type { JSONContent } from "@carbon/react";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Editor,
+ generateHTML,
+ HStack,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ toast,
+ useDebounce,
+} from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { nanoid } from "nanoid";
+import { useState } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl } from "~/utils/path";
+
+const SupplierInteractionNotes = ({
+ id,
+ table,
+ title,
+ internalNotes: initialInternalNotes,
+ externalNotes: initialExternalNotes,
+}: {
+ id: string | null;
+ table: "supplierQuote" | "purchaseOrder";
+ title: string;
+ internalNotes?: JSONContent;
+ externalNotes?: JSONContent;
+}) => {
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+ const { carbon } = useCarbon();
+ const permissions = usePermissions();
+ const [tab, setTab] = useState("internal");
+ const [internalNotes, setInternalNotes] = useState(
+ initialInternalNotes ?? {}
+ );
+ const [externalNotes, setExternalNotes] = useState(
+ initialExternalNotes ?? {}
+ );
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/supplier-interaction/${id}/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ const onUpdateExternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ externalNotes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
+
+ const onUpdateInternalNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from(table)
+ .update({
+ internalNotes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
+
+ if (!id) return null;
+
+ return (
+ <>
+ <Card>
+ <Tabs value={tab} onValueChange={setTab}>
+ <HStack className="w-full justify-between">
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <CardDescription>
+ {tab === "internal" ? "Internal Notes" : "External Notes"}
+ </CardDescription>
+ </CardHeader>
+ <CardAction>
+ <TabsList>
+ <TabsTrigger value="internal">Internal</TabsTrigger>
+ <TabsTrigger value="external">External</TabsTrigger>
+ </TabsList>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <TabsContent value="internal">
+ {permissions.can("update", "sales") ? (
+ <Editor
+ initialValue={(internalNotes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setInternalNotes(value);
+ onUpdateInternalNotes(value);
+ }}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(internalNotes as JSONContent),
+ }}
+ />
+ )}
+ </TabsContent>
+ <TabsContent value="external">
+ {permissions.can("update", "sales") ? (
+ <Editor
+ initialValue={(externalNotes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setExternalNotes(value);
+ onUpdateExternalNotes(value);
+ }}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(externalNotes as JSONContent),
+ }}
+ />
+ )}
+ </TabsContent>
+ </CardContent>
+ </Tabs>
+ </Card>
+ </>
+ );
+};
+
+export default SupplierInteractionNotes;
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx
new file mode 100644
index 0000000000..4b0a34aebf
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx
@@ -0,0 +1,125 @@
+import { Button, cn, Menubar } from "@carbon/react";
+import { useOptimisticLocation } from "@carbon/remix";
+import { Link } from "@remix-run/react";
+import { LuCircle, LuLayoutList, LuPackageSearch } from "react-icons/lu";
+import { path } from "~/utils/path";
+import type { SupplierInteraction } from "../../types";
+
+function getSupplierInteractionStarted(
+ interaction: SupplierInteraction,
+ state: string
+) {
+ switch (state) {
+ case "Purchase Order":
+ return interaction.purchaseOrderId !== null;
+ case "Supplier Quote":
+ return interaction.supplierQuoteId !== null;
+ }
+}
+
+function getSupplierInteractionCompleted(
+ interaction: SupplierInteraction,
+ state: string
+) {
+ switch (state) {
+ case "Purchase Order":
+ return interaction.purchaseOrderCompletedDate !== null;
+ case "Supplier Quote":
+ return interaction.supplierQuoteCompletedDate !== null;
+ }
+}
+
+function getSupplierInteractionIcon(state: string) {
+ switch (state) {
+ case "Purchase Order":
+ return LuLayoutList;
+ case "Supplier Quote":
+ return LuPackageSearch;
+ default:
+ return LuCircle;
+ }
+}
+
+function getPath(interaction: SupplierInteraction, state: string) {
+ switch (state) {
+ case "Purchase Order":
+ return path.to.purchaseOrderDetails(interaction.purchaseOrderId!);
+ case "Supplier Quote":
+ return path.to.supplierQuoteDetails(interaction.supplierQuoteId!);
+ }
+}
+
+function getIsCurrent(
+ interaction: SupplierInteraction,
+ pathname: string,
+ state: string
+) {
+ switch (state) {
+ case "Purchase Order":
+ return pathname.includes(
+ path.to.purchaseOrderDetails(interaction.purchaseOrderId!)
+ );
+ case "Supplier Quote":
+ return pathname.includes(
+ path.to.supplierQuoteDetails(interaction.supplierQuoteId!)
+ );
+
+ default:
+ return false;
+ }
+}
+
+const states = ["Purchase Order", "Supplier Quote"];
+
+const SupplierInteractionState = ({
+ interaction,
+}: {
+ interaction: SupplierInteraction;
+}) => {
+ const { pathname } = useOptimisticLocation();
+ return (
+ <Menubar>
+ {states.map((state, index) => {
+ const isStarted = getSupplierInteractionStarted(interaction, state);
+ const isCompleted = getSupplierInteractionCompleted(interaction, state);
+ const isCurrent = getIsCurrent(interaction, pathname, state);
+ const Icon = getSupplierInteractionIcon(state);
+ const to = getPath(interaction, state);
+
+ return isStarted && to ? (
+ <Button
+ leftIcon={
+ <Icon
+ className={cn(
+ isCurrent && "text-emerald-500",
+ !isCurrent && "opacity-80 hover:opacity-100"
+ )}
+ />
+ }
+ variant="ghost"
+ asChild
+ >
+ <Link to={to}>{state}</Link>
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ isDisabled
+ leftIcon={
+ <Icon
+ className={cn(
+ isCompleted && "text-emerald-500",
+ !isCurrent && "opacity-80 hover:opacity-100"
+ )}
+ />
+ }
+ >
+ {state}
+ </Button>
+ );
+ })}
+ </Menubar>
+ );
+};
+
+export default SupplierInteractionState;
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/index.ts b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/index.ts
new file mode 100644
index 0000000000..82393a21a6
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierInteraction/index.ts
@@ -0,0 +1,13 @@
+import SupplierInteractionDocuments from "./SupplierInteractionDocuments";
+import SupplierInteractionLineDocuments from "./SupplierInteractionLineDocuments";
+import SupplierInteractionLineNotes from "./SupplierInteractionLineNotes";
+import SupplierInteractionNotes from "./SupplierInteractionNotes";
+import SupplierInteractionState from "./SupplierInteractionState";
+
+export {
+ SupplierInteractionDocuments,
+ SupplierInteractionLineDocuments,
+ SupplierInteractionLineNotes,
+ SupplierInteractionNotes,
+ SupplierInteractionState,
+};
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteForm.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteForm.tsx
new file mode 100644
index 0000000000..6d67d26929
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteForm.tsx
@@ -0,0 +1,221 @@
+import { useCarbon } from "@carbon/auth";
+import { ValidatedForm } from "@carbon/form";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ VStack,
+ cn,
+ toast,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useState } from "react";
+import { flushSync } from "react-dom";
+import type { z } from "zod";
+import {
+ Currency,
+ CustomFormFields,
+ DatePicker,
+ Hidden,
+ Input,
+ Submit,
+ Supplier,
+ SupplierContact,
+ SupplierLocation,
+} from "~/components/Form";
+import ExchangeRate from "~/components/Form/ExchangeRate";
+import { usePermissions, useUser } from "~/hooks";
+import { supplierQuoteValidator } from "~/modules/purchasing";
+import { path } from "~/utils/path";
+
+type SupplierQuoteFormValues = z.infer<typeof supplierQuoteValidator>;
+
+type SupplierQuoteFormProps = {
+ initialValues: SupplierQuoteFormValues;
+};
+
+const SupplierQuoteForm = ({ initialValues }: SupplierQuoteFormProps) => {
+ const permissions = usePermissions();
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const [supplier, setSupplier] = useState<{
+ id: string | undefined;
+ currencyCode: string | undefined;
+ }>({
+ id: initialValues.supplierId,
+ currencyCode: initialValues.currencyCode,
+ });
+ const isSupplier = permissions.is("supplier");
+ const isDisabled = initialValues?.status !== "Draft";
+ const isEditing = initialValues.id !== undefined;
+
+ const exchangeRateFetcher = useFetcher<{ exchangeRate: number }>();
+
+ const onSupplierChange = async (
+ newValue: {
+ value: string | undefined;
+ label: string;
+ } | null
+ ) => {
+ if (!carbon) {
+ toast.error("Carbon client not found");
+ return;
+ }
+
+ if (newValue?.value) {
+ flushSync(() => {
+ // update the supplier immediately
+ setSupplier({
+ id: newValue?.value,
+ currencyCode: undefined,
+ });
+ });
+
+ const { data, error } = await carbon
+ ?.from("supplier")
+ .select("currencyCode")
+ .eq("id", newValue.value)
+ .single();
+ if (error) {
+ toast.error("Error fetching supplier data");
+ } else {
+ setSupplier((prev) => ({
+ ...prev,
+ currencyCode: data.currencyCode ?? undefined,
+ }));
+ }
+ } else {
+ setSupplier({
+ id: undefined,
+ currencyCode: undefined,
+ });
+ }
+ };
+
+ return (
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={supplierQuoteValidator}
+ defaultValues={initialValues}
+ >
+ <CardHeader>
+ <CardTitle>
+ {isEditing ? "Supplier Quote" : "New Supplier Quote"}
+ </CardTitle>
+ {!isEditing && (
+ <CardDescription>
+ A supplier quote is a set of prices for specific parts and
+ quantities.
+ </CardDescription>
+ )}
+ </CardHeader>
+ <CardContent>
+ <Hidden name="supplierQuoteId" />
+ <VStack>
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ isEditing
+ ? "grid-cols-1 lg:grid-cols-3"
+ : "grid-cols-1 md:grid-cols-2"
+ )}
+ >
+ <Supplier
+ autoFocus={!isEditing}
+ name="supplierId"
+ label="Supplier"
+ onChange={onSupplierChange}
+ />
+ <Input name="supplierReference" label="Supplier Ref. Number" />
+ <SupplierLocation
+ name="supplierLocationId"
+ label="Supplier Location"
+ isOptional
+ supplier={supplier.id}
+ />
+ <SupplierContact
+ name="supplierContactId"
+ label="Supplier Contact"
+ isOptional
+ supplier={supplier.id}
+ />
+ <DatePicker
+ name="dueDate"
+ label="Due Date"
+ isDisabled={isSupplier}
+ />
+ <DatePicker
+ name="expirationDate"
+ label="Expiration Date"
+ isDisabled={isSupplier}
+ />
+
+ <Currency
+ name="currencyCode"
+ label="Currency"
+ value={supplier.currencyCode}
+ onChange={(
+ newValue: {
+ value: string | undefined;
+ label: string;
+ } | null
+ ) => {
+ if (newValue?.value) {
+ setSupplier((prevSupplier) => ({
+ ...prevSupplier,
+ currencyCode: newValue.value,
+ }));
+ }
+ }}
+ />
+
+ {isEditing &&
+ !!supplier.currencyCode &&
+ supplier.currencyCode !== company.baseCurrencyCode && (
+ <ExchangeRate
+ name="exchangeRate"
+ value={initialValues.exchangeRate ?? 1}
+ exchangeRateUpdatedAt={initialValues.exchangeRateUpdatedAt}
+ isReadOnly
+ onRefresh={() => {
+ const formData = new FormData();
+ formData.append(
+ "currencyCode",
+ supplier.currencyCode ?? ""
+ );
+ exchangeRateFetcher.submit(formData, {
+ method: "post",
+ action: path.to.quoteExchangeRate(
+ initialValues.id ?? ""
+ ),
+ });
+ }}
+ />
+ )}
+
+ <CustomFormFields table="supplierQuote" />
+ </div>
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={
+ isDisabled ||
+ (isEditing
+ ? !permissions.can("update", "purchasing")
+ : !permissions.can("create", "purchasing"))
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+};
+
+export default SupplierQuoteForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
index 05e1ce4f40..0b559cd70e 100644
--- a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
@@ -300,14 +300,14 @@ const SupplierQuotesTable = memo(
}}
primaryAction={
permissions.can("create", "purchasing") && (
- <New label="Quote" to={path.to.newQuote} />
+ <New label="SupplierQuote" to={path.to.newSupplierQuote} />
)
}
renderContextMenu={renderContextMenu}
/>
{selectedSupplierQuote && selectedSupplierQuote.id && (
<ConfirmDelete
- action={path.to.deleteQuote(selectedSupplierQuote.id)}
+ action={path.to.deleteSupplierQuote(selectedSupplierQuote.id)}
isOpen={deleteSupplierQuoteModal.isOpen}
name={selectedSupplierQuote.supplierQuoteId!}
text={`Are you sure you want to delete ${selectedSupplierQuote.supplierQuoteId!}? This cannot be undone.`}
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/index.ts b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/index.ts
index 0599bcde9e..85a9d8ff49 100644
--- a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/index.ts
@@ -1,4 +1,5 @@
+import SupplierQuoteForm from "./SupplierQuoteForm";
import SupplierQuoteStatus from "./SupplierQuoteStatus";
import SupplierQuotesTable from "./SupplierQuotesTable";
-export { SupplierQuoteStatus, SupplierQuotesTable };
+export { SupplierQuoteForm, SupplierQuoteStatus, SupplierQuotesTable };
diff --git a/apps/carbon/app/modules/purchasing/ui/index.ts b/apps/carbon/app/modules/purchasing/ui/index.ts
index 191a4acb11..81452233b4 100644
--- a/apps/carbon/app/modules/purchasing/ui/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/index.ts
@@ -2,6 +2,7 @@ import usePurchasingSubmodules from "./usePurchasingSubmodules";
export * from "./PurchaseOrder";
export * from "./Supplier";
+export * from "./SupplierInteraction";
export * from "./SupplierQuote";
export * from "./SupplierStatuses";
export * from "./SupplierTypes";
diff --git a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
index ed5ea2c590..cc2a8d9f7b 100644
--- a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
@@ -34,11 +34,11 @@ import type { ChangeEvent } from "react";
import { useCallback } from "react";
import {
LuGripVertical,
+ LuMoreVertical,
LuRadioTower,
LuShoppingCart,
LuUpload,
} from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, FileDropzone } from "~/components";
import { usePermissions, useUser } from "~/hooks";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
@@ -135,7 +135,7 @@ const OpportunityDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index 8755c24a08..569b9021e6 100644
--- a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -22,8 +22,7 @@ import {
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
import type { FileObject } from "@supabase/storage-js";
-import { LuUpload } from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
+import { LuMoreVertical, LuUpload } from "react-icons/lu";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile } from "~/modules/items";
@@ -361,7 +360,7 @@ const OpportunityLineDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
@@ -423,7 +422,7 @@ const OpportunityLineDocuments = ({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="secondary"
/>
</DropdownMenuTrigger>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index 6fd8e68cf4..34b913fc59 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -25,11 +25,11 @@ import {
LuChevronDown,
LuCircle,
LuClock3,
+ LuMoreVertical,
LuPlusCircle,
LuTrash,
LuXCircle,
} from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
import { Empty, ItemThumbnail } from "~/components";
import type { Tree } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
@@ -272,7 +272,7 @@ function QuoteLineItem({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
size="sm"
variant="ghost"
onClick={(e) => e.stopPropagation()}
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteSummary.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteSummary.tsx
index a581194abb..0d2b6cc313 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteSummary.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteSummary.tsx
@@ -543,8 +543,6 @@ const QuoteSummary = () => {
salesOrderLines: SalesOrderLine[];
}>(path.to.quote(quoteId));
- console.log({ routeData });
-
const { locale } = useLocale();
const formatter = useMemo(
() =>
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index a4bad659ae..cfb64d49f0 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -20,8 +20,7 @@ import {
import { prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
-import { LuPlusCircle, LuTrash } from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
+import { LuMoreVertical, LuPlusCircle, LuTrash } from "react-icons/lu";
import { Empty, ItemThumbnail } from "~/components";
import {
useOptimisticLocation,
@@ -214,7 +213,7 @@ function SalesOrderLineItem({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="ghost"
onClick={(e) => e.stopPropagation()}
/>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index 783b1beb2b..7866d0d414 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -21,8 +21,7 @@ import { prettifyKeyboardShortcut } from "@carbon/utils";
import { useDroppable } from "@dnd-kit/core";
import { Link, useFetchers, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
-import { LuPlusCircle, LuTrash } from "react-icons/lu";
-import { MdMoreVert } from "react-icons/md";
+import { LuMoreVertical, LuPlusCircle, LuTrash } from "react-icons/lu";
import type { z } from "zod";
import { Empty, ItemThumbnail } from "~/components";
import { usePermissions, useRealtime, useRouteData } from "~/hooks";
@@ -306,7 +305,7 @@ function SalesRFQLineItem({
<DropdownMenuTrigger asChild>
<IconButton
aria-label="More"
- icon={<MdMoreVert />}
+ icon={<LuMoreVertical />}
variant="ghost"
onClick={(e) => e.stopPropagation()}
/>
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index ea82b18191..8150ea3064 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -283,7 +283,7 @@ export async function getSequences(
}
query = setGenericQueryFilters(query, args, [
- { column: "table", ascending: true },
+ { column: "name", ascending: true },
]);
return query;
}
diff --git a/apps/carbon/app/routes/x+/purchasing+/quotes.tsx b/apps/carbon/app/routes/x+/purchasing+/quotes.tsx
index 07cd277a50..8e0658a150 100644
--- a/apps/carbon/app/routes/x+/purchasing+/quotes.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/quotes.tsx
@@ -12,7 +12,7 @@ import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
breadcrumb: "Supplier Quotes",
- to: path.to.quotes,
+ to: path.to.supplierQuotes,
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$id._index.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$id._index.tsx
new file mode 100644
index 0000000000..4d667cdca2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$id._index.tsx
@@ -0,0 +1,9 @@
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+ throw redirect(path.to.supplierQuoteDetails(id));
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$id.delete.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$id.delete.tsx
new file mode 100644
index 0000000000..6311e93173
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$id.delete.tsx
@@ -0,0 +1,29 @@
+import { json, redirect } from "@remix-run/react";
+
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { deleteSupplierQuote } from "~/modules/purchasing";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const quoteDelete = await deleteSupplierQuote(client, id);
+
+ if (quoteDelete.error) {
+ return json(
+ path.to.supplierQuotes,
+ await flash(request, error(quoteDelete.error, quoteDelete.error.message))
+ );
+ }
+
+ throw redirect(path.to.supplierQuotes);
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$id.details.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$id.details.tsx
new file mode 100644
index 0000000000..c481d53f59
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$id.details.tsx
@@ -0,0 +1,118 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { Spinner, type JSONContent } from "@carbon/react";
+import { Await, useParams } from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { Suspense } from "react";
+import { useRouteData } from "~/hooks";
+import type { SupplierInteraction, SupplierQuote } from "~/modules/purchasing";
+import {
+ SupplierInteractionDocuments,
+ SupplierInteractionNotes,
+ supplierQuoteValidator,
+ upsertSupplierQuote,
+} from "~/modules/purchasing";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const validation = await validator(supplierQuoteValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { supplierQuoteId, ...data } = validation.data;
+ if (!supplierQuoteId) throw new Error("Could not find supplierQuoteId");
+
+ const update = await upsertSupplierQuote(client, {
+ id,
+ supplierQuoteId,
+ ...data,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(request, error(update.error, "Failed to update quote"))
+ );
+ }
+
+ throw redirect(
+ path.to.supplierQuote(id),
+ await flash(request, success("Updated quote"))
+ );
+}
+
+export default function SupplierQuoteDetailsRoute() {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const routeData = useRouteData<{
+ quote: SupplierQuote;
+ files: Promise<(FileObject & { quoteLineId: string | null })[]>;
+ interaction: SupplierInteraction;
+ }>(path.to.supplierQuote(id));
+
+ if (!routeData) throw new Error("Could not find quote data");
+ const initialValues = {
+ id: routeData?.quote?.id ?? "",
+ supplierId: routeData?.quote?.supplierId ?? "",
+ supplierLocationId: routeData?.quote?.supplierLocationId ?? "",
+ supplierContactId: routeData?.quote?.supplierContactId ?? "",
+ supplierReference: routeData?.quote?.supplierReference ?? "",
+ dueDate: routeData?.quote?.dueDate ?? "",
+ expirationDate: routeData?.quote?.expirationDate ?? "",
+ supplierQuoteId: routeData?.quote?.supplierQuoteId ?? "",
+ status: routeData?.quote?.status ?? "Draft",
+ currencyCode: routeData?.quote?.currencyCode ?? undefined,
+ exchangeRate: routeData?.quote?.exchangeRate ?? undefined,
+ exchangeRateUpdatedAt: routeData?.quote?.exchangeRateUpdatedAt ?? "",
+ };
+
+ return (
+ <>
+ <SupplierInteractionNotes
+ key={`notes-${initialValues.id}`}
+ id={routeData.quote.id}
+ title="Notes"
+ table="supplierQuote"
+ internalNotes={routeData.quote.internalNotes as JSONContent}
+ externalNotes={routeData.quote.externalNotes as JSONContent}
+ />
+ <Suspense
+ key={`documents-${id}`}
+ fallback={
+ <div className="flex w-full min-h-[480px] h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ <Await resolve={routeData.files}>
+ {(resolvedFiles) => (
+ <SupplierInteractionDocuments
+ interaction={routeData.interaction}
+ attachments={resolvedFiles}
+ id={id}
+ type="Supplier Quote"
+ />
+ )}
+ </Await>
+ </Suspense>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$id.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$id.tsx
new file mode 100644
index 0000000000..6ab09a031a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$id.tsx
@@ -0,0 +1,119 @@
+import { error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import { Outlet, useParams } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { defer, redirect } from "@vercel/remix";
+import { PanelProvider } from "~/components/Layout/Panels";
+import { getCurrencyByCode } from "~/modules/accounting";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
+import {
+ getPurchaseOrderLines,
+ getSupplierInteractionByQuote,
+ getSupplierInteractionDocuments,
+ getSupplierQuote,
+ getSupplierQuoteLinePricesByQuoteId,
+ getSupplierQuoteLines,
+} from "~/modules/purchasing";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Supplier Quotes",
+ to: path.to.supplierQuotes,
+ module: "purchasing",
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { companyId } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+ const serviceRole = await getCarbonServiceRole();
+
+ const [quote, lines, prices, interaction] = await Promise.all([
+ getSupplierQuote(serviceRole, id),
+ getSupplierQuoteLines(serviceRole, id),
+ getSupplierQuoteLinePricesByQuoteId(serviceRole, id),
+ getSupplierInteractionByQuote(serviceRole, id),
+ ]);
+
+ if (!interaction.data) throw new Error("Failed to get interaction record");
+
+ if (quote.error) {
+ throw redirect(
+ path.to.quotes,
+ await flash(request, error(quote.error, "Failed to load quote"))
+ );
+ }
+
+ let exchangeRate = 1;
+ if (quote.data?.currencyCode) {
+ const presentationCurrency = await getCurrencyByCode(
+ serviceRole,
+ companyId,
+ quote.data.currencyCode
+ );
+ if (presentationCurrency.data?.exchangeRate) {
+ exchangeRate = presentationCurrency.data.exchangeRate;
+ }
+ }
+
+ let purchaseOrderLines: PostgrestResponse<PurchaseOrderLine> | null = null;
+ if (interaction.data?.purchaseOrderId) {
+ purchaseOrderLines = await getPurchaseOrderLines(
+ serviceRole,
+ interaction.data.purchaseOrderId
+ );
+ }
+
+ return defer({
+ quote: quote.data,
+ lines: lines.data ?? [],
+ files: getSupplierInteractionDocuments(
+ serviceRole,
+ companyId,
+ interaction.data.id
+ ),
+ prices: prices.data ?? [],
+ interaction: interaction.data,
+ exchangeRate,
+ purchaseOrderLines: purchaseOrderLines?.data ?? null,
+ });
+}
+
+export default function SupplierQuoteRoute() {
+ const params = useParams();
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ return (
+ <PanelProvider>
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ {/* <SupplierQuoteHeader />
+ <div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
+ <div className="flex flex-grow overflow-hidden">
+
+ <ResizablePanels
+ explorer={<SupplierQuoteExplorer />}
+ content={
+ <div className="h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full"> */}
+ <VStack spacing={2} className="p-2">
+ <Outlet />
+ </VStack>
+ {/* </div>
+ }
+ properties={<SupplierQuoteProperties />}
+ />
+
+ </div>
+ </div>
+ */}
+ </div>
+ </PanelProvider>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.delete.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.delete.tsx
new file mode 100644
index 0000000000..c56094f2b3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.delete.tsx
@@ -0,0 +1,33 @@
+import { json, redirect } from "@remix-run/react";
+
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { deleteQuoteLine } from "~/modules/sales";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "sales",
+ });
+
+ const { quoteId, lineId: quoteLineId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!quoteLineId) throw new Error("Could not find quoteLineId");
+
+ const deleteLine = await deleteQuoteLine(client, quoteLineId);
+
+ if (deleteLine.error) {
+ return json(
+ path.to.quoteLine(quoteId, quoteLineId),
+ await flash(
+ request,
+ error(deleteLine.error, "Failed to update quote line")
+ )
+ );
+ }
+
+ throw redirect(path.to.quote(quoteId));
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.details.tsx
new file mode 100644
index 0000000000..e34e2937ca
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.$lineId.details.tsx
@@ -0,0 +1,225 @@
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import { Spinner } from "@carbon/react";
+import { Await, Outlet, useLoaderData, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { defer, redirect } from "@vercel/remix";
+import { Fragment, Suspense, useMemo } from "react";
+import { CadModel } from "~/components";
+import type { Tree } from "~/components/TreeView";
+import { usePermissions, useRealtime, useRouteData } from "~/hooks";
+import type {
+ Quotation,
+ QuotationOperation,
+ QuotationPrice,
+ QuoteMethod,
+} from "~/modules/sales";
+import {
+ getOpportunityLineDocuments,
+ getQuoteLine,
+ getQuoteLinePrices,
+ getQuoteOperationsByLine,
+ OpportunityLineDocuments,
+ OpportunityLineNotes,
+ QuoteLineCosting,
+ QuoteLineForm,
+ QuoteLinePricing,
+ quoteLineValidator,
+ upsertQuoteLine,
+ useLineCosts,
+} from "~/modules/sales";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export const config = {
+ runtime: "nodejs",
+};
+
+export const loader = async ({ request, params }: LoaderFunctionArgs) => {
+ const { companyId } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { quoteId, lineId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const serviceRole = await getCarbonServiceRole();
+
+ const [line, operations, prices] = await Promise.all([
+ getQuoteLine(serviceRole, lineId),
+ getQuoteOperationsByLine(serviceRole, lineId),
+ getQuoteLinePrices(serviceRole, lineId),
+ ]);
+
+ if (line.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(line.error, "Failed to load line"))
+ );
+ }
+
+ return defer({
+ line: line.data,
+ operations: operations?.data ?? [],
+ files: getOpportunityLineDocuments(serviceRole, companyId, lineId),
+ pricesByQuantity: (prices?.data ?? []).reduce<
+ Record<number, QuotationPrice>
+ >((acc, price) => {
+ acc[price.quantity] = price;
+ return acc;
+ }, {}),
+ });
+};
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { quoteId, lineId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const formData = await request.formData();
+
+ const validation = await validator(quoteLineValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const updateQuotationLine = await upsertQuoteLine(client, {
+ id: lineId,
+ ...data,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (updateQuotationLine.error) {
+ throw redirect(
+ path.to.quoteLine(quoteId, lineId),
+ await flash(
+ request,
+ error(updateQuotationLine.error, "Failed to update quote line")
+ )
+ );
+ }
+
+ throw redirect(path.to.quoteLine(quoteId, lineId));
+}
+
+export default function QuoteLine() {
+ const { line, operations, files, pricesByQuantity } =
+ useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+ const { quoteId, lineId } = useParams();
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ // useRealtime("quoteLine", `id=eq.${lineId}`);
+ useRealtime("quoteMaterial", `quoteLineId=eq.${lineId}`);
+ useRealtime("quoteOperation", `quoteLineId=eq.${lineId}`);
+
+ const quoteData = useRouteData<{
+ methods: Tree<QuoteMethod>[];
+ quote: Quotation;
+ }>(path.to.quote(quoteId));
+
+ const methodTree = useMemo(
+ () => quoteData?.methods?.find((m) => m.data.quoteLineId === line.id),
+ [quoteData, line.id]
+ );
+
+ const getLineCosts = useLineCosts({
+ methodTree,
+ operations: operations as QuotationOperation[],
+ unitCost: line.unitCost ?? 0,
+ });
+
+ const initialValues = {
+ ...line,
+ id: line.id ?? undefined,
+ quoteId: line.quoteId ?? "",
+ customerPartId: line.customerPartId ?? "",
+ customerPartRevision: line.customerPartRevision ?? "",
+ description: line.description ?? "",
+ estimatorId: line.estimatorId ?? "",
+ itemId: line.itemId ?? "",
+ itemReadableId: line.itemReadableId ?? "",
+ methodType: line.methodType ?? "Make",
+ modelUploadId: line.modelUploadId ?? undefined,
+ noQuoteReason: line.noQuoteReason ?? undefined,
+ status: line.status ?? "Not Started",
+ quantity: line.quantity ?? [1],
+ unitOfMeasureCode: line.unitOfMeasureCode ?? "",
+ taxPercent: line.taxPercent ?? 0,
+ };
+
+ return (
+ <Fragment key={lineId}>
+ <QuoteLineForm key={lineId} initialValues={initialValues} />
+ <OpportunityLineNotes
+ id={line.id}
+ table="quoteLine"
+ title="Notes"
+ subTitle={line.itemReadableId ?? ""}
+ notes={line.notes as JSONContent}
+ />
+ <div className="grid grid-cols-1 2xl:grid-cols-2 w-full flex-grow gap-2 ">
+ <Suspense
+ fallback={
+ <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ <Await resolve={files}>
+ {(resolvedFiles) => (
+ <OpportunityLineDocuments
+ files={resolvedFiles ?? []}
+ id={quoteId}
+ lineId={lineId}
+ modelUpload={line ?? undefined}
+ type="Quote"
+ />
+ )}
+ </Await>
+ </Suspense>
+
+ <CadModel
+ isReadOnly={!permissions.can("update", "sales")}
+ metadata={{
+ quoteLineId: line.id ?? undefined,
+ itemId: line.itemId ?? undefined,
+ }}
+ modelPath={line?.modelPath ?? null}
+ title="CAD Model"
+ uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ />
+ </div>
+
+ {line.methodType === "Make" && line.status !== "No Quote" && (
+ <QuoteLineCosting
+ quantities={line.quantity ?? [1]}
+ getLineCosts={getLineCosts}
+ />
+ )}
+ {line.status !== "No Quote" && (
+ <QuoteLinePricing
+ line={line}
+ pricesByQuantity={pricesByQuantity}
+ getLineCosts={getLineCosts}
+ />
+ )}
+ <Outlet />
+ </Fragment>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.convert.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.convert.tsx
new file mode 100644
index 0000000000..c846948074
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.convert.tsx
@@ -0,0 +1,73 @@
+import {
+ assertIsPost,
+ error,
+ getCarbonServiceRole,
+ success,
+} from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { convertQuoteToOrder, selectedLinesValidator } from "~/modules/sales";
+import { path } from "~/utils/path";
+
+// the edge function grows larger than 2MB - so this is a workaround to avoid the edge function limit
+export const config = {
+ runtime: "nodejs",
+};
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const formData = await request.formData();
+ const selectedLinesRaw = formData.get("selectedLines") ?? "{}";
+
+ if (typeof selectedLinesRaw !== "string") {
+ throw redirect(
+ path.to.quoteDetails(quoteId),
+ await flash(request, error("Invalid selected lines data"))
+ );
+ }
+
+ const parseResult = selectedLinesValidator.safeParse(
+ JSON.parse(selectedLinesRaw)
+ );
+
+ if (!parseResult.success) {
+ console.error("Validation error:", parseResult.error);
+ throw redirect(
+ path.to.quoteDetails(quoteId),
+ await flash(request, error("Invalid selected lines data"))
+ );
+ }
+
+ const selectedLines = parseResult.data;
+
+ const serviceRole = getCarbonServiceRole();
+ const convert = await convertQuoteToOrder(serviceRole, {
+ id: quoteId,
+ companyId,
+ userId,
+ selectedLines,
+ });
+
+ if (convert.error) {
+ throw redirect(
+ path.to.quoteDetails(quoteId),
+ await flash(
+ request,
+ error(convert.error, "Failed to convert quote to order")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.salesOrder(convert.data?.convertedId!),
+ await flash(request, success("Successfully converted quote to order"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.exchange-rate.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.exchange-rate.tsx
new file mode 100644
index 0000000000..3c42464ced
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.exchange-rate.tsx
@@ -0,0 +1,39 @@
+import { assertIsPost, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { getCurrencyByCode } from "~/modules/accounting";
+import { updateQuoteExchangeRate } from "~/modules/sales";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const formData = await request.formData();
+ const currencyCode = formData.get("currencyCode") as string;
+ if (!currencyCode) throw new Error("Could not find currencyCode");
+
+ const currency = await getCurrencyByCode(client, companyId, currencyCode);
+ if (currency.error || !currency.data.exchangeRate)
+ throw new Error("Could not find currency");
+
+ const update = await updateQuoteExchangeRate(client, {
+ id: quoteId,
+ exchangeRate: currency.data.exchangeRate,
+ });
+
+ if (update.error) {
+ throw new Error("Could not update exchange rate");
+ }
+
+ return redirect(
+ path.to.quoteDetails(quoteId),
+ await flash(request, success("Successfully updated exchange rate"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.finalize.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.finalize.tsx
new file mode 100644
index 0000000000..5e73a8827a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.finalize.tsx
@@ -0,0 +1,239 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { QuoteEmail } from "@carbon/documents";
+import { validationError, validator } from "@carbon/form";
+import { getLocalTimeZone, now } from "@internationalized/date";
+import { renderAsync } from "@react-email/components";
+import { tasks } from "@trigger.dev/sdk/v3";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertDocument } from "~/modules/documents";
+import {
+ finalizeQuote,
+ getCustomer,
+ getCustomerContact,
+ getOpportunityByQuote,
+ getQuote,
+ quoteFinalizeValidator,
+} from "~/modules/sales";
+import { getCompany, getCompanySettings } from "~/modules/settings";
+import { upsertExternalLink } from "~/modules/shared";
+import { getUser } from "~/modules/users/users.server";
+import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
+import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have this task defined
+import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
+
+export const config = { runtime: "nodejs" };
+
+export async function action(args: ActionFunctionArgs) {
+ const { request, params } = args;
+ assertIsPost(request);
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ role: "employee",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ let file: ArrayBuffer;
+ let fileName: string;
+
+ const [quote, opportunity] = await Promise.all([
+ getQuote(client, quoteId),
+ getOpportunityByQuote(client, quoteId),
+ ]);
+ if (quote.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(quote.error, "Failed to get quote"))
+ );
+ }
+ if (opportunity.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(opportunity.error, "Failed to get opportunity")
+ )
+ );
+ }
+
+ const [externalLink] = await Promise.all([
+ upsertExternalLink(client, {
+ id: quote.data.externalLinkId ?? undefined, // TODO
+ documentType: "Quote",
+ documentId: quoteId,
+ customerId: quote.data.customerId,
+ expiresAt: quote.data.expirationDate,
+ companyId,
+ }),
+ client
+ .from("opportunity")
+ .update({
+ quoteCompletedDate: now(getLocalTimeZone()).toAbsoluteString(),
+ })
+ .eq("quoteId", quoteId),
+ ]);
+
+ if (externalLink.data && quote.data.externalLinkId !== externalLink.data.id) {
+ await client
+ .from("quote")
+ .update({ externalLinkId: externalLink.data.id })
+ .eq("id", quoteId);
+ }
+
+ try {
+ const pdf = await pdfLoader({ ...args, params: { id: quoteId } });
+ if (pdf.headers.get("content-type") !== "application/pdf")
+ throw new Error("Failed to generate PDF");
+
+ file = await pdf.arrayBuffer();
+ fileName = stripSpecialCharacters(
+ `${quote.data.quoteId} - ${new Date().toISOString().slice(0, -5)}.pdf`
+ );
+
+ const documentFilePath = `${companyId}/opportunity/${opportunity.data.id}/${fileName}`;
+
+ const documentFileUpload = await client.storage
+ .from("private")
+ .upload(documentFilePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ upsert: true,
+ });
+
+ if (documentFileUpload.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(documentFileUpload.error, "Failed to upload file")
+ )
+ );
+ }
+
+ const createDocument = await upsertDocument(client, {
+ path: documentFilePath,
+ name: fileName,
+ size: Math.round(file.byteLength / 1024),
+ sourceDocument: "Quote",
+ sourceDocumentId: quoteId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ createdBy: userId,
+ companyId,
+ });
+
+ if (createDocument.error) {
+ return redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(createDocument.error, "Failed to create document")
+ )
+ );
+ }
+
+ const finalize = await finalizeQuote(client, quoteId, userId);
+ if (finalize.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(finalize.error, "Failed to finalize quote"))
+ );
+ }
+ } catch (err) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(err, "Failed to finalize quote"))
+ );
+ }
+
+ const validation = await validator(quoteFinalizeValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { notification, customerContact: customerContactId } = validation.data;
+
+ switch (notification) {
+ case "Email":
+ try {
+ if (!customerContactId) throw new Error("Customer contact is required");
+
+ const [company, companySettings, customer, customerContact, user] =
+ await Promise.all([
+ getCompany(client, companyId),
+ getCompanySettings(client, companyId),
+ getCustomer(client, quote.data.customerId!),
+ getCustomerContact(client, customerContactId),
+ getUser(client, userId),
+ ]);
+
+ if (!company.data) throw new Error("Failed to get company");
+ if (!companySettings.data)
+ throw new Error("Failed to get company settings");
+ if (!customer.data) throw new Error("Failed to get customer");
+ if (!customerContact.data)
+ throw new Error("Failed to get customer contact");
+ if (!user.data) throw new Error("Failed to get user");
+
+ const emailTemplate = QuoteEmail({
+ company: company.data,
+ companySettings: companySettings.data,
+ // @ts-ignore
+ quote: quote.data,
+ recipient: {
+ email: customerContact.data?.contact!.email!,
+ firstName: customerContact.data.contact!.firstName!,
+ lastName: customerContact.data.contact!.lastName!,
+ },
+ sender: {
+ email: user.data.email,
+ firstName: user.data.firstName,
+ lastName: user.data.lastName,
+ },
+ });
+
+ const html = await renderAsync(emailTemplate);
+ const text = await renderAsync(emailTemplate, { plainText: true });
+
+ await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
+ to: customerContact.data.contact!.email!,
+ from: user.data.email,
+ subject: `Quote ${quote.data.quoteId}`,
+ html,
+ text,
+ attachments: [
+ {
+ content: Buffer.from(file).toString("base64"),
+ filename: fileName,
+ },
+ ],
+ companyId,
+ });
+ } catch (err) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(err, "Failed to send email"))
+ );
+ }
+
+ break;
+ case undefined:
+ case "None":
+ break;
+ default:
+ throw new Error("Invalid notification type");
+ }
+
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, success("Quote finalized successfully"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.new.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.new.tsx
new file mode 100644
index 0000000000..227eb72543
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.new.tsx
@@ -0,0 +1,73 @@
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import {
+ quoteLineValidator,
+ upsertQuoteLine,
+ upsertQuoteLineMethod,
+} from "~/modules/sales";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const formData = await request.formData();
+ const validation = await validator(quoteLineValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const serviceRole = getCarbonServiceRole();
+ const createQuotationLine = await upsertQuoteLine(serviceRole, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createQuotationLine.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(createQuotationLine.error, "Failed to create quote line.")
+ )
+ );
+ }
+
+ const quoteLineId = createQuotationLine.data.id;
+ if (data.methodType === "Make") {
+ const upsertMethod = await upsertQuoteLineMethod(serviceRole, {
+ quoteId,
+ quoteLineId,
+ itemId: data.itemId,
+ companyId,
+ userId,
+ });
+
+ if (upsertMethod.error) {
+ throw redirect(
+ path.to.quoteLine(quoteId, quoteLineId),
+ await flash(
+ request,
+ error(upsertMethod.error, "Failed to create quote line method.")
+ )
+ );
+ }
+ }
+
+ throw redirect(path.to.quoteLine(quoteId, quoteLineId));
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.status.tsx b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.status.tsx
new file mode 100644
index 0000000000..2643257064
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/$quoteId.status.tsx
@@ -0,0 +1,45 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { quoteStatusType, updateQuoteStatus } from "~/modules/sales";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { quoteId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get("status") as (typeof quoteStatusType)[number];
+
+ if (!status || !quoteStatusType.includes(status)) {
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await updateQuoteStatus(client, {
+ id,
+ status,
+ assignee: ["Closed"].includes(status) ? null : undefined,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.quote(id),
+ await flash(request, error(update.error, "Failed to update quote status"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.quote(id),
+ await flash(request, success("Updated quote status"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/_layout.tsx b/apps/carbon/app/routes/x+/supplier-quote+/_layout.tsx
new file mode 100644
index 0000000000..ceb5f6fbf3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/_layout.tsx
@@ -0,0 +1,27 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, Outlet } from "@remix-run/react";
+import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Supplier Quote" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: "Purchasing",
+ to: path.to.supplierQuotes,
+ module: "purchasing",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ return json({});
+}
+
+export default function SupplierQuoteRoute() {
+ return <Outlet />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/new.tsx b/apps/carbon/app/routes/x+/supplier-quote+/new.tsx
new file mode 100644
index 0000000000..3ca9b4a727
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/new.tsx
@@ -0,0 +1,96 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { useUrlParams } from "~/hooks";
+import {
+ SupplierQuoteForm,
+ supplierQuoteValidator,
+ upsertSupplierQuote,
+} from "~/modules/purchasing";
+import { getNextSequence } from "~/modules/settings";
+import { setCustomFields } from "~/utils/form";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Supplier Quote",
+ to: path.to.supplierQuotes,
+ module: "purchasing",
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(supplierQuoteValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(
+ client,
+ "supplierQuote",
+ companyId
+ );
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.newSupplierQuote,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const createSupplierQuote = await upsertSupplierQuote(client, {
+ ...validation.data,
+ supplierQuoteId: nextSequence.data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createSupplierQuote.error || !createSupplierQuote.data?.[0]) {
+ throw redirect(
+ path.to.supplierQuotes,
+ await flash(
+ request,
+ error(createSupplierQuote.error, "Failed to insert supplier quote")
+ )
+ );
+ }
+
+ const order = createSupplierQuote.data?.[0];
+
+ throw redirect(path.to.supplierQuote(order.id!));
+}
+
+export default function SupplierQuoteNewRoute() {
+ const [params] = useUrlParams();
+ const supplierId = params.get("supplierId");
+ const initialValues = {
+ supplierContactId: "",
+ supplierId: supplierId ?? "",
+ supplierReference: "",
+ expirationDate: "",
+ dueDate: "",
+ supplierQuoteId: undefined,
+ status: "Draft" as const,
+ currencyCode: undefined,
+ exchangeRate: undefined,
+ exchangeRateUpdatedAt: "",
+ };
+
+ return (
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
+ <SupplierQuoteForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/update.tsx b/apps/carbon/app/routes/x+/supplier-quote+/update.tsx
new file mode 100644
index 0000000000..34d0d23a32
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier-quote+/update.tsx
@@ -0,0 +1,97 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { getCurrencyByCode } from "~/modules/accounting";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const formData = await request.formData();
+ const ids = formData.getAll("ids");
+ const field = formData.get("field");
+ const value = formData.get("value");
+
+ if (
+ typeof field !== "string" ||
+ (typeof value !== "string" && value !== null)
+ ) {
+ return json({ error: { message: "Invalid form data" }, data: null });
+ }
+
+ switch (field) {
+ case "supplierId":
+ let currencyCode: string | undefined;
+ if (value && ids.length === 1) {
+ const supplier = await client
+ ?.from("supplier")
+ .select("currencyCode")
+ .eq("id", value)
+ .single();
+
+ if (supplier.data?.currencyCode) {
+ currencyCode = supplier.data.currencyCode;
+ return json(
+ await client
+ .from("supplierQuote")
+ .update({
+ supplierId: value ?? undefined,
+ currencyCode: currencyCode ? currencyCode : undefined,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[])
+ );
+ }
+ }
+
+ return json(
+ await client
+ .from("supplierQuote")
+ .update({
+ supplierId: value ?? undefined,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[])
+ );
+ case "currencyCode":
+ const currency = await getCurrencyByCode(
+ client,
+ companyId,
+ value as string
+ );
+ if (currency.data) {
+ return json(
+ await client
+ .from("supplierQuote")
+ .update({
+ currencyCode: value,
+ exchangeRate: currency.data.exchangeRate,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[])
+ );
+ }
+ // don't break -- just let it catch the next case
+
+ case "supplierContactId":
+ case "supplierLocationId":
+ case "supplierReference":
+ case "dueDate":
+ case "expirationDate":
+ return json(
+ await client
+ .from("supplierQuote")
+ .update({
+ [field]: value ? value : null,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[])
+ );
+ default:
+ return json({ error: { message: "Invalid field" }, data: null });
+ }
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 25a1300fa3..3c9bd3d871 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -315,6 +315,8 @@ export const path = {
generatePath(`${x}/supplier/${supplierId}/locations/delete/${id}`),
deleteSupplierProcess: (supplierId: string, id: string) =>
generatePath(`${x}/supplier/${supplierId}/processes/delete/${id}`),
+ deleteSupplierQuote: (id: string) =>
+ generatePath(`${x}/supplier-quote/${id}/delete`),
deleteSupplierStatus: (id: string) =>
generatePath(`${x}/purchasing/supplier-statuses/delete/${id}`),
deleteSupplierType: (id: string) =>
@@ -549,6 +551,7 @@ export const path = {
generatePath(`${x}/supplier/${id}/locations/new`),
newSupplierProcess: (id: string) =>
generatePath(`${x}/supplier/${id}/processes/new`),
+ newSupplierQuote: `${x}/supplier-quote/new`,
newSupplierStatus: `${x}/purchasing/supplier-statuses/new`,
newSupplierType: `${x}/purchasing/supplier-types/new`,
newTag: `${x}/settings/tags/new`,
@@ -790,6 +793,7 @@ export const path = {
generatePath(`${x}/supplier/${id}/processes`),
supplierShipping: (id: string) =>
generatePath(`${x}/supplier/${id}/shipping`),
+ supplierQuote: (id: string) => generatePath(`${x}/supplier-quote/${id}`),
supplierQuotes: `${x}/purchasing/quotes`,
supplierQuoteFavorite: `${x}/purchasing/quotes/favorite`,
supplierQuoteDetails: (id: string) =>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a3cb1cd9ae..4f7bc8b7a4 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13286,7 +13286,9 @@ export type Database = {
customFields: Json | null;
exchangeRate: number | null;
exchangeRateUpdatedAt: string | null;
+ externalNotes: Json | null;
id: string;
+ internalNotes: Json | null;
notes: string | null;
orderDate: string;
purchaseOrderId: string;
@@ -13312,7 +13314,9 @@ export type Database = {
customFields?: Json | null;
exchangeRate?: number | null;
exchangeRateUpdatedAt?: string | null;
+ externalNotes?: Json | null;
id?: string;
+ internalNotes?: Json | null;
notes?: string | null;
orderDate?: string;
purchaseOrderId: string;
@@ -13338,7 +13342,9 @@ export type Database = {
customFields?: Json | null;
exchangeRate?: number | null;
exchangeRateUpdatedAt?: string | null;
+ externalNotes?: Json | null;
id?: string;
+ internalNotes?: Json | null;
notes?: string | null;
orderDate?: string;
purchaseOrderId?: string;
@@ -13841,6 +13847,7 @@ export type Database = {
itemId: string | null;
itemReadableId: string | null;
locationId: string | null;
+ notes: Json | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity: number | null;
@@ -13873,6 +13880,7 @@ export type Database = {
itemId?: string | null;
itemReadableId?: string | null;
locationId?: string | null;
+ notes?: Json | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
@@ -13905,6 +13913,7 @@ export type Database = {
itemId?: string | null;
itemReadableId?: string | null;
locationId?: string | null;
+ notes?: Json | null;
purchaseOrderId?: string;
purchaseOrderLineType?: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
@@ -20382,6 +20391,103 @@ export type Database = {
}
];
};
+ supplierInteraction: {
+ Row: {
+ companyId: string;
+ id: string;
+ purchaseOrderCompletedDate: string | null;
+ purchaseOrderId: string | null;
+ quoteDocumentPath: string | null;
+ salesOrderDocumentPath: string | null;
+ supplierQuoteCompletedDate: string | null;
+ supplierQuoteId: string | null;
+ };
+ Insert: {
+ companyId: string;
+ id?: string;
+ purchaseOrderCompletedDate?: string | null;
+ purchaseOrderId?: string | null;
+ quoteDocumentPath?: string | null;
+ salesOrderDocumentPath?: string | null;
+ supplierQuoteCompletedDate?: string | null;
+ supplierQuoteId?: string | null;
+ };
+ Update: {
+ companyId?: string;
+ id?: string;
+ purchaseOrderCompletedDate?: string | null;
+ purchaseOrderId?: string | null;
+ quoteDocumentPath?: string | null;
+ salesOrderDocumentPath?: string | null;
+ supplierQuoteCompletedDate?: string | null;
+ supplierQuoteId?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "companies";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "customFieldTables";
+ referencedColumns: ["companyId"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "integrations";
+ referencedColumns: ["companyId"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierQuoteId_fkey";
+ columns: ["supplierQuoteId"];
+ isOneToOne: false;
+ referencedRelation: "supplierQuote";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierQuoteId_fkey";
+ columns: ["supplierQuoteId"];
+ isOneToOne: false;
+ referencedRelation: "supplierQuotes";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
supplierLedger: {
Row: {
amount: number;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a3cb1cd9ae..4f7bc8b7a4 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -13286,7 +13286,9 @@ export type Database = {
customFields: Json | null;
exchangeRate: number | null;
exchangeRateUpdatedAt: string | null;
+ externalNotes: Json | null;
id: string;
+ internalNotes: Json | null;
notes: string | null;
orderDate: string;
purchaseOrderId: string;
@@ -13312,7 +13314,9 @@ export type Database = {
customFields?: Json | null;
exchangeRate?: number | null;
exchangeRateUpdatedAt?: string | null;
+ externalNotes?: Json | null;
id?: string;
+ internalNotes?: Json | null;
notes?: string | null;
orderDate?: string;
purchaseOrderId: string;
@@ -13338,7 +13342,9 @@ export type Database = {
customFields?: Json | null;
exchangeRate?: number | null;
exchangeRateUpdatedAt?: string | null;
+ externalNotes?: Json | null;
id?: string;
+ internalNotes?: Json | null;
notes?: string | null;
orderDate?: string;
purchaseOrderId?: string;
@@ -13841,6 +13847,7 @@ export type Database = {
itemId: string | null;
itemReadableId: string | null;
locationId: string | null;
+ notes: Json | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity: number | null;
@@ -13873,6 +13880,7 @@ export type Database = {
itemId?: string | null;
itemReadableId?: string | null;
locationId?: string | null;
+ notes?: Json | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
@@ -13905,6 +13913,7 @@ export type Database = {
itemId?: string | null;
itemReadableId?: string | null;
locationId?: string | null;
+ notes?: Json | null;
purchaseOrderId?: string;
purchaseOrderLineType?: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
@@ -20382,6 +20391,103 @@ export type Database = {
}
];
};
+ supplierInteraction: {
+ Row: {
+ companyId: string;
+ id: string;
+ purchaseOrderCompletedDate: string | null;
+ purchaseOrderId: string | null;
+ quoteDocumentPath: string | null;
+ salesOrderDocumentPath: string | null;
+ supplierQuoteCompletedDate: string | null;
+ supplierQuoteId: string | null;
+ };
+ Insert: {
+ companyId: string;
+ id?: string;
+ purchaseOrderCompletedDate?: string | null;
+ purchaseOrderId?: string | null;
+ quoteDocumentPath?: string | null;
+ salesOrderDocumentPath?: string | null;
+ supplierQuoteCompletedDate?: string | null;
+ supplierQuoteId?: string | null;
+ };
+ Update: {
+ companyId?: string;
+ id?: string;
+ purchaseOrderCompletedDate?: string | null;
+ purchaseOrderId?: string | null;
+ quoteDocumentPath?: string | null;
+ salesOrderDocumentPath?: string | null;
+ supplierQuoteCompletedDate?: string | null;
+ supplierQuoteId?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "companies";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "customFieldTables";
+ referencedColumns: ["companyId"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "integrations";
+ referencedColumns: ["companyId"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_purchaseOrderId_fkey";
+ columns: ["purchaseOrderId"];
+ isOneToOne: false;
+ referencedRelation: "purchaseOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierQuoteId_fkey";
+ columns: ["supplierQuoteId"];
+ isOneToOne: false;
+ referencedRelation: "supplierQuote";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierQuoteId_fkey";
+ columns: ["supplierQuoteId"];
+ isOneToOne: false;
+ referencedRelation: "supplierQuotes";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
supplierLedger: {
Row: {
amount: number;
diff --git a/packages/database/supabase/migrations/20241202192419_supplier-quotes.sql b/packages/database/supabase/migrations/20241202192419_supplier-quotes.sql
index 03cfe6f03d..47e6b49691 100644
--- a/packages/database/supabase/migrations/20241202192419_supplier-quotes.sql
+++ b/packages/database/supabase/migrations/20241202192419_supplier-quotes.sql
@@ -42,7 +42,6 @@ CREATE TABLE "supplierQuote" (
"supplierContactId" TEXT,
"supplierReference" TEXT,
"assignee" TEXT,
- "externalLinkId" UUID,
"currencyCode" TEXT,
"exchangeRate" NUMERIC(10,4),
"exchangeRateUpdatedAt" TIMESTAMP WITH TIME ZONE,
@@ -199,3 +198,7 @@ FROM
GROUP BY
"supplierQuoteId"
) ql ON ql."supplierQuoteId" = q.id;
+
+ALTER TABLE "purchaseOrder" ADD COLUMN "internalNotes" JSON DEFAULT '{}'::JSON;
+ALTER TABLE "purchaseOrder" ADD COLUMN "externalNotes" JSON DEFAULT '{}'::JSON;
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "notes" JSON DEFAULT '{}'::JSON;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20241203165446_supplier-interaction.sql b/packages/database/supabase/migrations/20241203165446_supplier-interaction.sql
new file mode 100644
index 0000000000..ee3939ca89
--- /dev/null
+++ b/packages/database/supabase/migrations/20241203165446_supplier-interaction.sql
@@ -0,0 +1,15 @@
+CREATE TABLE "supplierInteraction" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT,
+ "purchaseOrderCompletedDate" TIMESTAMP WITH TIME ZONE,
+ "supplierQuoteId" TEXT,
+ "supplierQuoteCompletedDate" TIMESTAMP WITH TIME ZONE,
+ "quoteDocumentPath" TEXT,
+ "salesOrderDocumentPath" TEXT,
+ "companyId" TEXT NOT NULL,
+
+ PRIMARY KEY ("id"),
+ FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder" ("id") ON DELETE SET NULL,
+ FOREIGN KEY ("supplierQuoteId") REFERENCES "supplierQuote" ("id") ON DELETE SET NULL,
+ FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE
+);
\ No newline at end of file