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.

refactor: use primaryAction prop instead of link locations to support documents table

Brad Barbinff7ad0dc5226
diff --git a/apps/carbon/app/components/New.tsx b/apps/carbon/app/components/New.tsx
index c6cd78c8af..533109e29d 100644
--- a/apps/carbon/app/components/New.tsx
+++ b/apps/carbon/app/components/New.tsx
@@ -1,6 +1,7 @@
import {
Button,
HStack,
+ Kbd,
Tooltip,
TooltipContent,
TooltipProvider,
@@ -30,11 +31,14 @@ const New = ({ label, to }: NewProps) => {
<Tooltip>
<TooltipTrigger>
<Button asChild leftIcon={<IoMdAdd />} ref={buttonRef}>
- <Link to={to}>New {label}</Link>
+ <Link to={to}>New</Link>
</Button>
</TooltipTrigger>
<TooltipContent>
- <HStack>N</HStack>
+ <HStack>
+ <span>New {label}</span>
+ <Kbd>N</Kbd>
+ </HStack>
</TooltipContent>
</Tooltip>
</TooltipProvider>
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 77aa1f1c0b..0e90147535 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -26,6 +26,7 @@ import {
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
+import type { ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { FaSort, FaSortDown, FaSortUp } from "react-icons/fa";
import type {
@@ -53,9 +54,7 @@ interface TableProps<T extends object> {
defaultColumnPinning?: ColumnPinningState;
defaultColumnVisibility?: Record<string, boolean>;
editableComponents?: Record<string, EditableTableCellComponent<T>>;
- label?: string;
- newPath?: string;
- newPermission?: boolean;
+ primaryAction?: ReactNode;
withColumnOrdering?: boolean;
withInlineEditing?: boolean;
withPagination?: boolean;
@@ -76,9 +75,7 @@ const Table = <T extends object>({
},
defaultColumnVisibility,
editableComponents,
- label,
- newPath,
- newPermission,
+ primaryAction,
withInlineEditing = false,
withColumnOrdering = false,
withPagination = true,
@@ -450,9 +447,7 @@ const Table = <T extends object>({
columns={table.getAllLeafColumns()}
editMode={editMode}
filters={filters}
- label={label}
- newPath={newPath}
- newPermission={newPermission}
+ primaryAction={primaryAction}
selectedRows={selectedRows}
setColumnOrder={setColumnOrder}
setEditMode={setEditMode}
diff --git a/apps/carbon/app/components/Table/components/TableHeader.tsx b/apps/carbon/app/components/Table/components/TableHeader.tsx
index 4427acfa4e..3a43670498 100644
--- a/apps/carbon/app/components/Table/components/TableHeader.tsx
+++ b/apps/carbon/app/components/Table/components/TableHeader.tsx
@@ -1,8 +1,8 @@
import { Button, HStack } from "@carbon/react";
import type { Column, ColumnOrderState } from "@tanstack/react-table";
+import type { ReactNode } from "react";
import { BsFillCheckCircleFill } from "react-icons/bs";
import { MdOutlineEditNote } from "react-icons/md";
-import New from "~/components/New";
import { DebouncedInput } from "~/components/Search";
import { useUrlParams } from "~/hooks";
import type { TableAction } from "../types";
@@ -21,9 +21,7 @@ type HeaderProps<T> = {
columns: Column<T, unknown>[];
editMode: boolean;
filters: ColumnFilter[];
- label?: string;
- newPath?: string;
- newPermission?: boolean;
+ primaryAction?: ReactNode;
pagination: PaginationProps;
selectedRows: T[];
setColumnOrder: (newOrder: ColumnOrderState) => void;
@@ -41,9 +39,7 @@ const TableHeader = <T extends object>({
columns,
editMode,
filters,
- label,
- newPath,
- newPermission,
+ primaryAction,
pagination,
selectedRows,
setColumnOrder,
@@ -98,9 +94,7 @@ const TableHeader = <T extends object>({
(pagination.canNextPage || pagination.canPreviousPage) && (
<PaginationButtons {...pagination} condensed />
)}
- {!!newPath && !!newPermission && (
- <New to={`${newPath}?${params.toString()}`} label={label} />
- )}
+ <>{primaryAction}</>
</HStack>
</HStack>
{currentFilters.length > 0 && (
diff --git a/apps/carbon/app/modules/documents/documents.models.ts b/apps/carbon/app/modules/documents/documents.models.ts
index d7fa374db7..96f4d58945 100644
--- a/apps/carbon/app/modules/documents/documents.models.ts
+++ b/apps/carbon/app/modules/documents/documents.models.ts
@@ -1,9 +1,22 @@
import { z } from "zod";
+export const documentTypes = [
+ "Archive",
+ "Document",
+ "Presentation",
+ "PDF",
+ "Spreadsheet",
+ "Text",
+ "Image",
+ "Video",
+ "Audio",
+ "Other",
+] as const;
+
export const documentValidator = z.object({
id: z.string().min(1, { message: "Document ID is required" }),
name: z.string().min(3).max(50),
- type: z.string().optional(),
+ extension: z.string().optional(),
description: z.string().optional(),
labels: z.array(z.string().min(1).max(50)).optional(),
readGroups: z
diff --git a/apps/carbon/app/modules/documents/documents.service.ts b/apps/carbon/app/modules/documents/documents.service.ts
index 142816a6e5..01e7838c0d 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,
+ documentTypes,
documentValidator,
} from "./documents.models";
@@ -69,8 +70,6 @@ export async function getDocuments(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
search: string | null;
- type: string | null;
- label: string | null;
favorite?: boolean;
recent?: boolean;
createdBy?: string;
@@ -90,50 +89,10 @@ export async function getDocuments(
);
}
- if (args?.type && args.type !== "all") {
- if (args.type === "image") {
- query = query.or("type.eq.png,type.eq.jpg,type.eq.jpeg,type.eq.gif");
- }
-
- if (args.type === "document") {
- query = query.or(
- "type.eq.pdf,type.eq.doc,type.eq.docx,type.eq.txt,type.eq.rtf"
- );
- }
-
- if (args.type === "presentation") {
- query = query.or("type.eq.ppt,type.eq.pptx");
- }
-
- if (args.type === "spreadsheet") {
- query = query.or("type.eq.xls,type.eq.xlsx");
- }
-
- if (args.type === "video") {
- query = query.or(
- "type.eq.mp4,type.eq.mov,type.eq.avi,type.eq.wmv,type.eq.flv,type.eq.mkv"
- );
- }
-
- if (args.type === "audio") {
- query = query.or(
- "type.eq.mp3,type.eq.wav,type.eq.wma,type.eq.aac,type.eq.ogg,type.eq.flac"
- );
- }
- }
-
- if (args.label) {
- query = query.contains("labels", [args.label]);
- }
-
if (args?.favorite) {
query = query.eq("favorite", true);
}
- if (args.createdBy) {
- query = query.eq("createdBy", args.createdBy);
- }
-
if (args.recent) {
query = query.order("lastActivityAt", { ascending: false });
}
@@ -145,6 +104,10 @@ export async function getDocuments(
return query;
}
+export async function getDocumentExtensions(client: SupabaseClient<Database>) {
+ return client.from("documentExtensions").select("extension");
+}
+
export async function getDocumentLabels(
client: SupabaseClient<Database>,
userId: string
@@ -152,6 +115,49 @@ export async function getDocumentLabels(
return client.from("documentLabels").select("*").eq("userId", userId);
}
+export function getDocumentType(
+ fileName: string
+): (typeof documentTypes)[number] {
+ const extension = fileName.split(".").pop()?.toLowerCase() ?? "";
+ if (["zip", "rar", "7z", "tar", "gz"].includes(extension)) {
+ return "Archive";
+ }
+
+ if (["pdf"].includes(extension)) {
+ return "PDF";
+ }
+
+ if (["doc", "docx", "txt", "rtf"].includes(extension)) {
+ return "Document";
+ }
+
+ if (["ppt", "pptx"].includes(extension)) {
+ return "Presentation";
+ }
+
+ if (["csv", "xls", "xlsx"].includes(extension)) {
+ return "Spreadsheet";
+ }
+
+ if (["txt"].includes(extension)) {
+ return "Text";
+ }
+
+ if (["png", "jpg", "jpeg", "gif"].includes(extension)) {
+ return "Image";
+ }
+
+ if (["mp4", "mov", "avi", "wmv", "flv", "mkv"].includes(extension)) {
+ return "Video";
+ }
+
+ if (["mp3", "wav", "wma", "aac", "ogg", "flac"].includes(extension)) {
+ return "Audio";
+ }
+
+ return "Other";
+}
+
export async function insertDocumentFavorite(
client: SupabaseClient<Database>,
id: string,
@@ -197,14 +203,20 @@ export async function upsertDocument(
updatedBy: string;
})
) {
+ const type = getDocumentType(document.name ?? "");
if ("createdBy" in document) {
- return client.from("document").insert(document).select("*").single();
+ return client
+ .from("document")
+ .insert({ ...document, type })
+ .select("*")
+ .single();
}
return client
.from("document")
.update(
sanitize({
...document,
+ type,
updatedAt: new Date().toISOString(),
})
)
diff --git a/apps/carbon/app/modules/documents/types.ts b/apps/carbon/app/modules/documents/types.ts
index e121e97767..5ed056eb9d 100644
--- a/apps/carbon/app/modules/documents/types.ts
+++ b/apps/carbon/app/modules/documents/types.ts
@@ -1,19 +1,10 @@
import type { Database } from "@carbon/database";
-import type { getDocumentLabels } from "./documents.service";
-export type Document = Omit<
- Database["public"]["Tables"]["document"]["Row"],
- "createdBy" | "updatedBy"
-> & {
- favorite: boolean;
- labels: string[];
- readGroups: string[];
- writeGroups: string[];
- createdByAvatar: string;
- createdByFullName: string;
- updatedByAvatar?: string | null;
- updatedByFullName?: string | null;
-};
+import type { getDocumentLabels, getDocuments } from "./documents.service";
+
+export type Document = NonNullable<
+ Awaited<ReturnType<typeof getDocuments>>["data"]
+>[number];
export type DocumentLabel = NonNullable<
Awaited<ReturnType<typeof getDocumentLabels>>["data"]
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentForm.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentForm.tsx
index 03b0103f2d..b2073567c2 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentForm.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentForm.tsx
@@ -45,17 +45,18 @@ const DocumentForm = ({ initialValues, ownerId }: DocumentFormProps) => {
className="flex flex-col h-full"
>
<DrawerHeader>
- <DrawerTitle>{`Edit ${initialValues.name}.${initialValues.type}`}</DrawerTitle>
+ <DrawerTitle>{`Edit ${initialValues.name}.${initialValues.extension}`}</DrawerTitle>
</DrawerHeader>
<DrawerBody>
<Hidden name="id" />
+ <Hidden name="extension" />
<Hidden name="type" />
<Hidden name="size" />
<VStack spacing={4}>
<Input
name="name"
label="Name"
- suffix={`.${initialValues.type}`}
+ suffix={`.${initialValues.extension}`}
/>
<TextArea name="description" label="Description" />
<Users
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
index afa42c7bb4..12e769bad8 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
@@ -9,53 +9,33 @@ import {
BsFileWordFill,
BsFileZipFill,
} from "react-icons/bs";
+import type { documentTypes } from "~/modules/documents";
type DocumentIconProps = {
- fileName: string;
+ type: (typeof documentTypes)[number];
};
-const DocumentIcon = ({ fileName }: DocumentIconProps) => {
- const fileExtension = [...fileName.split(".")].pop();
-
- switch (fileExtension) {
- case "doc":
- case "docx":
+const DocumentIcon = ({ type }: DocumentIconProps) => {
+ switch (type) {
+ case "Document":
return <BsFileWordFill className="w-6 h-6 color-blue-500" />;
- case "xls":
- case "xlsx":
+ case "Spreadsheet":
return <BsFileExcelFill className="w-6 h-6 text-green-700" />;
- case "ppt":
- case "pptx":
+ case "Presentation":
return <BsFilePptFill className="w-6 h-6 text-orange-400" />;
- case "pdf":
+ case "PDF":
return <BsFilePdfFill className="w-6 h-6 text-red-600" />;
- case "zip":
- case "rar":
+ case "Archive":
return <BsFileZipFill className="w-6 h-6" />;
- case "txt":
+ case "Text":
return <BsFileTextFill className="w-6 h-6" />;
- case "png":
- case "jpg":
- case "jpeg":
- case "gif":
- case "svg":
- case "avif":
- case "webp":
+ case "Image":
return <BsFileImageFill className="w-6 h-6 text-yellow-400" />;
- case "mp4":
- case "avi":
- case "mov":
- case "wmv":
- case "flv":
- case "mkv":
+ case "Video":
return <BsFileEarmarkPlayFill className="w-6 h-6 text-purple-500" />;
- case "mp3":
- case "wav":
- case "wma":
- case "aac":
- case "ogg":
- case "m4a":
+ case "Audio":
return <BsFileEarmarkPlayFill className="w-6 h-6 text-cyan-400" />;
+ case "Other":
default:
return <BsFileEarmarkFill className="w-6 h-6" />;
}
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
index 132b1a6198..3500fd81c8 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -5,6 +5,7 @@ import {
CommandGroup,
CommandInput,
CommandItem,
+ Enumerable,
HStack,
HoverCard,
HoverCardContent,
@@ -18,7 +19,7 @@ import {
cn,
useDisclosure,
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, filterEmpty } from "@carbon/utils";
import { useRevalidator } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
@@ -26,421 +27,468 @@ import { BsFillPenFill, BsPin, BsPinFill } from "react-icons/bs";
import { IoMdAdd, IoMdTrash } from "react-icons/io";
import { RxCheck } from "react-icons/rx";
import { VscOpenPreview } from "react-icons/vsc";
-import { Avatar, Table } from "~/components";
+import { Avatar, TableNew } from "~/components";
import { Confirm, ConfirmDelete } from "~/components/Modals";
-import { useUrlParams } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
import type { Document, DocumentLabel } from "~/modules/documents";
-import { DocumentIcon } from "~/modules/documents";
+import { DocumentIcon, documentTypes } from "~/modules/documents";
import { path } from "~/utils/path";
+import DocumentCreateForm from "./DocumentCreateForm";
import { useDocument } from "./useDocument";
type DocumentsTableProps = {
data: Document[];
count: number;
labels: DocumentLabel[];
+ extensions: (string | null)[];
};
-const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {
- const revalidator = useRevalidator();
- const [params] = useUrlParams();
- const filter = params.get("q");
- // put rows in state for use with optimistic ui updates
- const [rows, setRows] = useState<Document[]>(data);
- // we have to do this useEffect silliness since we're putitng rows
- // in state for optimistic ui updates
- useEffect(() => {
- setRows(data);
- }, [data]);
+const DocumentsTable = memo(
+ ({ data, count, labels, extensions }: DocumentsTableProps) => {
+ const permissions = usePermissions();
+ const revalidator = useRevalidator();
+ const [params] = useUrlParams();
+ const filter = params.get("q");
+ // put rows in state for use with optimistic ui updates
+ const [rows, setRows] = useState<Document[]>(data);
+ // we have to do this useEffect silliness since we're putitng rows
+ // in state for optimistic ui updates
+ useEffect(() => {
+ setRows(data);
+ }, [data]);
- const {
- canUpdate,
- canDelete,
- deleteLabel,
- download,
- edit,
- favorite,
- isImage,
- isPdf,
- label,
- setLabel,
- } = useDocument();
+ const {
+ canUpdate,
+ canDelete,
+ deleteLabel,
+ download,
+ edit,
+ favorite,
+ isImage,
+ isPdf,
+ label,
+ setLabel,
+ } = useDocument();
- const deleteDocumentModal = useDisclosure();
+ const deleteDocumentModal = useDisclosure();
- const [selectedDocument, setSelectedDocument] = useState<Document | null>(
- null
- );
+ const [selectedDocument, setSelectedDocument] = useState<Document | null>(
+ null
+ );
- const labelOptions = useMemo(
- () =>
- labels.map(({ label }) => ({
- value: label as string,
- label: label as string,
- })) ?? [],
- [labels]
- );
+ const labelOptions = useMemo(
+ () =>
+ labels.map(({ label }) => ({
+ value: label as string,
+ label: label as string,
+ })) ?? [],
+ [labels]
+ );
- const onDeleteLabel = useCallback(
- async (
- e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
- row: Document,
- label: string
- ) => {
- e.stopPropagation();
- // optimistically update the UI and then make the mutation
- setRows((prev) => {
- const index = prev.findIndex((item) => item.id === row.id);
- const updated = [...prev];
- const labelIndex = updated[index].labels.findIndex(
- (item) => item === label
- );
- updated[index].labels.splice(labelIndex, 1);
- return updated;
- });
- // mutate the database
- await deleteLabel(row, label);
- },
- [deleteLabel]
- );
+ const onDeleteLabel = useCallback(
+ async (
+ e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
+ row: Document,
+ label: string
+ ) => {
+ e.stopPropagation();
+ // optimistically update the UI and then make the mutation
+ setRows((prev) => {
+ const index = prev.findIndex((item) => item.id === row.id);
+ const updated = [...prev];
+ const labelIndex = updated[index].labels?.findIndex(
+ (item) => item === label
+ );
+ if (labelIndex) {
+ updated[index].labels?.splice(labelIndex, 1);
+ }
+ return updated;
+ });
+ // mutate the database
+ await deleteLabel(row, label);
+ },
+ [deleteLabel]
+ );
- const onLabel = useCallback(
- async (row: Document, labels: string[]) => {
- // optimistically update the UI and then make the mutation
- setRows((prev) => {
- const index = prev.findIndex((item) => item.id === row.id);
- const updated = [...prev];
- updated[index] = {
- ...updated[index],
- labels: labels.sort(),
- };
- return updated;
- });
- // mutate the database
- await label(row, labels);
- },
- [label]
- );
+ const onLabel = useCallback(
+ async (row: Document, labels: string[]) => {
+ // optimistically update the UI and then make the mutation
+ setRows((prev) => {
+ const index = prev.findIndex((item) => item.id === row.id);
+ const updated = [...prev];
+ updated[index] = {
+ ...updated[index],
+ labels: labels.sort(),
+ };
+ return updated;
+ });
+ // mutate the database
+ await label(row, labels);
+ },
+ [label]
+ );
- // TODO: rows shouldn't be in state -- we should use optimistic updates like purchase order favorites
- const onFavorite = useCallback(
- async (row: Document) => {
- // optimistically update the UI and then make the mutation
- setRows((prev) => {
- const index = prev.findIndex((item) => item.id === row.id);
- const updated = [...prev];
- updated[index] = {
- ...updated[index],
- favorite: !updated[index].favorite,
- };
- return filter === "starred"
- ? updated.filter((item) => item.favorite === true)
- : updated;
- });
- // mutate the database
- await favorite(row);
- },
- [favorite, filter]
- );
+ // TODO: rows shouldn't be in state -- we should use optimistic updates like purchase order favorites
+ const onFavorite = useCallback(
+ async (row: Document) => {
+ // optimistically update the UI and then make the mutation
+ setRows((prev) => {
+ const index = prev.findIndex((item) => item.id === row.id);
+ const updated = [...prev];
+ updated[index] = {
+ ...updated[index],
+ favorite: !updated[index].favorite,
+ };
+ return filter === "starred"
+ ? updated.filter((item) => item.favorite === true)
+ : updated;
+ });
+ // mutate the database
+ await favorite(row);
+ },
+ [favorite, filter]
+ );
- const columns = useMemo<ColumnDef<Document>[]>(() => {
- return [
- {
- accessorKey: "name",
- header: "Name",
- cell: ({ row }) => (
- <HStack>
- {row.original.favorite ? (
- <BsPinFill
- className="cursor-pointer w-4 h-4 text-yellow-400"
- onClick={() => onFavorite(row.original)}
- />
- ) : (
- <BsPin
- className="cursor-pointer w-4 h-4 text-muted-foreground"
- onClick={() => onFavorite(row.original)}
- />
- )}
- <DocumentIcon fileName={row.original.name} />
- <Hyperlink onClick={() => download(row.original)}>
- {row.original.type &&
- (isImage(row.original.type) || isPdf(row.original.type)) ? (
- <HoverCard>
- <HoverCardTrigger>{row.original.name}</HoverCardTrigger>
- {isPdf(row.original.type) ? (
- <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>
+ const columns = useMemo<ColumnDef<Document>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <HStack>
+ {row.original.favorite ? (
+ <BsPinFill
+ className="cursor-pointer w-4 h-4 text-yellow-400"
+ onClick={() => onFavorite(row.original)}
+ />
) : (
- <>{row.original.name}</>
- )}
- </Hyperlink>
- </HStack>
- ),
- },
- {
- id: "labels",
- header: "Labels",
- cell: ({ row }) => (
- <HStack spacing={1}>
- {row.original.labels.map((label) => (
- <Badge
- key={label}
- variant="secondary"
- className="cursor-pointer"
- onClick={() => setLabel(label)}
- >
- {label}
- <BadgeCloseButton
- onClick={(e) => onDeleteLabel(e, row.original, label)}
+ <BsPin
+ className="cursor-pointer w-4 h-4 text-muted-foreground"
+ onClick={() => onFavorite(row.original)}
/>
- </Badge>
- ))}
- <Popover>
- <PopoverTrigger>
- <Badge variant="secondary" className="cursor-pointer px-1">
- <IoMdAdd />
+ )}
+ <DocumentIcon type={row.original.type!} />
+ <Hyperlink onClick={() => download(row.original)}>
+ {row.original.type &&
+ (isImage(row.original.type) || isPdf(row.original.type)) ? (
+ <HoverCard>
+ <HoverCardTrigger>{row.original.name}</HoverCardTrigger>
+ {isPdf(row.original.type) ? (
+ <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>
+ ) : (
+ <>{row.original.name}</>
+ )}
+ </Hyperlink>
+ </HStack>
+ ),
+ },
+ {
+ id: "labels",
+ header: "Labels",
+ cell: ({ row }) => (
+ <HStack spacing={1}>
+ {row.original.labels?.map((label) => (
+ <Badge
+ key={label}
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setLabel(label)}
+ >
+ {label}
+ <BadgeCloseButton
+ onClick={(e) => onDeleteLabel(e, row.original, label)}
+ />
</Badge>
- </PopoverTrigger>
- <PopoverContent className="w-[300px] p-0">
- {/* TODO: we should have a CreateableMultiSelect component for this */}
+ ))}
+ <Popover>
+ <PopoverTrigger>
+ <Badge variant="secondary" className="cursor-pointer px-1">
+ <IoMdAdd />
+ </Badge>
+ </PopoverTrigger>
+ <PopoverContent className="w-[300px] p-0">
+ {/* TODO: we should have a CreateableMultiSelect component for this */}
- <CreatableCommand
- options={labelOptions}
- selected={row.original.labels}
- onChange={(newValue) =>
- onLabel(row.original, [...row.original.labels, newValue])
- }
- onCreateOption={async (newValue) => {
- await onLabel(row.original, [
- ...row.original.labels,
- newValue,
- ]);
- revalidator.revalidate();
- }}
- />
- </PopoverContent>
- </Popover>
- </HStack>
- ),
- },
- {
- accessorKey: "size",
- header: "Size",
- cell: ({ row }) => convertKbToString(row.original.size),
- },
- {
- accessorKey: "createdByFullName",
- header: "Created By",
- cell: ({ row }) => {
- return (
- <HStack>
- <Avatar
- size="sm"
- path={row.original.createdByAvatar ?? undefined}
- />
- <span>{row.original.createdByFullName}</span>
+ <CreatableCommand
+ options={labelOptions}
+ selected={row.original.labels ?? []}
+ onChange={(newValue) =>
+ onLabel(row.original, [
+ ...(row.original.labels ?? []),
+ newValue,
+ ])
+ }
+ onCreateOption={async (newValue) => {
+ await onLabel(row.original, [
+ ...(row.original.labels ?? []),
+ newValue,
+ ]);
+ revalidator.revalidate();
+ }}
+ />
+ </PopoverContent>
+ </Popover>
</HStack>
- );
+ ),
},
- },
- {
- accessorKey: "createdAt",
- header: "Created At",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "updatedByFullName",
- header: "Updated By",
- cell: ({ row }) => {
- return row.original.updatedByFullName ? (
- <HStack>
- <Avatar size="sm" path={row.original.updatedByAvatar ?? null} />
- <span>{row.original.updatedByFullName}</span>
- </HStack>
- ) : null;
+ {
+ accessorKey: "size",
+ header: "Size",
+ cell: ({ row }) => convertKbToString(row.original.size ?? 0),
+ },
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: documentTypes.map((type) => ({
+ label: (
+ <HStack spacing={2}>
+ <DocumentIcon type={type} />
+ <span>{type}</span>
+ </HStack>
+ ),
+ value: type,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "extension",
+ header: "File Extension",
+ cell: (item) => item.getValue(),
+ meta: {
+ filter: {
+ type: "static",
+ options: filterEmpty(extensions).map((extension) => ({
+ label: extension,
+ value: extension,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "createdByFullName",
+ header: "Created By",
+ cell: ({ row }) => {
+ return (
+ <HStack>
+ <Avatar
+ size="sm"
+ path={row.original.createdByAvatar ?? undefined}
+ />
+ <span>{row.original.createdByFullName}</span>
+ </HStack>
+ );
+ },
},
- },
- {
- accessorKey: "updatedAt",
- header: "Updated At",
- cell: (item) => item.getValue(),
- },
- ];
- }, [
- download,
- isImage,
- isPdf,
- labelOptions,
- onDeleteLabel,
- onFavorite,
- onLabel,
- revalidator,
- setLabel,
- ]);
-
- const actions = useMemo(() => {
- return [
- // {
- // label: "Add to Favorites",
- // icon: <BsBookmark />,
- // onClick: (selected: Document[]) => {
- // console.log("move to favorites", selected);
- // },
- // },
- // {
- // label: "Add Labels",
- // icon: <BsTag />,
- // // TODO - disabled can be a function of selected
- // disabled: true,
- // onClick: (selected: Document[]) => {
- // console.log("move to favorites", selected);
- // },
- // },
- // {
- // label: "Move to Trash",
- // icon: <IoMdTrash />,
- // // TODO - disabled can be a function of selected
- // disabled: true,
- // onClick: (selected: Document[]) => {
- // console.log("move to trash", selected);
- // },
- // },
- // {
- // label: "Update Visibility",
- // icon: <BsEyeFill />,
- // // TODO - disabled can be a function of selected
- // disabled: true,
- // onClick: (selected: Document[]) => {
- // console.log("update visibility", selected);
- // },
- // },
- ];
- }, []);
- const defaultColumnVisibility = {
- createdAt: false,
- updatedAt: false,
- updatedBy: false,
- description: false,
- };
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "updatedByFullName",
+ header: "Updated By",
+ cell: ({ row }) => {
+ return row.original.updatedByFullName ? (
+ <HStack>
+ <Avatar size="sm" path={row.original.updatedByAvatar ?? null} />
+ <span>{row.original.updatedByFullName}</span>
+ </HStack>
+ ) : null;
+ },
+ },
+ {
+ accessorKey: "updatedAt",
+ header: "Updated At",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, [
+ download,
+ extensions,
+ isImage,
+ isPdf,
+ labelOptions,
+ onDeleteLabel,
+ onFavorite,
+ onLabel,
+ revalidator,
+ setLabel,
+ ]);
- const renderContextMenu = useMemo(() => {
- // eslint-disable-next-line react/display-name
- return (row: Document) => (
- <>
- <MenuItem disabled={canUpdate(row)} onClick={() => edit(row)}>
- <MenuIcon icon={<BsFillPenFill />} />
- Edit
- </MenuItem>
- <MenuItem onClick={() => download(row)}>
- <MenuIcon icon={<VscOpenPreview />} />
- Download
- </MenuItem>
- <MenuItem
- onClick={() => {
- onFavorite(row);
- }}
- >
- <MenuIcon icon={<BsPin />} />
- Favorite
- </MenuItem>
- <MenuItem
- disabled={canDelete(row)}
- onClick={() => {
- setSelectedDocument(row);
- deleteDocumentModal.onOpen();
- }}
- >
- <MenuIcon icon={<IoMdTrash />} />
- {filter !== "trash" ? "Move to Trash" : "Restore from Trash"}
- </MenuItem>
- </>
- );
- }, [
- canDelete,
- canUpdate,
- deleteDocumentModal,
- download,
- edit,
- filter,
- onFavorite,
- ]);
+ const actions = useMemo(() => {
+ return [
+ // {
+ // label: "Add to Favorites",
+ // icon: <BsBookmark />,
+ // onClick: (selected: Document[]) => {
+ // console.log("move to favorites", selected);
+ // },
+ // },
+ // {
+ // label: "Add Labels",
+ // icon: <BsTag />,
+ // // TODO - disabled can be a function of selected
+ // disabled: true,
+ // onClick: (selected: Document[]) => {
+ // console.log("move to favorites", selected);
+ // },
+ // },
+ // {
+ // label: "Move to Trash",
+ // icon: <IoMdTrash />,
+ // // TODO - disabled can be a function of selected
+ // disabled: true,
+ // onClick: (selected: Document[]) => {
+ // console.log("move to trash", selected);
+ // },
+ // },
+ // {
+ // label: "Update Visibility",
+ // icon: <BsEyeFill />,
+ // // TODO - disabled can be a function of selected
+ // disabled: true,
+ // onClick: (selected: Document[]) => {
+ // console.log("update visibility", selected);
+ // },
+ // },
+ ];
+ }, []);
- return (
- <>
- <Table<Document>
- actions={actions}
- count={count}
- columns={columns}
- data={rows}
- defaultColumnVisibility={defaultColumnVisibility}
- withColumnOrdering
- withFilters
- withPagination
- withSimpleSorting
- withSelectableRows
- renderContextMenu={renderContextMenu}
- />
+ const defaultColumnVisibility = {
+ type: false,
+ extension: false,
+ createdAt: false,
+ updatedAt: false,
+ updatedBy: false,
+ description: false,
+ };
- {selectedDocument &&
- selectedDocument.id &&
- (filter !== "trash" ? (
- <ConfirmDelete
- action={path.to.deleteDocument(selectedDocument.id)}
- isOpen={deleteDocumentModal.isOpen}
- name={selectedDocument.name}
- text={`Are you sure you want to move ${selectedDocument.name} to the trash?`}
- onCancel={() => {
- deleteDocumentModal.onClose();
- setSelectedDocument(null);
- }}
- onSubmit={() => {
- deleteDocumentModal.onClose();
- setSelectedDocument(null);
- }}
- />
- ) : (
- <Confirm
- action={path.to.documentRestore(selectedDocument.id)}
- isOpen={deleteDocumentModal.isOpen}
- name={`Restore ${selectedDocument.name}`}
- text={`Are you sure you want to restore ${selectedDocument.name} from the trash?`}
- onCancel={() => {
- deleteDocumentModal.onClose();
- setSelectedDocument(null);
+ const renderContextMenu = useMemo(() => {
+ // eslint-disable-next-line react/display-name
+ return (row: Document) => (
+ <>
+ <MenuItem disabled={canUpdate(row)} onClick={() => edit(row)}>
+ <MenuIcon icon={<BsFillPenFill />} />
+ Edit
+ </MenuItem>
+ <MenuItem onClick={() => download(row)}>
+ <MenuIcon icon={<VscOpenPreview />} />
+ Download
+ </MenuItem>
+ <MenuItem
+ onClick={() => {
+ onFavorite(row);
}}
- onSubmit={() => {
- deleteDocumentModal.onClose();
- setSelectedDocument(null);
+ >
+ <MenuIcon icon={<BsPin />} />
+ Favorite
+ </MenuItem>
+ <MenuItem
+ disabled={canDelete(row)}
+ onClick={() => {
+ setSelectedDocument(row);
+ deleteDocumentModal.onOpen();
}}
- />
- ))}
- </>
- );
-});
+ >
+ <MenuIcon icon={<IoMdTrash />} />
+ {filter !== "trash" ? "Move to Trash" : "Restore from Trash"}
+ </MenuItem>
+ </>
+ );
+ }, [
+ canDelete,
+ canUpdate,
+ deleteDocumentModal,
+ download,
+ edit,
+ filter,
+ onFavorite,
+ ]);
+
+ return (
+ <>
+ <TableNew<Document>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ primaryAction={
+ permissions.can("create", "documents") && <DocumentCreateForm />
+ }
+ withColumnOrdering
+ withSelectableRows
+ renderContextMenu={renderContextMenu}
+ />
+
+ {selectedDocument &&
+ selectedDocument.id &&
+ (filter !== "trash" ? (
+ <ConfirmDelete
+ action={path.to.deleteDocument(selectedDocument.id)}
+ isOpen={deleteDocumentModal.isOpen}
+ name={selectedDocument.name ?? ""}
+ text={`Are you sure you want to move ${selectedDocument.name} to the trash?`}
+ onCancel={() => {
+ deleteDocumentModal.onClose();
+ setSelectedDocument(null);
+ }}
+ onSubmit={() => {
+ deleteDocumentModal.onClose();
+ setSelectedDocument(null);
+ }}
+ />
+ ) : (
+ <Confirm
+ action={path.to.documentRestore(selectedDocument.id)}
+ isOpen={deleteDocumentModal.isOpen}
+ name={`Restore ${selectedDocument.name}`}
+ text={`Are you sure you want to restore ${selectedDocument.name} from the trash?`}
+ onCancel={() => {
+ deleteDocumentModal.onClose();
+ setSelectedDocument(null);
+ }}
+ onSubmit={() => {
+ deleteDocumentModal.onClose();
+ setSelectedDocument(null);
+ }}
+ />
+ ))}
+ </>
+ );
+ }
+);
type CreatableCommandProps = {
options: {
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters.tsx
deleted file mode 100644
index 2cf03044f3..0000000000
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { HStack } from "@carbon/react";
-import { Combobox, Select } from "~/components";
-import { TableFilters } from "~/components/Layout";
-import { DebouncedInput } from "~/components/Search";
-import { usePermissions, useUrlParams } from "~/hooks";
-import type { DocumentLabel } from "~/modules/documents/types";
-import { capitalize } from "~/utils/string";
-import DocumentCreateForm from "./DocumentCreateForm";
-
-type DocumentTableFiltersProps = {
- labels: DocumentLabel[];
-};
-
-const documentTypeOptions = [
- "all",
- "document",
- "presentation",
- "spreadsheet",
- "image",
- "video",
- "audio",
-].map((type) => ({
- label: capitalize(type),
- value: type,
-}));
-
-const DocumentsTableFilters = ({ labels }: DocumentTableFiltersProps) => {
- const [params, setParams] = useUrlParams();
- const permissions = usePermissions();
-
- const labelOptions = labels.map<{ label: string; value: string }>((l) => ({
- value: l.label!,
- label: l.label!,
- }));
-
- return (
- <TableFilters>
- <HStack>
- <DebouncedInput param="search" size="sm" placeholder="Search" />
- <Select
- size="sm"
- value={params.get("type") ?? ""}
- isClearable
- options={documentTypeOptions}
- onChange={(selected) => {
- setParams({ type: selected });
- }}
- aria-label="Document Type"
- placeholder="Document Type"
- />
- {labels.length > 0 && (
- <Combobox
- size="sm"
- value={params.get("label") ?? ""}
- isClearable
- options={labelOptions}
- onChange={(selected) => {
- setParams({ label: selected });
- }}
- aria-label="Label"
- placeholder="Label"
- />
- )}
- </HStack>
- <HStack>
- {permissions.can("create", "documents") && <DocumentCreateForm />}
- </HStack>
- </TableFilters>
- );
-};
-
-export default DocumentsTableFilters;
diff --git a/apps/carbon/app/modules/documents/ui/Documents/index.ts b/apps/carbon/app/modules/documents/ui/Documents/index.ts
index 8d629feb00..59bd27abcc 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/index.ts
+++ b/apps/carbon/app/modules/documents/ui/Documents/index.ts
@@ -1,6 +1,5 @@
import DocumentForm from "./DocumentForm";
import DocumentIcon from "./DocumentIcon";
import DocumentsTable from "./DocumentsTable";
-import DocumentsTableFilters from "./DocumentsTableFilters";
-export { DocumentForm, DocumentIcon, DocumentsTable, DocumentsTableFilters };
+export { DocumentForm, DocumentIcon, DocumentsTable };
diff --git a/apps/carbon/app/modules/documents/ui/useDocumentsSubmodules.tsx b/apps/carbon/app/modules/documents/ui/useDocumentsSubmodules.tsx
index c6e6ed6bdb..145be2b48e 100644
--- a/apps/carbon/app/modules/documents/ui/useDocumentsSubmodules.tsx
+++ b/apps/carbon/app/modules/documents/ui/useDocumentsSubmodules.tsx
@@ -22,7 +22,7 @@ const documentsRoutes: Route[] = [
icon: <BsClock />,
},
{
- name: "Starred",
+ name: "Pinned",
to: path.to.documents,
q: "starred",
icon: <BsPin />,
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
index ebf1101ee7..e33f735cee 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
@@ -12,7 +12,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { Avatar, TableNew } from "~/components";
+import { Avatar, New, TableNew } from "~/components";
import { usePermissions, useRealtime, useUrlParams } from "~/hooks";
import type { Receipt } from "~/modules/inventory";
import {
@@ -247,9 +247,11 @@ const ReceiptsTable = memo(({ data, count, locations }: ReceiptsTableProps) => {
defaultColumnPinning={{
left: ["receiptId"],
}}
- label="Receipt"
- newPath={path.to.newReceipt}
- newPermission={permissions.can("create", "inventory")}
+ primaryAction={
+ permissions.can("create", "inventory") && (
+ <New label="Receipt" to={path.to.newReceipt} />
+ )
+ }
renderContextMenu={renderContextMenu}
withColumnOrdering
/>
diff --git a/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx b/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
index d5ae18e435..12b85194de 100644
--- a/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
+++ b/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import { shippingCarrierType, type ShippingMethod } from "~/modules/inventory";
import { path } from "~/utils/path";
@@ -113,9 +113,14 @@ const ShippingMethodsTable = memo(
data={data}
columns={columns}
count={count}
- label="Shipping Method"
- newPath={path.to.newShippingMethod}
- newPermission={permissions.can("create", "inventory")}
+ primaryAction={
+ permissions.can("create", "inventory") && (
+ <New
+ label="Shipping Method"
+ to={`${path.to.newShippingMethod}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable.tsx b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable.tsx
index 1092e4d713..617f915718 100644
--- a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { PartGroup } from "~/modules/parts";
import { path } from "~/utils/path";
@@ -82,9 +82,14 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
data={data}
columns={columns}
count={count}
- label="Part Group"
- newPath={`${path.to.newPartGroup}?${params.toString()}`}
- newPermission={permissions.can("create", "parts")}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New
+ label="Part Group"
+ to={`${path.to.newPartGroup}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
index 7d8b363774..7adcfd9eaa 100644
--- a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
@@ -3,7 +3,7 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { Part } from "~/modules/parts";
import { partReplenishmentSystems, partTypes } from "~/modules/parts";
@@ -104,9 +104,11 @@ const PartsTable = memo(({ data, count, partGroups }: PartsTableProps) => {
count={count}
columns={columns}
data={data}
- label="Part"
- newPath={path.to.newPart}
- newPermission={permissions.can("create", "parts")}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New label="Part" to={path.to.newPart} />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
</>
diff --git a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
index 8df1d83980..fe3d046f7f 100644
--- a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
@@ -3,7 +3,7 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import { serviceType, type Service } from "~/modules/parts";
import type { ListItem } from "~/types";
@@ -93,10 +93,11 @@ const ServicesTable = memo(
count={count}
columns={columns}
data={data}
- label="Service"
- newPath={path.to.newService}
- newPermission={permissions.can("create", "parts")}
- withPagination
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New label="Service" to={path.to.newService} />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
</>
diff --git a/apps/carbon/app/modules/parts/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx b/apps/carbon/app/modules/parts/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
index ce029463e3..411a64b075 100644
--- a/apps/carbon/app/modules/parts/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { UnitOfMeasure } from "~/modules/parts";
import { path } from "~/utils/path";
@@ -73,9 +73,14 @@ const UnitOfMeasuresTable = memo(
data={data}
columns={columns}
count={count}
- label="Unit of Measure"
- newPath={path.to.newUom}
- newPermission={permissions.can("create", "parts")}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New
+ label="Unit of Measure"
+ to={`${path.to.newUom}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
index f8cb1fc69c..7bbb5b3688 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
@@ -13,7 +13,7 @@ import { memo, useMemo, useState } from "react";
import { BsFillPenFill, BsPin, BsPinFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { MdCallReceived } from "react-icons/md";
-import { Avatar, TableNew } from "~/components";
+import { Avatar, New, TableNew } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import type { PurchaseOrder } from "~/modules/purchasing";
@@ -270,9 +270,11 @@ const PurchaseOrdersTable = memo(
defaultColumnPinning={{
left: ["purchaseOrderId"],
}}
- label="Purchase Order"
- newPath={path.to.newPurchaseOrder}
- newPermission={permissions.can("create", "purchasing")}
+ primaryAction={
+ permissions.can("create", "purchasing") && (
+ <New label="Purchase Order" to={path.to.newPurchaseOrder} />
+ )
+ }
withColumnOrdering
renderContextMenu={renderContextMenu}
/>
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx
index 3041d26ab9..5ee3894d07 100644
--- a/apps/carbon/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill, BsPeopleFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { SupplierStatus } from "~/modules/purchasing";
import { path } from "~/utils/path";
@@ -82,9 +82,14 @@ const SupplierStatusesTable = memo(
data={data}
columns={columns}
count={count}
- label="Supplier Status"
- newPath={path.to.newSupplierStatus}
- newPermission={permissions.can("create", "purchasing")}
+ primaryAction={
+ permissions.can("create", "purchasing") && (
+ <New
+ label="Supplier Status"
+ to={`${path.to.newSupplierStatus}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
index 3842b44416..97e88dd681 100644
--- a/apps/carbon/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill, BsPeopleFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { SupplierType } from "~/modules/purchasing";
import { path } from "~/utils/path";
@@ -78,9 +78,14 @@ const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {
data={data}
columns={columns}
count={count}
- label="Supplier Type"
- newPath={path.to.newSupplierType}
- newPermission={permissions.can("create", "purchasing")}
+ primaryAction={
+ permissions.can("create", "purchasing") && (
+ <New
+ label="Supplier Type"
+ to={`${path.to.newSupplierType}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
index d7e17e85a3..1241e0bfe6 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx
@@ -9,7 +9,7 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions } from "~/hooks";
import type {
Supplier,
@@ -122,9 +122,11 @@ const SuppliersTable = memo(
count={count}
columns={columns}
data={data}
- label="Supplier"
- newPath={path.to.newSupplier}
- newPermission={permissions.can("create", "purchasing")}
+ primaryAction={
+ permissions.can("create", "purchasing") && (
+ <New label="Supplier" to={path.to.newSupplier} />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
</>
diff --git a/apps/carbon/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx b/apps/carbon/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx
index 3ca1353748..e01e19cc32 100644
--- a/apps/carbon/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill, BsPeopleFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { CustomerStatus } from "~/modules/sales";
import { path } from "~/utils/path";
@@ -80,9 +80,14 @@ const CustomerStatusesTable = memo(
data={data}
columns={columns}
count={count}
- label="Customer Status"
- newPath={path.to.newCustomerStatus}
- newPermission={permissions.can("create", "sales")}
+ primaryAction={
+ permissions.can("create", "sales") && (
+ <New
+ label="Customer Status"
+ to={`${path.to.newCustomerStatus}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx b/apps/carbon/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
index 3757cc99b2..866507c249 100644
--- a/apps/carbon/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsFillPenFill, BsPeopleFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { CustomerType } from "~/modules/sales";
import { path } from "~/utils/path";
@@ -78,9 +78,14 @@ const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {
data={data}
columns={columns}
count={count}
- label="Customer Type"
- newPath={path.to.newCustomerType}
- newPermission={permissions.can("create", "sales")}
+ primaryAction={
+ permissions.can("create", "sales") && (
+ <New
+ label="Customer Types"
+ to={`${path.to.newCustomerType}?${params.toString()}`}
+ />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
);
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
index 507fda8e94..75cf9f1c55 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
@@ -3,7 +3,7 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { TableNew } from "~/components";
+import { New, TableNew } from "~/components";
import { usePermissions } from "~/hooks";
import type { Customer, CustomerStatus, CustomerType } from "~/modules/sales";
import { path } from "~/utils/path";
@@ -97,9 +97,11 @@ const CustomersTable = memo(
count={count}
columns={columns}
data={data}
- newPath={path.to.newCustomer}
- newPermission={permissions.can("create", "sales")}
- withPagination
+ primaryAction={
+ permissions.can("create", "sales") && (
+ <New label="Customer" to={path.to.newCustomer} />
+ )
+ }
renderContextMenu={renderContextMenu}
/>
</>
diff --git a/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx
index 04edc96d4c..3f96ac5796 100644
--- a/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotations/QuotationsTable.tsx
@@ -11,7 +11,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import { BsFillPenFill, BsPin, BsPinFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
-import { Avatar, TableNew } from "~/components";
+import { Avatar, New, TableNew } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import type { Quotation } from "~/modules/sales";
@@ -244,9 +244,11 @@ const QuotationsTable = memo(({ data, count }: QuotationsTableProps) => {
defaultColumnPinning={{
left: ["quoteId"],
}}
- label="Quote"
- newPath={path.to.newQuote}
- newPermission={permissions.can("create", "sales")}
+ primaryAction={
+ permissions.can("create", "sales") && (
+ <New label="Quote" to={path.to.newQuote} />
+ )
+ }
withColumnOrdering
renderContextMenu={renderContextMenu}
/>
diff --git a/apps/carbon/app/routes/x+/documents+/search.tsx b/apps/carbon/app/routes/x+/documents+/search.tsx
index 7dbc272773..9d9667e4a4 100644
--- a/apps/carbon/app/routes/x+/documents+/search.tsx
+++ b/apps/carbon/app/routes/x+/documents+/search.tsx
@@ -5,7 +5,7 @@ import { Outlet, useLoaderData } from "@remix-run/react";
import type { Document } from "~/modules/documents";
import {
DocumentsTable,
- DocumentsTableFilters,
+ getDocumentExtensions,
getDocumentLabels,
getDocuments,
} from "~/modules/documents";
@@ -23,8 +23,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const search = searchParams.get("search");
- const type = searchParams.get("type");
- const label = searchParams.get("label");
const filter = searchParams.get("q");
const createdBy = filter === "my" ? userId : undefined;
@@ -35,11 +33,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [documents, labels] = await Promise.all([
+ const [documents, labels, extensions] = await Promise.all([
getDocuments(client, {
search,
- type,
- label,
favorite,
recent,
createdBy,
@@ -50,6 +46,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
filters,
}),
getDocumentLabels(client, userId),
+ getDocumentExtensions(client),
]);
if (documents.error) {
@@ -63,16 +60,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
count: documents.count ?? 0,
documents: (documents.data ?? []) as Document[],
labels: labels.data ?? [],
+ extensions: extensions.data?.map(({ extension }) => extension) ?? [],
});
}
export default function DocumentsAllRoute() {
- const { count, documents, labels } = useLoaderData<typeof loader>();
+ const { count, documents, labels, extensions } =
+ useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <DocumentsTableFilters labels={labels} />
- <DocumentsTable data={documents} count={count} labels={labels} />
+ <DocumentsTable
+ data={documents}
+ count={count}
+ labels={labels}
+ extensions={extensions}
+ />
<Outlet />
</VStack>
);
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2074e08072..9d45929307 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2659,12 +2659,13 @@ export type Database = {
createdAt: string
createdBy: string
description: string | null
+ extension: string | null
id: string
name: string
path: string
readGroups: string[] | null
size: number
- type: string | null
+ type: Database["public"]["Enums"]["documentType"]
updatedAt: string | null
updatedBy: string | null
writeGroups: string[] | null
@@ -2674,12 +2675,13 @@ export type Database = {
createdAt?: string
createdBy: string
description?: string | null
+ extension?: string | null
id?: string
name: string
path: string
readGroups?: string[] | null
size: number
- type?: string | null
+ type: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
writeGroups?: string[] | null
@@ -2689,12 +2691,13 @@ export type Database = {
createdAt?: string
createdBy?: string
description?: string | null
+ extension?: string | null
id?: string
name?: string
path?: string
readGroups?: string[] | null
size?: number
- type?: string | null
+ type?: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
writeGroups?: string[] | null
@@ -12097,6 +12100,12 @@ export type Database = {
}
Relationships: []
}
+ documentExtensions: {
+ Row: {
+ extension: string | null
+ }
+ Relationships: []
+ }
documentLabels: {
Row: {
label: string | null
@@ -12134,6 +12143,7 @@ export type Database = {
createdByAvatar: string | null
createdByFullName: string | null
description: string | null
+ extension: string | null
favorite: boolean | null
id: string | null
labels: string[] | null
@@ -12142,7 +12152,7 @@ export type Database = {
path: string | null
readGroups: string[] | null
size: number | null
- type: string | null
+ type: Database["public"]["Enums"]["documentType"] | null
updatedAt: string | null
updatedBy: string | null
updatedByAvatar: string | null
@@ -13623,6 +13633,17 @@ export type Database = {
| "Label"
| "Unfavorite"
| "Upload"
+ documentType:
+ | "Archive"
+ | "Document"
+ | "Presentation"
+ | "PDF"
+ | "Spreadsheet"
+ | "Text"
+ | "Image"
+ | "Video"
+ | "Audio"
+ | "Other"
factor:
| "Hours/Piece"
| "Hours/100 Pieces"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2074e08072..9d45929307 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2659,12 +2659,13 @@ export type Database = {
createdAt: string
createdBy: string
description: string | null
+ extension: string | null
id: string
name: string
path: string
readGroups: string[] | null
size: number
- type: string | null
+ type: Database["public"]["Enums"]["documentType"]
updatedAt: string | null
updatedBy: string | null
writeGroups: string[] | null
@@ -2674,12 +2675,13 @@ export type Database = {
createdAt?: string
createdBy: string
description?: string | null
+ extension?: string | null
id?: string
name: string
path: string
readGroups?: string[] | null
size: number
- type?: string | null
+ type: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
writeGroups?: string[] | null
@@ -2689,12 +2691,13 @@ export type Database = {
createdAt?: string
createdBy?: string
description?: string | null
+ extension?: string | null
id?: string
name?: string
path?: string
readGroups?: string[] | null
size?: number
- type?: string | null
+ type?: Database["public"]["Enums"]["documentType"]
updatedAt?: string | null
updatedBy?: string | null
writeGroups?: string[] | null
@@ -12097,6 +12100,12 @@ export type Database = {
}
Relationships: []
}
+ documentExtensions: {
+ Row: {
+ extension: string | null
+ }
+ Relationships: []
+ }
documentLabels: {
Row: {
label: string | null
@@ -12134,6 +12143,7 @@ export type Database = {
createdByAvatar: string | null
createdByFullName: string | null
description: string | null
+ extension: string | null
favorite: boolean | null
id: string | null
labels: string[] | null
@@ -12142,7 +12152,7 @@ export type Database = {
path: string | null
readGroups: string[] | null
size: number | null
- type: string | null
+ type: Database["public"]["Enums"]["documentType"] | null
updatedAt: string | null
updatedBy: string | null
updatedByAvatar: string | null
@@ -13623,6 +13633,17 @@ export type Database = {
| "Label"
| "Unfavorite"
| "Upload"
+ documentType:
+ | "Archive"
+ | "Document"
+ | "Presentation"
+ | "PDF"
+ | "Spreadsheet"
+ | "Text"
+ | "Image"
+ | "Video"
+ | "Audio"
+ | "Other"
factor:
| "Hours/Piece"
| "Hours/100 Pieces"
diff --git a/packages/database/supabase/migrations/20230423023136_documents.sql b/packages/database/supabase/migrations/20230423023136_documents.sql
index 08ea1656f9..b494912197 100644
--- a/packages/database/supabase/migrations/20230423023136_documents.sql
+++ b/packages/database/supabase/migrations/20230423023136_documents.sql
@@ -1,10 +1,24 @@
+CREATE TYPE "documentType" AS ENUM (
+ 'Archive',
+ 'Document',
+ 'Presentation',
+ 'PDF',
+ 'Spreadsheet',
+ 'Text',
+ 'Image',
+ 'Video',
+ 'Audio',
+ 'Other'
+);
+
CREATE TABLE "document" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"path" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT DEFAULT '',
"size" INTEGER NOT NULL,
- "type" TEXT GENERATED ALWAYS AS (split_part("name", '.', -1)) STORED,
+ "extension" TEXT GENERATED ALWAYS AS (split_part("name", '.', -1)) STORED,
+ "type" "documentType" NOT NULL,
"readGroups" TEXT[],
"writeGroups" TEXT[],
"active" BOOLEAN NOT NULL DEFAULT TRUE,
@@ -219,26 +233,19 @@ CREATE OR REPLACE VIEW "documentLabels" AS
CREATE OR REPLACE VIEW "documents" AS
SELECT
- d.id,
- d.path,
- d.name,
- d.description,
- d.size,
- d.type,
- d.active,
- d."readGroups",
- d."writeGroups",
- d."createdBy",
+ d.*,
u."avatarUrl" AS "createdByAvatar",
u."fullName" AS "createdByFullName",
- d."createdAt",
- d."updatedBy",
u2."avatarUrl" AS "updatedByAvatar",
u2."fullName" AS "updatedByFullName",
- d."updatedAt",
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";
+
+CREATE OR REPLACE VIEW "documentExtensions" WITH(SECURITY_INVOKER=true) AS
+ SELECT DISTINCT
+ extension
+ FROM "document";
\ No newline at end of file
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 958a565905..06e19c966b 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -1,4 +1,5 @@
export * from "./accounting";
+export * from "./arrays";
export * from "./color";
export * from "./date";
export * from "./file";