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
refactor: modal component
Brad Barbin725b84d89e25
diff --git a/apps/carbon/app/components/Avatar/Avatar.tsx b/apps/carbon/app/components/Avatar/Avatar.tsxindex b847bcf8cf..b32047c016 100644--- a/apps/carbon/app/components/Avatar/Avatar.tsx+++ b/apps/carbon/app/components/Avatar/Avatar.tsx@@ -1,6 +1,6 @@import type { AvatarProps as AvatarBaseProps } from "@chakra-ui/react";import { Avatar as AvatarBase, forwardRef } from "@chakra-ui/react";-import { SUPABASE_API_URL } from "~/config/env";+import { getStoragePath } from "~/utils/path";type AvatarProps = AvatarBaseProps & {path: string | null;@@ -9,9 +9,7 @@ type AvatarProps = AvatarBaseProps & {export const Avatar = forwardRef(({ path, bucket = "avatars", ...props }: AvatarProps, ref) => {- const imagePath = path- ? `${SUPABASE_API_URL}/storage/v1/object/public/${bucket}/${path}`- : undefined;+ const imagePath = path ? getStoragePath(bucket, path) : undefined;return <AvatarBase ref={ref} src={imagePath} {...props} />;}diff --git a/apps/carbon/app/components/Form/CustomerContact.tsx b/apps/carbon/app/components/Form/CustomerContact.tsxindex 80e41a9b89..561faacfa8 100644--- a/apps/carbon/app/components/Form/CustomerContact.tsx+++ b/apps/carbon/app/components/Form/CustomerContact.tsx@@ -17,7 +17,7 @@ import type { SelectProps } from "./Select";type CustomerContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {customer?: string;- onChange?: (customerContact: CustomerContactType | undefined) => void;+ onChange?: (customerContact: CustomerContactType["contact"] | null) => void;};const CustomerContact = ({@@ -33,7 +33,7 @@ const CustomerContact = ({}: CustomerContactSelectProps) => {const initialLoad = useRef(true);const { error } = useField(name);- const [value, setValue] = useControlField<string | undefined>(name);+ const [value, setValue] = useControlField<string | null>(name);const customerContactFetcher =useFetcher<Awaited<ReturnType<typeof getCustomerContacts>>>();@@ -46,9 +46,9 @@ const CustomerContact = ({if (initialLoad.current) {initialLoad.current = false;} else {- setValue(undefined);+ setValue(null);if (onChange) {- onChange(undefined);+ onChange(null);}}// eslint-disable-next-line react-hooks/exhaustive-deps@@ -70,7 +70,7 @@ const CustomerContact = ({value: string | number;label: string;}) => {- const newValue = (selection.value as string) || undefined;+ const newValue = selection === null ? null : (selection.value as string);setValue(newValue);if (onChange && typeof onChange === "function") {if (newValue === undefined) onChange(newValue);@@ -78,7 +78,7 @@ const CustomerContact = ({(c) => c.id === newValue);- onChange(contact);+ onChange(contact?.contact ?? null);}};@@ -91,7 +91,7 @@ const CustomerContact = ({return (<FormControl isInvalid={!!error}>{label && <FormLabel htmlFor={name}>{label}</FormLabel>}- <input type="hidden" name={name} id={name} value={value} />+ <input type="hidden" name={name} id={name} value={value ?? ""} /><Select{...props}value={controlledValue}diff --git a/apps/carbon/app/components/Form/SupplierContact.tsx b/apps/carbon/app/components/Form/SupplierContact.tsxindex b1f52a96c7..136f356da4 100644--- a/apps/carbon/app/components/Form/SupplierContact.tsx+++ b/apps/carbon/app/components/Form/SupplierContact.tsx@@ -17,7 +17,7 @@ import type { SelectProps } from "./Select";type SupplierContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {supplier?: string;- onChange?: (supplierContact: SupplierContactType | null) => void;+ onChange?: (supplierContact: SupplierContactType["contact"] | null) => void;};const SupplierContact = ({@@ -80,7 +80,7 @@ const SupplierContact = ({(c) => c.id === newValue);- onChange(contact ?? null);+ onChange(contact?.contact ?? null);}};diff --git a/apps/carbon/app/components/Modals/Confirm/Confirm.tsx b/apps/carbon/app/components/Modals/Confirm/Confirm.tsxindex a0d88c9a41..4747d96c29 100644--- a/apps/carbon/app/components/Modals/Confirm/Confirm.tsx+++ b/apps/carbon/app/components/Modals/Confirm/Confirm.tsx@@ -1,17 +1,17 @@-import { Button } from "@carbon/react";import {+ Button,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,- ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";+import { Form } from "@remix-run/react";type ConfirmProps = {- action: string;+ action?: string;isOpen?: boolean;name: string;text: string;@@ -28,13 +28,17 @@ const Confirm = ({onSubmit,}: ConfirmProps) => {return (- <Modal isOpen={isOpen} onClose={onCancel}>- <ModalOverlay />+ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ ><ModalContent>- <ModalHeader>{name}</ModalHeader>- <ModalCloseButton />+ <ModalHeader>+ <ModalTitle>{name}</ModalTitle>+ </ModalHeader><ModalBody>{text}</ModalBody>-<ModalFooter><Button variant="secondary" className="mr-3" onClick={onCancel}>Canceldiff --git a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsxindex 2023b6678a..52ec69fa90 100644--- a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx+++ b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx@@ -1,13 +1,13 @@-import { Button } from "@carbon/react";import {+ Button,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";import { Form } from "@remix-run/react";type ConfirmDeleteProps = {@@ -28,11 +28,18 @@ const ConfirmDelete = ({onSubmit,}: ConfirmDeleteProps) => {return (- <Modal isOpen={isOpen} onClose={onCancel}>+ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ ><ModalOverlay /><ModalContent>- <ModalHeader>Delete {name}</ModalHeader>- <ModalCloseButton />+ <ModalHeader>+ <ModalTitle>Delete {name}</ModalTitle>+ </ModalHeader>+<ModalBody>{text}</ModalBody><ModalFooter>diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsxindex 47571b181d..111bbcbf6d 100644--- a/apps/carbon/app/components/Search/Search/Search.tsx+++ b/apps/carbon/app/components/Search/Search/Search.tsx@@ -1,27 +1,25 @@import {Button,+ HStack,+ Modal,+ ModalBody,+ ModalContent,VStack,- useColor,useDebounce,useDisclosure,useKeyboardShortcuts,} from "@carbon/react";import { clip } from "@carbon/utils";import {- HStack,Icon,Input,InputGroup,InputLeftElement,Kbd,List,- ListItem,- Modal,- ModalBody,- ModalContent,- ModalOverlay,} from "@chakra-ui/react";import { Link, useNavigate } from "@remix-run/react";+import clsx from "clsx";import { useCallback, useEffect, useRef, useState } from "react";import { AiOutlinePartition } from "react-icons/ai";import { BiListCheck } from "react-icons/bi";@@ -191,20 +189,18 @@ const SearchModal = ({return (<Modal- isOpen={isOpen}- onClose={() => {- onClose();+ open={isOpen}+ onOpenChange={(open) => {setQuery("");+ if (!open) onClose();}}>- <ModalOverlay />- <ModalContent borderRadius="lg">- <ModalBody p={0}>+ <ModalContent className="rounded-lg top-[10vh] translate-y-0 p-0">+ <ModalBody className="max-h-[66vh]"><InputGroup size="lg">- <InputLeftElement- pointerEvents="none"- children={<Icon as={FaSearch} color="gray.500" />}- />+ <InputLeftElement pointerEvents="none">+ <FaSearch className="text-muted-foreground" />+ </InputLeftElement><Inputplaceholder="Search..."value={query}@@ -221,7 +217,7 @@ const SearchModal = ({/></InputGroup>- <div className="bg-background rounded-lg shadow-lg max-h-[66vh] overflow-y-scroll p-4 pt-0">+ <div className="h-[calc(100%-3rem)] overflow-y-scroll p-4 pt-0"><List role="listbox" ref={listboxRef}>{moduleResults.map((item, itemIndex) => (<Module@@ -301,28 +297,34 @@ function Result({onClick: () => void;onHover: () => void;}) {- const bgColor = useColor("gray.100");return (<Link to={result.link} onClick={onClick}>- <HStack- as={ListItem}+ <li+ className={clsx(+ "flex w-full items-center bg-card rounded-lg min-h-[4rem] mt-2 p-2",+ {+ "bg-primary text-primary-foreground": selected,+ "bg-muted text-foreground": !selected,+ }+ )}role="option"- bg={selected ? "gray.900" : bgColor}- borderRadius="lg"- color={selected ? "white" : undefined}- minH={16}- mt={2}- px={4}- py={2}+ aria-selected={selected}onMouseEnter={onHover}><ResultIcon entity={result.entity} /><VStack spacing={0} className="flex-1">- <p className="text-sm text-muted-foreground">{result.entity}</p>+ <p+ className={clsx("text-sm", {+ "text-primary-foreground/60": selected,+ "text-muted-foreground": !selected,+ })}+ >+ {result.entity}+ </p><p className="font-bold">{result.name}</p></VStack><EnterIcon />- </HStack>+ </li></Link>);}@@ -338,30 +340,33 @@ function Module({onClick: () => void;onHover: () => void;}) {- const bgColor = useColor("gray.100");return (<Link to={item.to} onClick={onClick}>- <HStack- as={ListItem}+ <li+ className={clsx(+ "flex w-full items-center bg-card rounded-lg min-h-[4rem] mt-2 p-2",+ {+ "bg-primary text-primary-foreground": selected,+ "bg-muted text-foreground": !selected,+ }+ )}role="option"- bg={selected ? "gray.900" : bgColor}- borderRadius="lg"- color={selected ? "white" : undefined}- minH={16}- mt={2}- px={4}- py={2}+ aria-selected={selected}onMouseEnter={onHover}>- {/* {item.icon && ( // @ts-expect-error- <Icon as={item.icon} {...resultIconProps} />- )} */}<VStack spacing={0} className="flex-1">- <p className="text-sm text-muted-foreground">Module</p>+ <p+ className={clsx("text-sm", {+ "text-primary-foreground/60": selected,+ "text-muted-foreground": !selected,+ })}+ >+ Module+ </p><p className="font-bold">{item.name}</p></VStack><EnterIcon />- </HStack>+ </li></Link>);}@@ -380,7 +385,7 @@ const SearchButton = () => {className="text-muted-foreground w-[200px] mt-2"onClick={searchModal.onOpen}>- <HStack w="full">+ <HStack className="w-full"><div className="flex flex-grow">Search</div><Kbd size="lg">/</Kbd></HStack>diff --git a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsxindex 4eceba0ffe..cab576b9ec 100644--- a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx+++ b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx@@ -159,6 +159,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -199,6 +200,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -239,6 +241,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -287,6 +290,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -327,6 +331,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -367,6 +372,7 @@ function renderTypedForm({borderTopColor={borderColor}borderTopStyle="solid"borderTopWidth={1}+ columnGap={2}pt={3}w="full">@@ -629,7 +635,7 @@ function UpdateRemoveButtons({onSubmit: (value: string | boolean | number | undefined) => void;}) {return (- <HStack className="justify-between w-full self-center">+ <HStack className="justify-end w-full self-center">{userAttributeValueId && (<ValidatedFormmethod="post"diff --git a/apps/carbon/app/modules/account/ui/useAccountSidebar.tsx b/apps/carbon/app/modules/account/ui/useAccountSidebar.tsxindex e2f1ffa9c8..b3fdb99e9b 100644--- a/apps/carbon/app/modules/account/ui/useAccountSidebar.tsx+++ b/apps/carbon/app/modules/account/ui/useAccountSidebar.tsx@@ -1,3 +1,5 @@+import { BsKeyFill, BsShieldLock } from "react-icons/bs";+import { CgProfile } from "react-icons/cg";import type { Route } from "~/types";import { path } from "~/utils/path";@@ -5,18 +7,20 @@ const accountRoutes: Route[] = [{name: "Profile",to: path.to.profile,+ icon: <CgProfile />,},{name: "Personal",to: path.to.accountPersonal,+ icon: <BsShieldLock />,},{name: "Password",to: path.to.accountPassword,+ icon: <BsKeyFill />,},];export default function useAccountSidebar() {- // TODO: filter links based on employee typereturn { links: accountRoutes };}diff --git a/apps/carbon/app/modules/documents/types.ts b/apps/carbon/app/modules/documents/types.tsindex f907890cd5..e121e97767 100644--- a/apps/carbon/app/modules/documents/types.ts+++ b/apps/carbon/app/modules/documents/types.ts@@ -7,6 +7,8 @@ export type Document = Omit<> & {favorite: boolean;labels: string[];+ readGroups: string[];+ writeGroups: string[];createdByAvatar: string;createdByFullName: string;updatedByAvatar?: string | null;diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon/DocumentIcon.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon/DocumentIcon.tsxindex 816e346558..4a63608840 100644--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon/DocumentIcon.tsx+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon/DocumentIcon.tsx@@ -1,6 +1,7 @@import { Icon } from "@chakra-ui/react";import {BsFileEarmarkFill,+ BsFileEarmarkPlayFill,BsFileExcelFill,BsFileImageFill,BsFilePdfFill,@@ -8,7 +9,6 @@ import {BsFileTextFill,BsFileWordFill,BsFileZipFill,- BsFileEarmarkPlayFill,} from "react-icons/bs";type DocumentIconProps = {@@ -46,6 +46,7 @@ const DocumentIcon = ({ fileName }: DocumentIconProps) => {case "gif":case "svg":case "avif":+ case "webp":return <Icon color="yellow.400" {...iconSize} as={BsFileImageFill} />;case "mp4":case "avi":diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsxindex 84d467155b..cb8f311cd2 100644--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx@@ -1,21 +1,23 @@-import { CreatableSelect, HStack } from "@carbon/react";+import {+ CreatableSelect,+ HStack,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ Popover,+ PopoverContent,+ PopoverTrigger,+ useDisclosure,+} from "@carbon/react";import { convertKbToString } from "@carbon/utils";import {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";@@ -55,24 +57,25 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {edit,favorite,isImage,+ isPdf,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 labelOptions = useMemo(+ () =>+ labels.map(({ label }) => ({+ value: label as string,+ label: label as string,+ })) ?? [],+ [labels]+ );const onDeleteLabel = useCallback(async (@@ -152,7 +155,40 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {/><DocumentIcon fileName={row.original.name} /><Link onClick={() => download(row.original)}>- {row.original.name}+ {row.original.type &&+ (isImage(row.original.type) || isPdf(row.original.type)) ? (+ <HoverCard>+ <HoverCardTrigger>{row.original.name}</HoverCardTrigger>+ {isPdf(row.original.type) ? (+ <HoverCardContent className="w-[425px] h-[550px] overflow-hidden p-0">+ <iframe+ seamless+ title={row.original.path}+ width="425"+ height="550"+ src={path.to.file.previewFile(+ `private/${row.original.path}`+ )}+ />+ </HoverCardContent>+ ) : (+ <HoverCardContent className="w-[400px] h-[400px] overflow-hidden p-0">+ <iframe+ seamless+ title={row.original.path}+ width="400"+ height="400"+ src={path.to.file.previewImage(+ "private",+ row.original.path+ )}+ />+ </HoverCardContent>+ )}+ </HoverCard>+ ) : (+ <>{row.original.name}</>+ )}</Link></HStack>),@@ -170,18 +206,34 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {/></Tag>))}-- <Tag- cursor="pointer"- onClick={() => {- setSelectedDocument(row.original);- documentLabelModal.onOpen();- }}- >- <TagLabel>- <IoMdAdd />- </TagLabel>- </Tag>+ <Popover>+ <PopoverTrigger>+ <Tag cursor="pointer">+ <TagLabel>+ <IoMdAdd />+ </TagLabel>+ </Tag>+ </PopoverTrigger>+ <PopoverContent className="w-[300px] p-0">+ <CreatableSelect+ defaultValue={+ row.original.labels.map((label) => ({+ value: label,+ label: label,+ })) ?? []+ }+ isClearable+ isMulti+ options={labelOptions}+ onChange={(newValues) =>+ onLabel(+ row.original,+ newValues.map((v) => v.value)+ )+ }+ />+ </PopoverContent>+ </Popover></HStack>),},@@ -228,7 +280,16 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {cell: (item) => item.getValue(),},];- }, [documentLabelModal, download, onDeleteLabel, onFavorite, setLabel]);+ }, [+ download,+ isImage,+ isPdf,+ labelOptions,+ onDeleteLabel,+ onFavorite,+ onLabel,+ setLabel,+ ]);const actions = useMemo(() => {return [@@ -280,14 +341,6 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {// eslint-disable-next-line react/display-namereturn (row: Document) => (<>- <MenuItem- icon={<VscOpenPreview />}- isDisabled={!row.type || !isImage(row.type)}- onClick={async () => setPreviewImage(await makePreview(row))}- >- Preview- </MenuItem>-<MenuItemicon={<BsPencilSquare />}isDisabled={canUpdate(row)}@@ -325,8 +378,6 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {download,edit,filter,- isImage,- makePreview,onFavorite,]);@@ -346,54 +397,6 @@ const DocumentsTable = memo(({ data, count, labels }: DocumentsTableProps) => {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 &&selectedDocument.id &&(filter !== "trash" ? (diff --git a/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts b/apps/carbon/app/modules/documents/ui/Documents/useDocument.tsindex 72ea6ad7d8..14e387d70a 100644--- a/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts+++ b/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts@@ -3,7 +3,10 @@ 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";+import type {+ DocumentTransactionType,+ Document as DocumentType,+} from "~/modules/documents";import { path } from "~/utils/path";export const useDocument = () => {@@ -15,17 +18,17 @@ export const useDocument = () => {const user = useUser();const canDelete = useCallback(- (document: Document) => {+ (doc: DocumentType) => {return (!permissions.can("delete", "documents") ||- !document.writeGroups?.some((group) => user?.groups.includes(group))+ !doc.writeGroups?.some((group) => user?.groups.includes(group)));},[permissions, user]);const canUpdate = useCallback(- (document: Document) => {+ (document: DocumentType) => {return (!permissions.can("update", "documents") ||!document.writeGroups?.some((group) => user?.groups.includes(group))@@ -35,7 +38,7 @@ export const useDocument = () => {);const insertTransaction = useCallback(- (document: Document, type: DocumentTransactionType) => {+ (document: DocumentType, type: DocumentTransactionType) => {if (user?.id === undefined) throw new Error("User is undefined");return supabase?.from("documentTransaction").insert({documentId: document.id,@@ -47,7 +50,7 @@ export const useDocument = () => {);const deleteLabel = useCallback(- async (document: Document, label: string) => {+ async (document: DocumentType, label: string) => {return supabase?.from("documentLabel").delete()@@ -59,7 +62,7 @@ export const useDocument = () => {);const download = useCallback(- async (doc: Document) => {+ async (doc: DocumentType) => {const result = await supabase?.storage.from("private").download(doc.path);if (!result || result.error) {@@ -85,13 +88,13 @@ export const useDocument = () => {);const edit = useCallback(- (document: Document) =>+ (document: DocumentType) =>navigate(`${path.to.document(document.id)}?${params}`),[navigate, params]);const favorite = useCallback(- async (document: Document) => {+ async (document: DocumentType) => {if (document.favorite) {await supabase?.from("documentFavorite")@@ -110,11 +113,17 @@ export const useDocument = () => {);const isImage = useCallback((fileType: string) => {- return ["png", "jpg", "jpeg", "gif", "svg", "avif"].includes(fileType);+ return ["png", "jpg", "jpeg", "gif", "svg", "avif", "webp"].includes(+ fileType+ );+ }, []);++ const isPdf = useCallback((fileType: string) => {+ return fileType === "pdf";}, []);const label = useCallback(- async (document: Document, labels: string[]) => {+ async (document: DocumentType, labels: string[]) => {if (user?.id === undefined) throw new Error("User is undefined");await supabase?.from("documentLabel")@@ -137,7 +146,7 @@ export const useDocument = () => {);const makePreview = useCallback(- async (doc: Document) => {+ async (doc: DocumentType) => {const result = await supabase?.storage.from("private").download(doc.path);if (!result || result.error) {@@ -151,7 +160,7 @@ export const useDocument = () => {);const removeLabel = useCallback(- (document: Document, label: string) => {+ (document: DocumentType, label: string) => {return supabase?.from("documentLabel").delete()@@ -177,6 +186,7 @@ export const useDocument = () => {edit,favorite,isImage,+ isPdf,label,makePreview,removeLabel,diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsxindex ed955d2cff..e606fcf570 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx@@ -3,6 +3,7 @@ import {Drawer,DrawerBody,DrawerContent,+ DrawerDescription,DrawerFooter,DrawerHeader,DrawerTitle,@@ -23,8 +24,13 @@ import {} from "~/components/Form";import DataGrid from "~/components/Grid";import { SectionTitle } from "~/components/Layout";-import type { ReceiptLine, ReceiptSourceDocument } from "~/modules/inventory";+import type {+ ReceiptLine,+ ReceiptSourceDocument,+ receiptStatusType,+} from "~/modules/inventory";import {+ ReceiptStatus,receiptSourceDocumentType,receiptValidator,} from "~/modules/inventory";@@ -36,7 +42,7 @@ import useReceiptForm from "./useReceiptForm";type ReceiptFormProps = {initialValues: TypeOfValidator<typeof receiptValidator>;- isPosted: boolean;+ status: (typeof receiptStatusType)[number];notes: Note[];receiptLines?: ReceiptLine[];};@@ -45,7 +51,7 @@ const formId = "receipt-form";const ReceiptForm = ({initialValues,- isPosted,+ status,notes,receiptLines,}: ReceiptFormProps) => {@@ -71,6 +77,8 @@ const ReceiptForm = ({receiptLines: receiptLines ?? [],});+ const isPosted = status === "Posted";+return (<><Drawer@@ -82,6 +90,9 @@ const ReceiptForm = ({<DrawerContent size="full"><DrawerHeader><DrawerTitle>{initialValues.receiptId}</DrawerTitle>+ <DrawerDescription>+ <ReceiptStatus status={status} />+ </DrawerDescription></DrawerHeader><DrawerBody><VStack spacing={4}>diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsxindex 62642066ec..5bdd592754 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx@@ -1,13 +1,14 @@-import { Button, HStack } from "@carbon/react";import {+ Button,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";import { Form, useNavigate } from "@remix-run/react";type ReceiptPostModalProps = {};@@ -18,13 +19,18 @@ const ReceiptPostModal = (props: ReceiptPostModalProps) => {const onCancel = () => navigate(-1);return (- <Modal isOpen={true} onClose={onCancel}>+ <Modal+ open={true}+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ ><ModalOverlay /><ModalContent>- <ModalHeader>Post Receipt</ModalHeader>- <ModalCloseButton />+ <ModalHeader>+ <ModalTitle>Post Receipt</ModalTitle>+ </ModalHeader><ModalBody>Are you sure you want to post this receipt?</ModalBody>-<ModalFooter><HStack><Button variant="solid" onClick={onCancel}>diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal/PurchaseInvoicePostModal.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal/PurchaseInvoicePostModal.tsxindex 808924ec50..f35c244572 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal/PurchaseInvoicePostModal.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal/PurchaseInvoicePostModal.tsx@@ -1,15 +1,14 @@-import { Button, HStack } from "@carbon/react";import {- ListItem,+ Button,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,- ModalOverlay,- UnorderedList,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";+import { ListItem, UnorderedList } from "@chakra-ui/react";import { Form } from "@remix-run/react";import { path } from "~/utils/path";@@ -29,11 +28,16 @@ const PurchaseInvoicePostModal = ({const hasLinesToReceive = linesToReceive.length > 0;return (- <Modal isOpen={isOpen} onClose={onClose}>- <ModalOverlay />+ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ ><ModalContent>- <ModalHeader>Post Invoice</ModalHeader>- <ModalCloseButton />+ <ModalHeader>+ <ModalTitle>Post Invoice</ModalTitle>+ </ModalHeader><ModalBody>{hasLinesToReceive ? (<>@@ -53,7 +57,6 @@ const PurchaseInvoicePostModal = ({<p>Are you sure you want to post this invoice?</p>)}</ModalBody>-<ModalFooter><HStack><Button variant="solid" onClick={onClose}>diff --git a/apps/carbon/app/modules/users/ui/Customers/CreateCustomerModal/CreateCustomerModal.tsx b/apps/carbon/app/modules/users/ui/Customers/CreateCustomerModal/CreateCustomerModal.tsxindex 8e822c73f9..61b01446b3 100644--- a/apps/carbon/app/modules/users/ui/Customers/CreateCustomerModal/CreateCustomerModal.tsx+++ b/apps/carbon/app/modules/users/ui/Customers/CreateCustomerModal/CreateCustomerModal.tsx@@ -1,21 +1,31 @@-import { HStack, VStack } from "@carbon/react";import {- FormControl,- FormLabel,- Grid,- Input,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,+ ModalFooter,ModalHeader,ModalOverlay,+ ModalTitle,+ Select,+ VStack,+} from "@carbon/react";+import {+ FormControl,+ FormErrorMessage,+ FormLabel,+ Grid,+ Input,} from "@chakra-ui/react";import { useFetcher, useNavigate } from "@remix-run/react";-import { useRef, useState } from "react";-import { ValidatedForm } from "remix-validated-form";-import { Customer, CustomerContact, Submit } from "~/components/Form";+import { useEffect, useMemo, useRef, useState } from "react";+import { ValidatedForm, useControlField, useField } from "remix-validated-form";+import { Customer, Submit } from "~/components/Form";import { useUrlParams } from "~/hooks";+import type {+ CustomerContact as CustomerContactType,+ getCustomerContacts,+} from "~/modules/sales";import { createCustomerAccountValidator } from "~/modules/users";import type { Result } from "~/types";import { path } from "~/utils/path";@@ -23,46 +33,43 @@ import { path } from "~/utils/path";const CreateCustomerModal = () => {const navigate = useNavigate();const [params] = useUrlParams();- const initialFocusRef = useRef<HTMLInputElement>(null);+const formFetcher = useFetcher<Result>();const [customer, setCustomer] = useState<string | undefined>((params.get("customer") as string) ?? undefined);- const [contact, setContact] = useState<- | {- email: string;- firstName: string;- lastName: string;- }- | undefined- >();+ const [contact, setContact] = useState<CustomerContactType["contact"] | null>(+ null+ );return (<Modal- initialFocusRef={initialFocusRef}- isOpen={true}- onClose={() => navigate(-1)}+ open+ onOpenChange={(open) => {+ if (!open) navigate(path.to.customerAccounts);+ }}><ModalOverlay /><ModalContent>- <ModalHeader>Create an account</ModalHeader>- <ModalCloseButton />- <ModalBody pb={6}>- <ValidatedForm- method="post"- action={`${path.to.newCustomerAccount}${- params.get("customer")- ? `?customer=${params.get("customer")}`- : ""- }`}- validator={createCustomerAccountValidator}- defaultValues={{- id: params.get("id") ?? "",- customer: params.get("customer") ?? "",- }}- // @ts-ignore- fetcher={formFetcher}- >+ <ValidatedForm+ method="post"+ action={`${path.to.newCustomerAccount}${+ params.get("customer") ? `?customer=${params.get("customer")}` : ""+ }`}+ validator={createCustomerAccountValidator}+ defaultValues={{+ id: params.get("id") ?? "",+ customer: params.get("customer") ?? "",+ }}+ // @ts-ignore+ fetcher={formFetcher}+ className="flex flex-col h-full"+ >+ <ModalHeader>+ <ModalTitle>Create an account</ModalTitle>+ </ModalHeader>++ <ModalBody><VStack spacing={4}><Customername="customer"@@ -73,12 +80,8 @@ const CreateCustomerModal = () => {/><CustomerContactname="id"- label="Customer Contact"customer={customer}- onChange={(newValue) => {- // @ts-ignore- setContact(newValue?.contact);- }}+ onChange={setContact}/>{contact && (<>@@ -110,16 +113,110 @@ const CreateCustomerModal = () => {</Grid></>)}-+ </VStack>+ <ModalFooter><HStack><Submit>Create User</Submit></HStack>- </VStack>- </ValidatedForm>- </ModalBody>+ </ModalFooter>+ </ModalBody>+ </ValidatedForm></ModalContent></Modal>);};+const CustomerContact = ({+ name,+ customer,+ onChange,+}: {+ name: string;+ customer?: string;+ onChange?: (newValue: CustomerContactType["contact"] | null) => void;+}) => {+ const initialLoad = useRef(true);+ const { error, defaultValue } = useField(name);+ const [value, setValue] = useControlField<string | null>(name);++ const customerContactFetcher =+ useFetcher<Awaited<ReturnType<typeof getCustomerContacts>>>();++ useEffect(() => {+ if (customer) {+ customerContactFetcher.load(path.to.api.customerContacts(customer));+ }++ if (initialLoad.current) {+ initialLoad.current = false;+ } else {+ setValue(null);+ if (onChange) {+ onChange(null);+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [customer]);++ const options = useMemo(+ () =>+ customerContactFetcher.data?.data+ ? customerContactFetcher.data?.data.map((c) => ({+ value: c.id,+ // @ts-ignore+ label: `${c.contact?.firstName} ${c.contact?.lastName}`,+ }))+ : [],+ [customerContactFetcher.data]+ );++ const handleChange = (+ selection: {+ value: string | number;+ label: string;+ } | null+ ) => {+ const newValue = selection === null ? null : (selection.value as string);+ setValue(newValue);+ if (onChange && typeof onChange === "function") {+ if (newValue === null) onChange(newValue);+ const contact = customerContactFetcher.data?.data?.find(+ (c) => c.id === newValue+ );++ onChange(contact?.contact ?? null);+ }+ };++ const controlledValue = useMemo(+ // @ts-ignore+ () => options.find((option) => option.value === value),+ [value, options]+ );++ // so that we can call onChange on load+ useEffect(() => {+ if (controlledValue && controlledValue.value === defaultValue) {+ handleChange(controlledValue);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [controlledValue?.value]);++ return (+ <FormControl isInvalid={!!error}>+ <FormLabel htmlFor={name}>Customer Contact</FormLabel>+ <input type="hidden" name={name} id={name} value={value ?? ""} />+ <Select+ id={name}+ value={controlledValue}+ options={options}+ onChange={handleChange}+ isClearable+ w="full"+ />+ {error && <FormErrorMessage>{error}</FormErrorMessage>}+ </FormControl>+ );+};+export default CreateCustomerModal;diff --git a/apps/carbon/app/modules/users/ui/DeactivateUsersModal/DeactivateUsersModal.tsx b/apps/carbon/app/modules/users/ui/DeactivateUsersModal/DeactivateUsersModal.tsxindex 3fb56b0392..bcea6df4ad 100644--- a/apps/carbon/app/modules/users/ui/DeactivateUsersModal/DeactivateUsersModal.tsx+++ b/apps/carbon/app/modules/users/ui/DeactivateUsersModal/DeactivateUsersModal.tsx@@ -1,13 +1,13 @@-import { Button, HStack } from "@carbon/react";import {+ Button,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,- ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";import { ValidatedForm } from "remix-validated-form";import { UserSelect } from "~/components/Selectors";import { deactivateUsersValidator } from "~/modules/users";@@ -29,13 +29,18 @@ const DeactivateUsersModal = ({const isSingleUser = userIds.length === 1;return (- <Modal isOpen={isOpen} onClose={onClose}>- <ModalOverlay />+ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ ><ModalContent><ModalHeader>- {isSingleUser ? "Deactivate Employee" : "Deactivate Employees"}+ <ModalTitle>+ {isSingleUser ? "Deactivate Employee" : "Deactivate Employees"}+ </ModalTitle></ModalHeader>- <ModalCloseButton /><ModalBody><p className="mb-2">Are you sure you want to deactivediff --git a/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx b/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal/CreateEmployeeModal.tsxindex 1d923779bd..3699fc7351 100644--- a/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx+++ b/apps/carbon/app/modules/users/ui/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx@@ -1,13 +1,16 @@-import { HStack, VStack, useMount } from "@carbon/react";import {- Grid,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,+ ModalFooter,ModalHeader,ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+ VStack,+ useMount,+} from "@carbon/react";+import { Grid } from "@chakra-ui/react";import { useFetcher, useNavigate } from "@remix-run/react";import type { PostgrestResponse } from "@supabase/supabase-js";import { useRef } from "react";@@ -36,22 +39,26 @@ const CreateEmployeeModal = () => {return (<Modal- initialFocusRef={initialFocusRef}- isOpen={true}- onClose={() => navigate(-1)}+ open+ onOpenChange={(open) => {+ if (!open) navigate(path.to.employeeAccounts);+ }}><ModalOverlay /><ModalContent>- <ModalHeader>Create an account</ModalHeader>- <ModalCloseButton />- <ModalBody pb={6}>- <ValidatedForm- method="post"- action={path.to.newEmployee}- validator={createEmployeeValidator}- // @ts-ignore- fetcher={formFetcher}- >+ <ValidatedForm+ method="post"+ action={path.to.newEmployee}+ validator={createEmployeeValidator}+ // @ts-ignore+ fetcher={formFetcher}+ className="flex flex-col h-full"+ >+ <ModalHeader>+ <ModalTitle>Create an account</ModalTitle>+ </ModalHeader>++ <ModalBody><VStack spacing={4}><Input ref={initialFocusRef} name="email" label="Email" /><Grid templateColumns="1fr 1fr" gap={4}>@@ -65,12 +72,14 @@ const CreateEmployeeModal = () => {options={employeeTypeOptions}placeholder="Select Employee Type"/>+ </VStack>+ <ModalFooter><HStack><Submit>Create User</Submit></HStack>- </VStack>- </ValidatedForm>- </ModalBody>+ </ModalFooter>+ </ModalBody>+ </ValidatedForm></ModalContent></Modal>);diff --git a/apps/carbon/app/modules/users/ui/ResendInviteModal/ResendInviteModal.tsx b/apps/carbon/app/modules/users/ui/ResendInviteModal/ResendInviteModal.tsxindex e7cb303812..bb642e917b 100644--- a/apps/carbon/app/modules/users/ui/ResendInviteModal/ResendInviteModal.tsx+++ b/apps/carbon/app/modules/users/ui/ResendInviteModal/ResendInviteModal.tsx@@ -1,13 +1,13 @@-import { Button, HStack } from "@carbon/react";import {+ Button,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,ModalFooter,ModalHeader,- ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+} from "@carbon/react";import { useFetcher } from "@remix-run/react";import { ValidatedForm } from "remix-validated-form";import { UserSelect } from "~/components/Selectors";@@ -29,13 +29,19 @@ const ResendInviteModal = ({const isSingleUser = userIds.length === 1;return (- <Modal isOpen={isOpen} onClose={onClose}>- <ModalOverlay />+ <Modal+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ ><ModalContent><ModalHeader>- {isSingleUser ? "Resend Invite" : "Resend Invites"}+ <ModalTitle>+ {isSingleUser ? "Resend Invite" : "Resend Invites"}+ </ModalTitle></ModalHeader>- <ModalCloseButton />+<ModalBody><p className="mb-2">Are you sure you want to resend an invite todiff --git a/apps/carbon/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/carbon/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsxindex dca4911cd8..1926b49689 100644--- a/apps/carbon/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx+++ b/apps/carbon/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx@@ -1,21 +1,30 @@-import { HStack, VStack } from "@carbon/react";import {- FormControl,- FormLabel,- Grid,- Input,+ HStack,Modal,ModalBody,- ModalCloseButton,ModalContent,+ ModalFooter,ModalHeader,- ModalOverlay,+ ModalTitle,+ Select,+ VStack,+} from "@carbon/react";+import {+ FormControl,+ FormErrorMessage,+ FormLabel,+ Grid,+ Input,} from "@chakra-ui/react";import { useFetcher, useNavigate } from "@remix-run/react";-import { useRef, useState } from "react";-import { ValidatedForm } from "remix-validated-form";-import { Submit, Supplier, SupplierContact } from "~/components/Form";+import { useEffect, useMemo, useRef, useState } from "react";+import { ValidatedForm, useControlField, useField } from "remix-validated-form";+import { Submit, Supplier } from "~/components/Form";import { useUrlParams } from "~/hooks";+import type {+ SupplierContact as SupplierContactType,+ getSupplierContacts,+} from "~/modules/purchasing";import { createSupplierAccountValidator } from "~/modules/users";import type { Result } from "~/types";import { path } from "~/utils/path";@@ -23,46 +32,41 @@ import { path } from "~/utils/path";const CreateSupplierModal = () => {const navigate = useNavigate();const [params] = useUrlParams();- const initialFocusRef = useRef<HTMLInputElement>(null);+const formFetcher = useFetcher<Result>();const [supplier, setSupplier] = useState<string | undefined>((params.get("supplier") as string) ?? undefined);- const [contact, setContact] = useState<- | {- email: string;- firstName: string;- lastName: string;- }- | undefined- >();+ const [contact, setContact] = useState<SupplierContactType["contact"] | null>(+ null+ );return (<Modal- initialFocusRef={initialFocusRef}- isOpen={true}- onClose={() => navigate(-1)}+ open+ onOpenChange={(open) => {+ if (!open) navigate(path.to.supplierAccounts);+ }}>- <ModalOverlay /><ModalContent>- <ModalHeader>Create an account</ModalHeader>- <ModalCloseButton />- <ModalBody pb={6}>- <ValidatedForm- method="post"- action={`${path.to.newSupplierAccount}${- params.get("supplier")- ? `?supplier=${params.get("supplier")}`- : ""- }`}- validator={createSupplierAccountValidator}- defaultValues={{- id: params.get("id") ?? "",- supplier: params.get("supplier") ?? "",- }}- // @ts-ignore- fetcher={formFetcher}- >+ <ValidatedForm+ method="post"+ action={`${path.to.newSupplierAccount}${+ params.get("supplier") ? `?supplier=${params.get("supplier")}` : ""+ }`}+ validator={createSupplierAccountValidator}+ defaultValues={{+ id: params.get("id") ?? "",+ supplier: params.get("supplier") ?? "",+ }}+ // @ts-ignore+ fetcher={formFetcher}+ className="flex flex-col h-full"+ >+ <ModalHeader>+ <ModalTitle>Create an account</ModalTitle>+ </ModalHeader>+ <ModalBody><VStack spacing={4}><Suppliername="supplier"@@ -73,7 +77,6 @@ const CreateSupplierModal = () => {/><SupplierContactname="id"- label="Supplier Contact"supplier={supplier}onChange={setContact}/>@@ -107,16 +110,110 @@ const CreateSupplierModal = () => {</Grid></>)}-- <HStack spacing={4}>- <Submit>Create User</Submit>- </HStack></VStack>- </ValidatedForm>- </ModalBody>+ </ModalBody>+ <ModalFooter>+ <HStack spacing={4}>+ <Submit>Create User</Submit>+ </HStack>+ </ModalFooter>+ </ValidatedForm></ModalContent></Modal>);};+const SupplierContact = ({+ name,+ supplier,+ onChange,+}: {+ name: string;+ supplier?: string;+ onChange?: (newValue: SupplierContactType["contact"] | null) => void;+}) => {+ const initialLoad = useRef(true);+ const { error, defaultValue } = useField(name);+ const [value, setValue] = useControlField<string | null>(name);++ const supplierContactFetcher =+ useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();++ useEffect(() => {+ if (supplier) {+ supplierContactFetcher.load(path.to.api.supplierContacts(supplier));+ }++ if (initialLoad.current) {+ initialLoad.current = false;+ } else {+ setValue(null);+ if (onChange) {+ onChange(null);+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [supplier]);++ const options = useMemo(+ () =>+ supplierContactFetcher.data?.data+ ? supplierContactFetcher.data?.data.map((c) => ({+ value: c.id,+ // @ts-ignore+ label: `${c.contact?.firstName} ${c.contact?.lastName}`,+ }))+ : [],+ [supplierContactFetcher.data]+ );++ const handleChange = (+ selection: {+ value: string | number;+ label: string;+ } | null+ ) => {+ const newValue = selection === null ? null : (selection.value as string);+ setValue(newValue);+ if (onChange && typeof onChange === "function") {+ if (newValue === null) onChange(newValue);+ const contact = supplierContactFetcher.data?.data?.find(+ (c) => c.id === newValue+ );++ onChange(contact?.contact ?? null);+ }+ };++ const controlledValue = useMemo(+ // @ts-ignore+ () => options.find((option) => option.value === value),+ [value, options]+ );++ // so that we can call onChange on load+ useEffect(() => {+ if (controlledValue && controlledValue.value === defaultValue) {+ handleChange(controlledValue);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [controlledValue?.value]);++ return (+ <FormControl isInvalid={!!error}>+ <FormLabel htmlFor={name}>Supplier Contact</FormLabel>+ <input type="hidden" name={name} id={name} value={value ?? ""} />+ <Select+ id={name}+ value={controlledValue}+ options={options}+ onChange={handleChange}+ isClearable+ w="full"+ />+ {error && <FormErrorMessage>{error}</FormErrorMessage>}+ </FormControl>+ );+};+export default CreateSupplierModal;diff --git a/apps/carbon/app/modules/users/ui/useUsersSidebar.tsx b/apps/carbon/app/modules/users/ui/useUsersSidebar.tsxindex 687e032ccb..06cac3544e 100644--- a/apps/carbon/app/modules/users/ui/useUsersSidebar.tsx+++ b/apps/carbon/app/modules/users/ui/useUsersSidebar.tsx@@ -1,3 +1,7 @@+import { BsPeopleFill, BsPersonBadge } from "react-icons/bs";+import { GrGroup } from "react-icons/gr";+import { IoGitPullRequestOutline } from "react-icons/io5";+import { PiShareNetworkFill } from "react-icons/pi";import type { RouteGroup } from "~/types";import { path } from "~/utils/path";@@ -8,18 +12,22 @@ const usersRoutes: RouteGroup[] = [{name: "Employees",to: path.to.employeeAccounts,+ icon: <BsPeopleFill />,},{name: "Customers",to: path.to.customerAccounts,+ icon: <IoGitPullRequestOutline />,},{name: "Suppliers",to: path.to.supplierAccounts,+ icon: <PiShareNetworkFill />,},{name: "Groups",to: path.to.groups,+ icon: <GrGroup />,},],},@@ -29,6 +37,7 @@ const usersRoutes: RouteGroup[] = [{name: "Employee Types",to: path.to.employeeTypes,+ icon: <BsPersonBadge />,},],},diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsxindex 6cfc90d1c1..dd70f15fa5 100644--- a/apps/carbon/app/root.tsx+++ b/apps/carbon/app/root.tsx@@ -16,6 +16,7 @@ import {import { Analytics } from "@vercel/analytics/react";import React from "react";import { getBrowserEnv } from "~/config/env";+import Background from "~/styles/background.css";import NProgress from "~/styles/nprogress.css";import Tailwind from "~/styles/tailwind.css";diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsxnew file mode 100644index 0000000000..7642a93fd8--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]avif.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.avif`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/avif" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsxnew file mode 100644index 0000000000..48b3f4be03--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]gif.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.gif`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/gif" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsxnew file mode 100644index 0000000000..2bbfd1e222--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpeg.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.jpeg`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/jpeg" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsxnew file mode 100644index 0000000000..a8e1e85e4e--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]jpg.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.jpg`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/jpeg" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsxnew file mode 100644index 0000000000..59fb26ba56--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]pdf.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.pdf`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "application/pdf" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsxnew file mode 100644index 0000000000..2181efe20b--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]png.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.png`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/png" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsxnew file mode 100644index 0000000000..9626f84c59--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$folder.$path[.]svg.tsx@@ -0,0 +1,22 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";++export let loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client } = await requirePermissions(request, {+ view: "documents",+ });+ const { bucket, folder, path } = params;+ if (!bucket) throw new Error("Could not find bucket");+ if (!path) throw new Error("Could not find path");+ if (!folder) throw new Error("Could not find folder");++ const result = await client.storage+ .from(bucket)+ .download(`${folder}/${path}.svg`);+ if (result.error) {+ throw new Error("Failed to load file");+ }++ const headers = new Headers({ "Content-Type": "image/svg+xml" });+ return new Response(result.data, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/file+/preview+/image.tsx b/apps/carbon/app/routes/file+/preview+/image.tsxnew file mode 100644index 0000000000..93814599bb--- /dev/null+++ b/apps/carbon/app/routes/file+/preview+/image.tsx@@ -0,0 +1,39 @@+import { type LoaderFunctionArgs } from "@remix-run/node";+import { requirePermissions } from "~/services/auth";+import { path } from "~/utils/path";++// this route exists so we can apply some styles to the preview iframe+export let loader = async ({ request }: LoaderFunctionArgs) => {+ await requirePermissions(request, {+ view: "documents",+ });+ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const file = searchParams.get("file");+ if (!file) throw new Error("file not found");++ const body = `+ <!DOCTYPE html>+ <html>+ <head>+ <style>+ html, body{+ height: 100%;+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+ }+ img {+ max-width: 100%;+ height: auto;+ }+ </style>+ </head>+ <body>+ <img src=${path.to.file.previewFile(file)} />+ </body>+ </html>`;+ const headers = new Headers({ "Content-Type": "text/html" });+ return new Response(body, { status: 200, headers });+};diff --git a/apps/carbon/app/routes/onboarding+/_layout.tsx b/apps/carbon/app/routes/onboarding+/_layout.tsxindex 57b9c192f8..61b285105d 100644--- a/apps/carbon/app/routes/onboarding+/_layout.tsx+++ b/apps/carbon/app/routes/onboarding+/_layout.tsx@@ -1,4 +1,4 @@-import { HStack, IconButton, useColor } from "@carbon/react";+import { ClientOnly, HStack, IconButton, useColor } from "@carbon/react";import { Avatar, Grid, GridItem } from "@chakra-ui/react";import { redirect, type LoaderFunctionArgs } from "@remix-run/node";import { Outlet } from "@remix-run/react";@@ -46,18 +46,21 @@ export async function loader({ request }: LoaderFunctionArgs) {}export default function OnboardingLayout() {- // const { currentIndex, onboardingSteps } = useOnboarding();-return (- <Grid h="100vh" w="100vw" templateColumns="auto 1fr">- <SidebarPlaceholder />- <Grid templateRows="auto 1fr" h="full" w="full">- <TopbarPlaceholder />- <div>- <Outlet />- </div>- </Grid>- </Grid>+ // not sure why we need this ClientOnly, but things break without it+ <ClientOnly fallback={null}>+ {() => (+ <Grid h="100vh" w="100vw" templateColumns="auto 1fr">+ <SidebarPlaceholder />+ <Grid templateRows="auto 1fr" h="full" w="full">+ <TopbarPlaceholder />+ <div>+ <Outlet />+ </div>+ </Grid>+ </Grid>+ )}+ </ClientOnly>);}diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsxindex 1ea7ce8541..ad7fd7d172 100644--- a/apps/carbon/app/routes/onboarding+/company.tsx+++ b/apps/carbon/app/routes/onboarding+/company.tsx@@ -1,13 +1,15 @@-import { HStack, VStack } from "@carbon/react";import {Button,+ HStack,Modal,ModalBody,ModalContent,+ ModalDescription,ModalFooter,ModalHeader,- ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+ VStack,+} from "@carbon/react";import { getLocalTimeZone } from "@internationalized/date";import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";@@ -130,17 +132,19 @@ export default function OnboardingUser() {};return (- <Modal size="lg" isOpen onClose={() => 0}>- <ModalOverlay />+ <Modal open><ModalContent><ValidatedForm- autoComplete="off"validator={onboardingCompanyValidator}defaultValues={initialValues}method="post">- <ModalHeader>Now let's setup your company</ModalHeader>-+ <ModalHeader>+ <ModalTitle>Now let's setup your company</ModalTitle>+ <ModalDescription>+ You can always change this later+ </ModalDescription>+ </ModalHeader><ModalBody><Hidden name="next" value={next} /><VStack spacing={4}>@@ -158,8 +162,10 @@ export default function OnboardingUser() {variant="solid"isDisabled={!previous}size="md"- disabled- onClick={onPrevious}+ onClick={() => {+ onPrevious?.();+ }}+ tabIndex={-1}>Previous</Button>diff --git a/apps/carbon/app/routes/onboarding+/user.tsx b/apps/carbon/app/routes/onboarding+/user.tsxindex c91bac62e1..8180389ce5 100644--- a/apps/carbon/app/routes/onboarding+/user.tsx+++ b/apps/carbon/app/routes/onboarding+/user.tsx@@ -1,13 +1,14 @@-import { HStack, VStack } from "@carbon/react";import {Button,+ HStack,Modal,ModalBody,ModalContent,ModalFooter,ModalHeader,- ModalOverlay,-} from "@chakra-ui/react";+ ModalTitle,+ VStack,+} from "@carbon/react";import { redirect, type ActionFunctionArgs } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";import { ValidatedForm, validationError } from "remix-validated-form";@@ -100,8 +101,7 @@ export default function OnboardingUser() {}return (- <Modal size="lg" isOpen onClose={() => 0}>- <ModalOverlay />+ <Modal open><ModalContent><ValidatedFormautoComplete="off"@@ -109,8 +109,9 @@ export default function OnboardingUser() {defaultValues={initialValues}method="post">- <ModalHeader>First let's setup your account</ModalHeader>-+ <ModalHeader>+ <ModalTitle>First let's setup your account</ModalTitle>+ </ModalHeader><ModalBody><Hidden name="next" value={next} /><VStack spacing={4}>@@ -120,15 +121,16 @@ export default function OnboardingUser() {<Password autoComplete="off" name="password" label="Password" /></VStack></ModalBody>-<ModalFooter><HStack><Buttonvariant="solid"isDisabled={!previous}size="md"- disabled- onClick={onPrevious}+ onClick={() => {+ onPrevious?.();+ }}+ tabIndex={-1}>Previous</Button>diff --git a/apps/carbon/app/routes/x+/account+/profile.tsx b/apps/carbon/app/routes/x+/account+/profile.tsxindex b70919abce..305a36e9b4 100644--- a/apps/carbon/app/routes/x+/account+/profile.tsx+++ b/apps/carbon/app/routes/x+/account+/profile.tsx@@ -141,13 +141,15 @@ export default function AccountProfile() {<ProfileForm user={user} /><ProfilePhotoForm user={user} /></Grid>- {attributes.map((category: PublicAttributes) => (- <Box key={category.id} mb={8} w="full">- <SectionTitle title={category.name} />-- <UserAttributesForm attributeCategory={category} />- </Box>- ))}+ {attributes.map((category: PublicAttributes) => {+ console.log(category);+ return (+ <Box key={category.id} mb={8} w="full">+ <SectionTitle>{category.name}</SectionTitle>+ <UserAttributesForm attributeCategory={category} />+ </Box>+ );+ })}</>);}diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsxindex 9c79c7e6e8..9c6ddf7258 100644--- a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx@@ -97,7 +97,7 @@ export default function EditReceiptsRoute() {<ReceiptForm// @ts-ignoreinitialValues={initialValues}- isPosted={!!receipt?.postingDate ?? false}+ status={receipt.status}notes={notes}receiptLines={receiptLines}/>diff --git a/apps/carbon/app/routes/x+/users+/resend-invite.tsx b/apps/carbon/app/routes/x+/users+/resend-invite.tsxindex 715e28d481..b6d2588d22 100644--- a/apps/carbon/app/routes/x+/users+/resend-invite.tsx+++ b/apps/carbon/app/routes/x+/users+/resend-invite.tsx@@ -44,7 +44,7 @@ export async function action({ request }: ActionFunctionArgs) {await userAdminQueue.addBulk(jobs);return json({},- await flash(request, success("Successfully added invites to queue."))+ await flash(request, success("Successfully added invites to queue")));} catch (e) {return json(diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex c328106802..a9f76e2b7c 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -1,4 +1,5 @@import { generatePath } from "@remix-run/react";+import { SUPABASE_API_URL } from "~/config/env";const x = "/x"; // from ~/routes/x+ folderconst api = "/api"; // from ~/routes/api+ folder@@ -42,6 +43,9 @@ export const path = {generatePath(`${api}/resources/work-cells?location=${id}`),},file: {+ previewImage: (bucket: string, path: string) =>+ generatePath(`${file}/preview/image?file=${bucket}/${path}`),+ previewFile: (path: string) => generatePath(`${file}/preview/${path}`),purchaseOrder: (id: string) =>generatePath(`${file}/pdf/purchase-order/${id}`),},@@ -402,3 +406,7 @@ export const onboardingSequence = [path.to.onboarding.user,path.to.onboarding.company,] as const;++export const getStoragePath = (bucket: string, path: string) => {+ return `${SUPABASE_API_URL}/storage/v1/object/public/${bucket}/${path}`;+};diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.mdindex c01294cdf3..0a15f44aa3 100644--- a/packages/database/SCHEMA.md+++ b/packages/database/SCHEMA.md@@ -1,11 +1,11 @@-# Carbon Database Schema+# Carbon Database Schema by `scripts/generate-schema-md.ts` using the migrations in `packages/database/supabase/migrations`.+-This file is generated by `scripts/generate-schema-md.ts` using the migrations in `packages/database/supabase/migrations`.## `xid````sql--- xid is a globally unique id generator functions.+-- xid is a globally unique id generator functions.-- they are 20 characters long and ordered-- https://github.com/modfin/pg-xid@@ -163,6 +163,8 @@ END;$$;```++## `realtime````sql@@ -176,11 +178,13 @@ COMMIT;```++## `claims````sqlCREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"- LANGUAGE "plpgsql"+ LANGUAGE "plpgsql"AS $$BEGINIF session_user = 'authenticator' THEN@@ -192,14 +196,14 @@ CREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"--------------------------------------------IF extract(epoch from now()) > coalesce((current_setting('request.jwt.claims', true)::jsonb)->>'exp', '0')::numeric THENreturn false; -- jwt expired- END IF;+ END IF;IF coalesce((current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->'users_update', 'false')::bool THENreturn true; -- user has user_update set to trueELSEreturn false; -- user does NOT have user_update set to trueEND IF;--------------------------------------------- -- End of block+ -- End of block--------------------------------------------ELSE -- not a user session, probably being called from a trigger or somethingreturn true;@@ -210,13 +214,13 @@ $$;CREATE OR REPLACE FUNCTION get_my_claims() RETURNS "jsonb"LANGUAGE "sql" STABLEAS $$- select+ selectcoalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb -> 'app_metadata', '{}'::jsonb)::jsonb$$;CREATE OR REPLACE FUNCTION get_my_claim(claim TEXT) RETURNS "jsonb"LANGUAGE "sql" STABLEAS $$- select+ selectcoalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb -> 'app_metadata' -> claim, null)$$;@@ -227,7 +231,7 @@ CREATE OR REPLACE FUNCTION get_claims(uid uuid) RETURNS "jsonb"BEGINselect raw_app_meta_data from auth.users into retval where id = uid::uuid;return retval;-+END;$$;@@ -238,7 +242,7 @@ CREATE OR REPLACE FUNCTION get_claim(uid uuid, claim text) RETURNS "jsonb"BEGINselect coalesce(raw_app_meta_data->claim, null) from auth.users into retval where id = uid::uuid;return retval;-+END;$$;@@ -248,9 +252,9 @@ CREATE OR REPLACE FUNCTION set_claim(uid uuid, claim text, value jsonb) RETURNSBEGINIF NOT is_claims_admin() THENRETURN 'error: access denied';- ELSE- update auth.users set raw_app_meta_data =- raw_app_meta_data ||+ ELSE+ update auth.users set raw_app_meta_data =+ raw_app_meta_data ||json_build_object(claim, value)::jsonb where id = uid;return 'OK';END IF;@@ -263,8 +267,8 @@ CREATE OR REPLACE FUNCTION delete_claim(uid uuid, claim text) RETURNS "text"BEGINIF NOT is_claims_admin() THENRETURN 'error: access denied';- ELSE- update auth.users set raw_app_meta_data =+ ELSE+ update auth.users set raw_app_meta_data =raw_app_meta_data - claim where id = uid;return 'OK';END IF;@@ -273,6 +277,8 @@ $$;NOTIFY pgrst, 'reload schema';```++## `users````sql@@ -303,6 +309,8 @@ CREATE POLICY "Anyone that's authenticated can view users" ON "user" FOR SELECT```++## `employee-types````sql@@ -328,6 +336,8 @@ CREATE POLICY "Only claims admin can view/modify permissions for employee types"```++## `permissions````sql@@ -367,6 +377,8 @@ CREATE POLICY "Only claims admin can view/modify permissions for employee types"```++## `employee````sql@@ -387,12 +399,14 @@ CREATE POLICY "Anyone that's authenticated can view employees" ON "employee" FOR```++## `buckets````sqlINSERT INTO storage.buckets (id, name, public)-VALUES- ('public', 'public', true),+VALUES+ ('public', 'public', true),('avatars', 'avatars', true),('private', 'private', false);@@ -451,6 +465,8 @@ ON storage.objects FOR INSERT WITH CHECK ();```++## `attributes````sql@@ -482,55 +498,55 @@ CREATE TABLE "attributeDataType" ("isNumeric" BOOLEAN NOT NULL DEFAULT FALSE,"isText" BOOLEAN NOT NULL DEFAULT FALSE,"isUser" BOOLEAN NOT NULL DEFAULT FALSE,-+CONSTRAINT "userAttributeDataType_singleDataType"CHECK ((- "isBoolean" = true AND- "isDate" = false AND- "isList" = false AND- "isNumeric" = false AND- "isText" = false AND+ "isBoolean" = true AND+ "isDate" = false AND+ "isList" = false AND+ "isNumeric" = false AND+ "isText" = false AND"isUser" = false- )+ )OR (- "isBoolean" = false AND- "isDate" = true AND- "isList" = false AND- "isNumeric" = false AND- "isText" = false AND+ "isBoolean" = false AND+ "isDate" = true AND+ "isList" = false AND+ "isNumeric" = false AND+ "isText" = false AND"isUser" = false- )+ )OR (- "isBoolean" = false AND- "isDate" = false AND- "isList" = true AND- "isNumeric" = false AND- "isText" = false AND+ "isBoolean" = false AND+ "isDate" = false AND+ "isList" = true AND+ "isNumeric" = false AND+ "isText" = false AND"isUser" = false- )+ )OR (- "isBoolean" = false AND- "isDate" = false AND- "isList" = false AND- "isNumeric" = true AND- "isText" = false AND+ "isBoolean" = false AND+ "isDate" = false AND+ "isList" = false AND+ "isNumeric" = true AND+ "isText" = false AND"isUser" = false- )+ )OR (- "isBoolean" = false AND- "isDate" = false AND- "isList" = false AND- "isNumeric" = false AND- "isText" = true AND+ "isBoolean" = false AND+ "isDate" = false AND+ "isList" = false AND+ "isNumeric" = false AND+ "isText" = true AND"isUser" = false- )+ )OR (- "isBoolean" = false AND- "isDate" = false AND- "isList" = false AND- "isNumeric" = false AND- "isText" = false AND+ "isBoolean" = false AND+ "isDate" = false AND+ "isList" = false AND+ "isNumeric" = false AND+ "isText" = false AND"isUser" = true))@@ -584,35 +600,35 @@ CREATE TABLE "userAttributeValue" ("valueNumeric" IS NULL AND"valueText" IS NULL AND"valueUser" IS NULL- )+ )OR ("valueBoolean" IS NULL AND"valueDate" IS NULL AND"valueNumeric" IS NULL AND"valueText" IS NOT NULL AND"valueUser" IS NULL- )+ )OR ("valueBoolean" IS NULL AND"valueDate" IS NOT NULL AND"valueNumeric" IS NULL AND"valueText" IS NULL AND"valueUser" IS NULL- )+ )OR ("valueBoolean" IS NULL AND"valueDate" IS NULL AND"valueNumeric" IS NOT NULL AND"valueText" IS NULL AND"valueUser" IS NULL- )+ )OR ("valueBoolean" IS NULL AND"valueDate" IS NULL AND"valueNumeric" IS NULL AND"valueText" IS NULL AND"valueUser" IS NOT NULL- )+ )),CONSTRAINT "userAttributeValue_userAttributeId_fkey" FOREIGN KEY ("userAttributeId") REFERENCES "userAttribute"("id") ON DELETE CASCADE,@@ -620,7 +636,7 @@ CREATE TABLE "userAttributeValue" (CONSTRAINT "userAttributeValue_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE,CONSTRAINT "userAttributeValue_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "userAttributeValue_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"),- CONSTRAINT uq_userAttributeId_userId+ CONSTRAINT uq_userAttributeId_userIdUNIQUE ( "userAttributeId", "userId"));@@ -629,7 +645,7 @@ CREATE POLICY "Claims admin can view/modify user attribute values" ON "userAttriCREATE POLICY "Users can insert attributes for themselves" ON "userAttributeValue" FOR UPDATE WITH CHECK (auth.uid() = "userId"::uuid);CREATE POLICY "Users can modify attributes for themselves" ON "userAttributeValue" FOR UPDATE WITH CHECK (auth.uid() = "userId"::uuid);CREATE POLICY "Users can view their own attribtues" ON "userAttributeValue" FOR SELECT USING (auth.uid() = "userId"::uuid);-CREATE POLICY "Users can view other users attributes if the category is public" ON "userAttributeValue" FOR SELECT+CREATE POLICY "Users can view other users attributes if the category is public" ON "userAttributeValue" FOR SELECTUSING (auth.role() = 'authenticated' AND"userAttributeValue"."userAttributeId" IN (@@ -640,7 +656,7 @@ CREATE POLICY "Users can view other users attributes if the category is public");-- CREATE TABLE employee_personal_data (--- "id" TEXT NOT NULL DEFAULT xid(),+-- "id" TEXT NOT NULL DEFAULT xid(),-- bank_account_number TEXT,-- bank_routing_number TEXT,-- drivers_license_number TEXT,@@ -671,6 +687,8 @@ CREATE POLICY "Users can view other users attributes if the category is public"-- ALTER TABLE "employee_personal_data" ENABLE ROW LEVEL SECURITY;```++## `suppliers-and-customers````sql@@ -900,6 +918,8 @@ CREATE INDEX "customerAccount_customerId_index" ON "customerAccount"("customerId```++## `groups````sql@@ -914,7 +934,7 @@ CREATE TABLE "group" ("isSupplierOrgGroup" BOOLEAN NOT NULL DEFAULT false,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP WITH TIME ZONE,-+CONSTRAINT "group_pkey" PRIMARY KEY ("id"));@@ -928,14 +948,14 @@ CREATE TABLE "membership" (CONSTRAINT "membership_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "membership_memberGroupId_fkey" FOREIGN KEY ("memberGroupId") REFERENCES "group"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "membership_memberUserId_fkey" FOREIGN KEY ("memberUserId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,-+CONSTRAINT uq_membershipUNIQUE ( "groupId", "memberGroupId", "memberUserId" ),-+CONSTRAINT membership_hasPersonOrGroupCHECK (- ("memberGroupId" IS NULL AND "memberUserId" IS NOT NULL)- OR+ ("memberGroupId" IS NULL AND "memberUserId" IS NOT NULL)+ OR("memberGroupId" IS NOT NULL AND "memberUserId" IS NULL)));@@ -1014,7 +1034,7 @@ CREATE TRIGGER create_employee_type_groupCREATE TRIGGER create_user_identity_groupAFTER INSERT on public.user- FOR EACH ROW EXECUTE PROCEDURE public.create_user_identity_group();+ FOR EACH ROW EXECUTE PROCEDURE public.create_user_identity_group();CREATE TRIGGER add_employee_to_employee_type_groupAFTER INSERT on public.employee@@ -1032,7 +1052,7 @@ CREATE TRIGGER update_employee_type_groupAFTER UPDATE on public."employeeType"FOR EACH ROW EXECUTE PROCEDURE public.update_employee_type_group();-CREATE OR REPLACE VIEW "groupMembers" AS+CREATE OR REPLACE VIEW "groupMembers" ASSELECTgm.id,g.name,@@ -1046,17 +1066,17 @@ CREATE OR REPLACE VIEW "groupMembers" ASgm."memberGroupId",gm."memberUserId",to_jsonb(u) as user- FROM- "membership" gm+ FROM+ "membership" gmINNER JOIN "group" g ON g.id = gm."groupId"LEFT OUTER JOIN (SELECT * FROM "user" WHERE active = TRUE) u ON u.id = gm."memberUserId";+--CREATE RECURSIVE VIEW groups_recursive+CREATE RECURSIVE VIEW groups_recursive(- "groupId",+ "groupId","name","parentId","isIdentityGroup",@@ -1066,12 +1086,12 @@ CREATE RECURSIVE VIEW groups_recursive"isSupplierOrgGroup","isSupplierTypeGroup","user"-) AS- SELECT- "groupId",- "name",- NULL AS "parentId",- "isIdentityGroup",+) AS+ SELECT+ "groupId",+ "name",+ NULL AS "parentId",+ "isIdentityGroup","isEmployeeTypeGroup","isCustomerOrgGroup","isCustomerTypeGroup",@@ -1079,39 +1099,39 @@ CREATE RECURSIVE VIEW groups_recursive"isSupplierTypeGroup","user"FROM "groupMembers"- UNION ALL- SELECT- g2."groupId",- g2.name,- g1."groupId" AS "parentId",- g1."isIdentityGroup",- g2."isEmployeeTypeGroup",+ UNION ALL+ SELECT+ g2."groupId",+ g2.name,+ g1."groupId" AS "parentId",+ g1."isIdentityGroup",+ g2."isEmployeeTypeGroup",g2."isCustomerOrgGroup",g2."isCustomerTypeGroup",g2."isSupplierOrgGroup",g2."isSupplierTypeGroup",g2."user"- FROM "groupMembers" g1+ FROM "groupMembers" g1INNER JOIN "groupMembers" g2 ON g1."memberGroupId" = g2."groupId";CREATE OR REPLACE VIEW "groups" AS- SELECT- "groupId" as "id",+ SELECT+ "groupId" as "id","isEmployeeTypeGroup","isCustomerOrgGroup","isCustomerTypeGroup","isSupplierOrgGroup","isSupplierTypeGroup",- "name",- "parentId",+ "name",+ "parentId",coalesce(jsonb_agg("user") filter (where "user" is not null), '[]') as users- FROM groups_recursive+ FROM groups_recursiveWHERE "isIdentityGroup" = false- GROUP BY- "groupId",- "name",- "parentId",- "isEmployeeTypeGroup",+ GROUP BY+ "groupId",+ "name",+ "parentId",+ "isEmployeeTypeGroup","isCustomerOrgGroup","isCustomerTypeGroup","isSupplierOrgGroup",@@ -1122,7 +1142,7 @@ CREATE OR REPLACE VIEW "groups" ASCREATE OR REPLACE FUNCTION groups_query(_name TEXT DEFAULT '',_uid TEXT DEFAULT NULL-)+)RETURNS TABLE ("id" TEXT,"name" TEXT,@@ -1138,12 +1158,12 @@ AS $$BEGINRETURN QUERYWITH group_ids AS (- SELECT g."id"+ SELECT g."id"FROM "group" gWHERE g."isIdentityGroup" = false- AND g."name" ILIKE '%' || _name || '%'+ AND g."name" ILIKE '%' || _name || '%')- SELECT+ SELECTg."id",g."name",g."parentId",@@ -1163,7 +1183,7 @@ CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = publicAS $$DECLARE retval TEXT[];- BEGIN+ BEGINWITH RECURSIVE "groupsForUser" AS (SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"WHERE "memberUserId" = uid::text@@ -1179,7 +1199,7 @@ CREATE OR REPLACE FUNCTION users_for_groups(groups text[]) RETURNS "jsonb"LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = publicAS $$DECLARE retval jsonb;- BEGIN+ BEGINWITH RECURSIVE "usersForGroups" AS (SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"WHERE "groupId" = ANY(groups)@@ -1376,6 +1396,8 @@ NOTIFY pgrst, 'reload schema';```++## `search````sql@@ -1397,7 +1419,7 @@ ADD COLUMNfts tsvector GENERATED always as (to_tsvector('english', name || ' ' || description)) STORED;CREATE INDEX index_search_uuid ON public.search (uuid);-CREATE INDEX index_search_fts ON public.search USING GIN (fts);+CREATE INDEX index_search_fts ON public.search USING GIN (fts);CREATE FUNCTION public.create_employee_search_result()RETURNS TRIGGER AS $$@@ -1501,8 +1523,8 @@ CREATE POLICY "Employees with sales_view can search for customers and sales orde-- CREATE POLICY "Customers with sales_view can search for their own sales orders" ON "search"-- FOR SELECT-- USING (--- coalesce(get_my_claim('sales_view')::boolean, false) = true--- AND entity = 'Sales Order'+-- coalesce(get_my_claim('sales_view')::boolean, false) = true+-- AND entity = 'Sales Order'-- AND (get_my_claim('role'::text)) = '"customer"'::jsonb-- AND uuid IN (-- SELECT id FROM "salesOrder" WHERE "customerId" IN (@@ -1544,6 +1566,8 @@ CREATE POLICY "Employees with jobs_view can search for jobs" ON "search"-- TODO: customers should be able to search for their jobs```++## `abac````sql@@ -1554,7 +1578,7 @@ ALTER TABLE "contact" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with purchasing_view can view contacts that are suppliers" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ coalesce(get_my_claim('purchasing_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "supplierContact"@@ -1564,7 +1588,7 @@ CREATE POLICY "Employees with purchasing_view can view contacts that are supplieCREATE POLICY "Employees with sales_view can view contacts that are customer" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true+ coalesce(get_my_claim('sales_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "customerContact"@@ -1574,8 +1598,8 @@ CREATE POLICY "Employees with sales_view can view contacts that are customer" ONCREATE POLICY "Suppliers with purchasing_view can view contacts from their organization" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (@@ -1588,8 +1612,8 @@ CREATE POLICY "Suppliers with purchasing_view can view contacts from their organCREATE POLICY "Customers with sales_view can view contacts from their organization" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -1612,8 +1636,8 @@ CREATE POLICY "Many employees can create contact" ON "contact"CREATE POLICY "Suppliers with purchasing_update can create contacts from their organization" ON "contact"FOR INSERTWITH CHECK (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (@@ -1626,8 +1650,8 @@ CREATE POLICY "Suppliers with purchasing_update can create contacts from their oCREATE POLICY "Customers with sales_update can create contacts from their organization" ON "contact"FOR INSERTWITH CHECK (- coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -1640,7 +1664,7 @@ CREATE POLICY "Customers with sales_update can create contacts from their organiCREATE POLICY "Employees with purchasing_update can update supplier contacts" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ coalesce(get_my_claim('purchasing_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "supplierContact"@@ -1650,8 +1674,8 @@ CREATE POLICY "Employees with purchasing_update can update supplier contacts" ONCREATE POLICY "Suppliers with purchasing_update can update contacts from their organization" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (@@ -1664,7 +1688,7 @@ CREATE POLICY "Suppliers with purchasing_update can update contacts from their oCREATE POLICY "Employees with sales_update can update customer contacts" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ coalesce(get_my_claim('purchasing_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "customerContact"@@ -1674,8 +1698,8 @@ CREATE POLICY "Employees with sales_update can update customer contacts" ON "conCREATE POLICY "Customers with sales_update can update contacts from their organization" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -1688,7 +1712,7 @@ CREATE POLICY "Customers with sales_update can update contacts from their organiCREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON "contact"FOR DELETEUSING (- coalesce(get_my_claim('purchasing_delete')::boolean, false) = true+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "supplierContact"@@ -1698,8 +1722,8 @@ CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ONCREATE POLICY "Suppliers with purchasing_delete can delete contacts from their organization" ON "contact"FOR DELETEUSING (- coalesce(get_my_claim('purchasing_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (@@ -1712,7 +1736,7 @@ CREATE POLICY "Suppliers with purchasing_delete can delete contacts from their oCREATE POLICY "Employees with sales_delete can delete customer contacts" ON "contact"FOR DELETEUSING (- coalesce(get_my_claim('sales_delete')::boolean, false) = true+ coalesce(get_my_claim('sales_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND id IN (SELECT "contactId" FROM "customerContact"@@ -1722,8 +1746,8 @@ CREATE POLICY "Employees with sales_delete can delete customer contacts" ON "conCREATE POLICY "Customers with sales_delete can delete contacts from their organization" ON "contact"FOR DELETEUSING (- coalesce(get_my_claim('sales_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -1764,8 +1788,8 @@ CREATE POLICY "Employees with sales_view can view customer" ON "customer"CREATE POLICY "Customers with sales_view can their own organization" ON "customer"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND id IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -1782,8 +1806,8 @@ CREATE POLICY "Employees with sales_update can update customers" ON "customer"CREATE POLICY "Customers with sales_update can their own organization" ON "customer"FOR UPDATEUSING (- coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND id IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -1804,8 +1828,8 @@ CREATE POLICY "Employees with sales_view can view customer contact" ON "customerCREATE POLICY "Customers with sales_view can their own customer contacts" ON "customerContact"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -1817,8 +1841,8 @@ CREATE POLICY "Employees with sales_create can create customer contacts" ON "cusCREATE POLICY "Customers with sales_create can create customer contacts" ON "customerContact"FOR INSERT- WITH CHECK (coalesce(get_my_claim('sales_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ WITH CHECK (coalesce(get_my_claim('sales_create')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -1830,8 +1854,8 @@ CREATE POLICY "Employees with sales_update can update customer contacts" ON "cusCREATE POLICY "Customers with sales_update can update their customer contacts" ON "customerContact"FOR UPDATE- USING (coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ USING (coalesce(get_my_claim('sales_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonbAND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -1872,8 +1896,8 @@ CREATE POLICY "Employees with purchasing_view can view supplier" ON "supplier"CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "supplier"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND id IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -1890,8 +1914,8 @@ CREATE POLICY "Employees with purchasing_update can update suppliers" ON "suppliCREATE POLICY "Suppliers with purchasing_update can their own organization" ON "supplier"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND id IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -1912,8 +1936,8 @@ CREATE POLICY "Employees with purchasing_view can view supplier contact" ON "supCREATE POLICY "Suppliers with purchasing_view can their own supplier contacts" ON "supplierContact"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -1925,8 +1949,8 @@ CREATE POLICY "Employees with purchasing_create can create supplier contacts" ONCREATE POLICY "Suppliers with purchasing_create can create supplier contacts" ON "supplierContact"FOR INSERT- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -1938,8 +1962,8 @@ CREATE POLICY "Employees with purchasing_update can update supplier contacts" ONCREATE POLICY "Suppliers with purchasing_update can update their supplier contacts" ON "supplierContact"FOR UPDATE- USING (coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ USING (coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -1952,6 +1976,8 @@ CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON```++## `notes````sql@@ -1981,7 +2007,7 @@ CREATE POLICY "Employees can view notes" ON "note"CREATE POLICY "Employees can insert notes" ON "note"FOR INSERT- WITH CHECK (+ WITH CHECK ((get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2001,6 +2027,8 @@ CREATE POLICY "Employees can delete their own notes" ON "note"```++## `abilities````sql@@ -2025,28 +2053,28 @@ ALTER TABLE "ability" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with resources_view can view abilities" ON "ability"FOR SELECTUSING (- coalesce(get_my_claim('resources_view')::boolean, false) = true+ coalesce(get_my_claim('resources_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert abilities" ON "ability"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update abilities" ON "ability"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete abilities" ON "ability"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2071,33 +2099,35 @@ ALTER TABLE "employeeAbility" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with resources_view can view employeeAbilities" ON "employeeAbility"FOR SELECTUSING (- coalesce(get_my_claim('resources_view')::boolean, false) = true+ coalesce(get_my_claim('resources_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert employeeAbilities" ON "employeeAbility"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update employeeAbilities" ON "employeeAbility"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete employeeAbilities" ON "employeeAbility"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);```++## `shifts````sql@@ -2126,28 +2156,28 @@ ALTER TABLE "location" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view locations" ON "location"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert locations" ON "location"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update locations" ON "location"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete locations" ON "location"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2166,7 +2196,7 @@ CREATE TABLE "shift" ("friday" BOOLEAN NOT NULL DEFAULT false,"saturday" BOOLEAN NOT NULL DEFAULT false,"active" BOOLEAN NOT NULL DEFAULT true,-+CONSTRAINT "shifts_pkey" PRIMARY KEY ("id"),CONSTRAINT "shifts_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE);@@ -2176,28 +2206,28 @@ ALTER TABLE "shift" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view shifts" ON "shift"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert shifts" ON "shift"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update shifts" ON "shift"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete shifts" ON "shift"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2219,28 +2249,28 @@ ALTER TABLE "employeeShift" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view employee shifts" ON "employeeShift"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert employee shifts" ON "employeeShift"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update employee shifts" ON "employeeShift"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete employee shifts" ON "employeeShift"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2263,39 +2293,41 @@ CREATE TABLE "employeeJob" (CREATE POLICY "Employees can view employee jobs" ON "employeeJob"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert employee jobs" ON "employeeJob"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update employee jobs" ON "employeeJob"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete employee jobs" ON "employeeJob"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);```++## `equipment````sqlCREATE TYPE factor AS ENUM ('Hours/Piece',- 'Hours/100 Pieces',+ 'Hours/100 Pieces','Hours/1000 Pieces','Minutes/Piece','Minutes/100 Pieces',@@ -2327,28 +2359,28 @@ ALTER TABLE "department" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view departments" ON "department"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert departments" ON "department"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update departments" ON "department"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete departments" ON "department"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2376,28 +2408,28 @@ ALTER TABLE "workCellType" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view work cell types" ON "workCellType"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert work cell types" ON "workCellType"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update work cell types" ON "workCellType"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete work cell types" ON "workCellType"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2428,28 +2460,28 @@ ALTER TABLE "workCell" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view work cells" ON "workCell"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert work cells" ON "workCell"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update work cells" ON "workCell"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete work cells" ON "workCell"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2476,28 +2508,28 @@ ALTER TABLE "crew" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view crews" ON "crew"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert crews" ON "crew"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update crews" ON "crew"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete crews" ON "crew"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2517,29 +2549,29 @@ ALTER TABLE "crewAbility" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with resources_view can view crew abilities" ON "crewAbility"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonbAND (get_my_claim('resources_view')::boolean) = true);CREATE POLICY "Employees with resources_create can insert crew abilities" ON "crewAbility"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update crew abilities" ON "crewAbility"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete crew abilities" ON "crewAbility"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2567,28 +2599,28 @@ ALTER TABLE "equipmentType" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view equipment types" ON "equipmentType"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert equipment types" ON "equipmentType"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update equipment types" ON "equipmentType"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete equipment types" ON "equipmentType"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2602,7 +2634,7 @@ CREATE TABLE "equipment" ("locationId" TEXT NOT NULL,"workCellId" TEXT,"active" BOOLEAN NOT NULL DEFAULT true,- "activeDate" DATE,+ "activeDate" DATE DEFAULT CURRENT_DATE,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP NOT NULL DEFAULT now(),"updatedBy" TEXT,@@ -2621,28 +2653,28 @@ ALTER TABLE "equipment" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view equipment" ON "equipment"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert equipment" ON "equipment"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update equipment" ON "equipment"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete equipment" ON "equipment"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2684,6 +2716,8 @@ CREATE TRIGGER update_equipment_search_result```++## `holidays````sql@@ -2710,32 +2744,34 @@ ALTER TABLE "holiday" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view holidays" ON "holiday"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert holidays" ON "holiday"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update holidays" ON "holiday"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete holidays" ON "holiday"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);```++## `partners````sql@@ -2767,21 +2803,21 @@ CREATE TABLE "partnerAbility" ();CREATE OR REPLACE VIEW "partners" AS- SELECT- p.id AS "supplierLocationId",- p."active",- p."hoursPerWeek",- s.id AS "supplierId",- s.name AS "supplierName",+ SELECT+ p.id AS "supplierLocationId",+ p."active",+ p."hoursPerWeek",+ s.id AS "supplierId",+ s.name AS "supplierName",a.city,a.state,array_agg(pa."abilityId") AS "abilityIds"- FROM "partner" p- INNER JOIN "supplierLocation" sl+ FROM "partner" p+ INNER JOIN "supplierLocation" slON sl.id = p.idINNER JOIN "supplier" sON s.id = sl."supplierId"- INNER JOIN "address" a+ INNER JOIN "address" aON a.id = sl."addressId"INNER JOIN "partnerAbility" paON pa."partnerId" = p.id@@ -2790,6 +2826,8 @@ CREATE OR REPLACE VIEW "partners" AS;```++## `contractors````sql@@ -2813,28 +2851,28 @@ ALTER TABLE "contractor" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with resources_view can view contractors" ON "contractor"FOR SELECTUSING (- coalesce(get_my_claim('resources_view')::boolean, false) = true+ coalesce(get_my_claim('resources_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert contractors" ON "contractor"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update contractors" ON "contractor"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete contractors" ON "contractor"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -2856,49 +2894,49 @@ ALTER TABLE "contractorAbility" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with resources_view can view contractorAbilities" ON "contractorAbility"FOR SELECTUSING (- coalesce(get_my_claim('resources_view')::boolean, false) = true+ coalesce(get_my_claim('resources_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_create can insert contractorAbilities" ON "contractorAbility"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update contractorAbilities" ON "contractorAbility"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ coalesce(get_my_claim('resources_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete contractorAbilities" ON "contractorAbility"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ coalesce(get_my_claim('resources_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE OR REPLACE VIEW "contractors" AS- SELECT- p.id AS "supplierContactId",- p."active",- p."hoursPerWeek",- s.id AS "supplierId",- s.name AS "supplierName",+ SELECT+ p.id AS "supplierContactId",+ p."active",+ p."hoursPerWeek",+ s.id AS "supplierId",+ s.name AS "supplierName",c."firstName",c."lastName",c."email",array_agg(pa."abilityId") AS "abilityIds"- FROM "contractor" p- INNER JOIN "supplierContact" sc+ FROM "contractor" p+ INNER JOIN "supplierContact" scON sc.id = p.idINNER JOIN "supplier" sON s.id = sc."supplierId"- INNER JOIN "contact" c+ INNER JOIN "contact" cON c.id = sc."contactId"LEFT JOIN "contractorAbility" paON pa."contractorId" = p.id@@ -2907,6 +2945,8 @@ CREATE OR REPLACE VIEW "contractors" AS;```++## `accounts````sql@@ -2937,27 +2977,27 @@ ALTER TABLE "currency" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Authenticated users can view currencies" ON "currency"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated');CREATE POLICY "Employees with accounting_create can insert currencies" ON "currency"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update currencies" ON "currency"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_delete can delete currencies" ON "currency"FOR DELETEUSING (- coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3024,29 +3064,29 @@ ALTER TABLE "accountCategory" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view account categories" ON "accountCategory"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true+ coalesce(get_my_claim('accounting_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert account categories" ON "accountCategory"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update account categories" ON "accountCategory"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_delete can delete account categories" ON "accountCategory"FOR DELETEUSING (- coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3080,29 +3120,29 @@ ALTER TABLE "accountSubcategory" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view account subcategories" ON "accountSubcategory"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true+ coalesce(get_my_claim('accounting_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert account subcategories" ON "accountSubcategory"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update account subcategories" ON "accountSubcategory"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_delete can delete account subcategories" ON "accountSubcategory"FOR DELETEUSING (- coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3152,26 +3192,26 @@ CREATE POLICY "Certain employees can view accounts" ON "account")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert accounts" ON "account"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update accounts" ON "account"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_delete can delete accounts" ON "account"FOR DELETEUSING (- coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3190,7 +3230,7 @@ CREATE OR REPLACE VIEW "accountCategories" AS;CREATE OR REPLACE VIEW "accounts" AS- SELECT+ SELECT"id","number","name",@@ -3212,6 +3252,8 @@ CREATE OR REPLACE VIEW "accounts" AS;```++## `parts````sql@@ -3236,29 +3278,29 @@ ALTER TABLE "partGroup" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with parts can view part groups" ON "partGroup"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean, false) = true+ coalesce(get_my_claim('parts_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with parts_create can insert part groups" ON "partGroup"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part groups" ON "partGroup"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete part groups" ON "partGroup"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3319,26 +3361,26 @@ CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"USING (auth.role() = 'authenticated');-+CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3389,22 +3431,22 @@ CREATE POLICY "Employees can view parts" ON "part"CREATE POLICY "Employees with parts_create can insert parts" ON "part"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update parts" ON "part"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete parts" ON "part"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3433,7 +3475,7 @@ BEGININSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")-- TODO: get default currencyVALUES (new.id, 'USD', new."createdBy");-+RETURN new;END;$$ LANGUAGE plpgsql SECURITY DEFINER;@@ -3481,14 +3523,14 @@ ALTER TABLE "partCost" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with part_view can view part costs" ON "partCost"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part costs" ON "partCost"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3519,14 +3561,14 @@ ALTER TABLE "partUnitSalePrice" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with part_view can view part sale prices" ON "partUnitSalePrice"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part sale prices" ON "partUnitSalePrice"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3569,28 +3611,28 @@ CREATE POLICY "Employees with part/purchasing_view can view part suppliers" ON "CREATE POLICY "Employees with parts_update can update part suppliers" ON "partSupplier"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_create can create part suppliers" ON "partSupplier"FOR INSERTWITH CHECK (- coalesce(get_my_claim('parts_create')::boolean, false) = true+ coalesce(get_my_claim('parts_create')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "partSupplier"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()@@ -3600,7 +3642,7 @@ CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "partSupplier"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean,false)+ coalesce(get_my_claim('parts_update')::boolean,false)AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()@@ -3625,7 +3667,7 @@ CREATE TABLE "partReplenishment" ("createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,-+CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partReplenishment_preferredSupplierId_fkey" FOREIGN KEY ("preferredSupplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,CONSTRAINT "partReplenishment_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,@@ -3641,14 +3683,14 @@ ALTER TABLE "partReplenishment" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with part_view can view part costs" ON "partReplenishment"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part costs" ON "partReplenishment"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3656,8 +3698,8 @@ CREATE POLICY "Employees with parts_update can update part costs" ON "partReplenCREATE POLICY "Suppliers with parts can view parts they created or supply" ON "part"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND ("createdBy" = auth.uid()::textOR (@@ -3665,22 +3707,22 @@ CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "pSELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )- )+ )+ )));CREATE POLICY "Supliers with parts_create can insert parts" ON "part"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"supplier"'::jsonb);CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "part"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND ("createdBy" = auth.uid()::text@@ -3689,15 +3731,15 @@ CREATE POLICY "Suppliers with parts_update can update parts that they created orSELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )- )+ )+ )));CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "part"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND ("createdBy" = auth.uid()::text@@ -3706,64 +3748,64 @@ CREATE POLICY "Suppliers with parts_delete can delete parts that they created orSELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )- )- )+ )+ )+ ));CREATE POLICY "Suppliers with parts can view part costs they supply" ON "partCost"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND ("partId" IN (SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )+ )));CREATE POLICY "Suppliers with parts_update can update parts costs that they supply" ON "partCost"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND ("partId" IN (SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )+ )));CREATE POLICY "Suppliers with parts can view part replenishments they supply" ON "partReplenishment"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND ("partId" IN (SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )+ )));CREATE POLICY "Suppliers with parts_update can update parts replenishments that they supply" ON "partReplenishment"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonbAND ("partId" IN (SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())- )+ )));@@ -3816,26 +3858,26 @@ CREATE POLICY "Authenticated users can view shelves" ON "shelf"USING (auth.role() = 'authenticated');-+CREATE POLICY "Employees with parts_create can insert shelves" ON "shelf"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update shelves" ON "shelf"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3875,7 +3917,7 @@ ALTER TABLE "partPlanning" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with parts can view part planning" ON "partPlanning"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3883,14 +3925,14 @@ CREATE POLICY "Employees with parts can view part planning" ON "partPlanning"CREATE POLICY "Employees with parts can insert part planning" ON "partPlanning"FOR INSERTWITH CHECK (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part planning" ON "partPlanning"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3920,7 +3962,7 @@ ALTER TABLE "partInventory" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with part_view can view part planning" ON "partInventory"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3928,14 +3970,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "partInventorCREATE POLICY "Employees with part_view can insert part planning" ON "partInventory"FOR INSERTWITH CHECK (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update part planning" ON "partInventory"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -3945,6 +3987,8 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partInv```++## `services````sql@@ -3985,22 +4029,22 @@ CREATE POLICY "Employees can view services" ON "service"CREATE POLICY "Employees with parts_create can insert services" ON "service"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_update can update services" ON "service"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete services" ON "service"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -4041,28 +4085,28 @@ CREATE POLICY "Employees with part/purchasing_view can view service suppliers" OCREATE POLICY "Employees with parts_update can update service suppliers" ON "serviceSupplier"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean, false) = true+ coalesce(get_my_claim('parts_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_create can create service suppliers" ON "serviceSupplier"FOR INSERTWITH CHECK (- coalesce(get_my_claim('parts_create')::boolean, false) = true+ coalesce(get_my_claim('parts_create')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts_delete can delete service suppliers" ON "serviceSupplier"FOR DELETEUSING (- coalesce(get_my_claim('parts_delete')::boolean, false) = true+ coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "serviceSupplier"FOR SELECTUSING (- coalesce(get_my_claim('parts_view')::boolean,false)+ coalesce(get_my_claim('parts_view')::boolean,false)AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()@@ -4072,7 +4116,7 @@ CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "serviceSupplier"FOR UPDATEUSING (- coalesce(get_my_claim('parts_update')::boolean,false)+ coalesce(get_my_claim('parts_update')::boolean,false)AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()@@ -4102,6 +4146,8 @@ CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) ASs.active;```++## `documents````sql@@ -4121,7 +4167,7 @@ CREATE TABLE "document" ("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);@@ -4130,31 +4176,31 @@ CREATE INDEX "document_visibility_idx" ON "document" USING GIN ("readGroups", "wALTER TABLE "document" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Users with documents can view documents where they are in the readGroups" ON "document"+CREATE POLICY "Users with documents can view documents where they are in the readGroups" ON "document"FOR SELECT USING (- coalesce(get_my_claim('documents_view')::boolean, false) = true+ coalesce(get_my_claim('documents_view')::boolean, false) = trueAND (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"+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+ coalesce(get_my_claim('documents_create')::boolean, false) = trueAND (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+ coalesce(get_my_claim('documents_update')::boolean, false) = trueAND (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+ coalesce(get_my_claim('documents_delete')::boolean, false) = trueAND (groups_for_user(auth.uid()::text) && "writeGroups") = true);-CREATE POLICY "Private buckets view requires ownership or document.readGroups" ON storage.objects+CREATE POLICY "Private buckets view requires ownership or document.readGroups" ON storage.objectsFOR SELECT USING (bucket_id = 'private'AND (auth.role() = 'authenticated')@@ -4167,7 +4213,7 @@ FOR SELECT USING ());-CREATE POLICY "Private buckets insert requires ownership or document.writeGroups" ON storage.objects+CREATE POLICY "Private buckets insert requires ownership or document.writeGroups" ON storage.objectsFOR INSERT WITH CHECK (bucket_id = 'private'AND (auth.role() = 'authenticated')@@ -4180,7 +4226,7 @@ FOR INSERT WITH CHECK ());-CREATE POLICY "Private buckets update requires ownership or document.writeGroups" ON storage.objects+CREATE POLICY "Private buckets update requires ownership or document.writeGroups" ON storage.objectsFOR UPDATE USING (bucket_id = 'private'AND (auth.role() = 'authenticated')@@ -4193,7 +4239,7 @@ FOR UPDATE USING ());-CREATE POLICY "Private buckets delete requires ownership or document.writeGroups" ON storage.objects+CREATE POLICY "Private buckets delete requires ownership or document.writeGroups" ON storage.objectsFOR DELETE USING (bucket_id = 'private'AND (auth.role() = 'authenticated')@@ -4244,12 +4290,12 @@ CREATE INDEX "documentFavorites_documentId_idx" ON "documentFavorite" ("documentALTER TABLE "documentFavorite" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Users can view their own document favorites" ON "documentFavorite"+CREATE POLICY "Users can view their own document favorites" ON "documentFavorite"FOR SELECT USING (auth.uid()::text = "userId");-CREATE POLICY "Users can create their own document favorites" ON "documentFavorite"+CREATE POLICY "Users can create their own document favorites" ON "documentFavorite"FOR INSERT WITH CHECK (auth.uid()::text = "userId");@@ -4257,7 +4303,7 @@ CREATE POLICY "Users can create their own document favorites" ON "documentFavoriCREATE POLICY "Users can delete their own document favorites" ON "documentFavorite"FOR DELETE USING (auth.uid()::text = "userId"- );+ );CREATE TABLE "documentLabel" ("documentId" TEXT NOT NULL,@@ -4275,12 +4321,12 @@ 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"+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"+CREATE POLICY "Users can create their own labels" ON "documentLabel"FOR INSERT WITH CHECK (auth.uid()::text = "userId");@@ -4288,7 +4334,7 @@ CREATE POLICY "Users can create their own labels" ON "documentLabel"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 $$@@ -4324,7 +4370,7 @@ CREATE OR REPLACE VIEW "documentLabels" AS"userId"FROM "documentLabel";-CREATE OR REPLACE VIEW "documents" AS+CREATE OR REPLACE VIEW "documents" ASSELECTd.id,d.path,@@ -4352,6 +4398,8 @@ CREATE OR REPLACE VIEW "documents" AS```++## `purchasing````sql@@ -4394,29 +4442,29 @@ CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert payment terms" ON "paymentTerm"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update payment terms" ON "paymentTerm"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_delete can delete payment terms" ON "paymentTerm"FOR DELETEUSING (- coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE TYPE "shippingCarrier" AS ENUM ('UPS',@@ -4460,26 +4508,26 @@ CREATE POLICY "Certain employees can view shipping methods" ON "shippingMethod")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with inventory_create can insert shipping methods" ON "shippingMethod"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('inventory_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('inventory_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_update can update shipping methods" ON "shippingMethod"FOR UPDATEUSING (- coalesce(get_my_claim('inventory_update')::boolean, false) = true+ coalesce(get_my_claim('inventory_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_delete can delete shipping methods" ON "shippingMethod"FOR DELETEUSING (- coalesce(get_my_claim('inventory_delete')::boolean, false) = true+ coalesce(get_my_claim('inventory_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -4500,7 +4548,7 @@ CREATE TABLE "shippingTerm" (CREATE TYPE "purchaseOrderType" AS ENUM (- 'Purchase',+ 'Purchase','Return');@@ -4605,35 +4653,35 @@ CREATE TABLE "purchaseOrderLine" ("accountNumber" IS NULL AND"assetId" IS NULL AND"description" IS NOT NULL- )+ )OR ("purchaseOrderLineType" = 'G/L Account' AND"partId" IS NULL AND"serviceId" IS NULL AND"accountNumber" IS NOT NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("purchaseOrderLineType" = 'Part' AND"partId" IS NOT NULL AND"serviceId" IS NULL AND"accountNumber" IS NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("purchaseOrderLineType" = 'Service' AND"partId" IS NULL AND"serviceId" IS NOT NULL AND"accountNumber" IS NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("purchaseOrderLineType" = 'Fixed Asset' AND"partId" IS NULL AND"serviceId" IS NULL AND"accountNumber" IS NULL AND- "assetId" IS NOT NULL- )+ "assetId" IS NOT NULL+ )),CONSTRAINT "purchaseOrderLine_pkey" PRIMARY KEY ("id"),@@ -4736,12 +4784,12 @@ CREATE INDEX "purchaseOrderFavorites_purchaseOrderId_idx" ON "purchaseOrderFavorALTER TABLE "purchaseOrderFavorite" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Users can view their own purchase order favorites" ON "purchaseOrderFavorite"+CREATE POLICY "Users can view their own purchase order favorites" ON "purchaseOrderFavorite"FOR SELECT USING (auth.uid()::text = "userId");-CREATE POLICY "Users can create their own purchase order favorites" ON "purchaseOrderFavorite"+CREATE POLICY "Users can create their own purchase order favorites" ON "purchaseOrderFavorite"FOR INSERT WITH CHECK (auth.uid()::text = "userId");@@ -4749,7 +4797,7 @@ CREATE POLICY "Users can create their own purchase order favorites" ON "purchaseCREATE POLICY "Users can delete their own purchase order favorites" ON "purchaseOrderFavorite"FOR DELETE USING (auth.uid()::text = "userId"- );+ );CREATE OR REPLACE VIEW "purchaseOrders" ASSELECT@@ -4789,16 +4837,18 @@ CREATE OR REPLACE VIEW "purchaseOrderSuppliers" ASs."name"FROM "supplier" sINNER JOIN "purchaseOrder" p ON p."supplierId" = s."id";-+```++## `sequences````sqlCREATE TABLE "sequence" ("id" TEXT GENERATED ALWAYS AS (- CASE WHEN prefix IS NULL AND suffix IS NULL THEN+ CASE WHEN prefix IS NULL AND suffix IS NULL THENrepeat('0', "size")WHEN prefix IS NULL THENrepeat('0', "size") || suffix@@ -4829,17 +4879,19 @@ CREATE TABLE "sequence" (```++## `purchasing-files````sqlINSERT INTO storage.buckets (id, name, public)-VALUES+VALUES('purchasing-internal', 'purchasing-internal', false),('purchasing-external', 'purchasing-external', false);-- Internal purchasing documents-CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects+CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objectsFOR SELECT USING (bucket_id = 'purchasing-internal'AND (auth.role() = 'authenticated')@@ -4847,7 +4899,7 @@ FOR SELECT USING (AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects+CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objectsFOR INSERT WITH CHECK (bucket_id = 'purchasing-internal'AND (auth.role() = 'authenticated')@@ -4855,7 +4907,7 @@ FOR INSERT WITH CHECK (AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects+CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objectsFOR UPDATE USING (bucket_id = 'purchasing-internal'AND (auth.role() = 'authenticated')@@ -4863,7 +4915,7 @@ FOR UPDATE USING (AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects+CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objectsFOR DELETE USING (bucket_id = 'purchasing-internal'AND (auth.role() = 'authenticated')@@ -4873,7 +4925,7 @@ FOR DELETE USING (-- External purchasing documents-CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objects+CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objectsFOR SELECT USING (bucket_id = 'purchasing-external'AND (auth.role() = 'authenticated')@@ -4886,7 +4938,7 @@ FOR SELECT USING ());-CREATE POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects+CREATE POLICY "External purchasing documents insert requires purchasing_view" ON storage.objectsFOR INSERT WITH CHECK (bucket_id = 'purchasing-external'AND (auth.role() = 'authenticated')@@ -4899,7 +4951,7 @@ FOR INSERT WITH CHECK ());-CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objects+CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objectsFOR UPDATE USING (bucket_id = 'purchasing-external'AND (auth.role() = 'authenticated')@@ -4912,7 +4964,7 @@ FOR UPDATE USING ());-CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects+CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objectsFOR DELETE USING (bucket_id = 'purchasing-external'AND (auth.role() = 'authenticated')@@ -4926,6 +4978,8 @@ FOR DELETE USING ();```++## `purchasing-rls````sql@@ -4943,8 +4997,8 @@ CREATE POLICY "Employees with purchasing_view, inventory_view, or invoicing_viewCREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -4962,8 +5016,8 @@ CREATE POLICY "Employees with purchasing_update can update purchase orders" ON "CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" ON "purchaseOrder"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -5007,9 +5061,9 @@ CREATE TRIGGER update_purchase_order_search_resultCREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ coalesce(get_my_claim('purchasing_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"supplier"'::jsonb- AND entity = 'Purchase Order'+ AND entity = 'Purchase Order'AND uuid IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5038,8 +5092,8 @@ CREATE POLICY "Employees with purchasing_view can view purchase order lines" ONCREATE POLICY "Suppliers with purchasing_view can their own purchase order lines" ON "purchaseOrderLine"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "purchaseOrderId" IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5056,8 +5110,8 @@ CREATE POLICY "Employees with purchasing_create can create purchase order lines"CREATE POLICY "Suppliers with purchasing_create can create lines on their own purchase order" ON "purchaseOrderLine"FOR INSERTWITH CHECK (- coalesce(get_my_claim('purchasing_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_create')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "purchaseOrderId" IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5074,8 +5128,8 @@ CREATE POLICY "Employees with purchasing_update can update purchase order lines"CREATE POLICY "Suppliers with purchasing_update can their own purchase order lines" ON "purchaseOrderLine"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "purchaseOrderId" IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5092,8 +5146,8 @@ CREATE POLICY "Employees with purchasing_delete can delete purchase order lines"CREATE POLICY "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "purchaseOrderLine"FOR DELETEUSING (- coalesce(get_my_claim('purchasing_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND "purchaseOrderId" IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5115,8 +5169,8 @@ CREATE POLICY "Employees with purchasing_view can view purchase order deliveriesCREATE POLICY "Suppliers with purchasing_view can their own purchase order deliveries" ON "purchaseOrderDelivery"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND id IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5137,8 +5191,8 @@ CREATE POLICY "Employees with purchasing_update can update purchase order deliveCREATE POLICY "Suppliers with purchasing_update can their own purchase order deliveries" ON "purchaseOrderDelivery"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonbAND id IN (SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (@@ -5175,11 +5229,13 @@ CREATE POLICY "Employees with purchasing_delete can delete purchase order paymen```++## `supplier-view````sql-CREATE OR REPLACE VIEW "suppliers" AS- SELECT+CREATE OR REPLACE VIEW "suppliers" AS+ SELECTs.id,s.name,s."supplierTypeId",@@ -5192,22 +5248,22 @@ CREATE OR REPLACE VIEW "suppliers" ASLEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"LEFT JOIN (- SELECT+ SELECT"supplierId",COUNT(*) AS "count"FROM "purchaseOrder"GROUP BY "supplierId") po ON po."supplierId" = s.idLEFT JOIN (- SELECT+ SELECT"supplierId",COUNT(*) AS "count"FROM "partSupplier"GROUP BY "supplierId") p ON p."supplierId" = s.id;- CREATE OR REPLACE VIEW "customers" AS- SELECT+ CREATE OR REPLACE VIEW "customers" AS+ SELECTc.id,c.name,c."customerTypeId",@@ -5220,7 +5276,7 @@ CREATE OR REPLACE VIEW "suppliers" ASLEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId";-- LEFT JOIN (- -- SELECT+ -- SELECT-- "customerId",-- COUNT(*) AS "count"-- FROM "salesOrder"@@ -5229,10 +5285,12 @@ CREATE OR REPLACE VIEW "suppliers" AS```++## `parts-view````sql-CREATE OR REPLACE VIEW "parts" AS+CREATE OR REPLACE VIEW "parts" ASSELECTp.id,p.name,@@ -5254,10 +5312,12 @@ CREATE OR REPLACE VIEW "parts" ASpg.name,p."replenishmentSystem",p.active;-+```++## `view-rls````sql@@ -5274,6 +5334,8 @@ ALTER VIEW "parts" SET (security_invoker = on);```++## `warehouses````sql@@ -5345,21 +5407,23 @@ ALTER VIEW "parts" SET (security_invoker = on);```++## `ledgers````sqlCREATE TYPE "month" AS ENUM (- 'January',- 'February',- 'March',- 'April',- 'May',- 'June',- 'July',- 'August',- 'September',- 'October',- 'November',+ 'January',+ 'February',+ 'March',+ 'April',+ 'May',+ 'June',+ 'July',+ 'August',+ 'September',+ 'October',+ 'November','December');@@ -5376,7 +5440,7 @@ CREATE TABLE "fiscalYearSettings" ();CREATE TYPE "accountingPeriodStatus" AS ENUM (- 'Inactive',+ 'Inactive','Active');@@ -5417,15 +5481,15 @@ ALTER TABLE "journal" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view journals" ON "journal"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true+ coalesce(get_my_claim('accounting_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert journals" ON "journal"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -5445,7 +5509,7 @@ CREATE TABLE "journalLine" ("description" TEXT,"amount" NUMERIC(19, 4) NOT NULL,"quantity" NUMERIC(12, 4) NOT NULL DEFAULT 1,- "documentType" "journalLineDocumentType",+ "documentType" "journalLineDocumentType","documentId" TEXT,"externalDocumentId" TEXT,"journalLineReference" TEXT NOT NULL,@@ -5464,15 +5528,15 @@ ALTER TABLE "journalLine" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view journal lines" ON "journalLine"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true+ coalesce(get_my_claim('accounting_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with accounting_create can insert journal lines" ON "journalLine"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('accounting_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -5626,7 +5690,7 @@ CREATE TABLE "supplierLedger" (CREATE OR REPLACE FUNCTION "journalLinesByAccountNumber" (from_date DATE DEFAULT (now() - INTERVAL '100 year'),to_date DATE DEFAULT now()-)+)RETURNS TABLE ("number" TEXT,"balance" NUMERIC(19, 4),@@ -5636,7 +5700,7 @@ RETURNS TABLE (AS $$BEGINRETURN QUERY- SELECT+ SELECTa."number",SUM(jl."amount") AS "balance",SUM(CASE WHEN j."postingDate" <= to_date THEN jl."amount" ELSE 0 END) AS "balanceAtDate",@@ -5650,11 +5714,13 @@ $$;+++```-```## `receipts`@@ -5713,28 +5779,28 @@ ALTER TABLE "receipt" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"FOR SELECT- USING (coalesce(get_my_claim('inventory_view')::boolean, false) = true+ USING (coalesce(get_my_claim('inventory_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with inventory_create can insert receipts" ON "receipt"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('inventory_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('inventory_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_update can update receipts" ON "receipt"FOR UPDATEUSING (- coalesce(get_my_claim('inventory_update')::boolean, false) = true+ coalesce(get_my_claim('inventory_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_delete can delete receipts" ON "receipt"FOR DELETEUSING (- coalesce(get_my_claim('inventory_delete')::boolean, false) = true+ coalesce(get_my_claim('inventory_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -5775,29 +5841,29 @@ ALTER TABLE "receiptLine" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with inventory_view can view receipt lines" ON "receiptLine"FOR SELECTUSING (- coalesce(get_my_claim('inventory_view')::boolean, false) = true+ coalesce(get_my_claim('inventory_view')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-+CREATE POLICY "Employees with inventory_create can insert receipt lines" ON "receiptLine"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('inventory_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('inventory_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_update can update receipt lines" ON "receiptLine"FOR UPDATEUSING (- coalesce(get_my_claim('inventory_update')::boolean, false) = true+ coalesce(get_my_claim('inventory_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "receiptLine"FOR DELETEUSING (- coalesce(get_my_claim('inventory_delete')::boolean, false) = true+ coalesce(get_my_claim('inventory_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -5807,6 +5873,8 @@ CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "rec```++## `defaults````sql@@ -5818,6 +5886,8 @@ CREATE OR REPLACE VIEW "userDefaults" ASLEFT JOIN "employeeJob" ej ON ej.id = u.id;```++## `posting-groups````sql@@ -5937,14 +6007,14 @@ ALTER TABLE "accountDefault" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view account defaults" ON "accountDefault"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean,false)+ coalesce(get_my_claim('accounting_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update account defaults" ON "accountDefault"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -5998,14 +6068,14 @@ ALTER TABLE "postingGroupInventory" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view inventory posting groups" ON "postingGroupInventory"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean,false)+ coalesce(get_my_claim('accounting_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update inventory posting groups" ON "postingGroupInventory"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6042,14 +6112,14 @@ ALTER TABLE "postingGroupPurchasing" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with accounting_view can view purchasing posting groups" ON "postingGroupPurchasing"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean,false)+ coalesce(get_my_claim('accounting_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update purchasing posting groups" ON "postingGroupPurchasing"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6083,14 +6153,14 @@ CREATE INDEX "postingGroupSales_partGroupId_customerTypeId_idx" ON "postingGroupCREATE POLICY "Employees with accounting_view can view sales posting groups" ON "postingGroupSales"FOR SELECTUSING (- coalesce(get_my_claim('accounting_view')::boolean,false)+ coalesce(get_my_claim('accounting_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with accounting_update can update sales posting groups" ON "postingGroupSales"FOR UPDATEUSING (- coalesce(get_my_claim('accounting_update')::boolean, false) = true+ coalesce(get_my_claim('accounting_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6252,7 +6322,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",- "payablesAccount",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -6515,11 +6585,13 @@ CREATE TRIGGER create_posting_groups_for_supplier_type```++## `uninvoiced-receipts````sql-CREATE OR REPLACE VIEW "receiptsPostedNotInvoiced" AS- SELECT+CREATE OR REPLACE VIEW "receiptsPostedNotInvoiced" AS+ SELECTr."id",r."receiptId",r."sourceDocument",@@ -6541,7 +6613,7 @@ CREATE OR REPLACE VIEW "receiptsPostedNotInvoiced" ASAND r."sourceDocument" != 'Inbound Transfer'AND r."sourceDocument" != 'Outbound Transfer'- GROUP BY+ GROUP BYr."id",r."receiptId",r."sourceDocument",@@ -6552,7 +6624,7 @@ CREATE OR REPLACE VIEW "receiptsPostedNotInvoiced" ASs."name";;-CREATE OR REPLACE VIEW "totalReceiptsPostedNotInvoiced" AS+CREATE OR REPLACE VIEW "totalReceiptsPostedNotInvoiced" ASSELECT SUM(l."receivedQuantity" * l."unitPrice") AS "total"FROM "receipt" rINNER JOIN "receiptLine" l@@ -6565,54 +6637,58 @@ CREATE OR REPLACE VIEW "totalReceiptsPostedNotInvoiced" ASAND r."sourceDocument" != 'Outbound Transfer';```++## `quantity-on-hand````sql-CREATE OR REPLACE VIEW "partQuantities" AS- SELECT- p."id" AS "partId",+CREATE OR REPLACE VIEW "partQuantities" AS+ SELECT+ p."id" AS "partId",loc."id" AS "locationId",COALESCE(SUM(pl."quantity"), 0) AS "quantityOnHand",COALESCE(pol."quantityToReceive", 0) AS "quantityOnPurchaseOrder",0 AS "quantityOnSalesOrder",0 AS "quantityOnProdOrder",0 AS "quantityAvailable"- FROM "part" p+ FROM "part" pCROSS JOIN "location" locLEFT JOIN "partLedger" plON pl."partId" = p."id" AND pl."locationId" = loc."id"LEFT JOIN (- SELECT+ SELECTpol."partId",pol."locationId",COALESCE(SUM(GREATEST(pol."quantityToReceive", 0)), 0) AS "quantityToReceive"- FROM "purchaseOrderLine" pol- INNER JOIN "purchaseOrder" po+ FROM "purchaseOrderLine" pol+ INNER JOIN "purchaseOrder" poON pol."purchaseOrderId" = po."id"- WHERE po."status" != 'Draft'+ WHERE po."status" != 'Draft'AND po."status" != 'Rejected'AND po."status" != 'Closed'- GROUP BY+ GROUP BYpol."partId",pol."locationId") pol ON pol."partId" = p."id" AND pol."locationId" = loc."id"- GROUP BY- p."id",+ GROUP BY+ p."id",loc."id",pol."quantityToReceive"```++## `accounts-payable````sqlCREATE TYPE "purchaseInvoiceStatus" AS ENUM (- 'Draft',+ 'Draft','Pending','Submitted','Return','Debit Note Issued',- 'Paid',- 'Partially Paid',+ 'Paid',+ 'Partially Paid','Overdue','Voided');@@ -6667,28 +6743,28 @@ ALTER TABLE "purchaseInvoice" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoices" ON "purchaseInvoice"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_create can insert AP invoices" ON "purchaseInvoice"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('invoicing_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('invoicing_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_update can update AP invoices" ON "purchaseInvoice"FOR UPDATEUSING (- coalesce(get_my_claim('invoicing_update')::boolean, false) = true+ coalesce(get_my_claim('invoicing_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_delete can delete AP invoices" ON "purchaseInvoice"FOR DELETEUSING (- coalesce(get_my_claim('invoicing_delete')::boolean, false) = true+ coalesce(get_my_claim('invoicing_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6709,7 +6785,7 @@ ALTER TABLE "purchaseInvoiceStatusHistory" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoices status history" ON "purchaseInvoiceStatusHistory"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6755,35 +6831,35 @@ CREATE TABLE "purchaseInvoiceLine" ("accountNumber" IS NULL AND"assetId" IS NULL AND"description" IS NOT NULL- )+ )OR ("invoiceLineType" = 'G/L Account' AND"partId" IS NULL AND"serviceId" IS NULL AND"accountNumber" IS NOT NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("invoiceLineType" = 'Part' AND"partId" IS NOT NULL AND"serviceId" IS NULL AND"accountNumber" IS NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("invoiceLineType" = 'Service' AND"partId" IS NULL AND"serviceId" IS NOT NULL AND"accountNumber" IS NULL AND- "assetId" IS NULL- )+ "assetId" IS NULL+ )OR ("invoiceLineType" = 'Fixed Asset' AND"partId" IS NULL AND"serviceId" IS NULL AND"accountNumber" IS NULL AND- "assetId" IS NOT NULL- )+ "assetId" IS NOT NULL+ )),CONSTRAINT "purchaseInvoiceLines_pkey" PRIMARY KEY ("id"),@@ -6807,28 +6883,28 @@ ALTER TABLE "purchaseInvoiceLine" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoice lines" ON "purchaseInvoiceLine"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_create can insert AP invoice lines" ON "purchaseInvoiceLine"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('invoicing_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('invoicing_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_update can update AP invoice lines" ON "purchaseInvoiceLine"FOR UPDATEUSING (- coalesce(get_my_claim('invoicing_update')::boolean, false) = true+ coalesce(get_my_claim('invoicing_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_delete can delete AP invoice lines" ON "purchaseInvoiceLine"FOR DELETEUSING (- coalesce(get_my_claim('invoicing_delete')::boolean, false) = true+ coalesce(get_my_claim('invoicing_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6853,7 +6929,7 @@ ALTER TABLE "purchaseInvoicePriceChange" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoice price changes" ON "purchaseInvoicePriceChange"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6913,14 +6989,14 @@ ALTER TABLE "purchasePayment" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP payments" ON "purchasePayment"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with invoicing_create can insert AP payments" ON "purchasePayment"FOR INSERT- WITH CHECK (- coalesce(get_my_claim('invoicing_create')::boolean,false)+ WITH CHECK (+ coalesce(get_my_claim('invoicing_create')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6928,7 +7004,7 @@ CREATE POLICY "Employees with invoicing_update can update AP payments" ON "purchFOR UPDATEUSING ("paymentDate" IS NULL- AND coalesce(get_my_claim('invoicing_update')::boolean, false) = true+ AND coalesce(get_my_claim('invoicing_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6936,7 +7012,7 @@ CREATE POLICY "Employees with invoicing_delete can delete AP payments" ON "purchFOR DELETEUSING ("paymentDate" IS NULL- AND coalesce(get_my_claim('invoicing_delete')::boolean, false) = true+ AND coalesce(get_my_claim('invoicing_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -6955,13 +7031,13 @@ ALTER TABLE "purchaseInvoicePaymentRelation" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoice/payment relations" ON "purchaseInvoicePaymentRelation"FOR SELECTUSING (- coalesce(get_my_claim('invoicing_view')::boolean,false)+ coalesce(get_my_claim('invoicing_view')::boolean,false)AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE OR REPLACE VIEW "purchaseInvoices" AS- SELECT+CREATE OR REPLACE VIEW "purchaseInvoices" AS+ SELECTpi."id",pi."invoiceId",pi."supplierId",@@ -7007,6 +7083,8 @@ CREATE OR REPLACE VIEW "purchaseInvoices" ASALTER VIEW "purchaseInvoices" SET (security_invoker = on);```++## `supplier-details````sql@@ -7021,7 +7099,7 @@ CREATE TABLE "supplierPayment" ("currencyCode" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,"updatedBy" TEXT,-+CONSTRAINT "supplierPayment_pkey" PRIMARY KEY ("supplierId"),CONSTRAINT "supplierPayment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "supplierPayment_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE SET NULL,@@ -7089,6 +7167,8 @@ CREATE TRIGGER create_supplier_entriesFOR EACH ROW EXECUTE PROCEDURE public.create_supplier_entries();```++## `customer-details````sql@@ -7102,7 +7182,7 @@ CREATE TABLE "customerPayment" ("currencyCode" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,"updatedBy" TEXT,-+CONSTRAINT "customerPayment_pkey" PRIMARY KEY ("customerId"),CONSTRAINT "customerPayment_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "customerPayment_invoiceCustomerId_fkey" FOREIGN KEY ("invoiceCustomerId") REFERENCES "customer"("id") ON UPDATE CASCADE ON DELETE SET NULL,@@ -7170,6 +7250,8 @@ CREATE TRIGGER create_customer_entriesFOR EACH ROW EXECUTE PROCEDURE public.create_customer_entries();```++## `company````sql@@ -7189,7 +7271,7 @@ CREATE TABLE "company" ("email" TEXT,"website" TEXT,"updatedBy" TEXT,-+CONSTRAINT "company_pkey" PRIMARY KEY ("id"),-- this is a hack to make sure that this table only ever has one rowCONSTRAINT "accountDefault_id_check" CHECK ("id" = TRUE),@@ -7202,29 +7284,31 @@ ALTER TABLE "company" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Authenticated users can view company" ON "company"FOR SELECTUSING (- auth.role() = 'authenticated'+ auth.role() = 'authenticated');CREATE POLICY "Employees with settings_create can create company" ON "company"FOR INSERTWITH CHECK (- coalesce(get_my_claim('settings_create')::boolean, false) = true+ coalesce(get_my_claim('settings_create')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with settings_update can update company" ON "company"FOR UPDATEUSING (- coalesce(get_my_claim('settings_update')::boolean, false) = true+ coalesce(get_my_claim('settings_update')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);```++## `purchase-order-document````sqlCREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS- SELECT+ SELECTpol.*,po."supplierId" ,p.name AS "partName",@@ -7234,19 +7318,19 @@ CREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) ASs.description AS "serviceDescription",ss."supplierServiceId"FROM "purchaseOrderLine" pol- INNER JOIN "purchaseOrder" po+ INNER JOIN "purchaseOrder" poON po.id = pol."purchaseOrderId"LEFT OUTER JOIN "part" pON p.id = pol."partId"- LEFT OUTER JOIN "partSupplier" ps+ LEFT OUTER JOIN "partSupplier" psON p.id = ps."partId" AND po."supplierId" = ps."supplierId"LEFT OUTER JOIN "service" sON s.id = pol."serviceId"- LEFT OUTER JOIN "serviceSupplier" ss+ LEFT OUTER JOIN "serviceSupplier" ssON s.id = ss."serviceId" AND po."supplierId" = ss."supplierId";CREATE OR REPLACE VIEW "purchaseOrderLocations" WITH(SECURITY_INVOKER=true) AS- SELECT+ SELECTpo.id,s.name AS "supplierName",sa."addressLine1" AS "supplierAddressLine1",@@ -7270,15 +7354,15 @@ CREATE OR REPLACE VIEW "purchaseOrderLocations" WITH(SECURITY_INVOKER=true) ASca."state" AS "customerState",ca."postalCode" AS "customerPostalCode",ca."countryCode" AS "customerCountryCode"- FROM "purchaseOrder" po- LEFT OUTER JOIN "supplier" s+ FROM "purchaseOrder" po+ LEFT OUTER JOIN "supplier" sON s.id = po."supplierId"LEFT OUTER JOIN "supplierLocation" slON sl.id = po."supplierLocationId"LEFT OUTER JOIN "address" saON sa.id = sl."addressId"- INNER JOIN "purchaseOrderDelivery" pod- ON pod.id = po.id+ INNER JOIN "purchaseOrderDelivery" pod+ ON pod.id = po.idLEFT OUTER JOIN "location" dlON dl.id = pod."locationId"LEFT OUTER JOIN "customer" c@@ -7287,7 +7371,8 @@ CREATE OR REPLACE VIEW "purchaseOrderLocations" WITH(SECURITY_INVOKER=true) ASON cl.id = pod."customerLocationId"LEFT OUTER JOIN "address" caON ca.id = cl."addressId";--++```+diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsxindex 1e65f20a86..4f1480bde9 100644--- a/packages/react/src/Button.tsx+++ b/packages/react/src/Button.tsx@@ -116,7 +116,7 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(className,}))}- type={undefined}+ type={asChild ? undefined : props.type ?? "button"}disabled={isDisabled || props.disabled}role={asChild ? undefined : "button"}ref={ref}diff --git a/packages/react/src/HoverCard.tsx b/packages/react/src/HoverCard.tsxnew file mode 100644index 0000000000..c78f07b6e1--- /dev/null+++ b/packages/react/src/HoverCard.tsx@@ -0,0 +1,29 @@+"use client";++import * as HoverCardPrimitive from "@radix-ui/react-hover-card";+import type { ComponentPropsWithoutRef, ElementRef } from "react";+import { forwardRef } from "react";+import { cn } from "~/utils/cn";++const HoverCard = HoverCardPrimitive.Root;++const HoverCardTrigger = HoverCardPrimitive.Trigger;++const HoverCardContent = forwardRef<+ ElementRef<typeof HoverCardPrimitive.Content>,+ ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (+ <HoverCardPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-64 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className+ )}+ {...props}+ />+));+HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;++export { HoverCard, HoverCardContent, HoverCardTrigger };diff --git a/packages/react/src/Modal.tsx b/packages/react/src/Modal.tsxnew file mode 100644index 0000000000..f791b18dd8--- /dev/null+++ b/packages/react/src/Modal.tsx@@ -0,0 +1,133 @@+"use client";++import * as DialogPrimitive from "@radix-ui/react-dialog";+import type {+ ComponentPropsWithoutRef,+ ElementRef,+ HTMLAttributes,+} from "react";+import { forwardRef } from "react";+import { MdClose } from "react-icons/md";++import { cn } from "~/utils/cn";++const Modal = DialogPrimitive.Root;++const ModalTrigger = DialogPrimitive.Trigger;++const ModalPortal = DialogPrimitive.Portal;++const ModalClose = DialogPrimitive.Close;++const ModalOverlay = forwardRef<+ ElementRef<typeof DialogPrimitive.Overlay>,+ ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Overlay+ ref={ref}+ className={cn(+ "fixed inset-0 z-50 bg-black/10 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className+ )}+ {...props}+ />+));+ModalOverlay.displayName = DialogPrimitive.Overlay.displayName;++const ModalContent = forwardRef<+ ElementRef<typeof DialogPrimitive.Content>,+ ComponentPropsWithoutRef<typeof DialogPrimitive.Content>+>(({ className, children, ...props }, ref) => (+ <ModalPortal>+ <ModalOverlay />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",+ className+ )}+ {...props}+ >+ {children}+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">+ <MdClose className="h-4 w-4 text-muted-foreground" />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </ModalPortal>+));+ModalContent.displayName = DialogPrimitive.Content.displayName;++const ModalHeader = ({+ className,+ ...props+}: HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col space-y-1.5 text-center sm:text-left p-1 mb-2",+ className+ )}+ {...props}+ />+);+ModalHeader.displayName = "ModalHeader";++const ModalBody = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (+ <div className={cn(" w-full p-1 pt-0", className)} {...props} />+);+ModalBody.displayName = "ModalBody";++const ModalFooter = ({+ className,+ ...props+}: HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 pt-6",+ className+ )}+ {...props}+ />+);+ModalFooter.displayName = "ModalFooter";++const ModalTitle = forwardRef<+ ElementRef<typeof DialogPrimitive.Title>,+ ComponentPropsWithoutRef<typeof DialogPrimitive.Title>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Title+ ref={ref}+ className={cn(+ "text-xl font-semibold leading-none tracking-tight text-foreground",+ className+ )}+ {...props}+ />+));+ModalTitle.displayName = DialogPrimitive.Title.displayName;++const ModalDescription = forwardRef<+ ElementRef<typeof DialogPrimitive.Description>,+ ComponentPropsWithoutRef<typeof DialogPrimitive.Description>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Description+ ref={ref}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+));+ModalDescription.displayName = DialogPrimitive.Description.displayName;++export {+ Modal,+ ModalBody,+ ModalClose,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalPortal,+ ModalTitle,+ ModalTrigger,+};diff --git a/packages/react/src/Popover.tsx b/packages/react/src/Popover.tsxnew file mode 100644index 0000000000..c97b71be1a--- /dev/null+++ b/packages/react/src/Popover.tsx@@ -0,0 +1,32 @@+"use client";++import * as PopoverPrimitive from "@radix-ui/react-popover";+import type { ComponentPropsWithoutRef, ElementRef } from "react";+import { forwardRef } from "react";++import { cn } from "~/utils/cn";++const Popover = PopoverPrimitive.Root;++const PopoverTrigger = PopoverPrimitive.Trigger;++const PopoverContent = forwardRef<+ ElementRef<typeof PopoverPrimitive.Content>,+ ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-72 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className+ )}+ {...props}+ />+ </PopoverPrimitive.Portal>+));+PopoverContent.displayName = PopoverPrimitive.Content.displayName;++export { Popover, PopoverContent, PopoverTrigger };diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsxindex 3956696935..b7f5afc550 100644--- a/packages/react/src/index.tsx+++ b/packages/react/src/index.tsx@@ -37,9 +37,24 @@ import { File } from "./File";import { HStack } from "./HStack";import { HTML } from "./HTML";import { Heading } from "./Heading";+import { HoverCard, HoverCardContent, HoverCardTrigger } from "./HoverCard";import { IconButton } from "./IconButton";import { Loading } from "./Loading";import { Menubar, MenubarItem, MenubarTrigger } from "./Menubar";+import {+ Modal,+ ModalBody,+ ModalClose,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalPortal,+ ModalTitle,+ ModalTrigger,+} from "./Modal";+import { Popover, PopoverContent, PopoverTrigger } from "./Popover";import type {GroupBase,MultiValue,@@ -106,11 +121,28 @@ export {HStack,HTML,Heading,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,IconButton,Loading,Menubar,MenubarItem,MenubarTrigger,+ Modal,+ ModalBody,+ ModalClose,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalPortal,+ ModalTitle,+ ModalTrigger,+ Popover,+ PopoverContent,+ PopoverTrigger,Select,Status,Submit,