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.

Erp 46 quotes orders in documents (#114)

Neil Kanakia58127172b016
diff --git a/apps/carbon/app/components/DocumentPreview.tsx b/apps/carbon/app/components/DocumentPreview.tsx
new file mode 100644
index 0000000000..ce2eec499a
--- /dev/null
+++ b/apps/carbon/app/components/DocumentPreview.tsx
@@ -0,0 +1,60 @@
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+ cn,
+} from "@carbon/react";
+import type { ComponentPropsWithoutRef, ElementRef } from "react";
+import { forwardRef } from "react";
+import { path } from "~/utils/path";
+
+type DocumentPreviewProps = ComponentPropsWithoutRef<
+ typeof HoverCardContent
+> & {
+ bucket: "public" | "private";
+ pathToFile: string;
+ type: "PDF" | "Image";
+};
+
+const DocumentPreview = forwardRef<
+ ElementRef<typeof HoverCardContent>,
+ DocumentPreviewProps
+>(({ bucket, pathToFile, type, children, className, ...props }, ref) => {
+ return (
+ <HoverCard>
+ <HoverCardTrigger>{children}</HoverCardTrigger>
+ {type === "PDF" ? (
+ <HoverCardContent
+ align="start"
+ ref={ref}
+ {...props}
+ className={cn("w-[425px] h-[550px] overflow-hidden p-0", className)}
+ >
+ <iframe
+ seamless
+ title={pathToFile}
+ width="425"
+ height="550"
+ src={path.to.file.previewFile(`${bucket}/${pathToFile}`)}
+ />
+ </HoverCardContent>
+ ) : (
+ <HoverCardContent
+ align="start"
+ className="w-[400px] h-[400px] overflow-hidden p-0 z-[100]"
+ >
+ <iframe
+ seamless
+ title={pathToFile}
+ width="400"
+ height="400"
+ src={path.to.file.previewImage(bucket, pathToFile)}
+ />
+ </HoverCardContent>
+ )}
+ </HoverCard>
+ );
+});
+DocumentPreview.displayName = "DocumentPreview";
+
+export default DocumentPreview;
diff --git a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
index 2078baebe8..da04b92252 100644
--- a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
@@ -13,16 +13,16 @@ const ContentSidebar = ({ links }: { links: Route[] }) => {
<CollapsibleSidebar>
<div className="overflow-y-auto h-full w-full pb-8">
<VStack>
- <VStack spacing={1} className="border-b border-border p-2">
+ <VStack spacing={1} className="p-2">
{links.map((route) => {
const isActive =
- route.to === location.pathname && route.q === filter;
+ location.pathname.includes(route.to) && route.q === filter;
return (
<Button
key={route.name}
asChild
leftIcon={route.icon}
- variant={isActive ? "primary" : "ghost"}
+ variant={isActive ? "active" : "ghost"}
className="w-full justify-start"
>
<Link
diff --git a/apps/carbon/app/components/Layout/Navigation/DetailSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/DetailSidebar.tsx
index 66b00a2d7d..303a587beb 100644
--- a/apps/carbon/app/components/Layout/Navigation/DetailSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/DetailSidebar.tsx
@@ -39,14 +39,14 @@ const DetailSidebar = ({ links }: DetailSidebarProps) => {
return (
<VStack className="overflow-y-auto h-full" spacing={1}>
{links.map((route) => {
- const isActive = route.to === location.pathname;
+ const isActive = location.pathname.includes(route.to);
return (
<Tooltip key={route.name}>
<TooltipTrigger className="w-full">
<Button
asChild
- variant={isActive ? "primary" : "ghost"}
+ variant={isActive ? "active" : "ghost"}
className="w-full justify-start"
>
<Link to={route.to} prefetch="intent">
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index ffc6ffb9c0..a862476445 100644
--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -21,13 +21,13 @@ const GroupedContentSidebar = ({ groups }: { groups: RouteGroup[] }) => {
{group.name}
</h4>
{group.routes.map((route) => {
- const isActive = route.to === location.pathname;
+ const isActive = location.pathname.includes(route.to);
return (
<Button
key={route.name}
asChild
leftIcon={route.icon}
- variant={isActive ? "primary" : "ghost"}
+ variant={isActive ? "active" : "ghost"}
className="w-full justify-start"
>
<Link
diff --git a/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx
index 0d40d7c215..f7813bb7bb 100644
--- a/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx
@@ -100,10 +100,10 @@ const NavigationIconLink = forwardRef<
"flex items-center rounded-md",
"group-data-[state=collapsed]:justify-center",
"group-data-[state=expanded]:-space-x-2",
- "hover:bg-primary/10 active:",
+ "hover:bg-secondary active:",
`${
isActive
- ? "!bg-primary !text-primary-foreground shadow-sm hover:text-primary-foreground"
+ ? "dark:bg-primary/10 bg-primary/20 text-primary shadow-sm hover:text-primary hover:bg-primary/20 "
: "hover:text-foreground"
}`,
"group/item",
@@ -125,7 +125,7 @@ const NavigationIconLink = forwardRef<
<span
aria-hidden={isOpen || undefined}
className={cn(
- "min-w-[128px] text-sm font-medium",
+ "min-w-[128px] text-sm",
"absolute left-7 group-data-[state=expanded]:left-12",
"opacity-0 group-data-[state=expanded]:opacity-100"
)}
diff --git a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
index a82f8ec988..965a9d639f 100644
--- a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
+++ b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
@@ -8,7 +8,7 @@ import {
ModalOverlay,
ModalTitle,
} from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
+import { Form } from "@remix-run/react";
type ConfirmDeleteProps = {
action?: string;
@@ -27,8 +27,6 @@ const ConfirmDelete = ({
onCancel,
onSubmit,
}: ConfirmDeleteProps) => {
- const fetcher = useFetcher();
- const isLoading = fetcher.state !== "idle";
return (
<Modal
open={isOpen}
@@ -48,11 +46,11 @@ const ConfirmDelete = ({
<Button variant="secondary" className="mr-3" onClick={onCancel}>
Cancel
</Button>
- <fetcher.Form method="post" action={action} onSubmit={onSubmit}>
- <Button variant="destructive" type="submit" isLoading={isLoading}>
+ <Form method="post" action={action} onSubmit={onSubmit}>
+ <Button variant="destructive" type="submit">
Delete
</Button>
- </fetcher.Form>
+ </Form>
</ModalFooter>
</ModalContent>
</Modal>
diff --git a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
index d9932490e6..2d692ed2d2 100644
--- a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
+++ b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
@@ -26,7 +26,7 @@ const DebouncedInput = ({ param, ...props }: DebounceInputProps) => {
<Input
defaultValue={params.get(param) || ""}
onChange={(e) => setQuery(e.target.value)}
- className="w-[140px]"
+ className="w-[200px]"
{...props}
/>
);
diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsx
index c6d6a15b7b..5548516a91 100644
--- a/apps/carbon/app/components/Search/Search/Search.tsx
+++ b/apps/carbon/app/components/Search/Search/Search.tsx
@@ -259,7 +259,7 @@ const SearchButton = () => {
<Button
leftIcon={<RxMagnifyingGlass />}
variant="secondary"
- className="font-normal w-[200px] px-2"
+ className="w-[200px] px-2 text-muted-foreground "
onClick={searchModal.onOpen}
>
<HStack className="w-full">
diff --git a/apps/carbon/app/components/index.ts b/apps/carbon/app/components/index.ts
index 66e014761b..5c32013356 100644
--- a/apps/carbon/app/components/index.ts
+++ b/apps/carbon/app/components/index.ts
@@ -6,6 +6,7 @@ import Combobox from "./Combobox";
import Contact from "./Contact";
import CreatableCombobox from "./CreateableCombobox";
import CustomerAvatar from "./CustomerAvatar";
+import DocumentPreview from "./DocumentPreview";
import EmployeeAvatar from "./EmployeeAvatar";
import Hyperlink from "./Hyperlink";
import MultiSelect from "./MultiSelect";
@@ -25,6 +26,7 @@ export {
Contact,
CreatableCombobox,
CustomerAvatar,
+ DocumentPreview,
EmployeeAvatar,
Hyperlink,
MultiSelect,
diff --git a/apps/carbon/app/modules/documents/documents.models.ts b/apps/carbon/app/modules/documents/documents.models.ts
index 96f4d58945..99f38c23ec 100644
--- a/apps/carbon/app/modules/documents/documents.models.ts
+++ b/apps/carbon/app/modules/documents/documents.models.ts
@@ -13,6 +13,8 @@ export const documentTypes = [
"Other",
] as const;
+export const documentSourceTypes = ["Purchase Order", "Quote"] as const;
+
export const documentValidator = z.object({
id: z.string().min(1, { message: "Document ID is required" }),
name: z.string().min(3).max(50),
diff --git a/apps/carbon/app/modules/documents/documents.service.ts b/apps/carbon/app/modules/documents/documents.service.ts
index 104829ef80..eae6a310f5 100644
--- a/apps/carbon/app/modules/documents/documents.service.ts
+++ b/apps/carbon/app/modules/documents/documents.service.ts
@@ -6,6 +6,7 @@ import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
documentLabelsValidator,
+ documentSourceTypes,
documentTypes,
documentValidator,
} from "./documents.models";
@@ -190,6 +191,11 @@ export async function restoreDocument(
.eq("id", id);
}
+type SourceDocumentData = {
+ sourceDocument?: (typeof documentSourceTypes)[number];
+ sourceDocumentId?: string;
+};
+
export async function upsertDocument(
client: SupabaseClient<Database>,
document:
@@ -197,7 +203,7 @@ export async function upsertDocument(
path: string;
size: number;
createdBy: string;
- })
+ } & SourceDocumentData)
| (Omit<z.infer<typeof documentValidator>, "id"> & {
id: string;
updatedBy: string;
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
index e00b66e2c6..2173fcd78d 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -7,30 +7,41 @@ import {
CommandItem,
Enumerable,
HStack,
- HoverCard,
- HoverCardContent,
- HoverCardTrigger,
+ Heading,
MenuIcon,
MenuItem,
Popover,
PopoverContent,
PopoverTrigger,
+ VStack,
cn,
useDisclosure,
} from "@carbon/react";
-import { convertKbToString, filterEmpty } from "@carbon/utils";
-import { useRevalidator } from "@remix-run/react";
+import { convertKbToString, filterEmpty, formatDate } from "@carbon/utils";
+import { Link, useRevalidator } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { BsFillPenFill, BsPin, BsPinFill } from "react-icons/bs";
import { IoMdAdd, IoMdTrash } from "react-icons/io";
+import { LuExternalLink } from "react-icons/lu";
import { RxCheck } from "react-icons/rx";
import { VscOpenPreview } from "react-icons/vsc";
-import { Avatar, Hyperlink, Table } from "~/components";
+import {
+ DocumentPreview,
+ EmployeeAvatar,
+ Hyperlink,
+ Table,
+} from "~/components";
import { Confirm, ConfirmDelete } from "~/components/Modals";
+import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { usePermissions, useUrlParams } from "~/hooks";
import type { Document, DocumentLabel } from "~/modules/documents";
-import { DocumentIcon, documentTypes } from "~/modules/documents";
+import {
+ DocumentIcon,
+ documentSourceTypes,
+ documentTypes,
+} from "~/modules/documents";
+import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import DocumentCreateForm from "./DocumentCreateForm";
import { useDocument } from "./useDocument";
@@ -67,6 +78,8 @@ const DocumentsTable = memo(
setLabel,
} = useDocument();
+ const { hasFilters } = useFilters();
+ const [people] = usePeople();
const deleteDocumentModal = useDisclosure();
const [selectedDocument, setSelectedDocument] = useState<Document | null>(
@@ -94,7 +107,7 @@ const DocumentsTable = memo(
const index = prev.findIndex((item) => item.id === row.id);
const updated = [...prev];
const labelIndex = updated[index].labels?.findIndex(
- (item) => item === label
+ (item: string) => item === label
);
if (labelIndex) {
updated[index].labels?.splice(labelIndex, 1);
@@ -165,38 +178,20 @@ const DocumentsTable = memo(
/>
)}
<DocumentIcon type={row.original.type!} />
- <Hyperlink onClick={() => download(row.original)}>
+ <Hyperlink
+ onClick={() => download(row.original)}
+ className="max-w-[260px] truncate"
+ >
{row.original.type &&
["Image", "PDF"].includes(row.original.type) ? (
- <HoverCard>
- <HoverCardTrigger>{row.original.name}</HoverCardTrigger>
- {row.original.type === "PDF" ? (
- <HoverCardContent className="w-[425px] h-[550px] overflow-hidden p-0">
- <iframe
- seamless
- title={row.original.path!}
- width="425"
- height="550"
- src={path.to.file.previewFile(
- `private/${row.original.path}`
- )}
- />
- </HoverCardContent>
- ) : (
- <HoverCardContent className="w-[400px] h-[400px] overflow-hidden p-0">
- <iframe
- seamless
- title={row.original.path!}
- width="400"
- height="400"
- src={path.to.file.previewImage(
- "private",
- row.original.path!
- )}
- />
- </HoverCardContent>
- )}
- </HoverCard>
+ <DocumentPreview
+ bucket="private"
+ pathToFile={row.original.path!}
+ // @ts-ignore
+ type={row.original.type}
+ >
+ {row.original.name}
+ </DocumentPreview>
) : (
<>{row.original.name}</>
)}
@@ -204,12 +199,43 @@ const DocumentsTable = memo(
</HStack>
),
},
+ {
+ accessorKey: "sourceDocument",
+ header: "Source Document",
+ cell: ({ row }) =>
+ row.original.sourceDocument &&
+ row.original.sourceDocumentId && (
+ <HStack className="group" spacing={1}>
+ <Enumerable value={row.original.sourceDocument} />{" "}
+ <Link
+ className="group-hover:opacity-100 opacity-0 transition-opacity duration-200 w-4 h-4 text-foreground"
+ to={getDocumentLocation(
+ row.original
+ .sourceDocument as (typeof documentSourceTypes)[number],
+ row.original.sourceDocumentId
+ )}
+ prefetch="intent"
+ >
+ <LuExternalLink />
+ </Link>
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: documentSourceTypes?.map((type) => ({
+ value: type,
+ label: <Enumerable value={type} />,
+ })),
+ },
+ },
+ },
{
id: "labels",
header: "Labels",
cell: ({ row }) => (
<HStack spacing={1}>
- {row.original.labels?.map((label) => (
+ {row.original.labels?.map((label: string) => (
<Badge
key={label}
variant="secondary"
@@ -299,42 +325,46 @@ const DocumentsTable = memo(
},
},
{
- accessorKey: "createdByFullName",
+ id: "createdBy",
header: "Created By",
- cell: ({ row }) => {
- return (
- <HStack>
- <Avatar
- size="sm"
- path={row.original.createdByAvatar ?? undefined}
- />
- <span>{row.original.createdByFullName}</span>
- </HStack>
- );
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name,
+ })),
+ },
},
},
-
{
accessorKey: "createdAt",
header: "Created At",
- cell: (item) => item.getValue(),
+ cell: (item) => formatDate(item.getValue<string>()),
},
{
- accessorKey: "updatedByFullName",
+ id: "updatedBy",
header: "Updated By",
- cell: ({ row }) => {
- return row.original.updatedByFullName ? (
- <HStack>
- <Avatar size="sm" path={row.original.updatedByAvatar ?? null} />
- <span>{row.original.updatedByFullName}</span>
- </HStack>
- ) : null;
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.updatedBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name,
+ })),
+ },
},
},
{
accessorKey: "updatedAt",
- header: "Updated At",
- cell: (item) => item.getValue(),
+ header: "Created At",
+ cell: (item) => formatDate(item.getValue<string>()),
},
];
}, [
@@ -344,6 +374,7 @@ const DocumentsTable = memo(
onDeleteLabel,
onFavorite,
onLabel,
+ people,
revalidator,
setLabel,
]);
@@ -440,19 +471,33 @@ const DocumentsTable = memo(
return (
<>
- <Table<Document>
- actions={actions}
- count={count}
- columns={columns}
- data={rows}
- defaultColumnVisibility={defaultColumnVisibility}
- primaryAction={
- permissions.can("create", "documents") && <DocumentCreateForm />
- }
- withColumnOrdering
- // withSelectableRows
- renderContextMenu={renderContextMenu}
- />
+ {count === 0 && !hasFilters ? (
+ <HStack className="w-full h-screen flex items-start justify-center">
+ <VStack className="border rounded-md shadow-md w-96 mt-20">
+ <div className="w-full flex flex-col gap-4 items-center justify-center py-8 bg-gradient-to-bl from-card to-background rounded-lg text-center group ring-4 ring-transparent hover:ring-white/10">
+ <Heading size="h2">No Files Yet</Heading>
+ <p className="text-muted-foreground text-base font-light">
+ Start by uploading your first file
+ </p>
+ <DocumentCreateForm />
+ </div>
+ </VStack>
+ </HStack>
+ ) : (
+ <Table<Document>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ primaryAction={
+ permissions.can("create", "documents") && <DocumentCreateForm />
+ }
+ withColumnOrdering
+ // withSelectableRows
+ renderContextMenu={renderContextMenu}
+ />
+ )}
{selectedDocument &&
selectedDocument.id &&
@@ -561,3 +606,17 @@ const CreatableCommand = ({
DocumentsTable.displayName = "DocumentsTable";
export default DocumentsTable;
+
+function getDocumentLocation(
+ sourceDocument: (typeof documentSourceTypes)[number],
+ sourceDocumentId: string
+) {
+ switch (sourceDocument) {
+ case "Purchase Order":
+ return path.to.purchaseOrder(sourceDocumentId);
+ case "Quote":
+ return path.to.quote(sourceDocumentId);
+ default:
+ return "#";
+ }
+}
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 33c39f056f..bd8a6e3b85 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -109,18 +109,22 @@ export async function deleteSupplierType(
return client.from("supplierType").delete().eq("id", supplierTypeId);
}
-export async function getExternalDocuments(
+export async function getPurchaseOrderExternalDocuments(
client: SupabaseClient<Database>,
purchaseOrderId: string
) {
- return client.storage.from("purchasing-external").list(purchaseOrderId);
+ return client.storage
+ .from("private")
+ .list(`purchasing/external/${purchaseOrderId}`);
}
-export async function getInternalDocuments(
+export async function getPurchaseOrderInternalDocuments(
client: SupabaseClient<Database>,
purchaseOrderId: string
) {
- return client.storage.from("purchasing-internal").list(purchaseOrderId);
+ return client.storage
+ .from("private")
+ .list(`purchasing/internal/${purchaseOrderId}`);
}
export async function getPurchaseOrder(
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index 713759ffe7..03c6e1cafd 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -1,6 +1,6 @@
import type { Database } from "@carbon/database";
import type {
- getExternalDocuments,
+ getPurchaseOrderExternalDocuments,
getPurchaseOrderLines,
getPurchaseOrders,
getRequestsForQuotes,
@@ -14,7 +14,7 @@ import type {
// TODO: we should just use the FileObject type from supabase
export type PurchaseOrderAttachment = NonNullable<
- Awaited<ReturnType<typeof getExternalDocuments>>["data"]
+ Awaited<ReturnType<typeof getPurchaseOrderExternalDocuments>>["data"]
>[number];
export type PurchaseOrder = NonNullable<
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 5df1ae802d..441712aafb 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
@@ -1,8 +1,9 @@
import { File, toast } from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
+import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { IoMdAdd } from "react-icons/io";
import { useSupabase } from "~/lib/supabase";
+import { path } from "~/utils/path";
type PurchaseOrderDocumentFormProps = {
orderId: string;
@@ -13,16 +14,18 @@ const PurchaseOrderDocumentForm = ({
orderId,
isExternal,
}: PurchaseOrderDocumentFormProps) => {
- const fetcher = useFetcher();
+ const submit = useSubmit();
const { supabase } = useSupabase();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase) {
const file = e.target.files[0];
- const fileName = `${orderId}/${file.name}`;
+ const fileName = `purchasing/${
+ isExternal ? "external" : "internal"
+ }/${orderId}/${file.name}`;
const fileUpload = await supabase.storage
- .from(`purchasing-${isExternal ? "external" : "internal"}`)
+ .from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
});
@@ -33,12 +36,37 @@ const PurchaseOrderDocumentForm = ({
if (fileUpload.data?.path) {
toast.success("File uploaded");
- // refetch the loaders
- fetcher.submit(null, { method: "post" });
+ 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", "Purchase Order");
+ formData.append("sourceDocumentId", orderId);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ });
+ };
+
return (
<File leftIcon={<IoMdAdd />} onChange={uploadFile}>
New
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 d217262e43..7b03afc0ff 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 { Outlet } from "@remix-run/react";
import { MdMoreVert } from "react-icons/md";
-import { Hyperlink } from "~/components";
+import { DocumentPreview, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { PurchaseOrderAttachment } from "~/modules/purchasing";
import PurchaseOrderDocumentForm from "./PurchaseOrderDocumentForm";
@@ -37,11 +37,11 @@ const PurchaseOrderDocuments = ({
isExternal,
orderId,
}: PurchaseOrderDocumentsProps) => {
- const { canDelete, download, deleteAttachment } = usePurchaseOrderDocuments({
- attachments,
- isExternal,
- orderId,
- });
+ const { canDelete, download, deleteAttachment, getPath } =
+ usePurchaseOrderDocuments({
+ isExternal,
+ orderId,
+ });
return (
<>
@@ -71,49 +71,63 @@ const PurchaseOrderDocuments = ({
</Thead>
<Tbody>
{attachments.length ? (
- attachments.map((attachment) => (
- <Tr key={attachment.id}>
- <Td>
- <HStack>
- <DocumentIcon type={getDocumentType(attachment.name)} />
- <Hyperlink onClick={() => download(attachment)}>
- {attachment.name}
- </Hyperlink>
- </HStack>
- </Td>
- <Td>
- {convertKbToString(
- Math.floor((attachment.metadata?.size ?? 0) / 1024)
- )}
- </Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<MdMoreVert />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => download(attachment)}
- >
- Download
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canDelete}
- onClick={() => deleteAttachment(attachment)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- ))
+ attachments.map((attachment) => {
+ const type = getDocumentType(attachment.name);
+ return (
+ <Tr key={attachment.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <Hyperlink onClick={() => download(attachment)}>
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={type}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<MdMoreVert />}
+ 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
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
index b9ec0134fa..b04c5edd4a 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
@@ -6,16 +6,11 @@ import { useSupabase } from "~/lib/supabase";
import type { PurchaseOrderAttachment } from "~/modules/purchasing/types";
type Props = {
- attachments: PurchaseOrderAttachment[];
isExternal: boolean;
orderId: string;
};
-export const usePurchaseOrderDocuments = ({
- attachments,
- isExternal,
- orderId,
-}: Props) => {
+export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
const fetcher = useFetcher();
const permissions = usePermissions();
const { supabase } = useSupabase();
@@ -27,28 +22,37 @@ export const usePurchaseOrderDocuments = ({
[fetcher]
);
+ const getPath = useCallback(
+ (attachment: PurchaseOrderAttachment) => {
+ return `purchasing/${isExternal ? "external" : "internal"}/${orderId}/${
+ attachment.name
+ }`;
+ },
+ [isExternal, orderId]
+ );
+
const deleteAttachment = useCallback(
async (attachment: PurchaseOrderAttachment) => {
- const result = await supabase?.storage
- .from(isExternal ? "purchasing-external" : "purchasing-internal")
- .remove([`${orderId}/${attachment.name}`]);
+ const fileDelete = await supabase?.storage
+ .from("private")
+ .remove([getPath(attachment)]);
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error deleting file");
+ if (!fileDelete || fileDelete.error) {
+ toast.error(fileDelete?.error?.message || "Error deleting file");
return;
}
toast.success("File deleted successfully");
refresh();
},
- [supabase, orderId, isExternal, refresh]
+ [supabase, getPath, refresh]
);
const download = useCallback(
async (attachment: PurchaseOrderAttachment) => {
const result = await supabase?.storage
- .from(isExternal ? "purchasing-external" : "purchasing-internal")
- .download(`${orderId}/${attachment.name}`);
+ .from("private")
+ .download(getPath(attachment));
if (!result || result.error) {
toast.error(result?.error?.message || "Error downloading file");
@@ -67,50 +71,13 @@ export const usePurchaseOrderDocuments = ({
document.body.removeChild(a);
}, 0);
},
- [supabase, orderId, isExternal]
- );
-
- // const getAvatarPath = useCallback(
- // (userId: string) => {
- // return usersMap[userId]?.avatarUrl;
- // },
- // [usersMap]
- // );
-
- // const getFullName = useCallback(
- // (userId: string) => {
- // return usersMap[userId]?.fullName;
- // },
- // [usersMap]
- // );
-
- const isImage = useCallback((fileType: string) => {
- return ["png", "jpg", "jpeg", "gif", "svg", "avif"].includes(fileType);
- }, []);
-
- const makePreview = useCallback(
- async (attachment: PurchaseOrderAttachment) => {
- const result = await supabase?.storage
- .from(isExternal ? "purchasing-external" : "purchasing-internal")
- .download(`${orderId}/${attachment.name}`);
-
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error previewing file");
- return null;
- }
-
- return window.URL.createObjectURL(result.data);
- },
- [isExternal, orderId, supabase?.storage]
+ [supabase?.storage, getPath]
);
return {
canDelete,
deleteAttachment,
download,
- // getAvatarPath,
- // getFullName,
- isImage,
- makePreview,
+ getPath,
};
};
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
index a601cedc46..e452cf9388 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
@@ -107,7 +107,7 @@ const SuppliersTable = memo(
cell: ({ row }) => (
<Button variant="secondary" asChild>
<Link
- to={`${path.to.purchaseOrders}?filter=supplierName:eq:${row.original.name}`}
+ to={`${path.to.purchaseOrders}?filter=supplierId:eq:${row.original.id}`}
>
{row.original.orderCount ?? 0} Orders
</Link>
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 89a8ff1731..b5e4036199 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -328,14 +328,14 @@ export async function getQuoteExternalDocuments(
client: SupabaseClient<Database>,
quoteId: string
) {
- return client.storage.from("quote-external").list(quoteId);
+ return client.storage.from("private").list(`quote/external/${quoteId}`);
}
export async function getQuoteInternalDocuments(
client: SupabaseClient<Database>,
quoteId: string
) {
- return client.storage.from("quote-internal").list(quoteId);
+ return client.storage.from("private").list(`quote/internal/${quoteId}`);
}
export async function getQuoteLine(
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
index d060f59a94..2572660307 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
@@ -1,8 +1,9 @@
import { File, toast } from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
+import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { IoMdAdd } from "react-icons/io";
import { useSupabase } from "~/lib/supabase";
+import { path } from "~/utils/path";
type QuotationDocumentFormProps = {
id: string;
@@ -13,16 +14,18 @@ const QuotationDocumentForm = ({
id,
isExternal,
}: QuotationDocumentFormProps) => {
- const fetcher = useFetcher();
+ const submit = useSubmit();
const { supabase } = useSupabase();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase) {
const file = e.target.files[0];
- const fileName = `${id}/${file.name}`;
+ const fileName = `quote/${isExternal ? "external" : "internal"}/${id}/${
+ file.name
+ }`;
const fileUpload = await supabase.storage
- .from(`quote-${isExternal ? "external" : "internal"}`)
+ .from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
});
@@ -33,12 +36,37 @@ const QuotationDocumentForm = ({
if (fileUpload.data?.path) {
toast.success("File uploaded");
- // refetch the loaders
- fetcher.submit(null, { method: "post" });
+ 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", "Quote");
+ formData.append("sourceDocumentId", id);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ });
+ };
+
return (
<File leftIcon={<IoMdAdd />} onChange={uploadFile}>
New
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocuments.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocuments.tsx
index 2811c4b775..d236d542ba 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocuments.tsx
@@ -20,7 +20,7 @@ import {
import { convertKbToString } from "@carbon/utils";
import { Outlet } from "@remix-run/react";
import { MdMoreVert } from "react-icons/md";
-import { Hyperlink } from "~/components";
+import { DocumentPreview, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { QuotationAttachment } from "~/modules/sales";
import QuotationDocumentForm from "./QuotationDocumentForm";
@@ -37,11 +37,11 @@ const QuotationDocuments = ({
isExternal,
id,
}: QuotationDocumentsProps) => {
- const { canDelete, download, deleteAttachment } = useQuotationDocuments({
- attachments,
- isExternal,
- id,
- });
+ const { canDelete, download, deleteAttachment, getPath } =
+ useQuotationDocuments({
+ isExternal,
+ id,
+ });
return (
<>
@@ -66,49 +66,63 @@ const QuotationDocuments = ({
</Thead>
<Tbody>
{attachments.length ? (
- attachments.map((attachment) => (
- <Tr key={attachment.id}>
- <Td>
- <HStack>
- <DocumentIcon type={getDocumentType(attachment.name)} />
- <Hyperlink onClick={() => download(attachment)}>
- {attachment.name}
- </Hyperlink>
- </HStack>
- </Td>
- <Td>
- {convertKbToString(
- Math.floor((attachment.metadata?.size ?? 0) / 1024)
- )}
- </Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<MdMoreVert />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => download(attachment)}
- >
- Download
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canDelete}
- onClick={() => deleteAttachment(attachment)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- ))
+ attachments.map((attachment) => {
+ const type = getDocumentType(attachment.name);
+ return (
+ <Tr key={attachment.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <Hyperlink onClick={() => download(attachment)}>
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={type}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<MdMoreVert />}
+ 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
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/useQuotationDocuments.ts b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/useQuotationDocuments.ts
index e75006180e..30d481cf7a 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/useQuotationDocuments.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/useQuotationDocuments.ts
@@ -6,16 +6,11 @@ import { useSupabase } from "~/lib/supabase";
import type { QuotationAttachment } from "~/modules/sales/types";
type Props = {
- attachments: QuotationAttachment[];
isExternal: boolean;
id: string;
};
-export const useQuotationDocuments = ({
- attachments,
- isExternal,
- id,
-}: Props) => {
+export const useQuotationDocuments = ({ isExternal, id }: Props) => {
const fetcher = useFetcher();
const permissions = usePermissions();
const { supabase } = useSupabase();
@@ -27,11 +22,20 @@ export const useQuotationDocuments = ({
[fetcher]
);
+ const getPath = useCallback(
+ (attachment: QuotationAttachment) => {
+ return `quote/${isExternal ? "external" : "internal"}/${id}/${
+ attachment.name
+ }`;
+ },
+ [isExternal, id]
+ );
+
const deleteAttachment = useCallback(
async (attachment: QuotationAttachment) => {
const result = await supabase?.storage
- .from(isExternal ? "quote-external" : "quote-internal")
- .remove([`${id}/${attachment.name}`]);
+ .from("private")
+ .remove([getPath(attachment)]);
if (!result || result.error) {
toast.error(result?.error?.message || "Error deleting file");
@@ -41,14 +45,14 @@ export const useQuotationDocuments = ({
toast.success("File deleted successfully");
refresh();
},
- [supabase, id, isExternal, refresh]
+ [supabase?.storage, getPath, refresh]
);
const download = useCallback(
async (attachment: QuotationAttachment) => {
const result = await supabase?.storage
- .from(isExternal ? "quote-external" : "quote-internal")
- .download(`${id}/${attachment.name}`);
+ .from("private")
+ .download(getPath(attachment));
if (!result || result.error) {
toast.error(result?.error?.message || "Error downloading file");
@@ -67,34 +71,13 @@ export const useQuotationDocuments = ({
document.body.removeChild(a);
}, 0);
},
- [supabase, id, isExternal]
- );
-
- const isImage = useCallback((fileType: string) => {
- return ["png", "jpg", "jpeg", "gif", "svg", "avif"].includes(fileType);
- }, []);
-
- const makePreview = useCallback(
- async (attachment: QuotationAttachment) => {
- const result = await supabase?.storage
- .from(isExternal ? "quote-external" : "quote-internal")
- .download(`${id}/${attachment.name}`);
-
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error previewing file");
- return null;
- }
-
- return window.URL.createObjectURL(result.data);
- },
- [isExternal, id, supabase?.storage]
+ [supabase?.storage, getPath]
);
return {
canDelete,
deleteAttachment,
download,
- isImage,
- makePreview,
+ getPath,
};
};
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index 35329de240..c40034ac49 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -173,7 +173,7 @@ export function ErrorBoundary() {
alt="Carbon Logo"
className="block max-w-[60px]"
/>
- <Heading size="h2">Something went wrong</Heading>
+ <Heading size="h1">Something went wrong</Heading>
<p className="text-foreground">{message}</p>
<Button onClick={() => (window.location.href = "/")}>
Back Home
diff --git a/apps/carbon/app/routes/api+/assign.ts b/apps/carbon/app/routes/api+/assign.ts
index 4e54df01c1..b1a6b32fb7 100644
--- a/apps/carbon/app/routes/api+/assign.ts
+++ b/apps/carbon/app/routes/api+/assign.ts
@@ -12,11 +12,9 @@ export async function action({ request }: ActionFunctionArgs) {
const assignee = formData.get("assignee") as string;
const table = formData.get("table") as string;
- console.log({ id, assignee, table });
-
if (table && id) {
const result = await assign(client, { table, id, assignee });
- console.log({ result });
+
if (result.error) {
return json(
{ success: false },
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx
new file mode 100644
index 0000000000..f9a8d86502
--- /dev/null
+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx
@@ -0,0 +1,46 @@
+import { type LoaderFunctionArgs } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+
+const supportedFileTypes: Record<string, string> = {
+ pdf: "application/pdf",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ png: "image/png",
+ gif: "image/gif",
+ svg: "image/svg+xml",
+ avif: "image/avif",
+ webp: "image/webp",
+ mp4: "video/mp4",
+ webm: "video/webm",
+ mov: "video/quicktime",
+ avi: "video/x-msvideo",
+ wmv: "video/x-ms-wmv",
+ mp3: "audio/mpeg",
+ wav: "audio/wav",
+ ogg: "audio/ogg",
+ flac: "audio/flac",
+};
+
+export let loader = async ({ request, params }: LoaderFunctionArgs) => {
+ const { client } = await requirePermissions(request, {
+ view: "documents",
+ });
+ const { bucket } = params;
+ const path = params["*"];
+
+ if (!bucket) throw new Error("Bucket not found");
+ if (!path) throw new Error("Path not found");
+
+ const fileType = path.split(".").pop();
+ if (!fileType || !(fileType in supportedFileTypes))
+ throw new Error("File type not supported");
+ const contentType = supportedFileTypes[fileType];
+
+ const result = await client.storage.from(bucket).download(`${path}`);
+ if (result.error) {
+ throw new Error("Failed to load file");
+ }
+
+ const headers = new Headers({ "Content-Type": contentType });
+ return new Response(result.data, { status: 200, headers });
+};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsx
deleted file mode 100644
index 7642a93fd8..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.avif`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/avif" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsx
deleted file mode 100644
index 48b3f4be03..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.gif`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/gif" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsx
deleted file mode 100644
index 2bbfd1e222..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.jpeg`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/jpeg" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsx
deleted file mode 100644
index a8e1e85e4e..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.jpg`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/jpeg" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsx
deleted file mode 100644
index 59fb26ba56..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.pdf`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "application/pdf" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsx
deleted file mode 100644
index 2181efe20b..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.png`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/png" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsx
deleted file mode 100644
index 9626f84c59..0000000000
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type LoaderFunctionArgs } from "@remix-run/node";
-import { requirePermissions } from "~/services/auth";
-
-export let loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { client } = await requirePermissions(request, {
- view: "documents",
- });
- const { bucket, folder, path } = params;
- if (!bucket) throw new Error("Could not find bucket");
- if (!path) throw new Error("Could not find path");
- if (!folder) throw new Error("Could not find folder");
-
- const result = await client.storage
- .from(bucket)
- .download(`${folder}/${path}.svg`);
- if (result.error) {
- throw new Error("Failed to load file");
- }
-
- const headers = new Headers({ "Content-Type": "image/svg+xml" });
- return new Response(result.data, { status: 200, headers });
-};
diff --git a/apps/carbon/app/routes/x+/documents+/new.tsx b/apps/carbon/app/routes/x+/documents+/new.tsx
index 2882c101f6..554a333cf0 100644
--- a/apps/carbon/app/routes/x+/documents+/new.tsx
+++ b/apps/carbon/app/routes/x+/documents+/new.tsx
@@ -4,7 +4,7 @@ import { upsertDocument } from "~/modules/documents";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
import { error, success } from "~/utils/result";
export async function action({ request }: ActionFunctionArgs) {
@@ -14,16 +14,27 @@ export async function action({ request }: ActionFunctionArgs) {
const documentPath = formData.get("path");
const name = formData.get("name");
+ const sourceDocument = formData.get("sourceDocument");
+ const sourceDocumentId = formData.get("sourceDocumentId");
if (typeof documentPath !== "string") throw new Error("Invalid path");
if (typeof name !== "string") throw new Error("Invalid name");
const size = Number(formData.get("size"));
+ let source = {};
+ if (sourceDocument && sourceDocumentId) {
+ source = {
+ sourceDocument,
+ sourceDocumentId,
+ };
+ }
+
const createDocument = await upsertDocument(client, {
path: documentPath,
name,
size,
+ ...source,
readGroups: [userId],
writeGroups: [userId],
createdBy: userId,
@@ -39,7 +50,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
throw redirect(
- path.to.documents,
+ requestReferrer(request) ?? path.to.documents,
await flash(request, success(`Successfully uploaded ${name}`))
);
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
index 9164074d22..70ac27c78d 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
@@ -3,6 +3,7 @@ import { validationError, validator } from "@carbon/remix-validated-form";
import { renderAsync } from "@react-email/components";
import { redirect, type ActionFunctionArgs } from "@remix-run/node";
import { triggerClient } from "~/lib/trigger.server";
+import { upsertDocument } from "~/modules/documents";
import {
getPurchaseOrder,
getPurchaseOrderLines,
@@ -33,7 +34,6 @@ export async function action(args: ActionFunctionArgs) {
if (!orderId) throw new Error("Could not find orderId");
let file: ArrayBuffer;
- let bucketName = orderId;
let fileName: string;
const release = await releasePurchaseOrder(client, orderId, userId);
@@ -68,17 +68,44 @@ export async function action(args: ActionFunctionArgs) {
.toISOString()
.slice(0, -5)}.pdf`;
- const fileUpload = await client.storage
- .from("purchasing-external")
- .upload(`${bucketName}/${fileName}`, file, {
+ const documentFilePath = `purchasing/external/${orderId}/${fileName}`;
+
+ const documentFileUpload = await client.storage
+ .from("private")
+ .upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
+ upsert: true,
});
- if (fileUpload.error) {
+ if (documentFileUpload.error) {
throw redirect(
path.to.purchaseOrder(orderId),
- await flash(request, error(fileUpload.error, "Failed to upload file"))
+ 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: "Purchase Order",
+ sourceDocumentId: orderId,
+ createdBy: userId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ });
+
+ if (createDocument.error) {
+ return redirect(
+ path.to.purchaseOrder(orderId),
+ await flash(
+ request,
+ error(createDocument.error, "Failed to create document")
+ )
);
}
} catch (err) {
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
index 77b4fa160f..158f308850 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
@@ -5,9 +5,9 @@ import { useEffect } from "react";
import {
PurchaseOrderHeader,
PurchaseOrderSidebar,
- getExternalDocuments,
- getInternalDocuments,
getPurchaseOrder,
+ getPurchaseOrderExternalDocuments,
+ getPurchaseOrderInternalDocuments,
getPurchaseOrderLines,
usePurchaseOrderTotals,
} from "~/modules/purchasing";
@@ -40,8 +40,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
] = await Promise.all([
getPurchaseOrder(client, orderId),
getPurchaseOrderLines(client, orderId),
- getExternalDocuments(client, orderId),
- getInternalDocuments(client, orderId),
+ getPurchaseOrderExternalDocuments(client, orderId),
+ getPurchaseOrderInternalDocuments(client, orderId),
getLocationsList(client),
]);
diff --git a/apps/carbon/app/routes/x+/quote+/$id.release.tsx b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
index cfd57c48e1..46da290f87 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.release.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
@@ -3,6 +3,7 @@ import { validationError, validator } from "@carbon/remix-validated-form";
import { renderAsync } from "@react-email/components";
import { redirect, type ActionFunctionArgs } from "@remix-run/node";
import { triggerClient } from "~/lib/trigger.server";
+import { upsertDocument } from "~/modules/documents";
import {
getCustomer,
getCustomerContact,
@@ -33,7 +34,6 @@ export async function action(args: ActionFunctionArgs) {
if (!id) throw new Error("Could not find id");
let file: ArrayBuffer;
- let bucketName = id;
let fileName: string;
const release = await releaseQuote(client, id, userId);
@@ -62,17 +62,44 @@ export async function action(args: ActionFunctionArgs) {
.toISOString()
.slice(0, -5)}.pdf`;
- const fileUpload = await client.storage
- .from("quote-internal")
- .upload(`${bucketName}/${fileName}`, file, {
+ const documentFilePath = `quote/internal/${id}/${fileName}`;
+
+ const documentFileUpload = await client.storage
+ .from("private")
+ .upload(documentFilePath, file, {
cacheControl: `${12 * 60 * 60}`,
contentType: "application/pdf",
+ upsert: true,
});
- if (fileUpload.error) {
+ if (documentFileUpload.error) {
throw redirect(
path.to.quote(id),
- await flash(request, error(fileUpload.error, "Failed to upload file"))
+ 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: id,
+ createdBy: userId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ });
+
+ if (createDocument.error) {
+ return redirect(
+ path.to.quote(id),
+ await flash(
+ request,
+ error(createDocument.error, "Failed to create document")
+ )
);
}
} catch (err) {
diff --git a/apps/carbon/app/routes/x+/sales+/quotes.tsx b/apps/carbon/app/routes/x+/sales+/quotes.tsx
index d7f3ff7771..6424d36e9d 100644
--- a/apps/carbon/app/routes/x+/sales+/quotes.tsx
+++ b/apps/carbon/app/routes/x+/sales+/quotes.tsx
@@ -17,7 +17,7 @@ export const handle: Handle = {
export async function loader({ request }: LoaderFunctionArgs) {
const { client } = await requirePermissions(request, {
- view: "purchasing",
+ view: "sales",
});
const url = new URL(request.url);
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d324a12b15..c7af755213 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2913,6 +2913,10 @@ export type Database = {
path: string
readGroups: string[] | null
size: number
+ sourceDocument:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId: string | null
type: Database["public"]["Enums"]["documentType"]
updatedAt: string | null
updatedBy: string | null
@@ -2929,6 +2933,10 @@ export type Database = {
path: string
readGroups?: string[] | null
size: number
+ sourceDocument?:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId?: string | null
type: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
@@ -2945,6 +2953,10 @@ export type Database = {
path?: string
readGroups?: string[] | null
size?: number
+ sourceDocument?:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId?: string | null
type?: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
@@ -13737,8 +13749,6 @@ export type Database = {
active: boolean | null
createdAt: string | null
createdBy: string | null
- createdByAvatar: string | null
- createdByFullName: string | null
description: string | null
extension: string | null
favorite: boolean | null
@@ -13749,11 +13759,13 @@ export type Database = {
path: string | null
readGroups: string[] | null
size: number | null
+ sourceDocument:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId: string | null
type: Database["public"]["Enums"]["documentType"] | null
updatedAt: string | null
updatedBy: string | null
- updatedByAvatar: string | null
- updatedByFullName: string | null
writeGroups: string[] | null
}
Relationships: [
@@ -16082,6 +16094,20 @@ export type Database = {
| "Indirect Cost"
| "Variance"
| "Total"
+ documentSourceType:
+ | "Job"
+ | "Part"
+ | "Purchase Order"
+ | "Purchase Invoice"
+ | "Purchase Return Order"
+ | "Quote"
+ | "Receipt"
+ | "Request for Quote"
+ | "Sales Order"
+ | "Sales Invoice"
+ | "Sales Return Order"
+ | "Service"
+ | "Shipment"
documentTransactionType:
| "Download"
| "Edit"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d324a12b15..c7af755213 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2913,6 +2913,10 @@ export type Database = {
path: string
readGroups: string[] | null
size: number
+ sourceDocument:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId: string | null
type: Database["public"]["Enums"]["documentType"]
updatedAt: string | null
updatedBy: string | null
@@ -2929,6 +2933,10 @@ export type Database = {
path: string
readGroups?: string[] | null
size: number
+ sourceDocument?:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId?: string | null
type: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
@@ -2945,6 +2953,10 @@ export type Database = {
path?: string
readGroups?: string[] | null
size?: number
+ sourceDocument?:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId?: string | null
type?: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
@@ -13737,8 +13749,6 @@ export type Database = {
active: boolean | null
createdAt: string | null
createdBy: string | null
- createdByAvatar: string | null
- createdByFullName: string | null
description: string | null
extension: string | null
favorite: boolean | null
@@ -13749,11 +13759,13 @@ export type Database = {
path: string | null
readGroups: string[] | null
size: number | null
+ sourceDocument:
+ | Database["public"]["Enums"]["documentSourceType"]
+ | null
+ sourceDocumentId: string | null
type: Database["public"]["Enums"]["documentType"] | null
updatedAt: string | null
updatedBy: string | null
- updatedByAvatar: string | null
- updatedByFullName: string | null
writeGroups: string[] | null
}
Relationships: [
@@ -16082,6 +16094,20 @@ export type Database = {
| "Indirect Cost"
| "Variance"
| "Total"
+ documentSourceType:
+ | "Job"
+ | "Part"
+ | "Purchase Order"
+ | "Purchase Invoice"
+ | "Purchase Return Order"
+ | "Quote"
+ | "Receipt"
+ | "Request for Quote"
+ | "Sales Order"
+ | "Sales Invoice"
+ | "Sales Return Order"
+ | "Service"
+ | "Shipment"
documentTransactionType:
| "Download"
| "Edit"
diff --git a/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
new file mode 100644
index 0000000000..224d36d689
--- /dev/null
+++ b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
@@ -0,0 +1,143 @@
+-- these policies were taken from the purchasing-files migration
+ALTER POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+ALTER POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
+WITH CHECK (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+
+
+ALTER POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+
+ALTER POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+DELETE FROM storage.buckets WHERE id = 'purchasing-internal';
+
+
+-- External purchasing storage
+
+ALTER POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects
+WITH CHECK (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'purchasing'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+DELETE FROM storage.buckets WHERE id = 'purchasing-external';
+
+-- Internal purchasing documents view
+
+CREATE POLICY "Users with purchasing_view can view documents that start with purchasing" ON "document"
+ FOR SELECT USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (path LIKE 'purchasing%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with purchasing_create can create documents that start with purchasing" ON "document"
+ FOR INSERT WITH CHECK (
+ coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (path LIKE 'purchasing%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with purchasing_update can update documents that start with purchasing" ON "document"
+ FOR UPDATE USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (path LIKE 'purchasing%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with purchasing_delete can delete documents that start with purchasing" ON "document"
+ FOR DELETE USING (
+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (path LIKE 'purchasing%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+-- TODO: policies for suppliers
+
diff --git a/packages/database/supabase/migrations/20240330070421_my-claims-fix.sql b/packages/database/supabase/migrations/20240330070421_my-claims-fix.sql
new file mode 100644
index 0000000000..bbe7fbb40b
--- /dev/null
+++ b/packages/database/supabase/migrations/20240330070421_my-claims-fix.sql
@@ -0,0 +1,20 @@
+CREATE OR REPLACE FUNCTION get_my_claims() RETURNS "jsonb"
+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+ AS $$
+ DECLARE retval jsonb;
+ BEGIN
+ select raw_app_meta_data from auth.users into retval where id = auth.uid();
+ return retval;
+
+ END;
+$$;
+CREATE OR REPLACE FUNCTION get_my_claim(claim text) RETURNS "jsonb"
+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+ AS $$
+ DECLARE retval jsonb;
+ BEGIN
+ select coalesce(raw_app_meta_data->claim, null) from auth.users into retval where id = auth.uid();
+ return retval;
+
+ END;
+$$;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240330164855_quote-documents.sql b/packages/database/supabase/migrations/20240330164855_quote-documents.sql
new file mode 100644
index 0000000000..b37021ced5
--- /dev/null
+++ b/packages/database/supabase/migrations/20240330164855_quote-documents.sql
@@ -0,0 +1,143 @@
+-- these policies were taken from the quote-files migration
+ALTER POLICY "Internal quote documents view requires sales_view" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+ALTER POLICY "Internal quote documents insert requires sales_create" ON storage.objects
+WITH CHECK (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_create')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+
+
+ALTER POLICY "Internal quote documents update requires sales_update" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_update')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+
+ALTER POLICY "Internal quote documents delete requires sales_delete" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_delete')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'internal'
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+DELETE FROM storage.buckets WHERE id = 'quote-internal';
+
+
+-- External quote storage
+
+ALTER POLICY "External quote documents view requires sales_view" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External quote documents insert requires sales_view" ON storage.objects
+WITH CHECK (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_view')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External quote documents update requires sales_update" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_update')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+ALTER POLICY "External quote documents delete requires sales_delete" ON storage.objects
+USING (
+ bucket_id = 'private'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('sales_delete')::boolean, false) = true
+ AND (storage.foldername(name))[1] = 'quote'
+ AND (storage.foldername(name))[2] = 'external'
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+DELETE FROM storage.buckets WHERE id = 'quote-external';
+
+-- Internal quote documents view
+
+CREATE POLICY "Users with sales_view can view documents that start with quote" ON "document"
+ FOR SELECT USING (
+ coalesce(get_my_claim('sales_view')::boolean, false) = true
+ AND (path LIKE 'quote%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with sales_create can create documents that start with quote" ON "document"
+ FOR INSERT WITH CHECK (
+ coalesce(get_my_claim('sales_create')::boolean, false) = true
+ AND (path LIKE 'quote%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with sales_update can update documents that start with quote" ON "document"
+ FOR UPDATE USING (
+ coalesce(get_my_claim('sales_update')::boolean, false) = true
+ AND (path LIKE 'quote%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Users with sales_delete can delete documents that start with quote" ON "document"
+ FOR DELETE USING (
+ coalesce(get_my_claim('sales_delete')::boolean, false) = true
+ AND (path LIKE 'quote%')
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+-- TODO: policies for suppliers
+
diff --git a/packages/database/supabase/migrations/20240330174513_delete-documents.sql b/packages/database/supabase/migrations/20240330174513_delete-documents.sql
new file mode 100644
index 0000000000..2c062db74b
--- /dev/null
+++ b/packages/database/supabase/migrations/20240330174513_delete-documents.sql
@@ -0,0 +1,11 @@
+CREATE FUNCTION public.delete_orphaned_documents()
+RETURNS TRIGGER AS $$
+BEGIN
+ DELETE FROM public.document WHERE path = old.name;
+ RETURN old;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER delete_orphaned_storage_documents
+ AFTER DELETE on storage."objects"
+ FOR EACH ROW EXECUTE PROCEDURE public.delete_orphaned_documents();
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240330181457_document-types.sql b/packages/database/supabase/migrations/20240330181457_document-types.sql
new file mode 100644
index 0000000000..46ff9e7917
--- /dev/null
+++ b/packages/database/supabase/migrations/20240330181457_document-types.sql
@@ -0,0 +1,29 @@
+CREATE TYPE "documentSourceType" AS ENUM (
+ 'Job',
+ 'Part',
+ 'Purchase Order',
+ 'Purchase Invoice',
+ 'Purchase Return Order',
+ 'Quote',
+ 'Receipt',
+ 'Request for Quote',
+ 'Sales Order',
+ 'Sales Invoice',
+ 'Sales Return Order',
+ 'Service',
+ 'Shipment'
+);
+
+ALTER TABLE "document" ADD COLUMN "sourceDocument" "documentSourceType";
+ALTER TABLE "document" ADD COLUMN "sourceDocumentId" TEXT;
+
+DROP VIEW "documents";
+CREATE OR REPLACE VIEW "documents" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ d.*,
+ ARRAY(SELECT dl.label FROM "documentLabel" dl WHERE dl."documentId" = d.id AND dl."userId" = auth.uid()::text) AS labels,
+ EXISTS(SELECT 1 FROM "documentFavorite" df WHERE df."documentId" = d.id AND df."userId" = auth.uid()::text) AS favorite,
+ (SELECT MAX("createdAt") FROM "documentTransaction" dt WHERE dt."documentId" = d.id) AS "lastActivityAt"
+ FROM "document" d
+ LEFT JOIN "user" u ON u.id = d."createdBy"
+ LEFT JOIN "user" u2 ON u2.id = d."updatedBy";
\ No newline at end of file
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index bc05b7b24b..6f58f4c0c1 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -14,6 +14,8 @@ export const buttonVariants = cva(
variant: {
primary:
"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm",
+ active:
+ "dark:bg-primary/10 bg-primary/20 text-primary hover:bg-primary/20 shadow-sm",
secondary:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
solid: "bg-primary/25 text-accent-foreground hover:bg-primary/35",
diff --git a/packages/react/src/HoverCard.tsx b/packages/react/src/HoverCard.tsx
index c78f07b6e1..f511fbf585 100644
--- a/packages/react/src/HoverCard.tsx
+++ b/packages/react/src/HoverCard.tsx
@@ -18,7 +18,7 @@ const HoverCardContent = forwardRef<
align={align}
sideOffset={sideOffset}
className={cn(
- "z-50 w-64 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ "relative z-[100] w-64 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
diff --git a/www/utils/supabase.ts b/www/utils/supabase.ts
index a1e468e572..c61031a38c 100644
--- a/www/utils/supabase.ts
+++ b/www/utils/supabase.ts
@@ -4,7 +4,6 @@ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseKey) {
- console.log({ env: process.env, supabaseUrl, supabaseKey });
throw new Error("Supabase URL or Supabase Key is undefined.");
}