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: upload PO document

Brad Barbin25be8518e150
diff --git a/apps/carbon/app/lib/autodesk/autodesk.server.ts b/apps/carbon/app/lib/autodesk/autodesk.server.ts
index c26a1a09d1..3cb2736db1 100644
--- a/apps/carbon/app/lib/autodesk/autodesk.server.ts
+++ b/apps/carbon/app/lib/autodesk/autodesk.server.ts
@@ -325,6 +325,7 @@ export async function getThumbnail(
.from("private")
.upload(fileName, data, {
cacheControl: `${365 * 24 * 60 * 60}`,
+ upsert: true,
});
if (fileUpload.error) {
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index dbd3f98200..b587751104 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -269,7 +269,10 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
const result = await supabase?.storage
.from("private")
- .upload(fileName, file);
+ .upload(fileName, file, {
+ upsert: true,
+ cacheControl: "3600",
+ });
if (result?.error) {
throw new Error(result.error.message);
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx
index 369922ff5d..1b5ead6235 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx
@@ -27,6 +27,7 @@ const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
});
if (fileUpload.error) {
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
index 055a0dc1f0..cf83494da1 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
@@ -30,6 +30,7 @@ const PurchaseOrderDocumentForm = ({
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
});
if (fileUpload.error) {
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index 2e7a72d566..149dc998be 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -7,6 +7,7 @@ import type {
getCustomers,
getCustomerStatuses,
getCustomerTypes,
+ getOpportunityByQuote,
getQuoteDocuments,
getQuoteLinePrices,
getQuoteLines,
@@ -80,6 +81,10 @@ export type CustomerType = NonNullable<
Awaited<ReturnType<typeof getCustomerTypes>>["data"]
>[number];
+export type Opportunity = NonNullable<
+ Awaited<ReturnType<typeof getOpportunityByQuote>>["data"]
+>;
+
export type QuoteMethod = NonNullable<
Awaited<ReturnType<typeof getQuoteMethodTrees>>["data"]
>[number]["data"];
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocumentForm.tsx
deleted file mode 100644
index 4db8a55a9e..0000000000
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocumentForm.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { File, toast } from "@carbon/react";
-import { useSubmit } from "@remix-run/react";
-import type { ChangeEvent } from "react";
-import { LuUpload } from "react-icons/lu";
-import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import { path } from "~/utils/path";
-
-type OpportunityDocumentFormProps = {
- opportunityId: string;
- id: string;
- type: "Sales Order" | "Request for Quote" | "Quote";
-};
-
-const OpportunityDocumentForm = ({
- opportunityId,
- id,
- type,
-}: OpportunityDocumentFormProps) => {
- const submit = useSubmit();
- const { company } = useUser();
- const { supabase } = useSupabase();
- const permissions = usePermissions();
-
- const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
- const file = e.target.files[0];
- const fileName = `${company.id}/opportunity/${opportunityId}/${file.name}`;
-
- const fileUpload = await supabase.storage
- .from("private")
- .upload(fileName, file, {
- cacheControl: `${12 * 60 * 60}`,
- });
-
- if (fileUpload.error) {
- toast.error("Failed to upload file");
- }
-
- if (fileUpload.data?.path) {
- toast.success("File uploaded");
- submitFileData({
- path: fileUpload.data.path,
- name: file.name,
- size: file.size,
- });
- }
- }
- };
-
- const submitFileData = ({
- 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,
- });
- };
-
- return (
- <File
- isDisabled={!permissions.can("update", "sales")}
- leftIcon={<LuUpload />}
- onChange={uploadFile}
- >
- New
- </File>
- );
-};
-
-export default OpportunityDocumentForm;
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
index 09e7096d99..d82f0c218c 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
@@ -1,4 +1,5 @@
import {
+ Badge,
Card,
CardAction,
CardContent,
@@ -8,6 +9,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ File,
HStack,
IconButton,
Table,
@@ -16,32 +18,40 @@ import {
Th,
Thead,
Tr,
+ toast,
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
-import { Outlet } from "@remix-run/react";
+import { Outlet, useRevalidator, useSubmit } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
+import type { ChangeEvent } from "react";
+import { useCallback } from "react";
+import { LuUpload } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, Hyperlink } from "~/components";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
-import OpportunityDocumentForm from "./OpportunityDocumentForm";
-import { useOpportunityDocuments } from "./useOpportunityDocuments";
+import { path } from "~/utils/path";
+import type { Opportunity } from "../../types";
type OpportunityDocumentsProps = {
attachments: FileObject[];
- opportunityId: string;
+ opportunity: Opportunity;
id: string;
type: "Sales Order" | "Request for Quote" | "Quote";
};
const OpportunityDocuments = ({
attachments,
- opportunityId,
+ opportunity,
id,
type,
}: OpportunityDocumentsProps) => {
const { canDelete, download, deleteAttachment, getPath } =
useOpportunityDocuments({
- opportunityId,
+ opportunityId: opportunity.id,
+ id,
+ type,
});
return (
@@ -53,7 +63,7 @@ const OpportunityDocuments = ({
</CardHeader>
<CardAction>
<OpportunityDocumentForm
- opportunityId={opportunityId}
+ opportunityId={opportunity.id}
id={id}
type={type}
/>
@@ -92,6 +102,14 @@ const OpportunityDocuments = ({
attachment.name
)}
</Hyperlink>
+ {opportunity?.purchaseOrderDocumentPath ===
+ getPath(attachment) && (
+ <Badge variant="secondary">PO</Badge>
+ )}
+ {opportunity?.requestForQuoteDocumentPath ===
+ getPath(attachment) && (
+ <Badge variant="secondary">RFQ</Badge>
+ )}
</HStack>
</Td>
<Td className="text-xs font-mono">
@@ -100,7 +118,7 @@ const OpportunityDocuments = ({
)}
</Td>
<Td>
- <div className="flex justify-end w-full">
+ <div className="flex justify-end gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
@@ -147,4 +165,162 @@ const OpportunityDocuments = ({
);
};
+type OpportunityDocumentFormProps = {
+ opportunityId: string;
+ id: string;
+ type: "Sales Order" | "Request for Quote" | "Quote";
+};
+
+export const useOpportunityDocuments = ({
+ id,
+ opportunityId,
+ type,
+}: OpportunityDocumentFormProps) => {
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+ 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}/opportunity/${opportunityId}/${attachment.name}`;
+ },
+ [company.id, opportunityId]
+ );
+
+ const deleteAttachment = useCallback(
+ async (attachment: FileObject) => {
+ const result = await supabase?.storage
+ .from("private")
+ .remove([getPath(attachment)]);
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error deleting file");
+ return;
+ }
+
+ toast.success("File deleted successfully");
+ revalidator.revalidate();
+ },
+ [supabase?.storage, getPath, revalidator]
+ );
+
+ const download = useCallback(
+ async (attachment: FileObject) => {
+ const result = await supabase?.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);
+ },
+ [supabase?.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,
+ });
+ },
+ [id, submit, type]
+ );
+
+ const upload = useCallback(
+ async (file: File) => {
+ if (!supabase) {
+ toast.error("Supabase client not available");
+ return;
+ }
+ const fileName = getPath(file);
+
+ const fileUpload = await supabase.storage
+ .from("private")
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ toast.error("Failed to upload file");
+ }
+ if (fileUpload.data?.path) {
+ toast.success("File uploaded");
+ createDocumentRecord({
+ path: fileUpload.data.path,
+ name: file.name,
+ size: file.size,
+ });
+ }
+ },
+ [getPath, createDocumentRecord, supabase]
+ );
+
+ return {
+ canDelete,
+ deleteAttachment,
+ download,
+ upload,
+ getPath,
+ };
+};
+
+const OpportunityDocumentForm = (props: OpportunityDocumentFormProps) => {
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const { upload } = useOpportunityDocuments(props);
+
+ const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files && supabase && company) {
+ const file = e.target.files[0];
+ upload(file);
+ }
+ };
+
+ return (
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFile}
+ >
+ New
+ </File>
+ );
+};
+
export default OpportunityDocuments;
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
index 62b644a105..db4bdc6f98 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
@@ -35,17 +35,27 @@ import { path } from "~/utils/path";
import { useCallback } from "react";
-const useOpportunityLineDocuments = ({ lineId }: { lineId: string }) => {
+const useOpportunityLineDocuments = ({
+ id,
+ lineId,
+ type,
+}: {
+ id: string;
+ lineId: string;
+ type: "Request for Quote" | "Sales Order" | "Quote";
+}) => {
const navigate = useNavigate();
const permissions = usePermissions();
const revalidator = useRevalidator();
const { supabase } = useSupabase();
const { company } = useUser();
+ const submit = useSubmit();
const canDelete = permissions.can("delete", "sales");
const canUpdate = permissions.can("update", "sales");
+
const getPath = useCallback(
- (file: ItemFile) => {
+ (file: { name: string }) => {
return `${company.id}/opportunity-line/${lineId}/${file.name}`;
},
[company.id, lineId]
@@ -123,6 +133,61 @@ const useOpportunityLineDocuments = ({ lineId }: { lineId: string }) => {
[navigate]
);
+ 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,
+ });
+ },
+ [id, submit, type]
+ );
+
+ const upload = useCallback(
+ async (file: File) => {
+ if (!supabase) {
+ toast.error("Supabase client not available");
+ return;
+ }
+ const fileName = getPath(file);
+
+ const fileUpload = await supabase.storage
+ .from("private")
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ toast.error("Failed to upload file");
+ }
+ if (fileUpload.data?.path) {
+ toast.success("File uploaded");
+ createDocumentRecord({
+ path: fileUpload.data.path,
+ name: file.name,
+ size: file.size,
+ });
+ }
+ },
+ [getPath, createDocumentRecord, supabase]
+ );
+
return {
canDelete,
canUpdate,
@@ -131,6 +196,7 @@ const useOpportunityLineDocuments = ({ lineId }: { lineId: string }) => {
download,
getPath,
viewModel,
+ upload,
};
};
@@ -151,7 +217,9 @@ const OpportunityLineDocuments = ({
}: OpportunityLineDocumentsProps) => {
const { canDelete, download, deleteFile, deleteModel, getPath, viewModel } =
useOpportunityLineDocuments({
+ id,
lineId,
+ type,
});
return (
@@ -309,59 +377,16 @@ const OpportunityLineDocumentForm = ({
lineId,
type,
}: OpportunityLineDocumentFormProps) => {
- const submit = useSubmit();
- const { company } = useUser();
- const { supabase } = useSupabase();
const permissions = usePermissions();
+ const { upload } = useOpportunityLineDocuments({ id, lineId, type });
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
+ if (e.target.files) {
const file = e.target.files[0];
- const fileName = `${company.id}/opportunity-line/${lineId}/${file.name}`;
-
- const fileUpload = await supabase.storage
- .from("private")
- .upload(fileName, file, {
- cacheControl: `${12 * 60 * 60}`,
- });
-
- if (fileUpload.error) {
- toast.error("Failed to upload file");
- }
-
- if (fileUpload.data?.path) {
- toast.success("File uploaded");
- submitFileData({
- path: fileUpload.data.path,
- name: file.name,
- size: file.size,
- });
- }
+ upload(file);
}
};
- const submitFileData = ({
- 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,
- });
- };
-
return (
<File
isDisabled={!permissions.can("update", "sales")}
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/useOpportunityDocuments.ts b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/useOpportunityDocuments.ts
deleted file mode 100644
index 32716ed5fe..0000000000
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/useOpportunityDocuments.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { toast } from "@carbon/react";
-import { useRevalidator } from "@remix-run/react";
-import { useCallback } from "react";
-import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import type { QuotationAttachment } from "~/modules/sales/types";
-
-type Props = {
- opportunityId: string;
-};
-
-export const useOpportunityDocuments = ({ opportunityId }: Props) => {
- const permissions = usePermissions();
- const { company } = useUser();
- const { supabase } = useSupabase();
- const revalidator = useRevalidator();
-
- const canDelete = permissions.can("delete", "sales"); // TODO: or is document owner
-
- const getPath = useCallback(
- (attachment: QuotationAttachment) => {
- return `${company.id}/opportunity/${opportunityId}/${attachment.name}`;
- },
- [company.id, opportunityId]
- );
-
- const deleteAttachment = useCallback(
- async (attachment: QuotationAttachment) => {
- const result = await supabase?.storage
- .from("private")
- .remove([getPath(attachment)]);
-
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error deleting file");
- return;
- }
-
- toast.success("File deleted successfully");
- revalidator.revalidate();
- },
- [supabase?.storage, getPath, revalidator]
- );
-
- const download = useCallback(
- async (attachment: QuotationAttachment) => {
- const result = await supabase?.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);
- },
- [supabase?.storage, getPath]
- );
-
- return {
- canDelete,
- deleteAttachment,
- download,
- getPath,
- };
-};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 01b2c7eee8..03f7e77ec4 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -284,7 +284,7 @@ const QuoteBillOfProcess = ({
const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
const result = await supabase?.storage
.from("private")
- .upload(fileName, file);
+ .upload(fileName, file, { upsert: true });
if (result?.error) {
throw new Error(result.error.message);
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
index 26d7d2a091..f10b12fe1d 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
@@ -14,11 +14,13 @@ import {
NumberInput,
RadioGroup,
RadioGroupItem,
+ Spinner,
Table,
Tbody,
Td,
Th,
Thead,
+ toast,
Tr,
VStack,
} from "@carbon/react";
@@ -26,12 +28,14 @@ import { formatDate } from "@carbon/utils";
import { Form, useNavigation, useParams } from "@remix-run/react";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
+import { flushSync } from "react-dom";
import { useDropzone } from "react-dropzone";
import {
LuBan,
LuChevronDown,
LuCreditCard,
LuImage,
+ LuTrash,
LuTruck,
LuUpload,
LuUserSquare,
@@ -42,6 +46,7 @@ import { usePaymentTerm } from "~/components/Form/PaymentTerm";
import { useShippingMethod } from "~/components/Form/ShippingMethod";
import { useRouteData } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
import type {
Quotation,
@@ -50,6 +55,7 @@ import type {
QuotationPrice,
QuotationShipment,
} from "../../types";
+import { useOpportunityDocuments } from "../OpportunityDocuments/OpportunityDocuments";
type QuoteToOrderDrawerProps = {
isOpen: boolean;
@@ -79,17 +85,91 @@ const QuoteToOrderDrawer = ({
>
>({});
+ const { supabase } = useSupabase();
+ const { quoteId } = useParams();
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const quoteData = useRouteData<{
+ opportunity: { id: string };
+ }>(path.to.quote(quoteId));
+ const { deleteAttachment, getPath, upload } = useOpportunityDocuments({
+ opportunityId: quoteData?.opportunity.id!,
+ type: "Quote",
+ id: quoteId,
+ });
const [purchaseOrder, setPurchaseOrder] = useState<File | null>(null);
- const onDrop = (acceptedFiles: File[]) => {
+ const [uploading, setUploading] = useState(false);
+
+ const onDrop = async (acceptedFiles: File[]) => {
+ if (!supabase) {
+ toast.error("Supabase client not available");
+ return;
+ }
+
+ if (purchaseOrder) {
+ await removePurchaseOrder();
+ }
+
if (acceptedFiles.length > 0) {
- setPurchaseOrder(acceptedFiles[0]);
+ flushSync(() => {
+ setUploading(true);
+ });
+ const file = acceptedFiles[0];
+ if (file) upload(file);
+
+ const purchaseOrderDocumentPath = getPath(file);
+ const { error } = await supabase
+ .from("opportunity")
+ .update({
+ purchaseOrderDocumentPath,
+ })
+ .eq("id", quoteData?.opportunity?.id!);
+
+ if (error) {
+ console.error("Error updating opportunity:", error);
+ toast.error("Failed to update opportunity with purchase order");
+ } else {
+ setPurchaseOrder(file);
+ setStep(1);
+ }
+
+ setUploading(false);
+ }
+ };
+
+ const removePurchaseOrder = async () => {
+ if (!supabase) {
+ toast.error("Failed to initialize Supabase client");
+ return;
+ }
+
+ setUploading(true);
+
+ const [opportunityDelete] = await Promise.all([
+ supabase
+ .from("opportunity")
+ .update({
+ purchaseOrderDocumentPath: null,
+ })
+ .eq("id", quoteData?.opportunity.id!),
+ // @ts-expect-error
+ deleteAttachment(purchaseOrder!),
+ ]);
+
+ if (opportunityDelete.error) {
+ toast.error("Failed to remove purchase order");
+ } else {
+ setPurchaseOrder(null);
+ toast.success("Purchase order removed successfully");
}
+ setUploading(false);
};
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: { "application/pdf": [".pdf"] },
maxFiles: 1,
+ disabled: uploading,
});
const titles = [
@@ -110,7 +190,9 @@ const QuoteToOrderDrawer = ({
)}
>
<input {...getInputProps()} />
- {purchaseOrder ? (
+ {uploading ? (
+ <Spinner className="w-8 h-8" />
+ ) : purchaseOrder ? (
<p>{purchaseOrder.name}</p>
) : (
<p>
@@ -120,15 +202,29 @@ const QuoteToOrderDrawer = ({
)}
<LuUpload className="mx-auto mt-4 h-12 w-12 text-muted-foreground" />
</div>
- <Button
- className="w-full"
- leftIcon={<LuBan />}
- size="lg"
- variant="secondary"
- onClick={() => setStep(1)}
- >
- Skip
- </Button>
+ {purchaseOrder ? (
+ <Button
+ className="w-full"
+ leftIcon={<LuTrash />}
+ size="lg"
+ isDisabled={uploading}
+ isLoading={uploading}
+ variant="secondary"
+ onClick={removePurchaseOrder}
+ >
+ Remove
+ </Button>
+ ) : (
+ <Button
+ className="w-full"
+ leftIcon={<LuBan />}
+ size="lg"
+ variant="secondary"
+ onClick={() => setStep(1)}
+ >
+ Skip
+ </Button>
+ )}
</VStack>
);
case 1:
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index 6b96c5f6a1..bd4529af7b 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -20,6 +20,7 @@ import { nanoid } from "nanoid";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type {
+ Opportunity,
Quotation,
QuotationPayment,
QuotationShipment,
@@ -87,7 +88,7 @@ export default function QuoteDetailsRoute() {
files: (FileObject & { quoteLineId: string | null })[];
shipment: QuotationShipment;
payment: QuotationPayment;
- opportunity: { id: string };
+ opportunity: Opportunity;
}>(path.to.quote(quoteId));
if (!quoteData) throw new Error("Could not find quote data");
@@ -127,7 +128,7 @@ export default function QuoteDetailsRoute() {
<>
<QuoteForm key={initialValues.id} initialValues={initialValues} />
<OpportunityDocuments
- opportunityId={quoteData?.opportunity?.id}
+ opportunity={quoteData?.opportunity!}
attachments={quoteData?.files ?? []}
id={quoteId}
type="Quote"
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx
index 3fff89264a..cfc3637260 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx
@@ -6,7 +6,7 @@ import type { FileObject } from "@supabase/storage-js";
import { useRouteData } from "~/hooks";
import { getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
-import type { SalesOrder } from "~/modules/sales";
+import type { Opportunity, SalesOrder } from "~/modules/sales";
import {
getSalesOrderPayment,
getSalesOrderShipment,
@@ -137,7 +137,7 @@ export default function SalesOrderRoute() {
if (!orderId) throw new Error("Could not find orderId");
const orderData = useRouteData<{
salesOrder: SalesOrder;
- opportunity: { id: string };
+ opportunity: Opportunity;
files: FileObject[];
}>(path.to.salesOrder(orderId));
if (!orderData) throw new Error("Could not find order data");
@@ -188,7 +188,7 @@ export default function SalesOrderRoute() {
<>
<SalesOrderForm key={initialValues.id} initialValues={initialValues} />
<OpportunityDocuments
- opportunityId={orderData?.opportunity?.id}
+ opportunity={orderData?.opportunity!}
attachments={orderData?.files ?? []}
id={orderId}
type="Sales Order"
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index 40722bfc87..98bdd396b3 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -21,6 +21,7 @@ import { nanoid } from "nanoid";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type {
+ Opportunity,
SalesRFQ,
SalesRFQLine,
SalesRFQStatusType,
@@ -85,7 +86,7 @@ export default function SalesRFQDetailsRoute() {
rfqSummary: SalesRFQ;
lines: SalesRFQLine[];
files: FileObject[];
- opportunity: { id: string };
+ opportunity: Opportunity;
}>(path.to.salesRfq(rfqId));
if (!rfqData) throw new Error("Could not find rfq data");
@@ -114,7 +115,7 @@ export default function SalesRFQDetailsRoute() {
initialValues={initialValues}
/>
<OpportunityDocuments
- opportunityId={rfqData?.opportunity?.id}
+ opportunity={rfqData?.opportunity!}
attachments={rfqData?.files ?? []}
id={rfqId}
type="Request for Quote"
diff --git a/packages/database/supabase/migrations/20240905110632_opportunity-update-fix.sql b/packages/database/supabase/migrations/20240905110632_opportunity-update-fix.sql
new file mode 100644
index 0000000000..37f97bb58f
--- /dev/null
+++ b/packages/database/supabase/migrations/20240905110632_opportunity-update-fix.sql
@@ -0,0 +1,11 @@
+DROP POLICY "Employees with sales_create can insert opportunities" ON "opportunity";
+CREATE POLICY "Employees with sales_create can insert opportunities" ON "opportunity" FOR INSERT WITH CHECK (
+ has_company_permission('sales_create', "companyId") AND
+ has_role('employee', "companyId")
+);
+
+DROP POLICY "Employees with sales_create can update opportunities" ON "opportunity";
+CREATE POLICY "Employees with sales_create can update opportunities" ON "opportunity" FOR UPDATE USING (
+ has_company_permission('sales_update', "companyId") AND
+ has_role('employee', "companyId")
+);
\ No newline at end of file
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index ec127a0969..9ddb85c3fb 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -165,6 +165,7 @@ const QuotePDF = ({
<Text style={tw("w-1/5 text-right")}>Extended Price</Text>
</View>
</View>
+
{quoteLines.map((line) => {
const additionalCharges = line.additionalCharges ?? {};
const additionalChargesByQuantity = line.quantity.map(
@@ -183,7 +184,7 @@ const QuotePDF = ({
return (
<View
style={tw(
- "flex flex-row justify-between py-1.5 px-[6px] border-b border-gray-300"
+ "flex flex-row justify-between py-1.5 px-[6px] border-b border-gray-300 mb-2"
)}
key={line.id}
>
@@ -228,7 +229,7 @@ const QuotePDF = ({
</View>
)}
</View>
- <View style={tw("w-3/5")}>
+ <View style={tw("flex flex-col w-3/5 gap-2")}>
{line.quantity.map((quantity, index) => {
const prices = pricesByLine[line.id] ?? [];
const price = prices.find(
@@ -270,8 +271,8 @@ const QuotePDF = ({
);
})}
</View>
- <Note note={(quote.externalNotes ?? {}) as JSONContent} />
</View>
+ <Note note={(quote.externalNotes ?? {}) as JSONContent} />
</Template>
);
};
diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsx
index 698b16772f..99b8464a6e 100644
--- a/packages/react/src/Badge.tsx
+++ b/packages/react/src/Badge.tsx
@@ -21,8 +21,7 @@ const badgeVariants = cva(
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
- green:
- "border-transparent bg-green-100 text-green-800 dark:bg-green-900 dark:text-white",
+ green: "border-transparent bg-green-100 text-green-800",
yellow: "border-transparent bg-yellow-100 text-yellow-800",
orange: "border-transparent bg-orange-100 text-orange-800",
red: "border-transparent bg-red-100 text-red-800",