Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Documents (#30)
Brad Barbinbe08d424d5a6
diff --git a/SCHEMA.md b/SCHEMA.mdindex 5038fd47eb..9c7fdb4cc7 100644--- a/SCHEMA.md+++ b/SCHEMA.md@@ -409,30 +409,29 @@ VALUESCREATE POLICY "Anyone can view avatars"ON storage.objects FOR SELECT USING (bucket_id = 'avatars'+ AND (auth.role() = 'authenticated'));CREATE POLICY "Users can delete their own avatars"ON storage.objects FOR DELETE USING (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%'));CREATE POLICY "Users can update their own avatars"ON storage.objects FOR UPDATE USING (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%'));CREATE POLICY "Users can insert their own avatars"ON storage.objects FOR INSERT WITH CHECK (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%'));--```@@ -1146,10 +1145,10 @@ AS $$END;$$;-CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: return setof string+CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = publicAS $$- DECLARE retval jsonb;+ DECLARE retval TEXT[];BEGINWITH RECURSIVE "groupsForUser" AS (SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"@@ -1157,7 +1156,7 @@ CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: reUNIONSELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"- ) SELECT coalesce(jsonb_agg("groupId"), '[]') INTO retval AS groups FROM "groupsForUser";+ ) SELECT array_agg("groupId") INTO retval AS groups FROM "groupsForUser";RETURN retval;END;$$;@@ -3354,6 +3353,12 @@ CREATE TABLE "part" (CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));+CREATE INDEX "part_name_index" ON "part"("name");+CREATE INDEX "part_description_index" ON "part"("description");+CREATE INDEX "part_partType_index" ON "part"("partType");+CREATE INDEX "part_partGroupId_index" ON "part"("partGroupId");+CREATE INDEX "part_replenishmentSystem_index" ON "part"("replenishmentSystem");+ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view parts" ON "part"@@ -3830,3 +3835,255 @@ CREATE POLICY "Suppliers with parts_update can update part inventory that they s);```+++## `documents`++```sql+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,+ "readGroups" TEXT[],+ "writeGroups" TEXT[],+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "document_pkey" PRIMARY KEY ("id"),++ CONSTRAINT "document_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE,+ CONSTRAINT "document_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "document_visibility_idx" ON "document" USING GIN ("readGroups", "writeGroups");++ALTER TABLE "document" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users with documents_view can view documents where they are in the readGroups" ON "document"+ FOR SELECT USING (+ coalesce(get_my_claim('documents_view')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "readGroups") = true+ );++CREATE POLICY "Users with documents_create can create documents where they are in the writeGroups" ON "document"+ FOR INSERT WITH CHECK (+ coalesce(get_my_claim('documents_create')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Users with documents_update can update documents where they are in the writeGroups" ON "document"+ FOR UPDATE USING (+ coalesce(get_my_claim('documents_update')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Users with documents_delete can delete documents where they are in the writeGroups" ON "document"+ FOR DELETE USING (+ coalesce(get_my_claim('documents_delete')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Private buckets view requires ownership or document.readGroups" ON storage.objects+FOR SELECT USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_view')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets insert requires ownership or document.writeGroups" ON storage.objects+FOR INSERT WITH CHECK (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_create')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "writeGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets update requires ownership or document.writeGroups" ON storage.objects+FOR UPDATE USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_update')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets delete requires ownership or document.writeGroups" ON storage.objects+FOR DELETE USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_delete')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE TYPE "documentTransactionType" AS ENUM (+ 'Download',+ 'Edit',+ 'Favorite',+ 'Label',+ 'Unfavorite',+ 'Upload'+);++CREATE TABLE "documentTransaction" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "documentId" TEXT NOT NULL,+ "type" "documentTransactionType" NOT NULL,+ "userId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "documentActivity_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "documentActivity_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentActivity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentActivity_documentId_idx" ON "documentTransaction" ("documentId");+CREATE INDEX "documentActivity_userId_idx" ON "documentTransaction" ("userId");++CREATE TABLE "documentFavorite" (+ "documentId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,++ CONSTRAINT "documentFavorites_pkey" PRIMARY KEY ("documentId", "userId"),+ CONSTRAINT "documentFavorites_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentFavorites_userId_idx" ON "documentFavorite" ("userId");+CREATE INDEX "documentFavorites_documentId_idx" ON "documentFavorite" ("documentId");++ALTER TABLE "documentFavorite" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own favorites" ON "documentFavorite"+ FOR SELECT USING (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can create their own favorites" ON "documentFavorite"+ FOR INSERT WITH CHECK (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can delete their own favorites" ON "documentFavorite"+ FOR DELETE USING (+ auth.uid()::text = "userId"+ );++CREATE TABLE "documentLabel" (+ "documentId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "label" TEXT NOT NULL,++ CONSTRAINT "documentLabels_pkey" PRIMARY KEY ("documentId", "userId", "label"),+ CONSTRAINT "documentLabels_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentLabels_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentLabels_userId_idx" ON "documentLabel" ("userId");+CREATE INDEX "documentLabels_documentId_idx" ON "documentLabel" ("documentId");+CREATE INDEX "documentLabels_label_idx" ON "documentLabel" ("label");++ALTER TABLE "documentLabel" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own labels" ON "documentLabel"+ FOR SELECT USING (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can create their own labels" ON "documentLabel"+ FOR INSERT WITH CHECK (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can delete their own labels" ON "documentLabel"+ FOR DELETE USING (+ auth.uid()::text = "userId"+ );++CREATE FUNCTION public.upload_document_transaction()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."documentTransaction" ("documentId", "type", "userId")+ VALUES (new.id, 'Upload', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER upload_document_transaction+ AFTER INSERT on public."document"+ FOR EACH ROW EXECUTE PROCEDURE public.upload_document_transaction();++CREATE FUNCTION public.edit_document_transaction()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."documentTransaction" ("documentId", "type", "userId")+ VALUES (new.id, 'Edit', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER edit_document_transaction+ AFTER UPDATE on public."document"+ FOR EACH ROW EXECUTE PROCEDURE public.edit_document_transaction();++CREATE VIEW "documents_labels_view" AS+ SELECT DISTINCT+ "label",+ "userId"+ FROM "documentLabel";++CREATE VIEW "documents_view" AS+ SELECT+ d.id,+ d.path,+ d.name,+ d.description,+ d.size,+ d.type,+ d.active,+ d."readGroups",+ d."writeGroups",+ d."createdBy",+ 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";++```+diff --git a/apps/carbon/app/components/Form/CreatableMultiSelect.tsx b/apps/carbon/app/components/Form/CreatableMultiSelect.tsxnew file mode 100644index 0000000000..9fbedcb095--- /dev/null+++ b/apps/carbon/app/components/Form/CreatableMultiSelect.tsx@@ -0,0 +1,109 @@+import { CreatableSelect } from "@carbon/react";+import {+ FormControl,+ FormErrorMessage,+ FormHelperText,+ FormLabel,+} from "@chakra-ui/react";++import { useControlField, useField } from "remix-validated-form";++export type SelectProps = {+ name: string;+ label?: string;+ options: { value: string | number; label: string }[];+ helperText?: string;+ isReadOnly?: boolean;+ isLoading?: boolean;+ placeholder?: string;+ onChange?: (+ newValue: { value: string | number; label: string }[] | null+ ) => void;+ onUsingCreatedChanged?: (usingCreated: boolean) => void;+};++const Select = ({+ name,+ label,+ options,+ helperText,+ isLoading,+ isReadOnly,+ placeholder,+ onChange,+ onUsingCreatedChanged,+ ...props+}: SelectProps) => {+ const { error } = useField(name);+ const [value, setValue] = useControlField<string[]>(name);++ const handleChange = (+ newValue: { value: string | number; label: string }[] | null+ ) => {+ setValue(newValue?.map((option) => option.value.toString()) ?? []);+ onChange?.(newValue);+ onUsingCreatedChanged?.(false);+ };++ const handleCreate = (inputValue: string) => {+ setValue([...value, inputValue]);+ onChange?.(+ value.map((value) => ({+ value,+ label: value,+ }))+ );+ onUsingCreatedChanged?.(true);+ };++ const optionsWithCreation = options+ .concat(+ value.map((value) => ({+ value,+ label: value,+ }))+ )+ .filter((v, i, a) => a.findIndex((v2) => v2.label === v.label) === i);++ const selectedValues =+ optionsWithCreation.filter((option) =>+ value.some((v) => option.value === v)+ ) ?? [];++ // TODO: hack for default value+ return (+ <FormControl isInvalid={!!error}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ {value.map((v, index) => (+ <input+ key={`${name}[${index}]`}+ type="hidden"+ name={`${name}[${index}]`}+ value={v}+ />+ ))}+ <CreatableSelect+ {...props}+ value={selectedValues}+ isClearable+ isLoading={isLoading}+ isMulti+ options={options}+ placeholder={placeholder}+ w="full"+ onCreateOption={handleCreate}+ // @ts-ignore+ onChange={handleChange}+ />+ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}+ </FormControl>+ );+};++Select.displayName = "Select";++export default Select;diff --git a/apps/carbon/app/components/Form/CreatableSelect.tsx b/apps/carbon/app/components/Form/CreatableSelect.tsxindex 17faa1b813..ea4e1cc8cb 100644--- a/apps/carbon/app/components/Form/CreatableSelect.tsx+++ b/apps/carbon/app/components/Form/CreatableSelect.tsx@@ -1,6 +1,5 @@import { CreatableSelect } from "@carbon/react";import {- Box,FormControl,FormErrorMessage,FormHelperText,@@ -61,7 +60,7 @@ const Select = ({);// TODO: hack for default value- return optionsWithCreation.length > 0 ? (+ return (<FormControl isInvalid={!!error}>{label && <FormLabel htmlFor={name}>{label}</FormLabel>}<CreatableSelect@@ -86,17 +85,6 @@ const Select = ({helperText && <FormHelperText>{helperText}</FormHelperText>)}</FormControl>- ) : (- <Box>- {label && <FormLabel>{label}</FormLabel>}- <CreatableSelect- isDisabled- isLoading={isLoading}- options={[]}- // @ts-ignore- w="full"- />- </Box>);};diff --git a/apps/carbon/app/components/Form/Input.tsx b/apps/carbon/app/components/Form/Input.tsxindex 02a610d8fb..a891832e8a 100644--- a/apps/carbon/app/components/Form/Input.tsx+++ b/apps/carbon/app/components/Form/Input.tsx@@ -1,10 +1,12 @@import type { InputProps } from "@chakra-ui/react";-import { FormHelperText } from "@chakra-ui/react";import {FormControl,FormErrorMessage,+ FormHelperText,FormLabel,Input as ChakraInput,+ InputGroup,+ InputRightAddon,} from "@chakra-ui/react";import { forwardRef } from "react";import { useField } from "remix-validated-form";@@ -14,22 +16,26 @@ type FormInputProps = InputProps & {label?: string;isRequired?: boolean;helperText?: string;+ suffix?: string;};const Input = forwardRef<HTMLInputElement, FormInputProps>(- ({ name, label, isRequired, helperText, ...rest }, ref) => {+ ({ name, label, isRequired, helperText, suffix, ...rest }, ref) => {const { getInputProps, error } = useField(name);return (<FormControl isInvalid={!!error} isRequired={isRequired}>{label && <FormLabel htmlFor={name}>{label}</FormLabel>}- <ChakraInput- ref={ref}- {...getInputProps({- id: name,- ...rest,- })}- />+ <InputGroup>+ <ChakraInput+ ref={ref}+ {...getInputProps({+ id: name,+ ...rest,+ })}+ />+ {suffix && <InputRightAddon children={suffix} />}+ </InputGroup>{helperText && <FormHelperText>{helperText}</FormHelperText>}{error && <FormErrorMessage>{error}</FormErrorMessage>}</FormControl>diff --git a/apps/carbon/app/components/Form/Users.tsx b/apps/carbon/app/components/Form/Users.tsxindex f286032d14..0116e7bd86 100644--- a/apps/carbon/app/components/Form/Users.tsx+++ b/apps/carbon/app/components/Form/Users.tsx@@ -16,17 +16,27 @@ export type UsersProps = {name: string;label?: string;helperText?: string;+ verbose?: boolean; // prepends "user_" or "group_" to the value} & UserSelectProps;-const Users = ({ name, label, type, helperText, ...props }: UsersProps) => {+const Users = ({+ name,+ label,+ type,+ helperText,+ verbose = false,+ ...props+}: UsersProps) => {const { error, defaultValue, validate } = useField(name);const [selections, setSelections] = useState<string[]>(defaultValue);const handleChange = (items: IndividualOrGroup[]) => {setSelections(- items.map((item) =>- "users" in item ? `group_${item.id}` : `user_${item.id}`- )+ verbose+ ? items.map((item) =>+ "users" in item ? `group_${item.id}` : `user_${item.id}`+ )+ : items.map((item) => item.id));validate();};diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.tsindex 3564106f2b..aa50d662b9 100644--- a/apps/carbon/app/components/Form/index.ts+++ b/apps/carbon/app/components/Form/index.ts@@ -3,6 +3,7 @@ import Ability from "./Ability";import Array from "./Array";import Boolean from "./Boolean";import Color from "./Color";+import CreatableMultiSelect from "./CreatableMultiSelect";import CreatableSelect from "./CreatableSelect";import Customer from "./Customer";import CustomerContact from "./CustomerContact";@@ -36,6 +37,7 @@ export {Array,Boolean,Color,+ CreatableMultiSelect,CreatableSelect,Currency,Customer,diff --git a/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsxindex 238b021b25..54ff97accd 100644--- a/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx+++ b/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx@@ -1,11 +1,14 @@import { useColor } from "@carbon/react";import { Box, Button, VStack } from "@chakra-ui/react";import { Link, useMatches } from "@remix-run/react";+import { useUrlParams } from "~/hooks";import type { Route } from "~/types";import { CollapsibleSidebar } from "./CollapsibleSidebar";const ContentSidebar = ({ links }: { links: Route[] }) => {const matches = useMatches();+ const [params] = useUrlParams();+ const filter = params.get("q") ?? undefined;const borderColor = useColor("gray.200");return (@@ -23,14 +26,16 @@ const ContentSidebar = ({ links }: { links: Route[] }) => {w="full">{links.map((route) => {- const isActive = matches.some((match) =>- match.pathname.includes(route.to)+ const isActive = matches.some(+ (match) =>+ match.pathname.includes(route.to) && route.q === filter);return (<Buttonkey={route.name}as={Link}- to={route.to}+ to={route.to + (route.q ? `?q=${route.q}` : "")}+ leftIcon={route.icon}variant={isActive ? "solid" : "ghost"}border="none"fontWeight={isActive ? "bold" : "normal"}diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsxindex 07db4c34ef..27bad80ab5 100644--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx@@ -47,6 +47,11 @@ export default function useBreadcrumbs(): Route[] {name: "Accounting",to: match.pathname,});+ case "routes/x+/documents+/_layout":+ return acc.concat({+ name: "Documents",+ to: match.pathname,+ });case "routes/x+/parts+/index":return acc.concat({name: "Parts",diff --git a/apps/carbon/app/components/Modals/Confirm/Confirm.tsx b/apps/carbon/app/components/Modals/Confirm/Confirm.tsxnew file mode 100644index 0000000000..269a2a9ab6--- /dev/null+++ b/apps/carbon/app/components/Modals/Confirm/Confirm.tsx@@ -0,0 +1,53 @@+import {+ Button,+ Modal,+ ModalBody,+ ModalCloseButton,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+} from "@chakra-ui/react";+import { Form } from "@remix-run/react";++type ConfirmProps = {+ action: string;+ isOpen?: boolean;+ name: string;+ text: string;+ onCancel: () => void;+ onSubmit?: () => void;+};++const Confirm = ({+ action,+ isOpen = true,+ name,+ text,+ onCancel,+ onSubmit,+}: ConfirmProps) => {+ return (+ <Modal isOpen={isOpen} onClose={onCancel}>+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>{name}</ModalHeader>+ <ModalCloseButton />+ <ModalBody>{text}</ModalBody>++ <ModalFooter>+ <Button colorScheme="gray" mr={3} onClick={onCancel}>+ Cancel+ </Button>+ <Form method="post" action={action} onSubmit={onSubmit}>+ <Button colorScheme="brand" type="submit">+ Confirm+ </Button>+ </Form>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+};++export default Confirm;diff --git a/apps/carbon/app/components/Modals/Confirm/index.ts b/apps/carbon/app/components/Modals/Confirm/index.tsnew file mode 100644index 0000000000..cbbbe24334--- /dev/null+++ b/apps/carbon/app/components/Modals/Confirm/index.ts@@ -0,0 +1,3 @@+import Confirm from "./Confirm";++export default Confirm;diff --git a/apps/carbon/app/components/Modals/index.ts b/apps/carbon/app/components/Modals/index.tsindex 1ae61e532c..c9ff610005 100644--- a/apps/carbon/app/components/Modals/index.ts+++ b/apps/carbon/app/components/Modals/index.ts@@ -1,3 +1,4 @@+import Confirm from "./Confirm";import ConfirmDelete from "./ConfirmDelete";-export { ConfirmDelete };+export { Confirm, ConfirmDelete };diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsxindex 5a9ef84ae9..1db7618463 100644--- a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx+++ b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx@@ -17,7 +17,13 @@ import { isGroup } from "../useUserSelect";const SelectionList = () => {const {- innerProps: { checkedSelections, readOnly, selectionsMaxHeight, width },+ innerProps: {+ alwaysSelected,+ checkedSelections,+ readOnly,+ selectionsMaxHeight,+ width,+ },instanceId,selectionItemsById,onDeselect,@@ -102,7 +108,7 @@ const SelectionList = () => {</Tooltip>)}- {!readOnly && (+ {!readOnly && !alwaysSelected.includes(item.id) && (<Tooltip label="Remove"><IconButtonaria-label={`Remove ${item.label}`}diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsxindex ec70b0c125..b5b13d4faa 100644--- a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx+++ b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx@@ -51,6 +51,7 @@ const MoreIcon = ({ isExpanded }: { isExpanded: boolean }) => (const Group = ({ group }: { group: OptionGroup }) => {const {+ innerProps: { alwaysSelected },onGroupCollapse,onGroupExpand,focusedId,@@ -98,7 +99,11 @@ const Group = ({ group }: { group: OptionGroup }) => {isDisabled={isDisabled}isFocused={isFocused}isSelected={isSelected}- onClick={() => (isSelected ? onDeselect(item) : onSelect(item))}+ onClick={+ !alwaysSelected.includes(item.id)+ ? () => (isSelected ? onDeselect(item) : onSelect(item))+ : undefined+ }/>);})}@@ -125,7 +130,7 @@ const Option = ({isDisabled: boolean;isFocused: boolean;isSelected: boolean;- onClick: () => void;+ onClick?: () => void;}) => {const sx = useOptionStyles(isFocused, isSelected, isDisabled);const name = item.label;diff --git a/apps/carbon/app/components/Selectors/UserSelect/types.ts b/apps/carbon/app/components/Selectors/UserSelect/types.tsindex f1d0fe920e..0a685c822d 100644--- a/apps/carbon/app/components/Selectors/UserSelect/types.ts+++ b/apps/carbon/app/components/Selectors/UserSelect/types.ts@@ -20,6 +20,7 @@ export type ComboBoxRefs = {};export interface UserSelectProps {+ alwaysSelected?: string[];accessibilityLabel?: string;checkedSelections?: boolean;disabled?: boolean;diff --git a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.tsindex c85888713b..35de358f81 100644--- a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts+++ b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts@@ -17,6 +17,7 @@ import type {} from "./types";const defaultProps = {+ alwaysSelected: [],accessibilityLabel: "User selector",checkedSelections: false,disabled: false,diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsxindex 18b83172ed..bb82e902a5 100644--- a/apps/carbon/app/components/Table/Table.tsx+++ b/apps/carbon/app/components/Table/Table.tsx@@ -1,16 +1,18 @@import { ActionMenu, ContextMenu, useColor, useEscape } from "@carbon/react";import { clip } from "@carbon/utils";import type { ThemeTypings } from "@chakra-ui/react";-import { MenuList } from "@chakra-ui/react";-import { VisuallyHidden } from "@chakra-ui/react";-import { VStack } from "@chakra-ui/react";import {Box,Flex,Grid,+ MenuList,Table as ChakraTable,Tbody,Thead,+ Th,+ Tr,+ VisuallyHidden,+ VStack,chakra,} from "@chakra-ui/react";import type {@@ -24,16 +26,12 @@ import {getCoreRowModel,useReactTable,} from "@tanstack/react-table";-import { AnimatePresence } from "framer-motion";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { FaSort, FaSortUp, FaSortDown } from "react-icons/fa";import {TableHeader,IndeterminateCheckbox,Pagination,- Th,- Tr,- spring,usePagination,useSort,Row,@@ -496,7 +494,6 @@ const Table = <T extends object>({: undefined}cursor={sortable ? "pointer" : undefined}- transition={spring}colSpan={header.colSpan}px={4}py={2}@@ -533,69 +530,67 @@ const Table = <T extends object>({))}</Thead><Tbody>- <AnimatePresence>- {rows.map((row) => {- return renderContextMenu ? (- <ContextMenu<HTMLTableRowElement>- key={row.id}- renderMenu={() => (- <MenuList>{renderContextMenu(row.original)}</MenuList>- )}- >- {(ref) => (- <Row- borderColor={borderColor}- backgroundColor={rowBackground}- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isFrozenColumn- isRowSelected={- row.index in rowSelection &&- !!rowSelection[row.index]- }- selectedCell={selectedCell}- // @ts-ignore- row={row}- rowRef={ref}- withColumnOrdering={withColumnOrdering}- onCellClick={onCellClick}- onCellUpdate={onCellEditUpdate}- onRowClick={- rowsAreClickable- ? () => onRowClick(row.original)- : undefined- }- />- )}- </ContextMenu>- ) : (- <Row- key={row.id}- borderColor={borderColor}- backgroundColor={rowBackground}- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isFrozenColumn- isRowSelected={- row.index in rowSelection && !!rowSelection[row.index]- }- selectedCell={selectedCell}- // @ts-ignore- row={row}- withColumnOrdering={withColumnOrdering}- onCellClick={onCellClick}- onCellUpdate={onCellEditUpdate}- onRowClick={- rowsAreClickable- ? () => onRowClick(row.original)- : undefined- }- />- );- })}- </AnimatePresence>+ {rows.map((row) => {+ return renderContextMenu ? (+ <ContextMenu<HTMLTableRowElement>+ key={row.id}+ renderMenu={() => (+ <MenuList>{renderContextMenu(row.original)}</MenuList>+ )}+ >+ {(ref) => (+ <Row+ borderColor={borderColor}+ backgroundColor={rowBackground}+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isFrozenColumn+ isRowSelected={+ row.index in rowSelection &&+ !!rowSelection[row.index]+ }+ selectedCell={selectedCell}+ // @ts-ignore+ row={row}+ rowRef={ref}+ withColumnOrdering={withColumnOrdering}+ onCellClick={onCellClick}+ onCellUpdate={onCellEditUpdate}+ onRowClick={+ rowsAreClickable+ ? () => onRowClick(row.original)+ : undefined+ }+ />+ )}+ </ContextMenu>+ ) : (+ <Row+ key={row.id}+ borderColor={borderColor}+ backgroundColor={rowBackground}+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isFrozenColumn+ isRowSelected={+ row.index in rowSelection && !!rowSelection[row.index]+ }+ selectedCell={selectedCell}+ // @ts-ignore+ row={row}+ withColumnOrdering={withColumnOrdering}+ onCellClick={onCellClick}+ onCellUpdate={onCellEditUpdate}+ onRowClick={+ rowsAreClickable+ ? () => onRowClick(row.original)+ : undefined+ }+ />+ );+ })}</Tbody></ChakraTable>) : null}@@ -631,8 +626,6 @@ const Table = <T extends object>({borderRightStyle="solid"borderRightWidth={editMode ? 1 : undefined}cursor={sortable ? "pointer" : undefined}- layout- transition={spring}px={4}py={3}w={header.getSize()}@@ -672,83 +665,80 @@ const Table = <T extends object>({))}</Thead><Tbody>- <AnimatePresence>- {rows.map((row) => {- return renderContextMenu ? (- <ContextMenu<HTMLTableRowElement>- key={row.id}- renderMenu={() => (- <MenuList>{renderContextMenu(row.original)}</MenuList>- )}- >- {(ref) => (- <Row- borderColor={borderColor}- backgroundColor={rowBackground}- // @ts-ignore- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection &&- !!rowSelection[row.index]- }- pinnedColumns={- columnPinning?.left- ? columnPinning.left?.length -- (withSelectableRows ? 1 : 0)- : 0- }- selectedCell={selectedCell}- // @ts-ignore- row={row}- rowIsClickable={rowsAreClickable}- rowRef={ref}- withColumnOrdering={withColumnOrdering}- onCellClick={onCellClick}- onCellUpdate={onCellEditUpdate}- onRowClick={- rowsAreClickable- ? () => onRowClick(row.original)- : undefined- }- />- )}- </ContextMenu>- ) : (- <Row- key={row.id}- borderColor={borderColor}- backgroundColor={rowBackground}- // @ts-ignore- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection && !!rowSelection[row.index]- }- pinnedColumns={- columnPinning?.left- ? columnPinning.left?.length -- (withSelectableRows ? 1 : 0)- : 0- }- selectedCell={selectedCell}- // @ts-ignore- row={row}- rowIsClickable={rowsAreClickable}- withColumnOrdering={withColumnOrdering}- onCellClick={onCellClick}- onCellUpdate={onCellEditUpdate}- onRowClick={- rowsAreClickable- ? () => onRowClick(row.original)- : undefined- }- />- );- })}- </AnimatePresence>+ {rows.map((row) => {+ return renderContextMenu ? (+ <ContextMenu<HTMLTableRowElement>+ key={row.id}+ renderMenu={() => (+ <MenuList>{renderContextMenu(row.original)}</MenuList>+ )}+ >+ {(ref) => (+ <Row+ borderColor={borderColor}+ backgroundColor={rowBackground}+ // @ts-ignore+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={+ row.index in rowSelection && !!rowSelection[row.index]+ }+ pinnedColumns={+ columnPinning?.left+ ? columnPinning.left?.length -+ (withSelectableRows ? 1 : 0)+ : 0+ }+ selectedCell={selectedCell}+ // @ts-ignore+ row={row}+ rowIsClickable={rowsAreClickable}+ rowRef={ref}+ withColumnOrdering={withColumnOrdering}+ onCellClick={onCellClick}+ onCellUpdate={onCellEditUpdate}+ onRowClick={+ rowsAreClickable+ ? () => onRowClick(row.original)+ : undefined+ }+ />+ )}+ </ContextMenu>+ ) : (+ <Row+ key={row.id}+ borderColor={borderColor}+ backgroundColor={rowBackground}+ // @ts-ignore+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={+ row.index in rowSelection && !!rowSelection[row.index]+ }+ pinnedColumns={+ columnPinning?.left+ ? columnPinning.left?.length -+ (withSelectableRows ? 1 : 0)+ : 0+ }+ selectedCell={selectedCell}+ // @ts-ignore+ row={row}+ rowIsClickable={rowsAreClickable}+ withColumnOrdering={withColumnOrdering}+ onCellClick={onCellClick}+ onCellUpdate={onCellEditUpdate}+ onRowClick={+ rowsAreClickable+ ? () => onRowClick(row.original)+ : undefined+ }+ />+ );+ })}</Tbody></ChakraTable></Grid>diff --git a/apps/carbon/app/components/Table/components/Cell/Cell.tsx b/apps/carbon/app/components/Table/components/Cell/Cell.tsxindex df49abc62c..fee03eb766 100644--- a/apps/carbon/app/components/Table/components/Cell/Cell.tsx+++ b/apps/carbon/app/components/Table/components/Cell/Cell.tsx@@ -5,12 +5,12 @@ import {PopoverAnchor,PopoverBody,PopoverContent,+ Td,} from "@chakra-ui/react";import type { Cell as CellType } from "@tanstack/react-table";import { flexRender } from "@tanstack/react-table";import { useMovingCellRef } from "../../hooks/useMovingCellRef";import { memo } from "react";-import { Td, spring } from "../Animations";import type { EditableTableCellComponent } from "../../types";import { getAccessorKey } from "../../utils";@@ -64,8 +64,6 @@ const Cell = <T extends object>({ref={ref}data-row={cell.row.index}data-column={columnIndex}- layout- transition={spring}tabIndex={tabIndex}bgColor={isEditMode && !hasEditableTableCellComponent ? "gray.50" : undefineddiff --git a/apps/carbon/app/components/Table/components/Row/Row.tsx b/apps/carbon/app/components/Table/components/Row/Row.tsxindex 205d533e79..81ca5cc8a8 100644--- a/apps/carbon/app/components/Table/components/Row/Row.tsx+++ b/apps/carbon/app/components/Table/components/Row/Row.tsx@@ -1,10 +1,10 @@+import { useColor } from "@carbon/react";+import { Tr } from "@chakra-ui/react";import type { Row as RowType } from "@tanstack/react-table";import type { MutableRefObject } from "react";import { memo } from "react";-import { Tr, spring } from "../Animations";import Cell from "../Cell";import type { EditableTableCellComponent, Position } from "../../types";-import { useColor } from "@carbon/react";type RowProps<T> = {borderColor: string;@@ -48,9 +48,6 @@ const Row = <T extends object>({<Trkey={row.id}bg={isFrozenColumn ? frozenBackgroundColor : undefined}- exit={{ opacity: 0 }}- layout- transition={spring}onClick={onRowClick}ref={rowRef}_hover={{diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsxindex 7d99ef5fa9..3b7dadd6c9 100644--- a/apps/carbon/app/hooks/useUser.tsx+++ b/apps/carbon/app/hooks/useUser.tsx@@ -8,10 +8,22 @@ type User = {avatarUrl: string | null;};-export function useUser() {- const data = useRouteData<{ user: unknown }>("/x");- if (data?.user && isUser(data.user)) {- return data.user;+type Groups = string[];++type UserWithGroups = User & { groups: Groups };++export function useUser(): UserWithGroups {+ const data = useRouteData<{ user: unknown; groups: unknown }>("/x");+ if (+ data?.user &&+ isUser(data.user) &&+ data?.groups &&+ isGroups(data.groups)+ ) {+ return {+ ...data.user,+ groups: data.groups,+ };}// TODO: force logout -- the likely cause is development changesthrow new Error(@@ -19,6 +31,10 @@ export function useUser() {);}+function isGroups(value: any): value is Groups {+ return Array.isArray(value) && value.every((v) => typeof v === "string");+}+function isUser(value: any): value is User {return (typeof value.id === "string" &&diff --git a/apps/carbon/app/modules/account/interfaces/Profile/ProfilePhotoForm/ProfilePhotoForm.tsx b/apps/carbon/app/modules/account/interfaces/Profile/ProfilePhotoForm/ProfilePhotoForm.tsxindex 25827c1e47..cbb1b3ecea 100644--- a/apps/carbon/app/modules/account/interfaces/Profile/ProfilePhotoForm/ProfilePhotoForm.tsx+++ b/apps/carbon/app/modules/account/interfaces/Profile/ProfilePhotoForm/ProfilePhotoForm.tsx@@ -1,8 +1,7 @@-import { useNotification } from "@carbon/react";-import { Button, Input, InputGroup, VStack } from "@chakra-ui/react";+import { File, useNotification } from "@carbon/react";+import { Button, VStack } from "@chakra-ui/react";import { useSubmit } from "@remix-run/react";import type { ChangeEvent } from "react";-import { useRef } from "react";import { Avatar } from "~/components";import { useSupabase } from "~/lib/supabase";import type { Account } from "~/modules/account";@@ -13,7 +12,6 @@ type ProfilePhotoFormProps = {const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {const { supabase } = useSupabase();- const fileInputRef = useRef<HTMLInputElement>(null);const notification = useNotification();const submit = useSubmit();@@ -68,25 +66,10 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {return (<VStack w="full" spacing={2} px={8}><Avatar size="2xl" path={user?.avatarUrl} title={user?.fullName ?? ""} />- <InputGroup w="auto">- <Input- ref={fileInputRef}- id="avatar-upload"- type="file"- hidden- accept="image/*"- onChange={uploadImage}- />- <Button- variant="solid"- colorScheme="brand"- onClick={() => {- if (fileInputRef.current) fileInputRef.current.click();- }}- >- {user.avatarUrl ? "Change" : "Upload"}- </Button>- </InputGroup>+ <File accept="image/*" onChange={uploadImage}>+ {user.avatarUrl ? "Change" : "Upload"}+ </File>+{user.avatarUrl && (<Button variant="outline" onClick={deleteImage}>Removediff --git a/apps/carbon/app/modules/documents/index.ts b/apps/carbon/app/modules/documents/index.tsnew file mode 100644index 0000000000..684aed031a--- /dev/null+++ b/apps/carbon/app/modules/documents/index.ts@@ -0,0 +1,3 @@+export * from "./services";+export * from "./interfaces";+export * from "./types";diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsxnew file mode 100644index 0000000000..36b7e4ac30--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx@@ -0,0 +1,69 @@+import { File, useNotification } from "@carbon/react";+import { useSubmit } from "@remix-run/react";+import type { ChangeEvent } from "react";+import { IoMdAdd } from "react-icons/io";+import { useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";++const DocumentCreateForm = () => {+ const notification = useNotification();+ const submit = useSubmit();+ const { supabase } = useSupabase();+ const user = useUser();++ const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {+ if (e.target.files && supabase) {+ const file = e.target.files[0];+ const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);+ const fileName = `${user.id}/${Math.random()+ .toString(32)+ .slice(2)}.${fileExtension}`;++ const fileUpload = await supabase.storage+ .from("private")+ .upload(fileName, file, {+ cacheControl: `${12 * 60 * 60}`,+ upsert: true,+ });++ if (fileUpload.error) {+ notification.copyableError(fileUpload.error, "Failed to upload file");+ }++ if (fileUpload.data?.path) {+ submitFileData({+ path: fileUpload.data.path,+ name: file.name,+ size: file.size,+ });+ }+ }+ };++ const submitFileData = ({+ path,+ name,+ size,+ }: {+ path: string;+ name: string;+ size: number;+ }) => {+ const formData = new FormData();+ formData.append("path", path);+ formData.append("name", name);+ formData.append("size", Math.round(size / 1024).toString());+ submit(formData, {+ method: "post",+ action: "/x/documents/new",+ });+ };++ return (+ <File leftIcon={<IoMdAdd />} onChange={uploadFile}>+ New Document+ </File>+ );+};++export default DocumentCreateForm;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/index.tsnew file mode 100644index 0000000000..5303f4839e--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/index.ts@@ -0,0 +1,3 @@+import DocumentCreateForm from "./DocumentCreateForm";++export default DocumentCreateForm;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/DocumentForm.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/DocumentForm.tsxnew file mode 100644index 0000000000..205856847f--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/DocumentForm.tsx@@ -0,0 +1,86 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import { ValidatedForm } from "remix-validated-form";+import { Hidden, Input, Submit, TextArea, Users } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { documentValidator } from "~/modules/documents";+import type { TypeOfValidator } from "~/types/validators";++type DocumentFormProps = {+ initialValues: TypeOfValidator<typeof documentValidator>;+ ownerId: string;+};++const DocumentForm = ({ initialValues, ownerId }: DocumentFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const isDisabled = !permissions.can("update", "documents");++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={documentValidator}+ method="post"+ action={`/x/documents/search/${initialValues.id}`}+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>{`Edit ${initialValues.name}.${initialValues.type}`}</DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <Hidden name="type" />+ <Hidden name="size" />+ <VStack spacing={4} alignItems="start">+ <Input+ name="name"+ label="Name"+ suffix={`.${initialValues.type}`}+ />+ <TextArea name="description" label="Description" />+ <Users+ alwaysSelected={[ownerId]}+ name="readGroups"+ label="View Permissions"+ />+ <Users+ alwaysSelected={[ownerId]}+ name="writeGroups"+ label="Edit Permissions"+ />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack spacing={2}>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button+ size="md"+ colorScheme="gray"+ variant="solid"+ onClick={onClose}+ >+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default DocumentForm;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/index.tsnew file mode 100644index 0000000000..768fb2e84e--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentForm/index.ts@@ -0,0 +1,3 @@+import DocumentForm from "./DocumentForm";++export default DocumentForm;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsxnew file mode 100644index 0000000000..027914a591--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentIcon/DocumentIcon.tsx@@ -0,0 +1,70 @@+import { Icon } from "@chakra-ui/react";+import {+ BsFileEarmarkFill,+ BsFileExcelFill,+ BsFileImageFill,+ BsFilePdfFill,+ BsFilePptFill,+ BsFileTextFill,+ BsFileWordFill,+ BsFileZipFill,+ BsFileEarmarkPlayFill,+} from "react-icons/bs";++type DocumentIconProps = {+ fileName: string;+};++const iconSize = {+ h: 6,+ w: 6,+};++const DocumentIcon = ({ fileName }: DocumentIconProps) => {+ const fileExtension = [...fileName.split(".")].pop();++ switch (fileExtension) {+ case "doc":+ case "docx":+ return <Icon color="blue.500" {...iconSize} as={BsFileWordFill} />;+ case "xls":+ case "xlsx":+ return <Icon color="green.700" {...iconSize} as={BsFileExcelFill} />;+ case "ppt":+ case "pptx":+ return <Icon color="orange.400" {...iconSize} as={BsFilePptFill} />;+ case "pdf":+ return <Icon color="red.600" {...iconSize} as={BsFilePdfFill} />;+ case "zip":+ case "rar":+ return <Icon {...iconSize} as={BsFileZipFill} />;+ case "txt":+ return <Icon {...iconSize} as={BsFileTextFill} />;+ case "png":+ case "jpg":+ case "jpeg":+ case "gif":+ case "svg":+ return <Icon color="yellow.400" {...iconSize} as={BsFileImageFill} />;+ case "mp4":+ case "avi":+ case "mov":+ case "wmv":+ case "flv":+ case "mkv":+ return (+ <Icon color="purple.500" {...iconSize} as={BsFileEarmarkPlayFill} />+ );+ case "mp3":+ case "wav":+ case "wma":+ case "aac":+ case "ogg":+ case "m4a":+ return <Icon color="cyan.400" {...iconSize} as={BsFileEarmarkPlayFill} />;+ default:+ return <Icon {...iconSize} as={BsFileEarmarkFill} />;+ }+};++export default DocumentIcon;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsxnew file mode 100644index 0000000000..0ec0a1d843--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx@@ -0,0 +1,444 @@+import { CreatableSelect } from "@carbon/react";+import { convertKbToString } from "@carbon/utils";+import {+ Box,+ HStack,+ Icon,+ Image,+ Link,+ MenuItem,+ Modal,+ ModalBody,+ ModalCloseButton,+ ModalContent,+ ModalHeader,+ ModalOverlay,+ Tag,+ TagCloseButton,+ TagLabel,+ Text,+ useDisclosure,+} from "@chakra-ui/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useEffect, useMemo, useState } from "react";+import {+ BsEyeFill,+ BsPencilSquare,+ BsStar,+ BsStarFill,+ BsTag,+} from "react-icons/bs";+import { IoMdAdd, IoMdTrash } from "react-icons/io";+import { VscOpenPreview } from "react-icons/vsc";+import { Avatar, Table } from "~/components";+import { Confirm, ConfirmDelete } from "~/components/Modals";+import { useUrlParams } from "~/hooks";+import type { Document, DocumentLabel } from "~/modules/documents";+import DocumentIcon from "../DocumentIcon/DocumentIcon";+import { useDocument } from "../useDocument";++type DocumentsTableProps = {+ data: Document[];+ count: number;+ labels: DocumentLabel[];+};++const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {+ 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,+ label,+ makePreview,+ setLabel,+ } = useDocument();++ const documentLabelModal = useDisclosure();+ const deleteDocumentModal = useDisclosure();++ const [previewImage, setPreviewImage] = useState<string | null>(null);+ const [selectedDocument, setSelectedDocument] = useState<Document | null>(+ null+ );++ const labelOptions =+ labels.map(({ label }) => ({+ value: label as string,+ label: label as string,+ })) ?? [];++ 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 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 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>+ <Box+ color={row.original.favorite ? "yellow.400" : "gray.300"}+ cursor="pointer"+ >+ <Icon+ h={4}+ w={4}+ as={row.original.favorite ? BsStarFill : BsStar}+ onClick={() => onFavorite(row.original)}+ />+ </Box>+ <DocumentIcon fileName={row.original.name} />+ <Link onClick={() => download(row.original)}>+ {row.original.name}+ </Link>+ </HStack>+ ),+ },+ {+ id: "labels",+ header: "Labels",+ cell: ({ row }) => (+ <HStack spacing={1}>+ {row.original.labels.map((label) => (+ <Tag key={label} cursor="pointer" onClick={() => setLabel(label)}>+ <TagLabel>{label}</TagLabel>+ <TagCloseButton+ onClick={(e) => onDeleteLabel(e, row.original, label)}+ />+ </Tag>+ ))}++ <Tag+ cursor="pointer"+ onClick={() => {+ setSelectedDocument(row.original);+ documentLabelModal.onOpen();+ }}+ >+ <TagLabel>+ <IoMdAdd />+ </TagLabel>+ </Tag>+ </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}+ />+ <Text>{row.original.createdByFullName}</Text>+ </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} />+ <Text>{row.original.updatedByFullName}</Text>+ </HStack>+ ) : null;+ },+ },+ {+ accessorKey: "updatedAt",+ header: "Updated At",+ cell: (item) => item.getValue(),+ },+ ];+ }, [documentLabelModal, download, onDeleteLabel, onFavorite, setLabel]);++ const actions = useMemo(() => {+ return [+ {+ label: "Add to Favorites",+ icon: <BsStar />,+ 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,+ description: false,+ };++ const renderContextMenu = useMemo(() => {+ // eslint-disable-next-line react/display-name+ return (row: Document) => (+ <>+ <MenuItem+ icon={<VscOpenPreview />}+ isDisabled={!row.type || !isImage(row.type)}+ onClick={async () => setPreviewImage(await makePreview(row))}+ >+ Preview+ </MenuItem>++ <MenuItem+ icon={<BsPencilSquare />}+ isDisabled={canUpdate(row)}+ onClick={() => edit(row)}+ >+ Edit+ </MenuItem>+ <MenuItem icon={<VscOpenPreview />} onClick={() => download(row)}>+ Download+ </MenuItem>+ <MenuItem+ icon={<BsStar />}+ onClick={() => {+ onFavorite(row);+ }}+ >+ Favorite+ </MenuItem>+ <MenuItem+ icon={<IoMdTrash />}+ isDisabled={canDelete(row)}+ onClick={() => {+ setSelectedDocument(row);+ deleteDocumentModal.onOpen();+ }}+ >+ {filter !== "trash" ? "Move to Trash" : "Restore from Trash"}+ </MenuItem>+ </>+ );+ }, [+ canDelete,+ canUpdate,+ deleteDocumentModal,+ download,+ edit,+ filter,+ isImage,+ makePreview,+ onFavorite,+ ]);++ return (+ <>+ <Table<Document>+ actions={actions}+ count={count}+ columns={columns}+ data={rows}+ defaultColumnVisibility={defaultColumnVisibility}+ withColumnOrdering+ withFilters+ withPagination+ withSimpleSorting+ withSelectableRows+ renderContextMenu={renderContextMenu}+ />++ {previewImage && (+ <Modal isOpen onClose={() => setPreviewImage(null)} size="full">+ <ModalOverlay />+ <ModalContent>+ <ModalHeader />+ <ModalCloseButton />+ <ModalBody>+ <Image src={previewImage ?? ""} />+ </ModalBody>+ </ModalContent>+ </Modal>+ )}++ {selectedDocument && (+ <Modal+ isOpen={documentLabelModal.isOpen}+ onClose={() => {+ setSelectedDocument(null);+ documentLabelModal.onClose();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>{selectedDocument.name}</ModalHeader>+ <ModalCloseButton />+ <ModalBody pb={6}>+ <CreatableSelect+ defaultValue={+ selectedDocument.labels.map((label) => ({+ value: label,+ label: label,+ })) ?? []+ }+ isClearable+ isMulti+ options={labelOptions}+ onChange={(newValues) =>+ onLabel(+ selectedDocument,+ newValues.map((v) => v.value)+ )+ }+ />+ </ModalBody>+ </ModalContent>+ </Modal>+ )}++ {selectedDocument &&+ (filter !== "trash" ? (+ <ConfirmDelete+ action={`/x/documents/${selectedDocument?.id}/delete`}+ 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={`/x/documents/${selectedDocument?.id}/restore`}+ 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);+ }}+ />+ ))}+ </>+ );+});++DocumentsTable.displayName = "DocumentsTable";++export default DocumentsTable;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/index.tsnew file mode 100644index 0000000000..91d47f7721--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/index.ts@@ -0,0 +1,3 @@+import DocumentsTable from "./DocumentsTable";++export default DocumentsTable;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsxnew file mode 100644index 0000000000..fde41c21dd--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx@@ -0,0 +1,114 @@+import { Select, useColor } from "@carbon/react";+import { HStack } from "@chakra-ui/react";+import { DebouncedInput } from "~/components/Search";+import { usePermissions, useUrlParams } from "~/hooks";+import type { DocumentLabel } from "~/modules/documents/types";+import { mapRowsToOptions } from "~/utils/form";+import DocumentCreateForm from "../DocumentCreateForm";++type DocumentTableFiltersProps = {+ labels: DocumentLabel[];+};++const DocumentsTableFilters = ({ labels }: DocumentTableFiltersProps) => {+ const [params, setParams] = useUrlParams();+ const permissions = usePermissions();++ const borderColor = useColor("gray.200");+ const documentTypeOptions = [+ {+ label: "All",+ value: "all",+ },+ {+ label: "Document",+ value: "document",+ },+ {+ label: "Presentation",+ value: "presentation",+ },+ {+ label: "Spreadsheet",+ value: "spreadsheet",+ },+ {+ label: "Image",+ value: "image",+ },+ {+ label: "Video",+ value: "video",+ },+ {+ label: "Audio",+ value: "audio",+ },+ ];++ const labelOptions = mapRowsToOptions({+ data: labels,+ value: "label",+ label: "label",+ });++ return (+ <HStack+ px={4}+ py={3}+ justifyContent="space-between"+ borderBottomColor={borderColor}+ borderBottomStyle="solid"+ borderBottomWidth={1}+ w="full"+ >+ <HStack spacing={2}>+ <DebouncedInput+ param="search"+ size="sm"+ minW={180}+ placeholder="Search"+ />+ <Select+ // @ts-ignore+ size="sm"+ value={documentTypeOptions.filter(+ (type) => type.value === params.get("type")+ )}+ isClearable+ options={documentTypeOptions}+ onChange={(selected) => {+ setParams({ type: selected?.value });+ }}+ aria-label="Document Type"+ minW={180}+ placeholder="Document Type"+ />+ {labels.length > 0 && (+ <Select+ // @ts-ignore+ size="sm"+ value={labelOptions.filter(+ (label) =>+ params.getAll("labels").includes(label.value as string) ||+ label.value === params.get("label")+ )}+ isClearable+ options={labelOptions}+ onChange={(selected) => {+ setParams({ label: selected?.label });+ }}+ aria-label="Label"+ minW={180}+ placeholder="Label"+ />+ )}+ </HStack>+ <HStack spacing={2}>+ {permissions.can("create", "documents") && <DocumentCreateForm />}+ </HStack>+ </HStack>+ );+};++export default DocumentsTableFilters;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/index.tsnew file mode 100644index 0000000000..b19b42de83--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/index.ts@@ -0,0 +1,3 @@+import DocumentsTableFilters from "./DocumentsTableFilters";++export default DocumentsTableFilters;diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/index.tsnew file mode 100644index 0000000000..171f509e62--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/index.ts@@ -0,0 +1,5 @@+import DocumentForm from "./DocumentForm";+import DocumentsTable from "./DocumentsTable";+import DocumentsTableFilters from "./DocumentsTableFilters";++export { DocumentForm, DocumentsTable, DocumentsTableFilters };diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts b/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.tsnew file mode 100644index 0000000000..befa47703b--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/Documents/useDocument.ts@@ -0,0 +1,184 @@+import { useNotification } from "@carbon/react";+import { useNavigate } from "@remix-run/react";+import { useCallback } from "react";+import { usePermissions, useUrlParams, useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import type { Document, DocumentTransactionType } from "~/modules/documents";++export const useDocument = () => {+ const navigate = useNavigate();+ const notification = useNotification();+ const permissions = usePermissions();+ const { supabase } = useSupabase();+ const [params, setParams] = useUrlParams();+ const user = useUser();++ const canDelete = useCallback(+ (document: Document) => {+ return (+ !permissions.can("delete", "documents") ||+ !document.writeGroups?.some((group) => user?.groups.includes(group))+ );+ },+ [permissions, user]+ );++ const canUpdate = useCallback(+ (document: Document) => {+ return (+ !permissions.can("update", "documents") ||+ !document.writeGroups?.some((group) => user?.groups.includes(group))+ );+ },+ [permissions, user]+ );++ const insertTransaction = useCallback(+ (document: Document, type: DocumentTransactionType) => {+ if (user?.id === undefined) throw new Error("User is undefined");+ return supabase?.from("documentTransaction").insert({+ documentId: document.id,+ type,+ userId: user.id,+ });+ },+ [supabase, user?.id]+ );++ const deleteLabel = useCallback(+ async (document: Document, label: string) => {+ return supabase+ ?.from("documentLabel")+ .delete()+ .eq("documentId", document.id)+ .eq("userId", user?.id)+ .eq("label", label);+ },+ [supabase, user?.id]+ );++ const download = useCallback(+ async (doc: Document) => {+ const result = await supabase?.storage.from("private").download(doc.path);++ if (!result || result.error) {+ notification.error(result?.error?.message || "Error downloading file");+ return;+ }++ const a = document.createElement("a");+ document.body.appendChild(a);+ const url = window.URL.createObjectURL(result.data);+ a.href = url;+ a.download = doc.name;+ a.click();++ setTimeout(() => {+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);+ }, 0);++ await insertTransaction(doc, "Download");+ },+ [supabase, notification, insertTransaction]+ );++ const edit = useCallback(+ (document: Document) =>+ navigate(`/x/documents/search/${document.id}?${params}`),+ [navigate, params]+ );++ const favorite = useCallback(+ async (document: Document) => {+ if (document.favorite) {+ await supabase+ ?.from("documentFavorite")+ .delete()+ .eq("documentId", document.id)+ .eq("userId", user?.id);+ return insertTransaction(document, "Unfavorite");+ } else {+ await supabase+ ?.from("documentFavorite")+ .insert({ documentId: document.id, userId: user?.id });+ return insertTransaction(document, "Favorite");+ }+ },+ [insertTransaction, supabase, user?.id]+ );++ const isImage = useCallback((fileType: string) => {+ return ["png", "jpg", "jpeg", "gif", "svg"].includes(fileType);+ }, []);++ const label = useCallback(+ async (document: Document, labels: string[]) => {+ if (user?.id === undefined) throw new Error("User is undefined");+ await supabase+ ?.from("documentLabel")+ .delete()+ .eq("documentId", document.id)+ .eq("userId", user.id)+ .then(() => {+ return supabase?.from("documentLabel").insert(+ labels.map((label) => ({+ documentId: document.id,+ label,+ userId: user.id,+ }))+ );+ });++ return insertTransaction(document, "Label");+ },+ [insertTransaction, supabase, user.id]+ );++ const makePreview = useCallback(+ async (doc: Document) => {+ const result = await supabase?.storage.from("private").download(doc.path);++ if (!result || result.error) {+ notification.error(result?.error?.message || "Error previewing file");+ return null;+ }++ return window.URL.createObjectURL(result.data);+ },+ [notification, supabase]+ );++ const removeLabel = useCallback(+ (document: Document, label: string) => {+ return supabase+ ?.from("documentLabel")+ .delete()+ .eq("documentId", document.id)+ .eq("userId", user?.id)+ .eq("label", label);+ },+ [supabase, user?.id]+ );++ const setLabel = useCallback(+ (label: string) => {+ setParams({ label });+ },+ [setParams]+ );++ return {+ canDelete,+ canUpdate,+ download,+ deleteLabel,+ edit,+ favorite,+ isImage,+ label,+ makePreview,+ removeLabel,+ setLabel,+ };+};diff --git a/apps/carbon/app/modules/documents/interfaces/index.ts b/apps/carbon/app/modules/documents/interfaces/index.tsnew file mode 100644index 0000000000..2adc369414--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/index.ts@@ -0,0 +1,4 @@+import useDocumentsSidebar from "./useDocumentsSidebar";++export { useDocumentsSidebar };+export * from "./Documents";diff --git a/apps/carbon/app/modules/documents/interfaces/useDocumentsSidebar.tsx b/apps/carbon/app/modules/documents/interfaces/useDocumentsSidebar.tsxnew file mode 100644index 0000000000..6366b71f1a--- /dev/null+++ b/apps/carbon/app/modules/documents/interfaces/useDocumentsSidebar.tsx@@ -0,0 +1,39 @@+import { BsClock, BsFolder, BsFolderPlus, BsStar } from "react-icons/bs";+import { IoMdTrash } from "react-icons/io";+import type { Route } from "~/types";++const documentsRoutes: Route[] = [+ {+ name: "All Documents",+ to: "/x/documents/search",+ icon: <BsFolder />,+ },+ {+ name: "My Documents",+ to: "/x/documents/search",+ q: "my",+ icon: <BsFolderPlus />,+ },+ {+ name: "Recent",+ to: "/x/documents/search",+ q: "recent",+ icon: <BsClock />,+ },+ {+ name: "Starred",+ to: "/x/documents/search",+ q: "starred",+ icon: <BsStar />,+ },+ {+ name: "Trash",+ to: "/x/documents/search",+ q: "trash",+ icon: <IoMdTrash />,+ },+];++export default function useDocumentsSidebar() {+ return { links: documentsRoutes };+}diff --git a/apps/carbon/app/modules/documents/services/documents.form.ts b/apps/carbon/app/modules/documents/services/documents.form.tsnew file mode 100644index 0000000000..381f106fd7--- /dev/null+++ b/apps/carbon/app/modules/documents/services/documents.form.ts@@ -0,0 +1,26 @@+import { withZod } from "@remix-validated-form/with-zod";+import { z } from "zod";+import { zfd } from "zod-form-data";++export const documentValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(3).max(50),+ type: z.string().optional(),+ description: z.string().optional(),+ labels: z.array(z.string().min(1).max(50)).optional(),+ readGroups: z+ .array(z.string().min(36, { message: "Invalid selection" }))+ .min(1, { message: "Read permissions are required" }),+ writeGroups: z+ .array(z.string().min(36, { message: "Invalid selection" }))+ .min(1, { message: "Write permissions are required" }),+ })+);++export const documentLabelsValidator = withZod(+ z.object({+ documentId: z.string().min(20),+ labels: z.array(z.string().min(1).max(50)).optional(),+ })+);diff --git a/apps/carbon/app/modules/documents/services/documents.server.ts b/apps/carbon/app/modules/documents/services/documents.server.tsnew file mode 100644index 0000000000..4f1a630407--- /dev/null+++ b/apps/carbon/app/modules/documents/services/documents.server.ts@@ -0,0 +1,241 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { TypeOfValidator } from "~/types/validators";+import type { GenericQueryFilters } from "~/utils/query";+import { setGenericQueryFilters } from "~/utils/query";+import type {+ documentLabelsValidator,+ documentValidator,+} from "./documents.form";++export async function deleteDocument(+ client: SupabaseClient<Database>,+ id: string,+ userId: string+) {+ const deleteDocumentFavorites = await client+ .from("documentFavorite")+ .delete()+ .eq("documentId", id)+ .eq("userId", userId);++ if (deleteDocumentFavorites.error) {+ return deleteDocumentFavorites;+ }++ return client+ .from("document")+ .update({+ active: false,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id);+}++export async function deleteDocumentFavorite(+ client: SupabaseClient<Database>,+ id: string,+ userId: string+) {+ return client+ .from("documentFavorite")+ .delete()+ .eq("documentId", id)+ .eq("userId", userId);+}++export async function deleteDocumentLabel(+ client: SupabaseClient<Database>,+ id: string,+ label: string+) {+ return client+ .from("documentLabel")+ .delete()+ .eq("documentId", id)+ .eq("label", label);+}++export async function getDocument(+ client: SupabaseClient<Database>,+ documentId: string+) {+ return client+ .from("documents_view")+ .select("*")+ .eq("id", documentId)+ .single();+}++export async function getDocuments(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ search: string | null;+ type: string | null;+ label: string | null;+ favorite?: boolean;+ recent?: boolean;+ createdBy?: string;+ active: boolean;+ }+) {+ let query = client+ .from("documents_view")+ .select("*", {+ count: "exact",+ })+ .eq("active", args.active);++ if (args?.search) {+ query = query.or(+ `name.ilike.%${args.search}%,description.ilike.%${args.search}%`+ );+ }++ 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 });+ }++ query = setGenericQueryFilters(query, args);++ return query;+}++export async function getDocumentLabels(+ client: SupabaseClient<Database>,+ userId: string+) {+ return client+ .from("documents_labels_view")+ .select("*")+ .eq("userId", userId)+ .eq("active", true);+}++export async function insertDocumentFavorite(+ client: SupabaseClient<Database>,+ id: string,+ userId: string+) {+ return client.from("documentFavorite").insert({ documentId: id, userId });+}++export async function insertDocumentLabel(+ client: SupabaseClient<Database>,+ id: string,+ label: string,+ userId: string+) {+ return client.from("documentLabel").insert({ documentId: id, label, userId });+}++export async function restoreDocument(+ client: SupabaseClient<Database>,+ id: string,+ userId: string+) {+ return client+ .from("document")+ .update({+ active: true,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id);+}++export async function upsertDocument(+ client: SupabaseClient<Database>,+ document:+ | (Omit<TypeOfValidator<typeof documentValidator>, "id"> & {+ path: string;+ size: number;+ createdBy: string;+ })+ | (TypeOfValidator<typeof documentValidator> & {+ updatedBy: string;+ })+) {+ if ("createdBy" in document) {+ return client.from("document").insert(document).select("id");+ }+ return client+ .from("document")+ .update({+ ...document,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", document.id);+}++export async function updateDocumentLabels(+ client: SupabaseClient<Database>,+ document: TypeOfValidator<typeof documentLabelsValidator> & {+ userId: string;+ }+) {+ if (!document.labels) {+ throw new Error("No labels provided");+ }++ return client+ .from("documentLabel")+ .delete()+ .eq("documentId", document.documentId)+ .eq("userId", document.userId)+ .then(() => {+ return client.from("documentLabel").insert(+ // @ts-ignore+ document.labels.map((label) => ({+ documentId: document.documentId,+ label,+ userId: document.userId,+ }))+ );+ });+}diff --git a/apps/carbon/app/modules/documents/services/index.ts b/apps/carbon/app/modules/documents/services/index.tsnew file mode 100644index 0000000000..47c39e26cf--- /dev/null+++ b/apps/carbon/app/modules/documents/services/index.ts@@ -0,0 +1,2 @@+export * from "./documents.form";+export * from "./documents.server";diff --git a/apps/carbon/app/modules/documents/types.ts b/apps/carbon/app/modules/documents/types.tsnew file mode 100644index 0000000000..d04712aeee--- /dev/null+++ b/apps/carbon/app/modules/documents/types.ts@@ -0,0 +1,21 @@+import type { Database } from "@carbon/database";+import type { getDocumentLabels } from "./services";++export type Document = Omit<+ Database["public"]["Tables"]["document"]["Row"],+ "createdBy" | "updatedBy"+> & {+ favorite: boolean;+ labels: string[];+ createdByAvatar: string;+ createdByFullName: string;+ updatedByAvatar?: string | null;+ updatedByFullName?: string | null;+};++export type DocumentLabel = NonNullable<+ Awaited<ReturnType<typeof getDocumentLabels>>["data"]+>[number];++export type DocumentTransactionType =+ Database["public"]["Enums"]["documentTransactionType"];diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsxindex 32e8a477bd..f4fa00162a 100644--- a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx@@ -72,7 +72,6 @@ const UnitOfMeasuresTable = memo(columns={columns}count={count}renderContextMenu={renderContextMenu}- withInlineEditing/>);}diff --git a/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx b/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsxindex 2a69a053fe..c37f037f0d 100644--- a/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx+++ b/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx@@ -76,32 +76,36 @@ const CreateCustomerModal = () => {setContact(newValue?.contact);}}/>- <FormControl>- <FormLabel>Email</FormLabel>- <Input- isReadOnly- value={contact?.email ?? ""}- variant="filled"- />- </FormControl>- <Grid templateColumns="1fr 1fr" gap={4}>- <FormControl>- <FormLabel>First Name</FormLabel>- <Input- isReadOnly- value={contact?.firstName ?? ""}- variant="filled"- />- </FormControl>- <FormControl>- <FormLabel>Last Name</FormLabel>- <Input- isReadOnly- value={contact?.lastName ?? ""}- variant="filled"- />- </FormControl>- </Grid>+ {contact && (+ <>+ <FormControl>+ <FormLabel>Email</FormLabel>+ <Input+ isReadOnly+ value={contact?.email ?? ""}+ variant="filled"+ />+ </FormControl>+ <Grid templateColumns="1fr 1fr" gap={4}>+ <FormControl>+ <FormLabel>First Name</FormLabel>+ <Input+ isReadOnly+ value={contact?.firstName ?? ""}+ variant="filled"+ />+ </FormControl>+ <FormControl>+ <FormLabel>Last Name</FormLabel>+ <Input+ isReadOnly+ value={contact?.lastName ?? ""}+ variant="filled"+ />+ </FormControl>+ </Grid>+ </>+ )}<HStack spacing={4}><Submit>Create User</Submit>diff --git a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsxindex e0e6d75ce4..e1628dd238 100644--- a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx+++ b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx@@ -239,39 +239,6 @@ const EmployeesTable = memo(});-// const EditableName = ({-// value,-// row,-// accessorKey,-// onUpdate,-// }: EditableTableCellComponentProps<Employee>) => {-// const { supabase } = useSupabase();-// // @ts-ignore-// const userId = row?.user?.id as string;-// if (userId === undefined) {-// throw new Error("Expected user id to be defined");-// }--// const updateName = async (name: string) => {-// const [table, column] = accessorKey.split(".");-// onUpdate(name);-// await supabase-// ?.from(table)-// .update({ [column]: name })-// .eq("id", userId);-// };--// const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {-// if (event.key === "Enter") {-// updateName(event.currentTarget.value);-// }-// };--// return (-// <Input autoFocus defaultValue={value as string} onKeyDown={onKeyDown} />-// );-// };-EmployeesTable.displayName = "EmployeeTable";export default EmployeesTable;diff --git a/apps/carbon/app/modules/users/interfaces/Groups/GroupsForm/GroupsForm.tsx b/apps/carbon/app/modules/users/interfaces/Groups/GroupsForm/GroupsForm.tsxindex 8a4517b4ab..8c38a96432 100644--- a/apps/carbon/app/modules/users/interfaces/Groups/GroupsForm/GroupsForm.tsx+++ b/apps/carbon/app/modules/users/interfaces/Groups/GroupsForm/GroupsForm.tsx@@ -26,7 +26,8 @@ const GroupForm = ({ initialValues }: GroupFormProps) => {const navigate = useNavigate();const onClose = () => navigate(-1);- const isEditing = initialValues.id !== undefined;+ const isEditing = !!initialValues.id;+const isDisabled = isEditing? !permissions.can("update", "users"): !permissions.can("create", "users");@@ -55,6 +56,7 @@ const GroupForm = ({ initialValues }: GroupFormProps) => {name="selections"selectionsMaxHeight={"calc(100vh - 330px)"}label="Group Members"+ verbose/></VStack></DrawerBody>diff --git a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsxindex f6a022ff22..bfc2a8995f 100644--- a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx+++ b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx@@ -76,32 +76,36 @@ const CreateSupplierModal = () => {setContact(newValue?.contact);}}/>- <FormControl>- <FormLabel>Email</FormLabel>- <Input- isReadOnly- value={contact?.email ?? ""}- variant="filled"- />- </FormControl>- <Grid templateColumns="1fr 1fr" gap={4}>- <FormControl>- <FormLabel>First Name</FormLabel>- <Input- isReadOnly- value={contact?.firstName ?? ""}- variant="filled"- />- </FormControl>- <FormControl>- <FormLabel>Last Name</FormLabel>- <Input- isReadOnly- value={contact?.lastName ?? ""}- variant="filled"- />- </FormControl>- </Grid>+ {contact && (+ <>+ <FormControl>+ <FormLabel>Email</FormLabel>+ <Input+ isReadOnly+ value={contact?.email ?? ""}+ variant="filled"+ />+ </FormControl>+ <Grid templateColumns="1fr 1fr" gap={4}>+ <FormControl>+ <FormLabel>First Name</FormLabel>+ <Input+ isReadOnly+ value={contact?.firstName ?? ""}+ variant="filled"+ />+ </FormControl>+ <FormControl>+ <FormLabel>Last Name</FormLabel>+ <Input+ isReadOnly+ value={contact?.lastName ?? ""}+ variant="filled"+ />+ </FormControl>+ </Grid>+ </>+ )}<HStack spacing={4}><Submit>Create User</Submit>diff --git a/apps/carbon/app/modules/users/services/users.server.ts b/apps/carbon/app/modules/users/services/users.server.tsindex c887c6c1af..eeec6949ff 100644--- a/apps/carbon/app/modules/users/services/users.server.ts+++ b/apps/carbon/app/modules/users/services/users.server.ts@@ -554,6 +554,13 @@ export async function getUserClaims(}}+export async function getUserGroups(+ client: SupabaseClient<Database>,+ userId: string+) {+ return client.rpc("groups_for_user", { uid: userId });+}+export async function getUsers(client: SupabaseClient<Database>) {return client.from("user")diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsxindex 7d456e5852..7c431b65e6 100644--- a/apps/carbon/app/routes/x+/_layout.tsx+++ b/apps/carbon/app/routes/x+/_layout.tsx@@ -8,7 +8,7 @@ import NProgress from "nprogress";import { useEffect } from "react";import { IconSidebar, Topbar } from "~/components/Layout";import { getSupabase, SupabaseProvider } from "~/lib/supabase";-import { getUserClaims, getCurrentUser } from "~/modules/users";+import { getUserClaims, getUser, getUserGroups } from "~/modules/users";import {destroyAuthSession,getSessionFlash,@@ -16,22 +16,21 @@ import {} from "~/services/session";export async function loader({ request }: LoaderArgs) {- const { accessToken, expiresAt, expiresIn } = await requireAuthSession(- request,- { verify: true }- );+ const { accessToken, expiresAt, expiresIn, userId } =+ await requireAuthSession(request, { verify: true });// share a client between requestsconst client = getSupabase(accessToken);// parallelize the requests- const [sessionFlash, claims, user] = await Promise.all([+ const [sessionFlash, user, claims, groups] = await Promise.all([getSessionFlash(request),+ getUser(client, userId),getUserClaims(request, client),- getCurrentUser(request, client),+ getUserGroups(client, userId),]);- if (!claims || !user) {+ if (!claims || user.error || !user.data || !groups.data) {await destroyAuthSession(request);}@@ -43,7 +42,8 @@ export async function loader({ request }: LoaderArgs) {expiresAt,},- user,+ user: user.data,+ groups: groups.data,permissions: claims?.permissions,role: claims?.role,result: sessionFlash?.result,diff --git a/apps/carbon/app/routes/x+/account+/profile.tsx b/apps/carbon/app/routes/x+/account+/profile.tsxindex 69616535ab..c72e2dc39c 100644--- a/apps/carbon/app/routes/x+/account+/profile.tsx+++ b/apps/carbon/app/routes/x+/account+/profile.tsx@@ -83,7 +83,7 @@ export async function action({ request }: ActionArgs) {if (formData.get("intent") === "photo") {const path = formData.get("path");- if (path === null || typeof path === "string") {+ if (typeof path === "string") {const avatarUpdate = await updateAvatar(client, userId, path);if (avatarUpdate.error) {return redirect(diff --git a/apps/carbon/app/routes/x+/documents+/$documentId.delete.tsx b/apps/carbon/app/routes/x+/documents+/$documentId.delete.tsxnew file mode 100644index 0000000000..a0f3b71307--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/$documentId.delete.tsx@@ -0,0 +1,31 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { deleteDocument } from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ delete: "documents",+ });++ const { documentId } = params;+ if (!documentId) throw notFound("documentId not found");++ const moveToTrash = await deleteDocument(client, documentId, userId);++ if (moveToTrash.error) {+ return redirect(+ "/x/documents/search",+ await flash(+ request,+ error(moveToTrash.error, "Failed to delete document")+ )+ );+ }++ return redirect("/x/documents/search");+}diff --git a/apps/carbon/app/routes/x+/documents+/$documentId.labels.tsx b/apps/carbon/app/routes/x+/documents+/$documentId.labels.tsxnew file mode 100644index 0000000000..2f18332663--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/$documentId.labels.tsx@@ -0,0 +1,45 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import {+ documentLabelsValidator,+ updateDocumentLabels,+} from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error } from "~/utils/result";++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ view: "documents",+ });+ const validation = await documentLabelsValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { documentId, labels } = validation.data;++ const updateLabels = await updateDocumentLabels(client, {+ documentId,+ labels: labels ?? [],+ userId,+ });++ if (updateLabels.error) {+ return redirect(+ "/x/documents/search",+ await flash(+ request,+ error(updateLabels.error, "Failed to update document labels")+ )+ );+ }++ return redirect("/x/documents/search");+}diff --git a/apps/carbon/app/routes/x+/documents+/$documentId.restore.tsx b/apps/carbon/app/routes/x+/documents+/$documentId.restore.tsxnew file mode 100644index 0000000000..53fa654168--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/$documentId.restore.tsx@@ -0,0 +1,31 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { restoreDocument } from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ delete: "documents",+ });++ const { documentId } = params;+ if (!documentId) throw notFound("documentId not found");++ const removeFromTrash = await restoreDocument(client, documentId, userId);++ if (removeFromTrash.error) {+ return redirect(+ "/x/documents/search",+ await flash(+ request,+ error(removeFromTrash.error, "Failed to restore document")+ )+ );+ }++ return redirect("/x/documents/search?q=trash");+}diff --git a/apps/carbon/app/routes/x+/documents+/_layout.tsx b/apps/carbon/app/routes/x+/documents+/_layout.tsxnew file mode 100644index 0000000000..2dd09fe8af--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/_layout.tsx@@ -0,0 +1,22 @@+import { Grid, VStack } from "@chakra-ui/react";+import type { MetaFunction } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import { ContentSidebar } from "~/components/Layout/Sidebar";+import { useDocumentsSidebar } from "~/modules/documents";++export const meta: MetaFunction = () => ({+ title: "Carbon | Documents",+});++export default function DocumentsRoute() {+ const { links } = useDocumentsSidebar();++ return (+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">+ <ContentSidebar links={links} />+ <VStack w="full" h="full">+ <Outlet />+ </VStack>+ </Grid>+ );+}diff --git a/apps/carbon/app/routes/x+/documents+/index.tsx b/apps/carbon/app/routes/x+/documents+/index.tsxnew file mode 100644index 0000000000..188c439e81--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/index.tsx@@ -0,0 +1,5 @@+import { redirect } from "@remix-run/node";++export async function loader() {+ return redirect("/x/documents/search");+}diff --git a/apps/carbon/app/routes/x+/documents+/new.tsx b/apps/carbon/app/routes/x+/documents+/new.tsxnew file mode 100644index 0000000000..94ed559950--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/new.tsx@@ -0,0 +1,44 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { upsertDocument } from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {});+ const formData = await request.formData();++ const path = formData.get("path");+ const name = formData.get("name");++ if (typeof path !== "string") throw new Error("Invalid path");+ if (typeof name !== "string") throw new Error("Invalid name");++ const size = Number(formData.get("size"));++ const createDocument = await upsertDocument(client, {+ path,+ name,+ size,+ readGroups: [userId],+ writeGroups: [userId],+ createdBy: userId,+ });+ if (createDocument.error) {+ return redirect(+ "/x/documents/search",+ await flash(+ request,+ error(createDocument.error, "Failed to create document")+ )+ );+ }++ return redirect(+ "/x/documents/search",+ await flash(request, success(`Successfully uploaded ${name}`))+ );+}diff --git a/apps/carbon/app/routes/x+/documents+/search.$documentId.tsx b/apps/carbon/app/routes/x+/documents+/search.$documentId.tsxnew file mode 100644index 0000000000..e80edb8e29--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/search.$documentId.tsx@@ -0,0 +1,97 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import {+ DocumentForm,+ documentValidator,+ getDocument,+ upsertDocument,+} from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });++ const { documentId } = params;+ if (!documentId) throw notFound("documentId not found");++ const document = await getDocument(client, documentId);++ if (document.error) {+ return redirect(+ "/x/documents/search",+ await flash(request, error(document.error, "Failed to get document"))+ );+ }++ return json({+ document: document.data,+ });+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "documents",+ });++ const validation = await documentValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const { type, ...document } = validation.data;++ const updateDocument = await upsertDocument(client, {+ ...document,+ name: `${document.name}.${type}`,+ updatedBy: userId,+ });++ if (updateDocument.error) {+ return redirect(+ "/x/documents/search",+ await flash(+ request,+ error(updateDocument.error, "Failed to update document")+ )+ );+ }++ return redirect(+ "/x/documents/search",+ await flash(request, success("Updated document"))+ );+}++export default function EditDocumentRoute() {+ const { document } = useLoaderData<typeof loader>();++ let name = document.name;+ if (name) name = name.split(".").slice(0, -1).join(".");++ const initialValues = {+ id: document.id ?? "",+ name: name ?? "",+ description: document.description ?? "",+ type: document.type ?? "",+ size: document.size ?? 0,+ readGroups: document.readGroups ?? [],+ writeGroups: document.writeGroups ?? [],+ };++ return (+ <DocumentForm+ initialValues={initialValues}+ ownerId={document.createdBy ?? ""}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/documents+/search.tsx b/apps/carbon/app/routes/x+/documents+/search.tsxnew file mode 100644index 0000000000..d15d63d6ab--- /dev/null+++ b/apps/carbon/app/routes/x+/documents+/search.tsx@@ -0,0 +1,79 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import {+ DocumentsTable,+ DocumentsTableFilters,+ getDocumentLabels,+ getDocuments,+} from "~/modules/documents";+import type { Document } from "~/modules/documents";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client, userId } = await requirePermissions(request, {+ view: "documents",+ });++ 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;+ const favorite = filter === "starred" ? true : undefined;+ const recent = filter === "recent" ? true : undefined;+ const active = filter === "trash" ? false : true;++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const [documents, labels] = await Promise.all([+ getDocuments(client, {+ search,+ type,+ label,+ favorite,+ recent,+ createdBy,+ active,+ limit,+ offset,+ sorts,+ filters,+ }),+ getDocumentLabels(client, userId),+ ]);++ if (documents.error) {+ redirect(+ "/x",+ await flash(request, error(documents.error, "Failed to fetch documents"))+ );+ }++ return json({+ count: documents.count ?? 0,+ documents: (documents.data ?? []) as Document[],+ labels: labels.data ?? [],+ });+}++export default function DocumentsAllRoute() {+ const { count, documents, labels } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <DocumentsTableFilters labels={labels} />+ <DocumentsTable data={documents} count={count} labels={labels} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsxindex 4ec0186a53..f37f6938de 100644--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx@@ -38,7 +38,7 @@ export async function action({ request, params }: ActionArgs) {contactId,contact,});- console.log(update);+if (update.error) {return redirect(`/x/purchasing/suppliers/${supplierId}`,diff --git a/apps/carbon/app/routes/x+/resources+/ability.$abilityId.employee.$id.tsx b/apps/carbon/app/routes/x+/resources+/ability.$abilityId.employee.$id.tsxindex 0dc90541b3..138f1353f4 100644--- a/apps/carbon/app/routes/x+/resources+/ability.$abilityId.employee.$id.tsx+++ b/apps/carbon/app/routes/x+/resources+/ability.$abilityId.employee.$id.tsx@@ -49,8 +49,6 @@ export async function action({ params, request }: ActionArgs) {if (!abilityId) throw new Error("abilityId is not found");if (!id) throw new Error("id is not found");- console.log(params);-const { client } = await requirePermissions(request, {create: "resources",});diff --git a/apps/carbon/app/types/index.ts b/apps/carbon/app/types/index.tsindex 7f1b5b50dc..e89598725b 100644--- a/apps/carbon/app/types/index.ts+++ b/apps/carbon/app/types/index.ts@@ -40,6 +40,7 @@ export type Route = {name: string;to: string;icon?: any;+ q?: string;};export type RouteGroup = {diff --git a/apps/carbon/package.json b/apps/carbon/package.jsonindex 4e830cce3a..70fd207c81 100644--- a/apps/carbon/package.json+++ b/apps/carbon/package.json@@ -6,7 +6,7 @@"scripts": {"build": "remix build","dev": "PORT=3000 remix dev",- "clean": "rm -rf .cache && rm -rf node_modules && rm -rf public/build",+ "clean": "rimraf .cache .turbo node_modules dist public/build","lint": "TIMING=1 eslint \"app/**/*.ts*\"","types": "tsc"},diff --git a/package.json b/package.jsonindex 8577156063..0d27d13c2a 100755--- a/package.json+++ b/package.json@@ -8,7 +8,7 @@"scripts": {"build": "turbo run build","build:packages": "turbo run build --filter=./packages/*",- "clean": "turbo run clean && rm -rf node_modules && rm -rf supabase",+ "clean": "turbo run clean && rimraf node_modules","predb:build": "tsx scripts/generate-schema-md.ts","db:build": "run-s db:kill db:start setup","postdb:build": "tsx scripts/generate-db-types.ts",@@ -27,10 +27,10 @@"db:seed": "turbo run db:seed --no-cache","db:migrate:force": "turbo run db:migrate:force --no-cache","deploy": "turbo run deploy",- "dev": "turbo run dev --no-cache --parallel --continue --filter=./apps/* --filter=./packages/*",- "dev:apps": "turbo run dev --no-cache --parallel --continue --filter=./apps/*",- "dev:www": "turbo run dev --no-cache --parallel --continue --filter=./www",- "dev:packages": "turbo run dev --no-cache --parallel --continue --filter=./packages/*",+ "dev": "turbo run dev --filter=./apps/* --filter=./packages/*",+ "dev:apps": "turbo run dev --filter=./apps/*",+ "dev:www": "turbo run dev --filter=./www",+ "dev:packages": "turbo run dev --filter=./packages/*","format": "prettier --write \"**/*.{ts,tsx,md}\"","init": "run-s db:init db:start","lint": "turbo run lint",@@ -43,9 +43,10 @@"lint-staged": "^13.1.2","npm-run-all": "^4.1.5","prettier": "^2.8.0",+ "rimraf": "^5.0.0",+ "supabase": "1.27.1","tsx": "^3.12.1",- "turbo": "^1.8.3",- "supabase": "1.27.1"+ "turbo": "^1.8.3"},"packageManager": "[email protected]","engines": {diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.tsindex f57302f162..9c9cf945c9 100644--- a/packages/carbon-database/src/types.ts+++ b/packages/carbon-database/src/types.ts@@ -590,6 +590,107 @@ export interface Database {createdAt?: string;};};+ document: {+ Row: {+ path: string;+ name: string;+ size: number;+ readGroups: string[] | null;+ writeGroups: string[] | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ description: string | null;+ type: string | null;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ path: string;+ name: string;+ size: number;+ readGroups?: string[] | null;+ writeGroups?: string[] | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ description?: string | null;+ type?: string | null;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ path?: string;+ name?: string;+ size?: number;+ readGroups?: string[] | null;+ writeGroups?: string[] | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ description?: string | null;+ type?: string | null;+ active?: boolean;+ createdAt?: string;+ };+ };+ documentFavorite: {+ Row: {+ documentId: string;+ userId: string;+ };+ Insert: {+ documentId: string;+ userId: string;+ };+ Update: {+ documentId?: string;+ userId?: string;+ };+ };+ documentLabel: {+ Row: {+ documentId: string;+ userId: string;+ label: string;+ };+ Insert: {+ documentId: string;+ userId: string;+ label: string;+ };+ Update: {+ documentId?: string;+ userId?: string;+ label?: string;+ };+ };+ documentTransaction: {+ Row: {+ documentId: string;+ type: Database["public"]["Enums"]["documentTransactionType"];+ userId: string;+ id: string;+ createdAt: string;+ };+ Insert: {+ documentId: string;+ type: Database["public"]["Enums"]["documentTransactionType"];+ userId: string;+ id?: string;+ createdAt?: string;+ };+ Update: {+ documentId?: string;+ type?: Database["public"]["Enums"]["documentTransactionType"];+ userId?: string;+ id?: string;+ createdAt?: string;+ };+ };employee: {Row: {id: string;@@ -1958,6 +2059,36 @@ export interface Database {abilityIds: string[] | null;};};+ documents_labels_view: {+ Row: {+ label: string | null;+ userId: string | null;+ };+ };+ documents_view: {+ Row: {+ id: string | null;+ path: string | null;+ name: string | null;+ description: string | null;+ size: number | null;+ type: string | null;+ active: boolean | null;+ readGroups: string[] | null;+ writeGroups: string[] | null;+ createdBy: string | null;+ createdByAvatar: string | null;+ createdByFullName: string | null;+ createdAt: string | null;+ updatedBy: string | null;+ updatedByAvatar: string | null;+ updatedByFullName: string | null;+ updatedAt: string | null;+ labels: string[] | null;+ favorite: boolean | null;+ lastActivityAt: string | null;+ };+ };group_member: {Row: {id: number | null;@@ -2046,7 +2177,7 @@ export interface Database {};groups_for_user: {Args: { uid: string };- Returns: Json;+ Returns: string[];};groups_query: {Args: { _name: string; _uid: string };@@ -2105,6 +2236,13 @@ export interface Database {};Enums: {consolidatedRate: "Average" | "Current" | "Historical";+ documentTransactionType:+ | "Download"+ | "Edit"+ | "Favorite"+ | "Label"+ | "Unfavorite"+ | "Upload";factor:| "Hours/Piece"| "Hours/100 Pieces"diff --git a/packages/carbon-database/supabase/migrations/20230123004514_buckets.sql b/packages/carbon-database/supabase/migrations/20230123004514_buckets.sqlindex fb99ff265c..5763135e46 100644--- a/packages/carbon-database/supabase/migrations/20230123004514_buckets.sql+++ b/packages/carbon-database/supabase/migrations/20230123004514_buckets.sql@@ -7,26 +7,26 @@ VALUESCREATE POLICY "Anyone can view avatars"ON storage.objects FOR SELECT USING (bucket_id = 'avatars'+ AND (auth.role() = 'authenticated'));CREATE POLICY "Users can delete their own avatars"ON storage.objects FOR DELETE USING (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%'));CREATE POLICY "Users can update their own avatars"ON storage.objects FOR UPDATE USING (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%'));CREATE POLICY "Users can insert their own avatars"ON storage.objects FOR INSERT WITH CHECK (bucket_id = 'avatars'- and (auth.role() = 'authenticated')- and storage.filename(name) LIKE concat(auth.uid()::text, '%')-);-+ AND (auth.role() = 'authenticated')+ AND storage.filename(name) LIKE concat(auth.uid()::text, '%')+);\ No newline at end of filediff --git a/packages/carbon-database/supabase/migrations/20230123004632_groups.sql b/packages/carbon-database/supabase/migrations/20230123004632_groups.sqlindex cb2e1613d8..90ac232014 100644--- a/packages/carbon-database/supabase/migrations/20230123004632_groups.sql+++ b/packages/carbon-database/supabase/migrations/20230123004632_groups.sql@@ -254,10 +254,10 @@ AS $$END;$$;-CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: return setof string+CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = publicAS $$- DECLARE retval jsonb;+ DECLARE retval TEXT[];BEGINWITH RECURSIVE "groupsForUser" AS (SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"@@ -265,7 +265,7 @@ CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: reUNIONSELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"- ) SELECT coalesce(jsonb_agg("groupId"), '[]') INTO retval AS groups FROM "groupsForUser";+ ) SELECT array_agg("groupId") INTO retval AS groups FROM "groupsForUser";RETURN retval;END;$$;diff --git a/packages/carbon-database/supabase/migrations/20230423023136_documents.sql b/packages/carbon-database/supabase/migrations/20230423023136_documents.sqlnew file mode 100644index 0000000000..e051a8e810--- /dev/null+++ b/packages/carbon-database/supabase/migrations/20230423023136_documents.sql@@ -0,0 +1,244 @@+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,+ "readGroups" TEXT[],+ "writeGroups" TEXT[],+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "document_pkey" PRIMARY KEY ("id"),++ CONSTRAINT "document_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE,+ CONSTRAINT "document_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "document_visibility_idx" ON "document" USING GIN ("readGroups", "writeGroups");++ALTER TABLE "document" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users with documents_view can view documents where they are in the readGroups" ON "document"+ FOR SELECT USING (+ coalesce(get_my_claim('documents_view')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "readGroups") = true+ );++CREATE POLICY "Users with documents_create can create documents where they are in the writeGroups" ON "document"+ FOR INSERT WITH CHECK (+ coalesce(get_my_claim('documents_create')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Users with documents_update can update documents where they are in the writeGroups" ON "document"+ FOR UPDATE USING (+ coalesce(get_my_claim('documents_update')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Users with documents_delete can delete documents where they are in the writeGroups" ON "document"+ FOR DELETE USING (+ coalesce(get_my_claim('documents_delete')::boolean, false) = true+ AND (groups_for_user(auth.uid()::text) && "writeGroups") = true+ );++CREATE POLICY "Private buckets view requires ownership or document.readGroups" ON storage.objects+FOR SELECT USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_view')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets insert requires ownership or document.writeGroups" ON storage.objects+FOR INSERT WITH CHECK (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_create')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "writeGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets update requires ownership or document.writeGroups" ON storage.objects+FOR UPDATE USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_update')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE POLICY "Private buckets delete requires ownership or document.writeGroups" ON storage.objects+FOR DELETE USING (+ bucket_id = 'private'+ AND (auth.role() = 'authenticated')+ AND coalesce(get_my_claim('documents_delete')::boolean, false) = true+ AND (+ (storage.foldername(name))[1] = auth.uid()::text+ OR storage.filename(name) IN (+ SELECT "path" FROM public.document WHERE "readGroups" && groups_for_user(auth.uid()::text)+ )+ )+);++CREATE TYPE "documentTransactionType" AS ENUM (+ 'Download',+ 'Edit',+ 'Favorite',+ 'Label',+ 'Unfavorite',+ 'Upload'+);++CREATE TABLE "documentTransaction" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "documentId" TEXT NOT NULL,+ "type" "documentTransactionType" NOT NULL,+ "userId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "documentActivity_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "documentActivity_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentActivity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentActivity_documentId_idx" ON "documentTransaction" ("documentId");+CREATE INDEX "documentActivity_userId_idx" ON "documentTransaction" ("userId");++CREATE TABLE "documentFavorite" (+ "documentId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,++ CONSTRAINT "documentFavorites_pkey" PRIMARY KEY ("documentId", "userId"),+ CONSTRAINT "documentFavorites_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentFavorites_userId_idx" ON "documentFavorite" ("userId");+CREATE INDEX "documentFavorites_documentId_idx" ON "documentFavorite" ("documentId");++ALTER TABLE "documentFavorite" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own favorites" ON "documentFavorite"+ FOR SELECT USING (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can create their own favorites" ON "documentFavorite"+ FOR INSERT WITH CHECK (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can delete their own favorites" ON "documentFavorite"+ FOR DELETE USING (+ auth.uid()::text = "userId"+ );++CREATE TABLE "documentLabel" (+ "documentId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "label" TEXT NOT NULL,++ CONSTRAINT "documentLabels_pkey" PRIMARY KEY ("documentId", "userId", "label"),+ CONSTRAINT "documentLabels_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,+ CONSTRAINT "documentLabels_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE+);++CREATE INDEX "documentLabels_userId_idx" ON "documentLabel" ("userId");+CREATE INDEX "documentLabels_documentId_idx" ON "documentLabel" ("documentId");+CREATE INDEX "documentLabels_label_idx" ON "documentLabel" ("label");++ALTER TABLE "documentLabel" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own labels" ON "documentLabel"+ FOR SELECT USING (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can create their own labels" ON "documentLabel"+ FOR INSERT WITH CHECK (+ auth.uid()::text = "userId"+ );++CREATE POLICY "Users can delete their own labels" ON "documentLabel"+ FOR DELETE USING (+ auth.uid()::text = "userId"+ );++CREATE FUNCTION public.upload_document_transaction()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."documentTransaction" ("documentId", "type", "userId")+ VALUES (new.id, 'Upload', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER upload_document_transaction+ AFTER INSERT on public."document"+ FOR EACH ROW EXECUTE PROCEDURE public.upload_document_transaction();++CREATE FUNCTION public.edit_document_transaction()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."documentTransaction" ("documentId", "type", "userId")+ VALUES (new.id, 'Edit', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER edit_document_transaction+ AFTER UPDATE on public."document"+ FOR EACH ROW EXECUTE PROCEDURE public.edit_document_transaction();++CREATE VIEW "documents_labels_view" AS+ SELECT DISTINCT+ "label",+ "userId"+ FROM "documentLabel";++CREATE VIEW "documents_view" AS+ SELECT+ d.id,+ d.path,+ d.name,+ d.description,+ d.size,+ d.type,+ d.active,+ d."readGroups",+ d."writeGroups",+ d."createdBy",+ 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";diff --git a/packages/carbon-jest/package.json b/packages/carbon-jest/package.jsonindex b7e7537a76..738d63b184 100644--- a/packages/carbon-jest/package.json+++ b/packages/carbon-jest/package.json@@ -3,6 +3,9 @@"version": "0.0.0","private": true,"license": "MIT",+ "scripts": {+ "clean": "rimraf node_modules"+ },"dependencies": {"ts-jest": "^26.5.0"}diff --git a/packages/carbon-logger/package.json b/packages/carbon-logger/package.jsonindex a39e66de7b..8f2e8ee985 100644--- a/packages/carbon-logger/package.json+++ b/packages/carbon-logger/package.json@@ -10,7 +10,7 @@],"scripts": {"build": "tsup src/index.ts --format esm,cjs --dts --external react",- "clean": "rm -rf dist",+ "clean": "rimraf .turbo node_modules dist","dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react","lint": "TIMING=1 eslint \"src/**/*.ts*\"","test": "jest"diff --git a/packages/carbon-react/package.json b/packages/carbon-react/package.jsonindex 73c080ad72..65c8136f61 100644--- a/packages/carbon-react/package.json+++ b/packages/carbon-react/package.json@@ -12,7 +12,7 @@],"scripts": {"build": "tsup src/index.tsx --format esm,cjs --dts --external react",- "clean": "rm -rf dist",+ "clean": "rimraf .turbo node_modules dist","dev": "tsup src/index.tsx --format esm,cjs --watch --dts --external react","lint": "TIMING=1 eslint \"src/**/*.ts*\"","test": "jest"diff --git a/packages/carbon-react/src/Inputs/File/File.tsx b/packages/carbon-react/src/Inputs/File/File.tsxnew file mode 100644index 0000000000..884d3e397d--- /dev/null+++ b/packages/carbon-react/src/Inputs/File/File.tsx@@ -0,0 +1,39 @@+import type { ButtonProps } from "@chakra-ui/react";+import { Button, Input, InputGroup } from "@chakra-ui/react";+import type { ChangeEvent, PropsWithChildren } from "react";+import { useRef } from "react";++type FileProps = PropsWithChildren<+ Omit<ButtonProps, "onChange"> & {+ accept?: string;+ onChange: (e: ChangeEvent<HTMLInputElement>) => Promise<void>;+ }+>;++const File = ({ accept, children, onChange, ...props }: FileProps) => {+ const fileInputRef = useRef<HTMLInputElement>(null);++ return (+ <InputGroup w="auto">+ <Input+ ref={fileInputRef}+ type="file"+ hidden+ accept={accept}+ onChange={onChange}+ />+ <Button+ variant="solid"+ colorScheme="brand"+ {...props}+ onClick={() => {+ if (fileInputRef.current) fileInputRef.current.click();+ }}+ >+ {children}+ </Button>+ </InputGroup>+ );+};++export default File;diff --git a/packages/carbon-react/src/Inputs/File/index.ts b/packages/carbon-react/src/Inputs/File/index.tsnew file mode 100644index 0000000000..6c405123f0--- /dev/null+++ b/packages/carbon-react/src/Inputs/File/index.ts@@ -0,0 +1,3 @@+import File from "./File";++export default File;diff --git a/packages/carbon-react/src/Inputs/index.ts b/packages/carbon-react/src/Inputs/index.tsindex 033c93b430..17e01a1c0a 100644--- a/packages/carbon-react/src/Inputs/index.ts+++ b/packages/carbon-react/src/Inputs/index.ts@@ -6,6 +6,7 @@ import {TimePicker,} from "./Date";import { Editor, useEditor } from "./Editor";+import File from "./File";import { CreatableSelect, Select, createFilter } from "./Select";import type { OptionBase } from "./Select/types";@@ -16,6 +17,7 @@ export {DateTimePicker,DateRangePicker,Editor,+ File,Select,TimePicker,createFilter,diff --git a/packages/carbon-react/src/Message/useNotification.tsx b/packages/carbon-react/src/Message/useNotification.tsxindex 13d0d7f1e6..0255349b75 100644--- a/packages/carbon-react/src/Message/useNotification.tsx+++ b/packages/carbon-react/src/Message/useNotification.tsx@@ -14,7 +14,7 @@ import { ClientOnly } from "../SSR";const defaultOptions: UseToastOptions = {isClosable: true,- position: "top",+ position: "bottom-right",};export default function useNotification() {diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsxindex dfac251646..70daaac9df 100644--- a/packages/carbon-react/src/index.tsx+++ b/packages/carbon-react/src/index.tsx@@ -8,6 +8,7 @@ import {DateTimePicker,DateRangePicker,Editor,+ File,Select,TimePicker,createFilter,@@ -40,6 +41,7 @@ export {DateRangePicker,Dot,Editor,+ File,HTML,Loading,Select,diff --git a/packages/carbon-utils/package.json b/packages/carbon-utils/package.jsonindex ec94f402da..d6351766aa 100644--- a/packages/carbon-utils/package.json+++ b/packages/carbon-utils/package.json@@ -12,7 +12,7 @@],"scripts": {"build": "tsup src/index.ts --format esm,cjs --dts --external react",- "clean": "rm -rf dist",+ "clean": "rimraf .turbo node_modules dist","dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react","lint": "TIMING=1 eslint \"src/**/*.ts*\"","test": "jest"diff --git a/packages/carbon-utils/src/file.ts b/packages/carbon-utils/src/file.tsnew file mode 100644index 0000000000..2ffa2a3881--- /dev/null+++ b/packages/carbon-utils/src/file.ts@@ -0,0 +1,11 @@+export const convertKbToString = (kb: number) => {+ if (kb < 1024) {+ return `${kb} KB`;+ }+ const mb = kb / 1024;+ if (mb < 1024) {+ return `${mb.toFixed(2)} MB`;+ }+ const gb = mb / 1024;+ return `${gb.toFixed(2)} GB`;+};diff --git a/packages/carbon-utils/src/index.ts b/packages/carbon-utils/src/index.tsindex 61a46aa196..5de7bf2708 100644--- a/packages/carbon-utils/src/index.ts+++ b/packages/carbon-utils/src/index.ts@@ -1,4 +1,5 @@export * from "./date";+export * from "./file";export * from "./math";export * from "./ssr";export * from "./types";diff --git a/www/package.json b/www/package.jsonindex d2ed6f9105..621e5e40d0 100644--- a/www/package.json+++ b/www/package.json@@ -4,7 +4,7 @@"private": true,"scripts": {"build": "next build",- "clean": "rm -rf .turbo rm -rf .next && rm -rf node_modules",+ "clean": "rimraf .turbo node_modules .next","dev": "next dev -p 4111","lint": "TIMING=1 next lint","start": "next start "diff --git a/www/styles.css b/www/styles.cssindex ce8514db0d..d41d590ad5 100644--- a/www/styles.css+++ b/www/styles.css@@ -22,18 +22,6 @@ body {margin-top: 0;}-#__next article :not(pre) > code {- color: var(--shiki-token-string-expression);- background-color: transparent;- border: 0;- font-size: 90%;-}--#__next article :not(pre) > code::before,-#__next article :not(pre) > code::after {- content: "\`";-}-.dark body article pre {background-color: transparent;border: 1px solid rgba(224, 243, 255, 0.1);diff --git a/yarn.lock b/yarn.lockindex d8554c6d39..7fad1c361e 100644--- a/yarn.lock+++ b/yarn.lock@@ -3050,6 +3050,11 @@dependencies:json-parse-even-better-errors "^2.3.1"+"@pkgjs/parseargs@^0.11.0":+ version "0.11.0"+ resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33"+ integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==+"@pkgr/utils@^2.3.1":version "2.3.1"resolved "https://registry.npmjs.org/@pkgr/utils/-/utils-2.3.1.tgz"@@ -5878,6 +5883,15 @@ cliui@^6.0.0:strip-ansi "^6.0.0"wrap-ansi "^6.2.0"+cliui@^7.0.4:+ version "7.0.4"+ resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f"+ integrity sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==+ dependencies:+ string-width "^4.2.0"+ strip-ansi "^6.0.0"+ wrap-ansi "^7.0.0"+clone-response@^1.0.2:version "1.0.3"resolved "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz"@@ -8108,6 +8122,14 @@ for-in@^1.0.2:resolved "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz"integrity sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==+foreground-child@^3.1.0:+ version "3.1.1"+ resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.1.1.tgz#1d173e776d75d2772fed08efe4a0de1ea1b12d0d"+ integrity sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg==+ dependencies:+ cross-spawn "^7.0.0"+ signal-exit "^4.0.1"+form-data@^3.0.0:version "3.0.1"resolved "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz"@@ -8386,6 +8408,17 @@ [email protected]:once "^1.3.0"path-is-absolute "^1.0.0"+glob@^10.0.0:+ version "10.2.2"+ resolved "https://registry.yarnpkg.com/glob/-/glob-10.2.2.tgz#ce2468727de7e035e8ecf684669dc74d0526ab75"+ integrity sha512-Xsa0BcxIC6th9UwNjZkhrMtNo/MnyRL8jGCP+uEwhA5oFOCY1f2s1/oNKY47xQ0Bg5nkjsfAEIej1VeH62bDDQ==+ dependencies:+ foreground-child "^3.1.0"+ jackspeak "^2.0.3"+ minimatch "^9.0.0"+ minipass "^5.0.0"+ path-scurry "^1.7.0"+glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4:version "7.2.3"resolved "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz"@@ -9431,6 +9464,15 @@ istanbul-reports@^3.0.2:html-escaper "^2.0.0"istanbul-lib-report "^3.0.0"+jackspeak@^2.0.3:+ version "2.1.0"+ resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-2.1.0.tgz#69831fe5346532888f279102f39fc4452ebbe6c2"+ integrity sha512-DiEwVPqsieUzZBNxQ2cxznmFzfg/AMgJUjYw5xl6rSmCxAQXECcbSdwcLM6Ds6T09+SBfSNCGPhYUoQ96P4h7A==+ dependencies:+ cliui "^7.0.4"+ optionalDependencies:+ "@pkgjs/parseargs" "^0.11.0"+javascript-stringify@^2.0.1:version "2.1.0"resolved "https://registry.npmjs.org/javascript-stringify/-/javascript-stringify-2.1.0.tgz"@@ -10281,6 +10323,11 @@ lru-cache@^7.14.1:resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-7.16.1.tgz"integrity sha512-9kkuMZHnLH/8qXARvYSjNvq8S1GYFFzynQTAfKeaJ0sIrR3PUPuu37Z+EiIANiZBvpfTf2B5y8ecDLSMWlLv+w==+lru-cache@^9.0.0:+ version "9.1.1"+ resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-9.1.1.tgz#c58a93de58630b688de39ad04ef02ef26f1902f1"+ integrity sha512-65/Jky17UwSb0BuB9V+MyDpsOtXKmYwzhyl+cOa9XUiI4uV2Ouy/2voFP3+al0BjZbJgMBD8FojMpAf+Z+qn4A==+luxon@^3.1.0:version "3.1.1"resolved "https://registry.npmjs.org/luxon/-/luxon-3.1.1.tgz"@@ -11161,6 +11208,13 @@ minimatch@^7.4.1:dependencies:brace-expansion "^2.0.1"+minimatch@^9.0.0:+ version "9.0.0"+ resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.0.tgz#bfc8e88a1c40ffd40c172ddac3decb8451503b56"+ integrity sha512-0jJj8AvgKqWN05mrwuqi8QYKx1WmYSUoKSxu5Qhs9prezTz10sxAHGNZe9J9cqIJzta8DWsleh2KaVaLl6Ru2w==+ dependencies:+ brace-expansion "^2.0.1"+minimist@^1.1.1, minimist@^1.2.0, minimist@^1.2.6, minimist@~1.2.5:version "1.2.7"resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz"@@ -11206,6 +11260,11 @@ minipass@^4.0.2, minipass@^4.2.4:resolved "https://registry.npmjs.org/minipass/-/minipass-4.2.4.tgz"integrity sha512-lwycX3cBMTvcejsHITUgYj6Gy6A7Nh4Q6h9NP4sTHY1ccJlC7yKzDmiShEHsJ16Jf1nKGDEaiHxiltsJEvk0nQ==+minipass@^5.0.0:+ version "5.0.0"+ resolved "https://registry.yarnpkg.com/minipass/-/minipass-5.0.0.tgz#3e9788ffb90b694a5d0ec94479a45b5d8738133d"+ integrity sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==+minizlib@^2.1.1:version "2.1.2"resolved "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz"@@ -12012,6 +12071,14 @@ path-scurry@^1.6.1:lru-cache "^7.14.1"minipass "^4.0.2"+path-scurry@^1.7.0:+ version "1.7.0"+ resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.7.0.tgz#99c741a2cfbce782294a39994d63748b5a24f6db"+ integrity sha512-UkZUeDjczjYRE495+9thsgcVgsaCPkaw80slmfVFgllxY+IO8ubTsOpFVjDPROBqJdHfVPUFRHPBV/WciOVfWg==+ dependencies:+ lru-cache "^9.0.0"+ minipass "^5.0.0"+version "0.1.7"resolved "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz"@@ -13213,6 +13280,13 @@ rimraf@^4.4.0:dependencies:glob "^9.2.0"+rimraf@^5.0.0:+ version "5.0.0"+ resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-5.0.0.tgz#5bda14e410d7e4dd522154891395802ce032c2cb"+ integrity sha512-Jf9llaP+RvaEVS5nPShYFhtXIrb3LRKP281ib3So0KkeZKo2wIKyq0Re7TOSwanasA423PSr6CCIL4bP6T040g==+ dependencies:+ glob "^10.0.0"+rollup-plugin-inject@^3.0.0:version "3.0.2"resolved "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz"@@ -13490,6 +13564,11 @@ signal-exit@^3.0.0, signal-exit@^3.0.2, signal-exit@^3.0.3, signal-exit@^3.0.7:resolved "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz"integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==+signal-exit@^4.0.1:+ version "4.0.1"+ resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.0.1.tgz#96a61033896120ec9335d96851d902cc98f0ba2a"+ integrity sha512-uUWsN4aOxJAS8KOuf3QMyFtgm1pkb6I+KRZbRF/ghdf5T7sM+B1lLLzPDxswUjkmHyxQAVzEgG35E3NzDM9GVw==+sisteransi@^1.0.5:version "1.0.5"resolved "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz"