Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Suppliers and Customers (#7)

Brad Barbinf659caa80395
diff --git a/apps/carbon/README.md b/apps/carbon/README.md
new file mode 100644
index 0000000000..b1923908c1
--- /dev/null
+++ b/apps/carbon/README.md
@@ -0,0 +1,36 @@
+# Carbon
+
+ERP Application built with:
+
+- [Remix](https://remix.run)
+- [Chakra UI](https://chakra-ui.com/)
+- [Supabase](https://supabase.com/)
+- [Postgres](https://postgresql.org/)
+- [Redis](https://redis.io)
+- [BullMQ](https://docs.bullmq.io)
+
+## Code Organization
+
+### `app/components`
+
+Reusable react components that are specific to this project (and remix). Shared components should live in `packages/carbon-react` if they don't rely on some application-specific library. For example, the `Table` relies on some remix internals, so it lives in `app/components`, but the `Date` component is framework agnostic, so it lives in `packages/carbon-react`.
+
+### `app/interfaces`
+
+Where screens, modals and drawers live. Divided by module.
+
+### `app/services`
+
+Where backend services that talk to the database/cache live.
+
+### `app/routes`
+
+File-based route definitions using `remix`. This is where the services and interfaces meet. Each route is loaded in parallel for performance, so each route is responsible for defining it's own authorization and data needs. Each route has three parts (none are required):
+
+1. `export async function loader`: The data that the route returns, which can be accessed via `GET` or `useLoaderData` in the component (3)
+2. `export async function action`: The actions (`POST` or `DELETE`) for the route, which can be accessed via http methods or through the `ValidatedForm` component.
+3. `export default function`: The nested react component for the route. This renders inside the `<Outlet/>` component of the parent route.
+
+### `app/queues`
+
+Where async tasks are defined. For example, scheduling calculations or bulk updates to user permissions that could take a long time to run are put into a job queue to run when the resources become available. Under the hood this relies on `@carbon/redis` (to store the jobs) and `~/lib/bullmq` to manage execution.
diff --git a/apps/carbon/app/components/Address/Address.tsx b/apps/carbon/app/components/Address/Address.tsx
new file mode 100644
index 0000000000..8d2bc7cbd4
--- /dev/null
+++ b/apps/carbon/app/components/Address/Address.tsx
@@ -0,0 +1,51 @@
+import { ActionMenu } from "@carbon/react";
+import { Grid, Icon, MenuItem, Text, VStack } from "@chakra-ui/react";
+import { BsPencilSquare, BsPinMapFill } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+
+type AddressProps = {
+ address: {
+ city: string | null;
+ state: string | null;
+ addressLine1: string | null;
+ postalCode: string | null;
+ };
+ onEdit?: () => void;
+ onDelete?: () => void;
+};
+
+const Address = ({ address, onEdit, onDelete }: AddressProps) => {
+ const location = `${address.city ?? ""}, ${address.state ?? ""}`;
+ const addressZip = `${address.addressLine1 ?? ""} ${
+ address.postalCode ?? ""
+ }`;
+ return (
+ <Grid w="full" gridColumnGap={4} gridTemplateColumns="auto 1fr auto">
+ <Icon as={BsPinMapFill} w={8} h={8} />
+ <VStack spacing={0} alignItems="start">
+ <Text fontWeight="bold" noOfLines={1}>
+ {location}
+ </Text>
+ <Text fontSize="sm" color="gray.500" noOfLines={1}>
+ {addressZip}
+ </Text>
+ </VStack>
+ {(onEdit || onDelete) && (
+ <ActionMenu>
+ {onEdit && (
+ <MenuItem icon={<BsPencilSquare />} onClick={onEdit}>
+ Edit Location
+ </MenuItem>
+ )}
+ {onDelete && (
+ <MenuItem icon={<IoMdTrash />} onClick={onDelete}>
+ Delete Location
+ </MenuItem>
+ )}
+ </ActionMenu>
+ )}
+ </Grid>
+ );
+};
+
+export default Address;
diff --git a/apps/carbon/app/components/Address/index.ts b/apps/carbon/app/components/Address/index.ts
new file mode 100644
index 0000000000..0e4aaf6e37
--- /dev/null
+++ b/apps/carbon/app/components/Address/index.ts
@@ -0,0 +1,3 @@
+import Address from "./Address";
+
+export default Address;
diff --git a/apps/carbon/app/components/Contact/Contact.tsx b/apps/carbon/app/components/Contact/Contact.tsx
new file mode 100644
index 0000000000..1bcdbdd149
--- /dev/null
+++ b/apps/carbon/app/components/Contact/Contact.tsx
@@ -0,0 +1,82 @@
+import { ActionMenu } from "@carbon/react";
+import { Avatar, Grid, MenuItem, Text, VStack } from "@chakra-ui/react";
+import { BsPencilSquare, BsShieldLock } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Dot } from "~/components";
+
+type ContactProps = {
+ contact: {
+ firstName: string | null;
+ lastName: string | null;
+ email: string | null;
+ };
+ user?: {
+ id: string;
+ active: boolean | null;
+ } | null;
+ onCreateAccount?: () => void;
+ onEdit?: () => void;
+ onDelete?: () => void;
+};
+
+enum UserStatus {
+ Active,
+ Inactive,
+ None,
+}
+
+const Contact = ({
+ contact,
+ user,
+ onEdit,
+ onDelete,
+ onCreateAccount,
+}: ContactProps) => {
+ const name = `${contact.firstName ?? ""} ${contact.lastName ?? ""}`;
+ const userStatus = user
+ ? user.active
+ ? UserStatus.Active
+ : UserStatus.Inactive
+ : UserStatus.None;
+
+ return (
+ <Grid w="full" gridColumnGap={4} gridTemplateColumns="auto 1fr auto">
+ <Avatar size="sm" name={`${name}`} />
+ <VStack spacing={0} alignItems="start">
+ <Text fontWeight="bold" noOfLines={1}>
+ {name}
+ {userStatus === UserStatus.Active && (
+ <Dot color="green.400" title="Active" />
+ )}
+ {userStatus === UserStatus.Inactive && (
+ <Dot color="red.400" title="Inactive" />
+ )}
+ </Text>
+ <Text fontSize="sm" color="gray.500" noOfLines={1}>
+ {contact.email ?? ""}
+ </Text>
+ </VStack>
+ {(onEdit || onDelete || onCreateAccount) && (
+ <ActionMenu>
+ {onEdit && (
+ <MenuItem icon={<BsPencilSquare />} onClick={onEdit}>
+ Edit Contact
+ </MenuItem>
+ )}
+ {onDelete && (
+ <MenuItem icon={<IoMdTrash />} onClick={onDelete}>
+ Delete Contact
+ </MenuItem>
+ )}
+ {onCreateAccount && (
+ <MenuItem icon={<BsShieldLock />} onClick={onCreateAccount}>
+ Create Account
+ </MenuItem>
+ )}
+ </ActionMenu>
+ )}
+ </Grid>
+ );
+};
+
+export default Contact;
diff --git a/apps/carbon/app/components/Contact/index.ts b/apps/carbon/app/components/Contact/index.ts
new file mode 100644
index 0000000000..8f11a2d04e
--- /dev/null
+++ b/apps/carbon/app/components/Contact/index.ts
@@ -0,0 +1,3 @@
+import Contact from "./Contact";
+
+export default Contact;
diff --git a/apps/carbon/app/components/Dot/Dot.tsx b/apps/carbon/app/components/Dot/Dot.tsx
new file mode 100644
index 0000000000..87aba6ff85
--- /dev/null
+++ b/apps/carbon/app/components/Dot/Dot.tsx
@@ -0,0 +1,26 @@
+import type { BoxProps } from "@chakra-ui/react";
+import { Box } from "@chakra-ui/react";
+
+type DotProps = BoxProps & {
+ color: string;
+ size?: number;
+ title?: string;
+};
+
+const Dot = ({ color, size = 3, title, ...props }: DotProps) => {
+ return (
+ <Box
+ as="span"
+ title={title}
+ display="inline-block"
+ bg={color}
+ borderRadius="full"
+ w={size}
+ h={size}
+ ml={size / 2}
+ {...props}
+ />
+ );
+};
+
+export default Dot;
diff --git a/apps/carbon/app/components/Dot/index.ts b/apps/carbon/app/components/Dot/index.ts
new file mode 100644
index 0000000000..95c3a69d6a
--- /dev/null
+++ b/apps/carbon/app/components/Dot/index.ts
@@ -0,0 +1,3 @@
+import Dot from "./Dot";
+
+export default Dot;
diff --git a/apps/carbon/app/components/Form/Customer.tsx b/apps/carbon/app/components/Form/Customer.tsx
new file mode 100644
index 0000000000..fd7012690e
--- /dev/null
+++ b/apps/carbon/app/components/Form/Customer.tsx
@@ -0,0 +1,87 @@
+import { Select } from "@carbon/react";
+import {
+ Box,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useField } from "remix-validated-form";
+import type { getCustomersList } from "~/services/sales";
+import { mapRowsToOptions } from "~/utils/form";
+import type { SelectProps } from "./Select";
+
+type CustomerSelectProps = Omit<SelectProps, "options">;
+
+const Customer = ({
+ name,
+ label = "Customer",
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder,
+ onChange,
+ ...props
+}: CustomerSelectProps) => {
+ const { getInputProps, error, defaultValue } = useField(name);
+
+ const customerFetcher =
+ useFetcher<Awaited<ReturnType<typeof getCustomersList>>>();
+
+ useEffect(() => {
+ customerFetcher.load("/resource/sales/customers");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = useMemo(
+ () =>
+ mapRowsToOptions({
+ data: customerFetcher.data?.data,
+ value: "id",
+ label: "name",
+ }),
+ [customerFetcher.data]
+ );
+
+ const initialValue = useMemo(
+ () => options.filter((option) => option.value === defaultValue),
+ [defaultValue, options]
+ );
+
+ // TODO: hack for default value
+ return customerFetcher.state !== "loading" ? (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <Select
+ {...getInputProps({
+ // @ts-ignore
+ id: name,
+ })}
+ {...props}
+ defaultValue={initialValue}
+ isReadOnly={isReadOnly}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={onChange ?? undefined}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Select isDisabled isLoading options={[]} />
+ </Box>
+ );
+};
+
+Customer.displayName = "Customer";
+
+export default Customer;
diff --git a/apps/carbon/app/components/Form/CustomerContact.tsx b/apps/carbon/app/components/Form/CustomerContact.tsx
new file mode 100644
index 0000000000..937e1e6edf
--- /dev/null
+++ b/apps/carbon/app/components/Form/CustomerContact.tsx
@@ -0,0 +1,133 @@
+import { Select } from "@carbon/react";
+import {
+ Box,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { CustomerContact as CustomerContactType } from "~/interfaces/Sales/types";
+import type { getCustomerContacts } from "~/services/sales";
+import type { SelectProps } from "./Select";
+
+type CustomerContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ customer?: string;
+ onChange?: (customerContact: CustomerContactType | undefined) => void;
+};
+
+const CustomerContact = ({
+ name,
+ label = "CustomerContact",
+ customer,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Customer Contact",
+ onChange,
+ ...props
+}: CustomerContactSelectProps) => {
+ const initialLoad = useRef(true);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const customerContactFetcher =
+ useFetcher<Awaited<ReturnType<typeof getCustomerContacts>>>();
+
+ useEffect(() => {
+ customerContactFetcher.load(
+ `/resource/sales/customer-contacts?customerId=${customer}`
+ );
+ if (initialLoad.current) {
+ initialLoad.current = false;
+ } else {
+ setValue(undefined);
+ if (onChange) {
+ onChange(undefined);
+ }
+ }
+ // 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;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ if (newValue === undefined) onChange(newValue);
+ const contact = customerContactFetcher.data?.data?.find(
+ (c) => c.id === newValue
+ );
+
+ onChange(contact);
+ }
+ };
+
+ 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]);
+
+ // TODO: hack for default value
+ return customerContactFetcher.state !== "loading" ? (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} id={name} value={value} />
+ <Select
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ w="full"
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ w="full"
+ />
+ </Box>
+ );
+};
+
+CustomerContact.displayName = "CustomerContact";
+
+export default CustomerContact;
diff --git a/apps/carbon/app/components/Form/Phone.tsx b/apps/carbon/app/components/Form/Phone.tsx
new file mode 100644
index 0000000000..6aa5386df1
--- /dev/null
+++ b/apps/carbon/app/components/Form/Phone.tsx
@@ -0,0 +1,40 @@
+import type { InputProps } from "@chakra-ui/react";
+import {
+ FormControl,
+ FormErrorMessage,
+ FormLabel,
+ Input as ChakraInput,
+} from "@chakra-ui/react";
+import { forwardRef } from "react";
+import { useField } from "remix-validated-form";
+
+type FormPhoneProps = InputProps & {
+ name: string;
+ label?: string;
+ isRequired?: boolean;
+};
+
+const Phone = forwardRef<HTMLInputElement, FormPhoneProps>(
+ ({ name, label, isRequired, ...rest }, ref) => {
+ const { getInputProps, error } = useField(name);
+
+ return (
+ <FormControl isInvalid={!!error} isRequired={isRequired}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <ChakraInput
+ ref={ref}
+ {...getInputProps({
+ id: name,
+ ...rest,
+ })}
+ type="tel"
+ />
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ );
+ }
+);
+
+Phone.displayName = "Phone";
+
+export default Phone;
diff --git a/apps/carbon/app/components/Form/Select.tsx b/apps/carbon/app/components/Form/Select.tsx
index c133224933..0f77727503 100644
--- a/apps/carbon/app/components/Form/Select.tsx
+++ b/apps/carbon/app/components/Form/Select.tsx
@@ -1,5 +1,6 @@
import { Select as CarbonSelect } from "@carbon/react";
import {
+ Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -8,7 +9,7 @@ import {
import { useMemo } from "react";
import { useField } from "remix-validated-form";
-type SelectProps = {
+export type SelectProps = {
name: string;
label?: string;
options: { value: string | number; label: string }[];
@@ -36,7 +37,7 @@ const Select = ({
[defaultValue, options]
);
- // hack for default value
+ // TODO: hack for default value
return options.length > 0 ? (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
@@ -60,7 +61,12 @@ const Select = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : null;
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <CarbonSelect isDisabled isLoading={isLoading} options={[]} />
+ </Box>
+ );
};
Select.displayName = "Select";
diff --git a/apps/carbon/app/components/Form/Supplier.tsx b/apps/carbon/app/components/Form/Supplier.tsx
new file mode 100644
index 0000000000..38b263d4e1
--- /dev/null
+++ b/apps/carbon/app/components/Form/Supplier.tsx
@@ -0,0 +1,94 @@
+import { Select } from "@carbon/react";
+import {
+ Box,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useField } from "remix-validated-form";
+import type { getSuppliersList } from "~/services/purchasing";
+import { mapRowsToOptions } from "~/utils/form";
+import type { SelectProps } from "./Select";
+
+type SupplierSelectProps = Omit<SelectProps, "options">;
+
+const Supplier = ({
+ name,
+ label = "Supplier",
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Supplier",
+ onChange,
+ ...props
+}: SupplierSelectProps) => {
+ const { getInputProps, error, defaultValue } = useField(name);
+
+ const supplierFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSuppliersList>>>();
+
+ useEffect(() => {
+ supplierFetcher.load("/resource/purchasing/suppliers");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = useMemo(
+ () =>
+ mapRowsToOptions({
+ data: supplierFetcher.data?.data,
+ value: "id",
+ label: "name",
+ }),
+ [supplierFetcher.data]
+ );
+
+ const initialValue = useMemo(
+ () => options.filter((option) => option.value === defaultValue),
+ [defaultValue, options]
+ );
+
+ // TODO: hack for default value
+ return supplierFetcher.state !== "loading" ? (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <Select
+ {...getInputProps({
+ // @ts-ignore
+ id: name,
+ })}
+ {...props}
+ defaultValue={initialValue}
+ isReadOnly={isReadOnly}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ w="full"
+ // @ts-ignore
+ onChange={onChange ?? undefined}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ // @ts-ignore
+ w="full"
+ />
+ </Box>
+ );
+};
+
+Supplier.displayName = "Supplier";
+
+export default Supplier;
diff --git a/apps/carbon/app/components/Form/SupplierContact.tsx b/apps/carbon/app/components/Form/SupplierContact.tsx
new file mode 100644
index 0000000000..383cff6dda
--- /dev/null
+++ b/apps/carbon/app/components/Form/SupplierContact.tsx
@@ -0,0 +1,133 @@
+import { Select } from "@carbon/react";
+import {
+ Box,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { SupplierContact as SupplierContactType } from "~/interfaces/Purchasing/types";
+import type { getSupplierContacts } from "~/services/purchasing";
+import type { SelectProps } from "./Select";
+
+type SupplierContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ supplier?: string;
+ onChange?: (supplierContact: SupplierContactType | undefined) => void;
+};
+
+const SupplierContact = ({
+ name,
+ label = "SupplierContact",
+ supplier,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Supplier Contact",
+ onChange,
+ ...props
+}: SupplierContactSelectProps) => {
+ const initialLoad = useRef(true);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const supplierContactFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();
+
+ useEffect(() => {
+ supplierContactFetcher.load(
+ `/resource/purchasing/supplier-contacts?supplierId=${supplier}`
+ );
+ if (initialLoad.current) {
+ initialLoad.current = false;
+ } else {
+ setValue(undefined);
+ if (onChange) {
+ onChange(undefined);
+ }
+ }
+ // 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;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ if (newValue === undefined) onChange(newValue);
+ const contact = supplierContactFetcher.data?.data?.find(
+ (c) => c.id === newValue
+ );
+
+ onChange(contact);
+ }
+ };
+
+ 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]);
+
+ // TODO: hack for default value
+ return supplierContactFetcher.state !== "loading" ? (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} id={name} value={value} />
+ <Select
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ w="full"
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ w="full"
+ />
+ </Box>
+ );
+};
+
+SupplierContact.displayName = "SupplierContact";
+
+export default SupplierContact;
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 5cd7d2e035..7fac7dcbed 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -1,14 +1,19 @@
import Array from "./Array";
import Boolean from "./Boolean";
import Color from "./Color";
+import Customer from "./Customer";
+import CustomerContact from "./CustomerContact";
import DatePicker from "./DatePicker";
import Input from "./Input";
import Hidden from "./Hidden";
import Number from "./Number";
import Password from "./Password";
+import Phone from "./Phone";
import Radios from "./Radios";
import Select from "./Select";
import Submit from "./Submit";
+import Supplier from "./Supplier";
+import SupplierContact from "./SupplierContact";
import TextArea from "./Textarea";
import User from "./User";
import Users from "./Users";
@@ -17,14 +22,19 @@ export {
Array,
Boolean,
Color,
+ Customer,
+ CustomerContact,
DatePicker,
Input,
Hidden,
Number,
Password,
+ Phone,
Radios,
Select,
Submit,
+ Supplier,
+ SupplierContact,
TextArea,
User,
Users,
diff --git a/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx
new file mode 100644
index 0000000000..8527376805
--- /dev/null
+++ b/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx
@@ -0,0 +1,61 @@
+import { useColor } from "@carbon/react";
+import { Box, IconButton, Tooltip, useDisclosure } from "@chakra-ui/react";
+import { motion } from "framer-motion";
+import type { PropsWithChildren } from "react";
+import { TbArrowBarLeft, TbArrowBarRight } from "react-icons/tb";
+
+const MotionBox = motion(Box);
+const variants = {
+ visible: {
+ width: "15rem",
+ },
+ hidden: {
+ width: 15,
+ },
+ transition: { duration: 0.5 },
+};
+
+export const CollapsibleSidebar = ({ children }: PropsWithChildren<{}>) => {
+ const sidebar = useDisclosure({
+ defaultIsOpen: true,
+ });
+
+ return (
+ <MotionBox
+ animate={sidebar.isOpen ? "visible" : "hidden"}
+ initial={variants.visible}
+ variants={variants}
+ h="full"
+ bg={useColor("white")}
+ borderRight={1}
+ borderRightColor={useColor("gray.300")}
+ borderRightStyle="solid"
+ position="relative"
+ >
+ <Tooltip label={sidebar.isOpen ? "Collapse" : "Expand"} placement="right">
+ <IconButton
+ onClick={sidebar.onToggle}
+ icon={sidebar.isOpen ? <TbArrowBarLeft /> : <TbArrowBarRight />}
+ aria-label="Toggle sidebar"
+ display="inline-block"
+ borderWidth="1px 1px 1px 0px"
+ borderStyle="solid"
+ borderColor={useColor("gray.200")}
+ position="absolute"
+ pl={2}
+ bottom="60px"
+ color={useColor("gray.700")}
+ right="-32px"
+ left="auto"
+ backgroundColor={useColor("white")}
+ borderRadius="0px 4px 4px 0px"
+ zIndex={3}
+ _hover={{
+ backgroundColor: useColor("white"),
+ }}
+ />
+ </Tooltip>
+ {sidebar.isOpen ? children : null}
+ </MotionBox>
+ );
+};
diff --git a/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx
index 95e353f2e9..42014b5b14 100644
--- a/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsx
@@ -1,22 +1,52 @@
import { useColor } from "@carbon/react";
-import { Box, VStack } from "@chakra-ui/react";
-import type { PropsWithChildren } from "react";
+import { Box, Button, VStack } from "@chakra-ui/react";
+import { Link, useMatches } from "@remix-run/react";
+import type { Route } from "~/types";
+import { CollapsibleSidebar } from "./CollapsibleSidebar";
-const ContentSidebar = ({ children }: PropsWithChildren<{}>) => (
- <Box
- h="full"
- w="15rem"
- bg={useColor("white")}
- borderRight={1}
- borderRightColor={useColor("gray.300")}
- borderRightStyle="solid"
- >
- <VStack h="full" alignItems="start">
- <Box overflowY="auto" w="full" h="full" pb={8}>
- {children}
- </Box>
- </VStack>
- </Box>
-);
+const ContentSidebar = ({ links }: { links: Route[] }) => {
+ const matches = useMatches();
+ const borderColor = useColor("gray.200");
+
+ return (
+ <CollapsibleSidebar>
+ <VStack h="full" alignItems="start">
+ <Box overflowY="auto" w="full" h="full" pb={8}>
+ <VStack spacing={2}>
+ <VStack
+ spacing={1}
+ alignItems="start"
+ borderBottomStyle={"solid"}
+ borderBottomWidth={1}
+ borderBottomColor={borderColor}
+ px={2}
+ py={4}
+ w="full"
+ >
+ {links.map((route) => {
+ const isActive = matches.some((match) =>
+ match.pathname.includes(route.to)
+ );
+ return (
+ <Button
+ key={route.name}
+ as={Link}
+ to={route.to}
+ variant={isActive ? "solid" : "ghost"}
+ fontWeight={isActive ? "bold" : "normal"}
+ justifyContent="start"
+ w="full"
+ >
+ {route.name}
+ </Button>
+ );
+ })}
+ </VStack>
+ </VStack>
+ </Box>
+ </VStack>
+ </CollapsibleSidebar>
+ );
+};
export default ContentSidebar;
diff --git a/apps/carbon/app/components/Layout/Sidebar/GroupContentSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/GroupContentSidebar.tsx
new file mode 100644
index 0000000000..ab558397bf
--- /dev/null
+++ b/apps/carbon/app/components/Layout/Sidebar/GroupContentSidebar.tsx
@@ -0,0 +1,65 @@
+import { useColor } from "@carbon/react";
+import { Box, Button, Text, VStack } from "@chakra-ui/react";
+import { Link, useMatches } from "@remix-run/react";
+import type { Route } from "~/types";
+import { CollapsibleSidebar } from "./CollapsibleSidebar";
+
+const GroupedContentSidebar = ({
+ links,
+}: {
+ links: Record<string, Route[]>[];
+}) => {
+ const matches = useMatches();
+ const borderColor = useColor("gray.200");
+ const labelColor = useColor("gray.500");
+
+ return (
+ <CollapsibleSidebar>
+ <VStack h="full" alignItems="start">
+ <Box overflowY="auto" w="full" h="full" pb={8}>
+ <VStack spacing={2}>
+ {links.map((groups) =>
+ Object.entries(groups).map(([group, routes]) => (
+ <VStack
+ key={group}
+ spacing={1}
+ alignItems="start"
+ borderBottomStyle={"solid"}
+ borderBottomWidth={1}
+ borderBottomColor={borderColor}
+ px={2}
+ py={4}
+ w="full"
+ >
+ <Text color={labelColor} fontSize="sm" pl={3} py={1}>
+ {group}
+ </Text>
+ {routes.map((route) => {
+ const isActive = matches.some((match) =>
+ match.pathname.includes(route.to)
+ );
+ return (
+ <Button
+ key={route.name}
+ as={Link}
+ to={route.to}
+ variant={isActive ? "solid" : "ghost"}
+ fontWeight={isActive ? "bold" : "normal"}
+ justifyContent="start"
+ w="full"
+ >
+ {route.name}
+ </Button>
+ );
+ })}
+ </VStack>
+ ))
+ )}
+ </VStack>
+ </Box>
+ </VStack>
+ </CollapsibleSidebar>
+ );
+};
+
+export default GroupedContentSidebar;
diff --git a/apps/carbon/app/components/Layout/Sidebar/index.ts b/apps/carbon/app/components/Layout/Sidebar/index.ts
index 592b2ac31e..4a60747df2 100644
--- a/apps/carbon/app/components/Layout/Sidebar/index.ts
+++ b/apps/carbon/app/components/Layout/Sidebar/index.ts
@@ -1,5 +1,6 @@
import ContentSidebar from "./ContentSidebar";
+import GroupedContentSidebar from "./GroupContentSidebar";
import IconSidebar from "./IconSidebar";
import MultiTabSidebar from "./MultiTabSidebar";
-export { ContentSidebar, IconSidebar, MultiTabSidebar };
+export { ContentSidebar, GroupedContentSidebar, IconSidebar, MultiTabSidebar };
diff --git a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
index dbdbfbee7f..1e16d3cb7f 100644
--- a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx
@@ -5,12 +5,12 @@ import {
BsCalendar2Week,
BsCartDash,
BsCartPlus,
+ BsPeopleFill,
BsShieldLock,
} from "react-icons/bs";
import { CgProfile } from "react-icons/cg";
import { GoSettings } from "react-icons/go";
import { HiOutlineCube, HiOutlineDocumentDuplicate } from "react-icons/hi";
-import { SiHandshake } from "react-icons/si";
import { usePermissions } from "~/hooks";
const sidebarItems: Authenticated<NavItem>[] = [
@@ -45,9 +45,9 @@ const sidebarItems: Authenticated<NavItem>[] = [
icon: <AiOutlineFieldTime />,
},
{
- permission: "orders",
- name: "Orders",
- to: "/app/orders",
+ permission: "sales",
+ name: "Sales",
+ to: "/app/sales",
icon: <BsCartPlus />,
},
{
@@ -69,10 +69,10 @@ const sidebarItems: Authenticated<NavItem>[] = [
icon: <BiMessage />,
},
{
- permission: "partners",
- name: "Partners",
- to: "/app/partners",
- icon: <SiHandshake />,
+ permission: "people",
+ name: "People",
+ to: "/app/people",
+ icon: <BsPeopleFill />,
},
{
permission: "users",
diff --git a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
index 43517138a3..a5ac466dc2 100644
--- a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
@@ -32,9 +32,7 @@ const Topbar = () => {
colorScheme="gray"
leftIcon={<FaSearch />}
variant="outline"
- border={1}
- borderColor={borderColor}
- borderStyle="solid"
+ boxShadow="sm"
color="gray.500"
w={200}
mt={2}
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index cf52c3f4cf..862e1a89f9 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -49,6 +49,36 @@ export default function useBreadcrumbs(): Route[] {
name: "Parts",
to: match.pathname,
});
+ case "routes/app.purchasing":
+ return acc.concat({
+ name: "Purchasing",
+ to: match.pathname,
+ });
+ case "routes/app.purchasing.suppliers":
+ return acc.concat({
+ name: "Suppliers",
+ to: match.pathname,
+ });
+ case "routes/app.purchasing.supplier-types":
+ return acc.concat({
+ name: "Supplier Types",
+ to: match.pathname,
+ });
+ case "routes/app.sales":
+ return acc.concat({
+ name: "Sales",
+ to: match.pathname,
+ });
+ case "routes/app.sales.customers":
+ return acc.concat({
+ name: "Customers",
+ to: match.pathname,
+ });
+ case "routes/app.sales.customer-types":
+ return acc.concat({
+ name: "Customer Types",
+ to: match.pathname,
+ });
case "routes/app.users":
return acc.concat({
name: "Users",
diff --git a/apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/DeleteGroupsModal.tsx b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
similarity index 56%
rename from apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/DeleteGroupsModal.tsx
rename to apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
index a50b1c684c..b24e6713cb 100644
--- a/apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/DeleteGroupsModal.tsx
+++ b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
@@ -10,29 +10,36 @@ import {
} from "@chakra-ui/react";
import { Form } from "@remix-run/react";
-type DeleteGroupModalProps = {
- groupId: string;
- data: { id: string; name: string };
+type ConfirmDeleteProps = {
+ action: string;
+ isOpen?: boolean;
+ name: string;
+ text: string;
onCancel: () => void;
+ onSubmit?: () => void;
};
-const DeleteGroupModal = ({ data, onCancel }: DeleteGroupModalProps) => {
+const ConfirmDelete = ({
+ action,
+ isOpen = true,
+ name,
+ text,
+ onCancel,
+ onSubmit,
+}: ConfirmDeleteProps) => {
return (
- <Modal isOpen={true} onClose={onCancel}>
+ <Modal isOpen={isOpen} onClose={onCancel}>
<ModalOverlay />
<ModalContent>
- <ModalHeader>Delete {data?.name}</ModalHeader>
+ <ModalHeader>Delete {name}</ModalHeader>
<ModalCloseButton />
- <ModalBody>
- Are you sure you want to delete the group: {data?.name}? This cannot
- be undone.
- </ModalBody>
+ <ModalBody>{text}</ModalBody>
<ModalFooter>
<Button colorScheme="gray" mr={3} onClick={onCancel}>
Cancel
</Button>
- <Form method="post">
+ <Form method="post" action={action} onSubmit={onSubmit}>
<Button colorScheme="red" type="submit">
Delete
</Button>
@@ -43,4 +50,4 @@ const DeleteGroupModal = ({ data, onCancel }: DeleteGroupModalProps) => {
);
};
-export default DeleteGroupModal;
+export default ConfirmDelete;
diff --git a/apps/carbon/app/components/Modals/ConfirmDelete/index.ts b/apps/carbon/app/components/Modals/ConfirmDelete/index.ts
new file mode 100644
index 0000000000..8cf9196823
--- /dev/null
+++ b/apps/carbon/app/components/Modals/ConfirmDelete/index.ts
@@ -0,0 +1,3 @@
+import ConfirmDelete from "./ConfirmDelete";
+
+export default ConfirmDelete;
diff --git a/apps/carbon/app/components/Modals/index.ts b/apps/carbon/app/components/Modals/index.ts
new file mode 100644
index 0000000000..1ae61e532c
--- /dev/null
+++ b/apps/carbon/app/components/Modals/index.ts
@@ -0,0 +1,3 @@
+import ConfirmDelete from "./ConfirmDelete";
+
+export { ConfirmDelete };
diff --git a/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx b/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx
new file mode 100644
index 0000000000..402c21f7a5
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx
@@ -0,0 +1,45 @@
+import { Select, createFilter } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect } from "react";
+import type { getCustomersList } from "~/services/sales";
+import { mapRowsToOptions } from "~/utils/form";
+
+type CustomerSelectProps = {
+ value?: string;
+ onChange?: (
+ newValue: { value: string | number; label: string } | null
+ ) => void;
+};
+
+const CustomerSelect = ({ value, onChange }: CustomerSelectProps) => {
+ const customerFetcher =
+ useFetcher<Awaited<ReturnType<typeof getCustomersList>>>();
+
+ useEffect(() => {
+ customerFetcher.load("/resource/sales/customers");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = mapRowsToOptions({
+ data: customerFetcher.data?.data,
+ value: "id",
+ label: "name",
+ });
+
+ return (
+ <Select
+ options={options}
+ // Only search the labels (not the values)
+ filterOption={createFilter({
+ matchFrom: "any",
+ stringify: (option) => `${option.label}`,
+ })}
+ isLoading={customerFetcher.state === "loading"}
+ isMulti={false}
+ placeholder="Select customer"
+ onChange={onChange ? (newValue) => onChange(newValue) : undefined}
+ />
+ );
+};
+
+export default CustomerSelect;
diff --git a/apps/carbon/app/components/Selectors/CustomerSelect/index.ts b/apps/carbon/app/components/Selectors/CustomerSelect/index.ts
new file mode 100644
index 0000000000..88dc8b3c9e
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/CustomerSelect/index.ts
@@ -0,0 +1,3 @@
+import CustomerSelect from "./CustomerSelect";
+
+export default CustomerSelect;
diff --git a/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx b/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx
new file mode 100644
index 0000000000..8dc5185238
--- /dev/null
+++ b/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx
@@ -0,0 +1,46 @@
+import { Select, createFilter } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect } from "react";
+import type { getSuppliersList } from "~/services/purchasing";
+import { mapRowsToOptions } from "~/utils/form";
+
+type SupplierSelectProps = {
+ value?: string;
+ onChange?: (
+ newValue: { value: string | number; label: string } | null
+ ) => void;
+};
+
+const SupplierSelect = ({ value, onChange }: SupplierSelectProps) => {
+ const supplierFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSuppliersList>>>();
+
+ useEffect(() => {
+ supplierFetcher.load("/resource/purchasing/suppliers");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = mapRowsToOptions({
+ data: supplierFetcher.data?.data,
+ value: "id",
+ label: "name",
+ });
+
+ return (
+ <Select
+ options={options}
+ // Only search the labels (not the values)
+ filterOption={createFilter({
+ matchFrom: "any",
+ stringify: (option) => `${option.label}`,
+ })}
+ isLoading={supplierFetcher.state === "loading"}
+ isMulti={false}
+ placeholder="Select supplier"
+ onChange={onChange ? (newValue) => onChange(newValue) : undefined}
+ w="full"
+ />
+ );
+};
+
+export default SupplierSelect;
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
index 0f62c475bc..5a9ef84ae9 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
@@ -90,7 +90,7 @@ const SelectionList = () => {
</>
)}
- {canExpand && (
+ {!!canExpand && (
<Tooltip label="Expand">
<IconButton
aria-label={`Expand ${item.label}`}
diff --git a/apps/carbon/app/components/Selectors/index.ts b/apps/carbon/app/components/Selectors/index.ts
index a6719e57fb..9b01910f81 100644
--- a/apps/carbon/app/components/Selectors/index.ts
+++ b/apps/carbon/app/components/Selectors/index.ts
@@ -1,3 +1,4 @@
+import CustomerSelect from "./CustomerSelect";
import UserSelect from "./UserSelect";
-export { UserSelect };
+export { CustomerSelect, UserSelect };
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 8cb148f028..8cc953dd54 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -55,6 +55,8 @@ interface TableProps<T extends object> {
actions?: TableAction<T>[];
count?: number;
colorScheme?: ThemeTypings["colorSchemes"];
+ defaultColumnOrder?: string[];
+ defaultColumnPinning?: ColumnPinningState;
defaultColumnVisibility?: Record<string, boolean>;
editableComponents?: Record<string, EditableTableCellComponent<T>>;
withColumnOrdering?: boolean;
@@ -74,6 +76,10 @@ const Table = <T extends object>({
count = 0,
colorScheme = "blackAlpha",
editableComponents = {},
+ defaultColumnOrder = [],
+ defaultColumnPinning = {
+ left: ["select"],
+ },
defaultColumnVisibility = {},
withFilters = false,
withInlineEditing = false,
@@ -86,30 +92,33 @@ const Table = <T extends object>({
}: TableProps<T>) => {
const tableContainerRef = useRef<HTMLDivElement>(null);
+ /* Data for Optimistic Updates */
const [internalData, setInternalData] = useState<T[]>(data);
useEffect(() => {
setInternalData(data);
}, [data]);
+ /* Seletable Rows */
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
- if (withSelectableRows) columns.unshift(getRowSelectionColumn<T>());
+ /* Pagination */
const pagination = usePagination(count, setRowSelection);
+ /* Column Visibility */
const [columnVisibility, setColumnVisibility] = useState(
defaultColumnVisibility
);
- const { isSorted, toggleSortBy } = useSort();
- const [columnOrder, setColumnOrder] = useState<ColumnOrderState>([]);
+ /* Column Ordering */
+ const [columnOrder, setColumnOrder] =
+ useState<ColumnOrderState>(defaultColumnOrder);
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(
- withColumnOrdering
- ? {
- left: ["select"],
- }
- : {}
+ withColumnOrdering ? defaultColumnPinning : {}
);
+ /* Sorting */
+ const { isSorted, toggleSortBy } = useSort();
+
const columnAccessors = useMemo(
() =>
columns.reduce<Record<string, string>>((acc, column) => {
@@ -131,12 +140,14 @@ const Table = <T extends object>({
const table = useReactTable({
data: internalData,
- columns,
+ columns: withSelectableRows
+ ? getRowSelectionColumn<T>().concat(columns)
+ : columns,
state: {
- rowSelection,
columnVisibility,
columnOrder,
columnPinning,
+ rowSelection,
},
onColumnVisibilityChange: setColumnVisibility,
onColumnOrderChange: setColumnOrder,
@@ -171,6 +182,13 @@ const Table = <T extends object>({
? table.getSelectedRowModel().flatRows.map((row) => row.original)
: [];
+ useEffect(() => {
+ if (typeof onSelectedRowsChange === "function") {
+ onSelectedRowsChange(selectedRows);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [rowSelection, onSelectedRowsChange]);
+
const [editMode, setEditMode] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [selectedCell, setSelectedCell] = useState<Position>(null);
@@ -320,12 +338,13 @@ const Table = <T extends object>({
row: y1,
column: x1,
});
+ // any other key activates editing
+ // if the column is editable and a cell is selected
} else if (
!isEditing &&
selectedCell &&
isColumnEditable(selectedCell.column)
) {
- // any other key activates editing if the column is editable and a cell is selected
setIsEditing(true);
}
},
@@ -357,13 +376,6 @@ const Table = <T extends object>({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- useEffect(() => {
- if (typeof onSelectedRowsChange === "function") {
- onSelectedRowsChange(selectedRows);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [rowSelection, onSelectedRowsChange]);
-
const rows = table.getRowModel().rows;
const rowsAreClickable = !editMode && typeof onRowClick === "function";
@@ -424,7 +436,7 @@ const Table = <T extends object>({
>
<Grid
w="full"
- gridTemplateColumns={withColumnOrdering ? "auto 1fr auto" : "1fr"}
+ gridTemplateColumns={withColumnOrdering ? "auto 1fr" : "1fr"}
>
{/* Pinned left columns */}
{withColumnOrdering ? (
@@ -465,7 +477,7 @@ const Table = <T extends object>({
py={2}
whiteSpace="nowrap"
>
- {header.isPlaceholder ? null : (
+ {!header.isPlaceholder ? null : (
<Flex
justify="flex-start"
align="center"
@@ -519,7 +531,9 @@ const Table = <T extends object>({
onCellClick={onCellClick}
onCellUpdate={onCellEditUpdate}
onRowClick={
- onRowClick ? () => onRowClick(row.original) : undefined
+ rowsAreClickable
+ ? () => onRowClick(row.original)
+ : undefined
}
/>
);
@@ -655,28 +669,31 @@ const Table = <T extends object>({
);
};
-function getRowSelectionColumn<T>(): ColumnDef<T> {
- return {
- id: "select",
- header: ({ table }) => (
- <IndeterminateCheckbox
- {...{
- checked: table.getIsAllRowsSelected(),
- indeterminate: table.getIsSomeRowsSelected(),
- onChange: table.getToggleAllRowsSelectedHandler(),
- }}
- />
- ),
- cell: ({ row }) => (
- <IndeterminateCheckbox
- {...{
- checked: row.getIsSelected(),
- indeterminate: row.getIsSomeSelected(),
- onChange: row.getToggleSelectedHandler(),
- }}
- />
- ),
- };
+function getRowSelectionColumn<T>(): ColumnDef<T>[] {
+ return [
+ {
+ id: "select",
+ size: 40,
+ header: ({ table }) => (
+ <IndeterminateCheckbox
+ {...{
+ checked: table.getIsAllRowsSelected(),
+ indeterminate: table.getIsSomeRowsSelected(),
+ onChange: table.getToggleAllRowsSelectedHandler(),
+ }}
+ />
+ ),
+ cell: ({ row }) => (
+ <IndeterminateCheckbox
+ {...{
+ checked: row.getIsSelected(),
+ indeterminate: row.getIsSomeSelected(),
+ onChange: row.getToggleSelectedHandler(),
+ }}
+ />
+ ),
+ },
+ ];
}
export default Table;
diff --git a/apps/carbon/app/components/Todo/Todo.tsx b/apps/carbon/app/components/Todo/Todo.tsx
deleted file mode 100644
index a7cb92c1f5..0000000000
--- a/apps/carbon/app/components/Todo/Todo.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { Box, Heading, ListItem, UnorderedList } from "@chakra-ui/react";
-
-const Todo = ({ items }: { items: string[] }) => {
- return (
- <Box py={4} px={8}>
- <Heading size="md" py={4}>
- TODO
- </Heading>
- <UnorderedList>
- {items.map((item) => (
- <ListItem key={item}>{item}</ListItem>
- ))}
- </UnorderedList>
- </Box>
- );
-};
-
-export default Todo;
diff --git a/apps/carbon/app/components/Todo/index.ts b/apps/carbon/app/components/Todo/index.ts
deleted file mode 100644
index 5b2fda1a61..0000000000
--- a/apps/carbon/app/components/Todo/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Todo from "./Todo";
-
-export default Todo;
diff --git a/apps/carbon/app/components/index.ts b/apps/carbon/app/components/index.ts
index 3fce9611b7..eb6cb126d2 100644
--- a/apps/carbon/app/components/index.ts
+++ b/apps/carbon/app/components/index.ts
@@ -1,4 +1,7 @@
+import Address from "./Address";
import Avatar from "./Avatar";
+import Contact from "./Contact";
+import Dot from "./Dot";
import Table from "./Table";
-export { Avatar, Table };
+export { Address, Avatar, Contact, Dot, Table };
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/SupplierTypeForm.tsx b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/SupplierTypeForm.tsx
new file mode 100644
index 0000000000..aad292bf89
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/SupplierTypeForm.tsx
@@ -0,0 +1,76 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { Color, Hidden, Input, Submit } from "~/components/Form";
+import { supplierTypeValidator } from "~/services/purchasing";
+
+type SupplierTypeFormProps = {
+ initialValues: {
+ id?: string;
+ name: string;
+ color: string;
+ };
+};
+
+const SupplierTypeForm = ({ initialValues }: SupplierTypeFormProps) => {
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={supplierTypeValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/purchasing/supplier-types/${initialValues.id}`
+ : "/app/purchasing/supplier-types/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Supplier Type
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="name" label="Supplier Type" />
+ <Color name="color" label="Color" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default SupplierTypeForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/index.ts b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/index.ts
new file mode 100644
index 0000000000..17448614fc
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypeForm/index.ts
@@ -0,0 +1,3 @@
+import SupplierTypeForm from "./SupplierTypeForm";
+
+export default SupplierTypeForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx
new file mode 100644
index 0000000000..24d1973acc
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx
@@ -0,0 +1,103 @@
+import { ActionMenu } from "@carbon/react";
+import { Box, Flex, MenuItem, VisuallyHidden } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import { BsPencilSquare, BsPeopleFill } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { SupplierType } from "~/interfaces/Purchasing/types";
+
+type SupplierTypesTableProps = {
+ data: SupplierType[];
+ count: number;
+};
+
+const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Supplier Type",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "color",
+ header: "Color",
+ cell: (item) => (
+ <Box
+ aria-label="Color"
+ w={6}
+ h={6}
+ borderRadius="md"
+ bg={item.getValue() ?? "#000000"}
+ role="img"
+ />
+ ),
+ },
+ {
+ accessorKey: "id",
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ cell: ({ row }) => (
+ <Flex justifyContent="end">
+ <ActionMenu>
+ <MenuItem
+ icon={<BsPeopleFill />}
+ onClick={() => {
+ navigate(`/app/purchasing/suppliers?type=${row.original.id}`);
+ }}
+ >
+ View Suppliers
+ </MenuItem>
+ <MenuItem
+ isDisabled={
+ row.original.protected ||
+ !permissions.can("update", "purchasing")
+ }
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/app/purchasing/supplier-types/${
+ row.original.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Edit Supplier Type
+ </MenuItem>
+ <MenuItem
+ isDisabled={
+ row.original.protected ||
+ !permissions.can("delete", "purchasing")
+ }
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/app/purchasing/supplier-types/delete/${
+ row.original.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Delete Supplier Type
+ </MenuItem>
+ </ActionMenu>
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ return (
+ <Table<typeof data[number]> data={data} columns={columns} count={count} />
+ );
+});
+
+SupplierTypesTable.displayName = "SupplierTypesTable";
+export default SupplierTypesTable;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/index.ts b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/index.ts
new file mode 100644
index 0000000000..2bb37f3f4e
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTable/index.ts
@@ -0,0 +1,3 @@
+import SupplierTypesTable from "./SupplierTypesTable";
+
+export default SupplierTypesTable;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx
new file mode 100644
index 0000000000..164df8bc04
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx
@@ -0,0 +1,46 @@
+import { useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+const SupplierTypesTableFilters = () => {
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Supplier Type
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default SupplierTypesTableFilters;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/index.ts b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/index.ts
new file mode 100644
index 0000000000..551303386f
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/SupplierTypesTableFilters/index.ts
@@ -0,0 +1,3 @@
+import SupplierTypesTableFilters from "./SupplierTypesTableFilters";
+
+export default SupplierTypesTableFilters;
diff --git a/apps/carbon/app/interfaces/Purchasing/SupplierTypes/index.ts b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/index.ts
new file mode 100644
index 0000000000..f0fd2e611b
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/SupplierTypes/index.ts
@@ -0,0 +1,5 @@
+import SupplierTypeForm from "./SupplierTypeForm";
+import SupplierTypesTable from "./SupplierTypesTable";
+import SupplierTypesTableFilters from "./SupplierTypesTableFilters";
+
+export { SupplierTypeForm, SupplierTypesTable, SupplierTypesTableFilters };
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/SupplierForm.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/SupplierForm.tsx
new file mode 100644
index 0000000000..31cd926139
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/SupplierForm.tsx
@@ -0,0 +1,175 @@
+import {
+ Box,
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ FormLabel,
+ Grid,
+ HStack,
+ Skeleton,
+ Stack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Input,
+ Select,
+ Submit,
+ User,
+ TextArea,
+ Hidden,
+} from "~/components/Form";
+import { supplierValidator } from "~/services/purchasing";
+import type {
+ SupplierContact,
+ SupplierLocation,
+ SupplierStatus,
+ SupplierType,
+} from "~/interfaces/Purchasing/types";
+import { mapRowsToOptions } from "~/utils/form";
+import { useRouteData } from "~/hooks";
+import { SupplierContacts, SupplierLocations } from "./components";
+import { IoMdAdd } from "react-icons/io";
+
+type SupplierFormProps = {
+ initialValues: {
+ id?: string;
+ name: string;
+ description?: string;
+ accountManagerId?: string;
+ supplierTypeId?: string;
+ supplierStatusId?: number;
+ taxId?: string;
+ };
+ contacts?: SupplierContact[];
+ locations?: SupplierLocation[];
+};
+
+const SupplierForm = ({
+ initialValues,
+ contacts,
+ locations,
+}: SupplierFormProps) => {
+ const navigate = useNavigate();
+ const onClose = () => navigate("/app/purchasing/suppliers");
+
+ const routeData = useRouteData<{
+ supplierTypes: { data: SupplierType[] };
+ supplierStatuses: { data: SupplierStatus[] };
+ }>("/app/purchasing/suppliers");
+
+ const supplierTypeOptions = routeData?.supplierTypes
+ ? mapRowsToOptions({
+ data: routeData.supplierTypes.data ?? [],
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const supplierStatusOptions = routeData?.supplierStatuses
+ ? mapRowsToOptions({
+ data: routeData.supplierStatuses.data ?? [],
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const isEditing = initialValues.id !== undefined;
+
+ return (
+ <Drawer onClose={onClose} isOpen size="full">
+ <ValidatedForm
+ method="post"
+ action={
+ isEditing
+ ? `/app/purchasing/suppliers/${initialValues.id}`
+ : "/app/purchasing/suppliers/new"
+ }
+ validator={supplierValidator}
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? initialValues.name : "New Supplier"}
+ </DrawerHeader>
+ <DrawerBody>
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
+ gridColumnGap={8}
+ w="full"
+ >
+ <Box w="full">
+ <Hidden name="id" />
+ <VStack spacing={4} w="full" alignItems="start">
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={4}
+ w="full"
+ >
+ <Input name="name" label="Name" />
+ <Input name="taxId" label="Tax ID" />
+ <Select
+ name="supplierTypeId"
+ label="Supplier Type"
+ options={supplierTypeOptions}
+ placeholder="Select Supplier Type"
+ />
+ <User name="accountManagerId" label="Account Manager" />
+ <Select
+ name="supplierStatusId"
+ label="Supplier Status"
+ options={supplierStatusOptions}
+ placeholder="Select Supplier Status"
+ />
+ </Grid>
+
+ <TextArea
+ name="description"
+ label="Description"
+ characterLimit={500}
+ my={2}
+ />
+ </VStack>
+ </Box>
+ <VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
+ <SupplierLocations
+ locations={locations}
+ isEditing={isEditing}
+ />
+ <SupplierContacts
+ contacts={contacts}
+ locations={locations}
+ isEditing={isEditing}
+ />
+ </VStack>
+ </Grid>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default SupplierForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContacts.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContacts.tsx
new file mode 100644
index 0000000000..ce9f402ede
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContacts.tsx
@@ -0,0 +1,137 @@
+import {
+ Button,
+ HStack,
+ Heading,
+ IconButton,
+ List,
+ ListItem,
+ Text,
+ VStack,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
+import { IoMdAdd } from "react-icons/io";
+import type {
+ SupplierContact,
+ SupplierLocation,
+} from "~/interfaces/Purchasing/types";
+import { Contact } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import SupplierContactForm from "./SupplierContactsForm";
+import { usePermissions } from "~/hooks";
+
+type SupplierContactProps = {
+ contacts?: SupplierContact[];
+ locations?: SupplierLocation[];
+ isEditing?: boolean;
+};
+
+const SupplierContacts = ({
+ contacts = [],
+ locations = [],
+ isEditing = false,
+}: SupplierContactProps) => {
+ const { supplierId } = useParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const [contact, setContact] = useState<SupplierContact | undefined>(
+ undefined
+ );
+
+ const canCreateAccount = permissions.can("create", "users");
+
+ const contactDrawer = useDisclosure();
+ const deleteContactModal = useDisclosure();
+
+ const isEmpty = contacts === undefined || contacts?.length === 0;
+
+ return (
+ <>
+ <VStack alignItems="start" w="full" spacing={4} mb={4}>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Contacts</Heading>
+ <IconButton
+ icon={<IoMdAdd />}
+ aria-label="Add contact"
+ variant="outline"
+ onClick={() => {
+ setContact(undefined);
+ contactDrawer.onOpen();
+ }}
+ />
+ </HStack>
+ {isEmpty && (
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any contacts yet.
+ </Text>
+ )}
+ {!isEmpty && (
+ <List w="full" spacing={4}>
+ {contacts?.map((contact) => (
+ <ListItem key={contact.id}>
+ {contact.contact &&
+ !Array.isArray(contact.contact) &&
+ !Array.isArray(contact.user) ? (
+ <Contact
+ contact={contact.contact}
+ user={contact.user}
+ onDelete={() => {
+ setContact(contact);
+ deleteContactModal.onOpen();
+ }}
+ onEdit={() => {
+ setContact(contact);
+ contactDrawer.onOpen();
+ }}
+ onCreateAccount={
+ canCreateAccount && contact.user === null
+ ? () =>
+ navigate(
+ `/app/users/suppliers/new?id=${contact.id}&supplier=${supplierId}`
+ )
+ : undefined
+ }
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ {isEmpty && (
+ <Button
+ leftIcon={<IoMdAdd />}
+ colorScheme="brand"
+ onClick={() => {
+ setContact(undefined);
+ contactDrawer.onOpen();
+ }}
+ disabled={!isEditing}
+ >
+ New Contact
+ </Button>
+ )}
+ </VStack>
+ {contactDrawer.isOpen && (
+ <SupplierContactForm
+ onClose={contactDrawer.onClose}
+ contact={contact}
+ locations={locations}
+ />
+ )}
+ {deleteContactModal.isOpen && (
+ <ConfirmDelete
+ action={`/app/purchasing/suppliers/${supplierId}/contact/delete/${contact?.id}`}
+ // @ts-ignore
+ name={`${contact?.contact.firstName} ${contact?.contact.lastName}`}
+ text="Are you sure you want to delete this contact?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+ )}
+ </>
+ );
+};
+
+export default SupplierContacts;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContactsForm.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContactsForm.tsx
new file mode 100644
index 0000000000..9cd18e24d5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierContactsForm.tsx
@@ -0,0 +1,120 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ DatePicker,
+ Hidden,
+ Input,
+ Phone,
+ Submit,
+ TextArea,
+} from "~/components/Form";
+import type {
+ SupplierContact,
+ SupplierLocation,
+} from "~/interfaces/Purchasing/types";
+import { supplierContactValidator } from "~/services/purchasing";
+
+type SupplierContactFormProps = {
+ contact?: SupplierContact;
+ locations?: SupplierLocation[];
+ onClose: () => void;
+};
+
+const SupplierContactForm = ({
+ contact,
+ locations = [],
+ onClose,
+}: SupplierContactFormProps) => {
+ const { supplierId } = useParams();
+ const isEditing = !!contact?.id;
+ if (Array.isArray(contact?.contact))
+ throw new Error("contact.contact is an array");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={supplierContactValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/purchasing/suppliers/${supplierId}/contact/${contact?.id}`
+ : `/app/purchasing/suppliers/${supplierId}/contact/new`
+ }
+ defaultValues={{
+ id: contact?.id ?? undefined,
+ contactId: contact?.contact?.id ?? undefined,
+ firstName: contact?.contact?.firstName ?? "",
+ lastName: contact?.contact?.lastName ?? "",
+ email: contact?.contact?.email ?? "",
+ title: contact?.contact?.title ?? "",
+ mobilePhone: contact?.contact?.mobilePhone ?? "",
+ homePhone: contact?.contact?.homePhone ?? "",
+ workPhone: contact?.contact?.workPhone ?? "",
+ fax: contact?.contact?.fax ?? "",
+ addressLine1: contact?.contact?.addressLine1 ?? "",
+ addressLine2: contact?.contact?.addressLine2 ?? "",
+ city: contact?.contact?.city ?? "",
+ state: contact?.contact?.state ?? "",
+ postalCode: contact?.contact?.postalCode ?? "",
+ birthday: contact?.contact?.birthday ?? undefined,
+ }}
+ onSubmit={onClose}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Contact</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="contactId" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="firstName" label="First Name" />
+ <Input name="lastName" label="Last Name" />
+ <Input name="email" label="Email" />
+ <Input name="title" label="Title" />
+ <Phone name="mobilePhone" label="Mobile Phone" />
+ <Phone name="homePhone" label="Home Phone" />
+ <Phone name="workPhone" label="Work Phone" />
+ <Phone name="fax" label="Fax" />
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ <DatePicker name="birthday" label="Birthday" />
+ <TextArea name="notes" label="Notes" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default SupplierContactForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocationForm.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocationForm.tsx
new file mode 100644
index 0000000000..65eb2e8312
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocationForm.tsx
@@ -0,0 +1,90 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { DatePicker, Hidden, Input, Submit, TextArea } from "~/components/Form";
+import type { SupplierLocation } from "~/interfaces/Purchasing/types";
+import { supplierLocationValidator } from "~/services/purchasing";
+
+type SupplierLocationFormProps = {
+ location?: SupplierLocation;
+ onClose: () => void;
+};
+
+const SupplierLocationForm = ({
+ location,
+ onClose,
+}: SupplierLocationFormProps) => {
+ const { supplierId } = useParams();
+ const isEditing = !!location?.id;
+ if (Array.isArray(location?.address))
+ throw new Error("location.address is an array");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={supplierLocationValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/purchasing/suppliers/${supplierId}/location/${location?.id}`
+ : `/app/purchasing/suppliers/${supplierId}/location/new`
+ }
+ defaultValues={{
+ id: location?.id ?? undefined,
+ addressId: location?.address?.id ?? undefined,
+
+ addressLine1: location?.address?.addressLine1 ?? "",
+ addressLine2: location?.address?.addressLine2 ?? "",
+ city: location?.address?.city ?? "",
+ state: location?.address?.state ?? "",
+ postalCode: location?.address?.postalCode ?? "",
+ }}
+ onSubmit={onClose}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Location</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="addressId" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default SupplierLocationForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocations.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocations.tsx
new file mode 100644
index 0000000000..b4596fa80f
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/SupplierLocations.tsx
@@ -0,0 +1,115 @@
+import {
+ Button,
+ Heading,
+ HStack,
+ IconButton,
+ List,
+ ListItem,
+ Text,
+ VStack,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import { IoMdAdd } from "react-icons/io";
+import { Address } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import type { SupplierLocation } from "~/interfaces/Purchasing/types";
+import SupplierLocationForm from "./SupplierLocationForm";
+
+type SupplierLocationProps = {
+ locations?: SupplierLocation[];
+ isEditing?: boolean;
+};
+
+const SupplierLocations = ({
+ locations = [],
+ isEditing = false,
+}: SupplierLocationProps) => {
+ const locationDrawer = useDisclosure();
+ const deleteContactModal = useDisclosure();
+
+ const { supplierId } = useParams();
+
+ const [location, setLocation] = useState<SupplierLocation | undefined>(
+ undefined
+ );
+
+ const isEmpty = locations === undefined || locations?.length === 0;
+
+ return (
+ <>
+ <VStack alignItems="start" w="full" spacing={4} mb={4}>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Locations</Heading>
+ <IconButton
+ icon={<IoMdAdd />}
+ aria-label="Add location"
+ variant="outline"
+ onClick={() => {
+ setLocation(undefined);
+ locationDrawer.onOpen();
+ }}
+ />
+ </HStack>
+ {isEmpty && (
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any locations yet.
+ </Text>
+ )}
+ {!isEmpty && (
+ <List w="full" spacing={4}>
+ {locations?.map((location) => (
+ <ListItem key={location.id}>
+ {location.address && !Array.isArray(location.address) ? (
+ <Address
+ address={location.address}
+ onDelete={() => {
+ setLocation(location);
+ deleteContactModal.onOpen();
+ }}
+ onEdit={() => {
+ setLocation(location);
+ locationDrawer.onOpen();
+ }}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ {isEmpty && (
+ <Button
+ leftIcon={<IoMdAdd />}
+ colorScheme="brand"
+ onClick={() => {
+ setLocation(undefined);
+ locationDrawer.onOpen();
+ }}
+ disabled={!isEditing}
+ >
+ New Location
+ </Button>
+ )}
+ </VStack>
+ {locationDrawer.isOpen && (
+ <SupplierLocationForm
+ onClose={locationDrawer.onClose}
+ location={location}
+ />
+ )}
+ {deleteContactModal.isOpen && (
+ <ConfirmDelete
+ action={`/app/purchasing/suppliers/${supplierId}/location/delete/${location?.id}`}
+ // @ts-ignore
+ name={location?.address?.city ?? ""}
+ text="Are you sure you want to delete this location?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+ )}
+ </>
+ );
+};
+
+export default SupplierLocations;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/index.ts b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/index.ts
new file mode 100644
index 0000000000..856b54a2f5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/components/index.ts
@@ -0,0 +1,4 @@
+import SupplierContacts from "./SupplierContacts";
+import SupplierLocations from "./SupplierLocations";
+
+export { SupplierContacts, SupplierLocations };
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/index.ts b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/index.ts
new file mode 100644
index 0000000000..ed1e84d2b7
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SupplierForm/index.ts
@@ -0,0 +1,3 @@
+import SupplierForm from "./SupplierForm";
+
+export default SupplierForm;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/SuppliersTable.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/SuppliersTable.tsx
new file mode 100644
index 0000000000..a336561132
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/SuppliersTable.tsx
@@ -0,0 +1,119 @@
+import { ActionMenu } from "@carbon/react";
+import {
+ Button,
+ ButtonGroup,
+ Flex,
+ IconButton,
+ MenuItem,
+ VisuallyHidden,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import { BsPencilSquare, BsPlus } from "react-icons/bs";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Supplier } from "~/interfaces/Purchasing/types";
+
+type SuppliersTableProps = {
+ data: Supplier[];
+ count: number;
+};
+
+const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const columns = useMemo<ColumnDef<Supplier>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ // @ts-ignore
+ accessorFn: (item) => item.supplierType?.name ?? "",
+ header: "Supplier Type",
+ cell: (item) => item.getValue(),
+ },
+ {
+ // @ts-ignore
+ accessorFn: (item) => item.supplierStatus?.name ?? "",
+ header: "Supplier Status",
+ cell: (item) => item.getValue(),
+ },
+ {
+ id: "orders",
+ header: "Orders",
+ cell: () => (
+ <ButtonGroup
+ size="sm"
+ isAttached
+ variant="outline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button onClick={() => console.log("orders")}>0 Orders</Button>
+ <IconButton
+ aria-label="New Order"
+ icon={<BsPlus />}
+ onClick={() => console.log("new order")}
+ />
+ </ButtonGroup>
+ ),
+ },
+ {
+ id: "parts",
+ header: "Parts",
+ cell: () => (
+ <ButtonGroup
+ size="sm"
+ isAttached
+ variant="outline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button onClick={() => console.log("orders")}>0 Parts</Button>
+ <IconButton
+ aria-label="New Part"
+ icon={<BsPlus />}
+ onClick={() => console.log("new part")}
+ />
+ </ButtonGroup>
+ ),
+ },
+ {
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ accessorKey: "id",
+ cell: (item) => (
+ <Flex justifyContent="end">
+ {permissions.can("update", "users") && (
+ <ActionMenu>
+ <MenuItem icon={<BsPencilSquare />}>Edit Supplier</MenuItem>
+ </ActionMenu>
+ )}
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ return (
+ <>
+ <Table<Supplier>
+ count={count}
+ columns={columns}
+ data={data}
+ withPagination
+ onRowClick={(row) =>
+ navigate(`/app/purchasing/suppliers/${row.id}?${params.toString()}`)
+ }
+ />
+ </>
+ );
+});
+
+SuppliersTable.displayName = "SupplierTable";
+
+export default SuppliersTable;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/index.ts b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/index.ts
new file mode 100644
index 0000000000..733d42d3b6
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTable/index.ts
@@ -0,0 +1,3 @@
+import SuppliersTable from "./SuppliersTable";
+
+export default SuppliersTable;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
new file mode 100644
index 0000000000..de11167292
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
@@ -0,0 +1,106 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type {
+ SupplierStatus,
+ SupplierType,
+} from "~/interfaces/Purchasing/types";
+import { mapRowsToOptions } from "~/utils/form";
+
+type SuppliersTableFiltersProps = {
+ supplierTypes: Partial<SupplierType>[];
+ supplierStatuses: SupplierStatus[];
+};
+
+const SuppliersTableFilters = ({
+ supplierTypes,
+ supplierStatuses,
+}: SuppliersTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const supplierTypeOptions = mapRowsToOptions({
+ data: supplierTypes,
+ value: "id",
+ label: "name",
+ });
+
+ const supplierStatusOptions = mapRowsToOptions({
+ data: supplierStatuses,
+ value: (status) => status.id.toString(),
+ label: "name",
+ });
+
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ {supplierTypeOptions.length > 0 && (
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={supplierTypeOptions.filter(
+ (type) => type.value === params.get("type")
+ )}
+ isClearable
+ options={supplierTypeOptions}
+ onChange={(selected) => {
+ setParams({ type: selected?.value });
+ }}
+ aria-label="Supplier Type"
+ placeholder="Supplier Type"
+ minW={180}
+ />
+ )}
+ {supplierStatusOptions && (
+ <Select
+ // @ts-ignore
+ size="sm"
+ isClearable
+ value={supplierStatusOptions.filter(
+ (type) => type.value === params.get("status")
+ )}
+ options={supplierStatusOptions}
+ onChange={(selected) => {
+ setParams({ status: selected?.value });
+ }}
+ aria-label="Status"
+ placeholder="Supplier Status"
+ minW={180}
+ />
+ )}
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Supplier
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default SuppliersTableFilters;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/index.ts b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/index.ts
new file mode 100644
index 0000000000..0136d93af5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/SuppliersTableFilters/index.ts
@@ -0,0 +1,3 @@
+import SuppliersTableFilters from "./SuppliersTableFilters";
+
+export default SuppliersTableFilters;
diff --git a/apps/carbon/app/interfaces/Purchasing/Suppliers/index.ts b/apps/carbon/app/interfaces/Purchasing/Suppliers/index.ts
new file mode 100644
index 0000000000..919c9675a2
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/Suppliers/index.ts
@@ -0,0 +1,5 @@
+import SupplierForm from "./SupplierForm";
+import SuppliersTable from "./SuppliersTable";
+import SuppliersTableFilters from "./SuppliersTableFilters";
+
+export { SupplierForm, SuppliersTable, SuppliersTableFilters };
diff --git a/apps/carbon/app/interfaces/Purchasing/index.ts b/apps/carbon/app/interfaces/Purchasing/index.ts
new file mode 100644
index 0000000000..938fcc8f88
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/index.ts
@@ -0,0 +1,3 @@
+import usePurchasingSidebar from "./usePurchasingSidebar";
+
+export { usePurchasingSidebar };
diff --git a/apps/carbon/app/interfaces/Purchasing/types.ts b/apps/carbon/app/interfaces/Purchasing/types.ts
new file mode 100644
index 0000000000..a166ca66ca
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/types.ts
@@ -0,0 +1,27 @@
+import type {
+ getSupplierContacts,
+ getSupplierLocations,
+ getSuppliers,
+ getSupplierStatuses,
+ getSupplierTypes,
+} from "~/services/purchasing";
+
+export type Supplier = NonNullable<
+ Awaited<ReturnType<typeof getSuppliers>>["data"]
+>[number];
+
+export type SupplierContact = NonNullable<
+ Awaited<ReturnType<typeof getSupplierContacts>>["data"]
+>[number];
+
+export type SupplierLocation = NonNullable<
+ Awaited<ReturnType<typeof getSupplierLocations>>["data"]
+>[number];
+
+export type SupplierStatus = NonNullable<
+ Awaited<ReturnType<typeof getSupplierStatuses>>["data"]
+>[number];
+
+export type SupplierType = NonNullable<
+ Awaited<ReturnType<typeof getSupplierTypes>>["data"]
+>[number];
diff --git a/apps/carbon/app/interfaces/Purchasing/usePurchasingSidebar.tsx b/apps/carbon/app/interfaces/Purchasing/usePurchasingSidebar.tsx
new file mode 100644
index 0000000000..1510254900
--- /dev/null
+++ b/apps/carbon/app/interfaces/Purchasing/usePurchasingSidebar.tsx
@@ -0,0 +1,20 @@
+import type { Route } from "~/types";
+
+const purchasingRoutes: Record<string, Route[]>[] = [
+ {
+ Configuration: [
+ {
+ name: "Suppliers",
+ to: "/app/purchasing/suppliers",
+ },
+ {
+ name: "Supplier Types",
+ to: "/app/purchasing/supplier-types",
+ },
+ ],
+ },
+];
+
+export default function useSalesSidebar() {
+ return { links: purchasingRoutes };
+}
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx
new file mode 100644
index 0000000000..61cbeeb744
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx
@@ -0,0 +1,76 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { Color, Hidden, Input, Submit } from "~/components/Form";
+import { customerTypeValidator } from "~/services/sales";
+
+type CustomerTypeFormProps = {
+ initialValues: {
+ id?: string;
+ name: string;
+ color: string;
+ };
+};
+
+const CustomerTypeForm = ({ initialValues }: CustomerTypeFormProps) => {
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={customerTypeValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/sales/customer-types/${initialValues.id}`
+ : "/app/sales/customer-types/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Customer Type
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="name" label="Customer Type" />
+ <Color name="color" label="Color" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default CustomerTypeForm;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/index.ts b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/index.ts
new file mode 100644
index 0000000000..9afadaf30c
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypeForm/index.ts
@@ -0,0 +1,3 @@
+import CustomerTypeForm from "./CustomerTypeForm";
+
+export default CustomerTypeForm;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx
new file mode 100644
index 0000000000..e13535618b
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx
@@ -0,0 +1,101 @@
+import { ActionMenu } from "@carbon/react";
+import { Box, Flex, MenuItem, VisuallyHidden } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import { BsPencilSquare, BsPeopleFill } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { CustomerType } from "~/interfaces/Sales/types";
+
+type CustomerTypesTableProps = {
+ data: CustomerType[];
+ count: number;
+};
+
+const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Customer Type",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "color",
+ header: "Color",
+ cell: (item) => (
+ <Box
+ aria-label="Color"
+ w={6}
+ h={6}
+ borderRadius="md"
+ bg={item.getValue() ?? "#000000"}
+ role="img"
+ />
+ ),
+ },
+ {
+ accessorKey: "id",
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ cell: ({ row }) => (
+ <Flex justifyContent="end">
+ <ActionMenu>
+ <MenuItem
+ icon={<BsPeopleFill />}
+ onClick={() => {
+ navigate(`/app/sales/customers?type=${row.original.id}`);
+ }}
+ >
+ View Customers
+ </MenuItem>
+ <MenuItem
+ isDisabled={
+ row.original.protected || !permissions.can("update", "sales")
+ }
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/app/sales/customer-types/${
+ row.original.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Edit Customer Type
+ </MenuItem>
+ <MenuItem
+ isDisabled={
+ row.original.protected || !permissions.can("delete", "sales")
+ }
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/app/sales/customer-types/delete/${
+ row.original.id
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Delete Customer Type
+ </MenuItem>
+ </ActionMenu>
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ return (
+ <Table<typeof data[number]> data={data} columns={columns} count={count} />
+ );
+});
+
+CustomerTypesTable.displayName = "CustomerTypesTable";
+export default CustomerTypesTable;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/index.ts b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/index.ts
new file mode 100644
index 0000000000..7c52ef6811
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTable/index.ts
@@ -0,0 +1,3 @@
+import CustomerTypesTable from "./CustomerTypesTable";
+
+export default CustomerTypesTable;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx
new file mode 100644
index 0000000000..4017e48867
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx
@@ -0,0 +1,46 @@
+import { useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+const CustomerTypesTableFilters = () => {
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Customer Type
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default CustomerTypesTableFilters;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/index.ts b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/index.ts
new file mode 100644
index 0000000000..0f3529f802
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/CustomerTypesTableFilters/index.ts
@@ -0,0 +1,3 @@
+import CustomerTypesTableFilters from "./CustomerTypesTableFilters";
+
+export default CustomerTypesTableFilters;
diff --git a/apps/carbon/app/interfaces/Sales/CustomerTypes/index.ts b/apps/carbon/app/interfaces/Sales/CustomerTypes/index.ts
new file mode 100644
index 0000000000..bff6a6b24a
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/CustomerTypes/index.ts
@@ -0,0 +1,5 @@
+import CustomerTypeForm from "./CustomerTypeForm";
+import CustomerTypesTable from "./CustomerTypesTable";
+import CustomerTypesTableFilters from "./CustomerTypesTableFilters";
+
+export { CustomerTypeForm, CustomerTypesTable, CustomerTypesTableFilters };
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/CustomerForm.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/CustomerForm.tsx
new file mode 100644
index 0000000000..e0b0ff5acf
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/CustomerForm.tsx
@@ -0,0 +1,172 @@
+import {
+ Box,
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ Grid,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Input,
+ Select,
+ Submit,
+ User,
+ TextArea,
+ Hidden,
+} from "~/components/Form";
+import { customerValidator } from "~/services/sales";
+import type {
+ CustomerContact,
+ CustomerLocation,
+ CustomerStatus,
+ CustomerType,
+} from "~/interfaces/Sales/types";
+import { mapRowsToOptions } from "~/utils/form";
+import { useRouteData } from "~/hooks";
+import { CustomerContacts, CustomerLocations } from "./components";
+import { IoMdAdd } from "react-icons/io";
+
+type CustomerFormProps = {
+ initialValues: {
+ id?: string;
+ name: string;
+ description?: string;
+ accountManagerId?: string;
+ customerTypeId?: string;
+ customerStatusId?: number;
+ taxId?: string;
+ };
+ contacts?: CustomerContact[];
+ locations?: CustomerLocation[];
+};
+
+const CustomerForm = ({
+ initialValues,
+ contacts,
+ locations,
+}: CustomerFormProps) => {
+ const navigate = useNavigate();
+ const onClose = () => navigate("/app/sales/customers");
+
+ const routeData = useRouteData<{
+ customerTypes: { data: CustomerType[] };
+ customerStatuses: { data: CustomerStatus[] };
+ }>("/app/sales/customers");
+
+ const customerTypeOptions = routeData?.customerTypes
+ ? mapRowsToOptions({
+ data: routeData.customerTypes.data ?? [],
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const customerStatusOptions = routeData?.customerStatuses
+ ? mapRowsToOptions({
+ data: routeData.customerStatuses.data ?? [],
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const isEditing = initialValues.id !== undefined;
+
+ return (
+ <Drawer onClose={onClose} isOpen size="full">
+ <ValidatedForm
+ method="post"
+ action={
+ isEditing
+ ? `/app/sales/customers/${initialValues.id}`
+ : "/app/sales/customers/new"
+ }
+ validator={customerValidator}
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? initialValues.name : "New Customer"}
+ </DrawerHeader>
+ <DrawerBody>
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
+ gridColumnGap={8}
+ w="full"
+ >
+ <Box w="full">
+ <Hidden name="id" />
+ <VStack spacing={4} w="full" alignItems="start">
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={4}
+ w="full"
+ >
+ <Input name="name" label="Name" />
+ <Input name="taxId" label="Tax ID" />
+ <Select
+ name="customerTypeId"
+ label="Customer Type"
+ options={customerTypeOptions}
+ placeholder="Select Customer Type"
+ />
+ <User name="accountManagerId" label="Account Manager" />
+ <Select
+ name="customerStatusId"
+ label="Customer Status"
+ options={customerStatusOptions}
+ placeholder="Select Customer Status"
+ />
+ </Grid>
+
+ <TextArea
+ name="description"
+ label="Description"
+ characterLimit={500}
+ my={2}
+ />
+ </VStack>
+ </Box>
+ <VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
+ <CustomerLocations
+ locations={locations}
+ isEditing={isEditing}
+ />
+ <CustomerContacts
+ contacts={contacts}
+ locations={locations}
+ isEditing={isEditing}
+ />
+ </VStack>
+ </Grid>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default CustomerForm;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContacts.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContacts.tsx
new file mode 100644
index 0000000000..1ab5fbc053
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContacts.tsx
@@ -0,0 +1,137 @@
+import {
+ Button,
+ HStack,
+ Heading,
+ IconButton,
+ List,
+ ListItem,
+ Text,
+ VStack,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
+import { IoMdAdd } from "react-icons/io";
+import type {
+ CustomerContact,
+ CustomerLocation,
+} from "~/interfaces/Sales/types";
+import { Contact } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import CustomerContactForm from "./CustomerContactsForm";
+import { usePermissions } from "~/hooks";
+
+type CustomerContactProps = {
+ contacts?: CustomerContact[];
+ locations?: CustomerLocation[];
+ isEditing?: boolean;
+};
+
+const CustomerContacts = ({
+ contacts = [],
+ locations = [],
+ isEditing = false,
+}: CustomerContactProps) => {
+ const { customerId } = useParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const canCreateAccount = permissions.can("create", "users");
+
+ const [contact, setContact] = useState<CustomerContact | undefined>(
+ undefined
+ );
+
+ const contactDrawer = useDisclosure();
+ const deleteContactModal = useDisclosure();
+
+ const isEmpty = contacts === undefined || contacts?.length === 0;
+
+ return (
+ <>
+ <VStack alignItems="start" w="full" spacing={4} mb={4}>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Contacts</Heading>
+ <IconButton
+ icon={<IoMdAdd />}
+ aria-label="Add contact"
+ variant="outline"
+ onClick={() => {
+ setContact(undefined);
+ contactDrawer.onOpen();
+ }}
+ />
+ </HStack>
+ {isEmpty && (
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any contacts yet.
+ </Text>
+ )}
+ {!isEmpty && (
+ <List w="full" spacing={4}>
+ {contacts?.map((contact) => (
+ <ListItem key={contact.id}>
+ {contact.contact &&
+ !Array.isArray(contact.contact) &&
+ !Array.isArray(contact.user) ? (
+ <Contact
+ contact={contact.contact}
+ user={contact.user}
+ onDelete={() => {
+ setContact(contact);
+ deleteContactModal.onOpen();
+ }}
+ onEdit={() => {
+ setContact(contact);
+ contactDrawer.onOpen();
+ }}
+ onCreateAccount={
+ canCreateAccount && contact.user === null
+ ? () =>
+ navigate(
+ `/app/users/customers/new?id=${contact.id}&customer=${customerId}`
+ )
+ : undefined
+ }
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ {isEmpty && (
+ <Button
+ leftIcon={<IoMdAdd />}
+ colorScheme="brand"
+ onClick={() => {
+ setContact(undefined);
+ contactDrawer.onOpen();
+ }}
+ disabled={!isEditing}
+ >
+ New Contact
+ </Button>
+ )}
+ </VStack>
+ {contactDrawer.isOpen && (
+ <CustomerContactForm
+ onClose={contactDrawer.onClose}
+ contact={contact}
+ locations={locations}
+ />
+ )}
+ {deleteContactModal.isOpen && (
+ <ConfirmDelete
+ action={`/app/sales/customers/${customerId}/contact/delete/${contact?.id}`}
+ // @ts-ignore
+ name={`${contact?.contact.firstName} ${contact?.contact.lastName}`}
+ text="Are you sure you want to delete this contact?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+ )}
+ </>
+ );
+};
+
+export default CustomerContacts;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContactsForm.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContactsForm.tsx
new file mode 100644
index 0000000000..09afc29f28
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerContactsForm.tsx
@@ -0,0 +1,120 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ DatePicker,
+ Hidden,
+ Input,
+ Phone,
+ Submit,
+ TextArea,
+} from "~/components/Form";
+import type {
+ CustomerContact,
+ CustomerLocation,
+} from "~/interfaces/Sales/types";
+import { customerContactValidator } from "~/services/sales";
+
+type CustomerContactFormProps = {
+ contact?: CustomerContact;
+ locations?: CustomerLocation[];
+ onClose: () => void;
+};
+
+const CustomerContactForm = ({
+ contact,
+ locations = [],
+ onClose,
+}: CustomerContactFormProps) => {
+ const { customerId } = useParams();
+ const isEditing = !!contact?.id;
+ if (Array.isArray(contact?.contact))
+ throw new Error("contact.contact is an array");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={customerContactValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/sales/customers/${customerId}/contact/${contact?.id}`
+ : `/app/sales/customers/${customerId}/contact/new`
+ }
+ defaultValues={{
+ id: contact?.id ?? undefined,
+ contactId: contact?.contact?.id ?? undefined,
+ firstName: contact?.contact?.firstName ?? "",
+ lastName: contact?.contact?.lastName ?? "",
+ email: contact?.contact?.email ?? "",
+ title: contact?.contact?.title ?? "",
+ mobilePhone: contact?.contact?.mobilePhone ?? "",
+ homePhone: contact?.contact?.homePhone ?? "",
+ workPhone: contact?.contact?.workPhone ?? "",
+ fax: contact?.contact?.fax ?? "",
+ addressLine1: contact?.contact?.addressLine1 ?? "",
+ addressLine2: contact?.contact?.addressLine2 ?? "",
+ city: contact?.contact?.city ?? "",
+ state: contact?.contact?.state ?? "",
+ postalCode: contact?.contact?.postalCode ?? "",
+ birthday: contact?.contact?.birthday ?? undefined,
+ }}
+ onSubmit={onClose}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Contact</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="contactId" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="firstName" label="First Name" />
+ <Input name="lastName" label="Last Name" />
+ <Input name="email" label="Email" />
+ <Input name="title" label="Title" />
+ <Phone name="mobilePhone" label="Mobile Phone" />
+ <Phone name="homePhone" label="Home Phone" />
+ <Phone name="workPhone" label="Work Phone" />
+ <Phone name="fax" label="Fax" />
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ <DatePicker name="birthday" label="Birthday" />
+ <TextArea name="notes" label="Notes" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default CustomerContactForm;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocationForm.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocationForm.tsx
new file mode 100644
index 0000000000..2a168a30a0
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocationForm.tsx
@@ -0,0 +1,90 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { Hidden, Input, Submit } from "~/components/Form";
+import type { CustomerLocation } from "~/interfaces/Sales/types";
+import { customerLocationValidator } from "~/services/sales";
+
+type CustomerLocationFormProps = {
+ location?: CustomerLocation;
+ onClose: () => void;
+};
+
+const CustomerLocationForm = ({
+ location,
+ onClose,
+}: CustomerLocationFormProps) => {
+ const { customerId } = useParams();
+ const isEditing = !!location?.id;
+ if (Array.isArray(location?.address))
+ throw new Error("location.address is an array");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={customerLocationValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/sales/customers/${customerId}/location/${location?.id}`
+ : `/app/sales/customers/${customerId}/location/new`
+ }
+ defaultValues={{
+ id: location?.id ?? undefined,
+ addressId: location?.address?.id ?? undefined,
+
+ addressLine1: location?.address?.addressLine1 ?? "",
+ addressLine2: location?.address?.addressLine2 ?? "",
+ city: location?.address?.city ?? "",
+ state: location?.address?.state ?? "",
+ postalCode: location?.address?.postalCode ?? "",
+ }}
+ onSubmit={onClose}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Location</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="addressId" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ {/* Country dropdown */}
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default CustomerLocationForm;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocations.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocations.tsx
new file mode 100644
index 0000000000..a63375a499
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/CustomerLocations.tsx
@@ -0,0 +1,115 @@
+import {
+ Button,
+ Heading,
+ HStack,
+ IconButton,
+ List,
+ ListItem,
+ Text,
+ VStack,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import { IoMdAdd } from "react-icons/io";
+import { Address } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import type { CustomerLocation } from "~/interfaces/Sales/types";
+import CustomerLocationForm from "./CustomerLocationForm";
+
+type CustomerLocationProps = {
+ locations?: CustomerLocation[];
+ isEditing?: boolean;
+};
+
+const CustomerLocations = ({
+ locations = [],
+ isEditing = false,
+}: CustomerLocationProps) => {
+ const locationDrawer = useDisclosure();
+ const deleteContactModal = useDisclosure();
+
+ const { customerId } = useParams();
+
+ const [location, setLocation] = useState<CustomerLocation | undefined>(
+ undefined
+ );
+
+ const isEmpty = locations === undefined || locations?.length === 0;
+
+ return (
+ <>
+ <VStack alignItems="start" w="full" spacing={4} mb={4}>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Locations</Heading>
+ <IconButton
+ icon={<IoMdAdd />}
+ aria-label="Add location"
+ variant="outline"
+ onClick={() => {
+ setLocation(undefined);
+ locationDrawer.onOpen();
+ }}
+ />
+ </HStack>
+ {isEmpty && (
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any locations yet.
+ </Text>
+ )}
+ {!isEmpty && (
+ <List w="full" spacing={4}>
+ {locations?.map((location) => (
+ <ListItem key={location.id}>
+ {location.address && !Array.isArray(location.address) ? (
+ <Address
+ address={location.address}
+ onDelete={() => {
+ setLocation(location);
+ deleteContactModal.onOpen();
+ }}
+ onEdit={() => {
+ setLocation(location);
+ locationDrawer.onOpen();
+ }}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ {isEmpty && (
+ <Button
+ leftIcon={<IoMdAdd />}
+ colorScheme="brand"
+ onClick={() => {
+ setLocation(undefined);
+ locationDrawer.onOpen();
+ }}
+ disabled={!isEditing}
+ >
+ New Location
+ </Button>
+ )}
+ </VStack>
+ {locationDrawer.isOpen && (
+ <CustomerLocationForm
+ onClose={locationDrawer.onClose}
+ location={location}
+ />
+ )}
+ {deleteContactModal.isOpen && (
+ <ConfirmDelete
+ action={`/app/sales/customers/${customerId}/location/delete/${location?.id}`}
+ // @ts-ignore
+ name={location?.address?.city ?? ""}
+ text="Are you sure you want to delete this location?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+ )}
+ </>
+ );
+};
+
+export default CustomerLocations;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/index.ts b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/index.ts
new file mode 100644
index 0000000000..a298cd1300
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/components/index.ts
@@ -0,0 +1,4 @@
+import CustomerContacts from "./CustomerContacts";
+import CustomerLocations from "./CustomerLocations";
+
+export { CustomerContacts, CustomerLocations };
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/index.ts b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/index.ts
new file mode 100644
index 0000000000..80153745e0
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomerForm/index.ts
@@ -0,0 +1,3 @@
+import CustomerForm from "./CustomerForm";
+
+export default CustomerForm;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/CustomersTable.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/CustomersTable.tsx
new file mode 100644
index 0000000000..e536a3453f
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/CustomersTable.tsx
@@ -0,0 +1,119 @@
+import { ActionMenu } from "@carbon/react";
+import {
+ Button,
+ ButtonGroup,
+ Flex,
+ IconButton,
+ MenuItem,
+ VisuallyHidden,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import { BsPencilSquare, BsPlus } from "react-icons/bs";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Customer } from "~/interfaces/Sales/types";
+
+type CustomersTableProps = {
+ data: Customer[];
+ count: number;
+};
+
+const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const columns = useMemo<ColumnDef<Customer>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ // @ts-ignore
+ accessorFn: (item) => item.customerType?.name ?? "",
+ header: "Customer Type",
+ cell: (item) => item.getValue(),
+ },
+ {
+ // @ts-ignore
+ accessorFn: (item) => item.customerStatus?.name ?? "",
+ header: "Customer Status",
+ cell: (item) => item.getValue(),
+ },
+ {
+ id: "orders",
+ header: "Orders",
+ cell: () => (
+ <ButtonGroup
+ size="sm"
+ isAttached
+ variant="outline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button onClick={() => console.log("orders")}>0 Orders</Button>
+ <IconButton
+ aria-label="New Order"
+ icon={<BsPlus />}
+ onClick={() => console.log("new order")}
+ />
+ </ButtonGroup>
+ ),
+ },
+ {
+ id: "parts",
+ header: "Parts",
+ cell: () => (
+ <ButtonGroup
+ size="sm"
+ isAttached
+ variant="outline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button onClick={() => console.log("orders")}>0 Parts</Button>
+ <IconButton
+ aria-label="New Part"
+ icon={<BsPlus />}
+ onClick={() => console.log("new part")}
+ />
+ </ButtonGroup>
+ ),
+ },
+ {
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ accessorKey: "id",
+ cell: (item) => (
+ <Flex justifyContent="end">
+ {permissions.can("update", "users") && (
+ <ActionMenu>
+ <MenuItem icon={<BsPencilSquare />}>Edit Customer</MenuItem>
+ </ActionMenu>
+ )}
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ return (
+ <>
+ <Table<Customer>
+ count={count}
+ columns={columns}
+ data={data}
+ withPagination
+ onRowClick={(row) =>
+ navigate(`/app/sales/customers/${row.id}?${params.toString()}`)
+ }
+ />
+ </>
+ );
+});
+
+CustomersTable.displayName = "CustomerTable";
+
+export default CustomersTable;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/index.ts b/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/index.ts
new file mode 100644
index 0000000000..c6fe5c0540
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomersTable/index.ts
@@ -0,0 +1,3 @@
+import CustomersTable from "./CustomersTable";
+
+export default CustomersTable;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/CustomersTableFilters.tsx b/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/CustomersTableFilters.tsx
new file mode 100644
index 0000000000..c12f6591b1
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/CustomersTableFilters.tsx
@@ -0,0 +1,103 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { CustomerStatus, CustomerType } from "~/interfaces/Sales/types";
+import { mapRowsToOptions } from "~/utils/form";
+
+type CustomersTableFiltersProps = {
+ customerTypes: Partial<CustomerType>[];
+ customerStatuses: CustomerStatus[];
+};
+
+const CustomersTableFilters = ({
+ customerTypes,
+ customerStatuses,
+}: CustomersTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const customerTypeOptions = mapRowsToOptions({
+ data: customerTypes,
+ value: "id",
+ label: "name",
+ });
+
+ const customerStatusOptions = mapRowsToOptions({
+ data: customerStatuses,
+ value: (status) => status.id.toString(),
+ label: "name",
+ });
+
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ {customerTypeOptions.length > 0 && (
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={customerTypeOptions.filter(
+ (type) => type.value === params.get("type")
+ )}
+ isClearable
+ options={customerTypeOptions}
+ onChange={(selected) => {
+ setParams({ type: selected?.value });
+ }}
+ aria-label="Customer Type"
+ placeholder="Customer Type"
+ minW={180}
+ />
+ )}
+ {customerStatusOptions && (
+ <Select
+ // @ts-ignore
+ size="sm"
+ isClearable
+ value={customerStatusOptions.filter(
+ (type) => type.value === params.get("status")
+ )}
+ options={customerStatusOptions}
+ onChange={(selected) => {
+ setParams({ status: selected?.value });
+ }}
+ aria-label="Status"
+ placeholder="Customer Status"
+ minW={180}
+ />
+ )}
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Customer
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default CustomersTableFilters;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/index.ts b/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/index.ts
new file mode 100644
index 0000000000..56e106d5cf
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/CustomersTableFilters/index.ts
@@ -0,0 +1,3 @@
+import CustomersTableFilters from "./CustomersTableFilters";
+
+export default CustomersTableFilters;
diff --git a/apps/carbon/app/interfaces/Sales/Customers/index.ts b/apps/carbon/app/interfaces/Sales/Customers/index.ts
new file mode 100644
index 0000000000..e56992acd2
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/Customers/index.ts
@@ -0,0 +1,5 @@
+import CustomerForm from "./CustomerForm";
+import CustomersTable from "./CustomersTable";
+import CustomersTableFilters from "./CustomersTableFilters";
+
+export { CustomerForm, CustomersTable, CustomersTableFilters };
diff --git a/apps/carbon/app/interfaces/Sales/index.ts b/apps/carbon/app/interfaces/Sales/index.ts
new file mode 100644
index 0000000000..64e2b65aa8
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/index.ts
@@ -0,0 +1,3 @@
+import useSalesSidebar from "./useSalesSidebar";
+
+export { useSalesSidebar };
diff --git a/apps/carbon/app/interfaces/Sales/types.ts b/apps/carbon/app/interfaces/Sales/types.ts
new file mode 100644
index 0000000000..e3e4f4ba0e
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/types.ts
@@ -0,0 +1,27 @@
+import type {
+ getCustomerContacts,
+ getCustomerLocations,
+ getCustomers,
+ getCustomerStatuses,
+ getCustomerTypes,
+} from "~/services/sales";
+
+export type Customer = NonNullable<
+ Awaited<ReturnType<typeof getCustomers>>["data"]
+>[number];
+
+export type CustomerContact = NonNullable<
+ Awaited<ReturnType<typeof getCustomerContacts>>["data"]
+>[number];
+
+export type CustomerLocation = NonNullable<
+ Awaited<ReturnType<typeof getCustomerLocations>>["data"]
+>[number];
+
+export type CustomerStatus = NonNullable<
+ Awaited<ReturnType<typeof getCustomerStatuses>>["data"]
+>[number];
+
+export type CustomerType = NonNullable<
+ Awaited<ReturnType<typeof getCustomerTypes>>["data"]
+>[number];
diff --git a/apps/carbon/app/interfaces/Sales/useSalesSidebar.tsx b/apps/carbon/app/interfaces/Sales/useSalesSidebar.tsx
new file mode 100644
index 0000000000..77e482952b
--- /dev/null
+++ b/apps/carbon/app/interfaces/Sales/useSalesSidebar.tsx
@@ -0,0 +1,20 @@
+import type { Route } from "~/types";
+
+const salesRoutes: Record<string, Route[]>[] = [
+ {
+ Configuration: [
+ {
+ name: "Customers",
+ to: "/app/sales/customers",
+ },
+ {
+ name: "Customer Types",
+ to: "/app/sales/customer-types",
+ },
+ ],
+ },
+];
+
+export default function useSalesSidebar() {
+ return { links: salesRoutes };
+}
diff --git a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
index b08d7400c8..66c748a352 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
+++ b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
@@ -9,16 +9,16 @@ import {
useDisclosure,
VisuallyHidden,
} from "@chakra-ui/react";
-import { Link, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import { BiAddToQueue } from "react-icons/bi";
import { BsPencilSquare, BsListUl, BsPlus } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { Table } from "~/components";
-import { usePermissions } from "~/hooks";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions, useUrlParams } from "~/hooks";
import type { AttributeCategory } from "~/interfaces/Users/types";
-import DeleteAttributeCategoryModal from "../DeleteAttributeCategoryModal";
type AttributeCategoriesTableProps = {
data: AttributeCategory[];
@@ -28,6 +28,7 @@ type AttributeCategoriesTableProps = {
const AttributeCategoriesTable = memo(
({ data, count }: AttributeCategoriesTableProps) => {
const navigate = useNavigate();
+ const [params] = useUrlParams();
const permissions = usePermissions();
const deleteModal = useDisclosure();
const [selectedCategory, setSelectedCategory] = useState<
@@ -57,7 +58,11 @@ const AttributeCategoriesTable = memo(
<ButtonGroup size="sm" isAttached variant="outline">
<Button
onClick={() => {
- navigate(`/app/users/attributes/list/${row.original.id}`);
+ navigate(
+ `/app/users/attributes/list/${
+ row.original.id
+ }?${params.toString()}`
+ );
}}
>
{Array.isArray(row.original.userAttribute)
@@ -66,10 +71,14 @@ const AttributeCategoriesTable = memo(
Attributes
</Button>
<IconButton
- aria-label="Add to friends"
+ aria-label="Add attribute"
icon={<BsPlus />}
onClick={() => {
- navigate(`/app/users/attributes/list/${row.original.id}/new`);
+ navigate(
+ `/app/users/attributes/list/${
+ row.original.id
+ }/new?${params.toString()}`
+ );
}}
/>
</ButtonGroup>
@@ -102,7 +111,9 @@ const AttributeCategoriesTable = memo(
icon={<BiAddToQueue />}
onClick={() => {
navigate(
- `/app/users/attributes/list/${row.original.id}/new`
+ `/app/users/attributes/list/${
+ row.original.id
+ }/new?${params.toString()}`
);
}}
>
@@ -111,7 +122,11 @@ const AttributeCategoriesTable = memo(
<MenuItem
icon={<BsListUl />}
onClick={() => {
- navigate(`/app/users/attributes/list/${row.original.id}`);
+ navigate(
+ `/app/users/attributes/list/${
+ row.original.id
+ }?${params.toString()}`
+ );
}}
>
View Attributes
@@ -140,7 +155,7 @@ const AttributeCategoriesTable = memo(
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [params]);
return (
<>
@@ -149,10 +164,14 @@ const AttributeCategoriesTable = memo(
columns={columns}
count={count}
/>
- <DeleteAttributeCategoryModal
- onCancel={onDeleteCancel}
+
+ <ConfirmDelete
+ action={`/app/users/attributes/delete/${selectedCategory?.id}`}
+ name={selectedCategory?.name ?? ""}
+ text={`Are you sure you want to deactivate the ${selectedCategory?.name} attribute category?`}
isOpen={deleteModal.isOpen}
- data={selectedCategory}
+ onCancel={onDeleteCancel}
+ onSubmit={onDeleteCancel}
/>
</>
);
diff --git a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
index da21a4b9cc..2134ef8eaf 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
+++ b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
@@ -3,10 +3,11 @@ import { Button, HStack } from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
const AttributesTableFilters = () => {
const permissions = usePermissions();
+ const [params] = useUrlParams();
const borderColor = useColor("gray.200");
return (
<HStack
@@ -28,7 +29,12 @@ const AttributesTableFilters = () => {
</HStack>
<HStack spacing={2}>
{permissions.can("update", "users") && (
- <Button as={Link} to="new" colorScheme="brand" leftIcon={<IoMdAdd />}>
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
New Attribute Category
</Button>
)}
diff --git a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryDetail/AttributeCategoryDetail.tsx b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryDetail/AttributeCategoryDetail.tsx
index cf9e3c361b..7af2014148 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryDetail/AttributeCategoryDetail.tsx
+++ b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryDetail/AttributeCategoryDetail.tsx
@@ -25,11 +25,12 @@ import { BsCalendarDate, BsPencilSquare, BsToggleOn } from "react-icons/bs";
import { CgProfile } from "react-icons/cg";
import { IoMdTrash } from "react-icons/io";
import { MdOutlineDragIndicator } from "react-icons/md";
+import { ConfirmDelete } from "~/components/Modals";
import type {
Attribute,
AttributeCategoryDetail as AttributeCategoryDetailType,
} from "~/interfaces/Users/types";
-import { DeleteAttributeModal } from "~/interfaces/Users/Attributes";
+import { useUrlParams } from "~/hooks";
type AttributeCategoryDetailProps = {
attributeCategory: AttributeCategoryDetailType;
@@ -40,6 +41,7 @@ const AttributeCategoryDetail = ({
attributeCategory,
onClose,
}: AttributeCategoryDetailProps) => {
+ const [params] = useUrlParams();
const sortOrderFetcher = useFetcher();
const attributeMap = useMemo(
@@ -168,12 +170,12 @@ const AttributeCategoryDetail = ({
to={sortId.toString()}
aria-label="Edit"
icon={<BsPencilSquare />}
- variant="ghost"
+ variant="outline"
/>
<IconButton
aria-label="Delete"
icon={<IoMdTrash />}
- variant="ghost"
+ variant="outline"
onClick={() =>
// @ts-ignore
onDelete(attributeMap[sortId])
@@ -187,16 +189,23 @@ const AttributeCategoryDetail = ({
)}
</DrawerBody>
<DrawerFooter>
- <Button as={Link} to="new" colorScheme="brand" size="md">
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ size="md"
+ >
New Attribute
</Button>
</DrawerFooter>
</DrawerContent>
</Drawer>
- <DeleteAttributeModal
- onCancel={onDeleteCancel}
+ <ConfirmDelete
isOpen={deleteModal.isOpen}
- data={selectedAttribute}
+ action={`/app/users/attribute/delete/${selectedAttribute?.id}`}
+ name={selectedAttribute?.name ?? ""}
+ text={`Are you sure you want to deactivate the ${selectedAttribute?.name} attribute?`}
+ onCancel={onDeleteCancel}
/>
</>
);
diff --git a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryForm/AttributeCategoryForm.tsx b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryForm/AttributeCategoryForm.tsx
index 3b7d12e45b..87d3e697d5 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryForm/AttributeCategoryForm.tsx
+++ b/apps/carbon/app/interfaces/Users/Attributes/AttributeCategoryForm/AttributeCategoryForm.tsx
@@ -4,6 +4,7 @@ import {
DrawerBody,
DrawerCloseButton,
DrawerContent,
+ DrawerFooter,
DrawerHeader,
DrawerOverlay,
HStack,
@@ -30,25 +31,25 @@ const AttributeCategoryForm = ({
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>
- {isEditing ? "Edit" : "New"} Attribute Category
- </DrawerHeader>
- <DrawerBody pb={8}>
- <ValidatedForm
- validator={attributeCategoryValidator}
- method="post"
- action={
- isEditing
- ? `/app/users/attributes/${initialValues.id}`
- : "/app/users/attributes/new"
- }
- defaultValues={initialValues}
- >
+ <ValidatedForm
+ validator={attributeCategoryValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/users/attributes/${initialValues.id}`
+ : "/app/users/attributes/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Attribute Category
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
<VStack spacing={4} alignItems="start">
- <Hidden name="id" />
<Input name="name" label="Category Name" />
<Boolean
name="isPublic"
@@ -56,6 +57,8 @@ const AttributeCategoryForm = ({
description="Visible on a user's public profile"
/>
</VStack>
+ </DrawerBody>
+ <DrawerFooter>
<HStack spacing={2} mt={8}>
<Submit>Save</Submit>
<Button
@@ -67,9 +70,9 @@ const AttributeCategoryForm = ({
Cancel
</Button>
</HStack>
- </ValidatedForm>
- </DrawerBody>
- </DrawerContent>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
</Drawer>
);
};
diff --git a/apps/carbon/app/interfaces/Users/Attributes/AttributeForm/AttributeForm.tsx b/apps/carbon/app/interfaces/Users/Attributes/AttributeForm/AttributeForm.tsx
index 4df064267e..05d19546de 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/AttributeForm/AttributeForm.tsx
+++ b/apps/carbon/app/interfaces/Users/Attributes/AttributeForm/AttributeForm.tsx
@@ -4,6 +4,7 @@ import {
DrawerBody,
DrawerCloseButton,
DrawerContent,
+ DrawerFooter,
DrawerHeader,
DrawerOverlay,
HStack,
@@ -68,23 +69,23 @@ const AttributeForm = ({
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{isEditing ? "Edit" : "New"} Attribute</DrawerHeader>
- <DrawerBody pb={8}>
- <ValidatedForm
- validator={attributeValidator}
- method="post"
- action={
- isEditing
- ? `/app/users/attribute/${initialValues.id}`
- : "/app/users/attribute/new"
- }
- defaultValues={initialValues}
- >
+ <ValidatedForm
+ validator={attributeValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/users/attribute/${initialValues.id}`
+ : "/app/users/attribute/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Attribute</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
<VStack spacing={2} alignItems="start">
- <Hidden name="id" />
<Input name="name" label="Name" />
<Hidden name="userAttributeCategoryId" />
@@ -105,7 +106,9 @@ const AttributeForm = ({
description="Users can update this value for themselves"
/>
</VStack>
- <HStack spacing={2} mt={8}>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
<Submit>Save</Submit>
<Button
size="md"
@@ -116,9 +119,9 @@ const AttributeForm = ({
Cancel
</Button>
</HStack>
- </ValidatedForm>
- </DrawerBody>
- </DrawerContent>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
</Drawer>
);
};
diff --git a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/DeleteAttributeCategoryModal.tsx b/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/DeleteAttributeCategoryModal.tsx
deleted file mode 100644
index a560cb2514..0000000000
--- a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/DeleteAttributeCategoryModal.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import {
- Button,
- Modal,
- ModalBody,
- ModalCloseButton,
- ModalContent,
- ModalFooter,
- ModalHeader,
- ModalOverlay,
-} from "@chakra-ui/react";
-import { Form } from "@remix-run/react";
-import type { AttributeCategory } from "../../types";
-
-type DeleteAttributeCategoryModalProps = {
- data?: AttributeCategory;
- isOpen: boolean;
- onCancel: () => void;
-};
-
-const DeleteAttributeCategoryModal = ({
- data,
- isOpen,
- onCancel,
-}: DeleteAttributeCategoryModalProps) => {
- return (
- <Modal isOpen={isOpen} onClose={onCancel}>
- <ModalOverlay />
- <ModalContent>
- <ModalHeader>Delete {data?.name}</ModalHeader>
- <ModalCloseButton />
- <ModalBody>
- Are you sure you want to deactivate the {data?.name} attribute
- category?
- </ModalBody>
-
- <ModalFooter>
- <Button colorScheme="gray" mr={3} onClick={onCancel}>
- Cancel
- </Button>
- <Form
- method="post"
- action={`/app/users/attributes/delete/${data?.id}`}
- onSubmit={onCancel}
- >
- <Button colorScheme="red" type="submit">
- Delete
- </Button>
- </Form>
- </ModalFooter>
- </ModalContent>
- </Modal>
- );
-};
-
-export default DeleteAttributeCategoryModal;
diff --git a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/index.ts b/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/index.ts
deleted file mode 100644
index 758047f1b2..0000000000
--- a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeCategoryModal/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DeleteAttributeCategoryModal from "./DeleteAttributeCategoryModal";
-
-export default DeleteAttributeCategoryModal;
diff --git a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/DeleteAttributeModal.tsx b/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/DeleteAttributeModal.tsx
deleted file mode 100644
index 75cea8bee8..0000000000
--- a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/DeleteAttributeModal.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import {
- Button,
- Modal,
- ModalBody,
- ModalCloseButton,
- ModalContent,
- ModalFooter,
- ModalHeader,
- ModalOverlay,
-} from "@chakra-ui/react";
-import { Form } from "@remix-run/react";
-import type { Attribute } from "../../types";
-
-type DeleteAttributeModalProps = {
- data?: Attribute;
- isOpen: boolean;
- onCancel: () => void;
-};
-
-const DeleteAttributeModal = ({
- data,
- isOpen,
- onCancel,
-}: DeleteAttributeModalProps) => {
- if (Array.isArray(data?.userAttributeCategory))
- throw new Error("received an array for userAttributeCategory");
-
- return (
- <Modal isOpen={isOpen} onClose={onCancel}>
- <ModalOverlay />
- <ModalContent>
- <ModalHeader>Delete {data?.name}</ModalHeader>
- <ModalCloseButton />
- <ModalBody>
- Are you sure you want to deactivate the {data?.name} attribute?
- </ModalBody>
-
- <ModalFooter>
- <Button colorScheme="gray" mr={3} onClick={onCancel}>
- Cancel
- </Button>
- <Form
- method="post"
- action={`/app/users/attribute/delete/${data?.id}`}
- onSubmit={onCancel}
- >
- <Button colorScheme="red" type="submit">
- Delete
- </Button>
- </Form>
- </ModalFooter>
- </ModalContent>
- </Modal>
- );
-};
-
-export default DeleteAttributeModal;
diff --git a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/index.ts b/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/index.ts
deleted file mode 100644
index a7fdb6d203..0000000000
--- a/apps/carbon/app/interfaces/Users/Attributes/DeleteAttributeModal/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DeleteAttributeModal from "./DeleteAttributeModal";
-
-export default DeleteAttributeModal;
diff --git a/apps/carbon/app/interfaces/Users/Attributes/index.ts b/apps/carbon/app/interfaces/Users/Attributes/index.ts
index 74c1ac62d5..7fc8699c10 100644
--- a/apps/carbon/app/interfaces/Users/Attributes/index.ts
+++ b/apps/carbon/app/interfaces/Users/Attributes/index.ts
@@ -3,8 +3,6 @@ import AttributeCategoriesTable from "./AttributeCategoriesTable";
import AttributeCategoriesTableFilters from "./AttributeCategoriesTableFilters";
import AttributeCategoryDetail from "./AttributeCategoryDetail";
import AttributeCategoryForm from "./AttributeCategoryForm";
-import DeleteAttributeModal from "./DeleteAttributeModal";
-import DeleteAttributeCategoryModal from "./DeleteAttributeCategoryModal";
export {
AttributeForm,
@@ -12,6 +10,4 @@ export {
AttributeCategoriesTableFilters,
AttributeCategoryDetail,
AttributeCategoryForm,
- DeleteAttributeModal,
- DeleteAttributeCategoryModal,
};
diff --git a/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/CreateCustomerModal.tsx b/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/CreateCustomerModal.tsx
new file mode 100644
index 0000000000..4e56c5414b
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/CreateCustomerModal.tsx
@@ -0,0 +1,117 @@
+import {
+ Grid,
+ HStack,
+ Input,
+ FormControl,
+ FormLabel,
+ Modal,
+ ModalBody,
+ ModalCloseButton,
+ ModalContent,
+ ModalHeader,
+ ModalOverlay,
+ VStack,
+} from "@chakra-ui/react";
+import { useFetcher, useNavigate } from "@remix-run/react";
+import { useRef, useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import { Customer, Submit, CustomerContact } from "~/components/Form";
+import { useUrlParams } from "~/hooks";
+import { createCustomerValidator } from "~/services/users";
+import type { Result } from "~/types";
+
+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
+ >();
+
+ return (
+ <Modal
+ initialFocusRef={initialFocusRef}
+ isOpen={true}
+ onClose={() => navigate(-1)}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>Create an account</ModalHeader>
+ <ModalCloseButton />
+ <ModalBody pb={6}>
+ <ValidatedForm
+ method="post"
+ action="/app/users/customers/new"
+ validator={createCustomerValidator}
+ defaultValues={{
+ id: params.get("id") ?? "",
+ customer: params.get("customer") ?? "",
+ }}
+ // @ts-ignore
+ fetcher={formFetcher}
+ >
+ <VStack spacing={4} alignItems="start" w="full">
+ <Customer
+ name="customer"
+ label="Customer"
+ onChange={(newValue) =>
+ setCustomer(newValue?.value as string | undefined)
+ }
+ />
+ <CustomerContact
+ name="id"
+ label="Customer Contact"
+ customer={customer}
+ onChange={(newValue) => {
+ // @ts-ignore
+ setContact(newValue?.contact);
+ }}
+ />
+ <FormControl>
+ <FormLabel>Email</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.email ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ <Grid templateColumns="1fr 1fr" gap={4}>
+ <FormControl>
+ <FormLabel>First Name</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.firstName ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ <FormControl>
+ <FormLabel>Last Name</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.lastName ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ </Grid>
+
+ <HStack spacing={4}>
+ <Submit>Create User</Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default CreateCustomerModal;
diff --git a/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/index.ts b/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/index.ts
new file mode 100644
index 0000000000..5d5da0c5ce
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CreateCustomerModal/index.ts
@@ -0,0 +1,3 @@
+import CreateCustomerModal from "./CreateCustomerModal";
+
+export default CreateCustomerModal;
diff --git a/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx
new file mode 100644
index 0000000000..d370d60c18
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx
@@ -0,0 +1,245 @@
+import { ActionMenu } from "@carbon/react";
+import {
+ Flex,
+ HStack,
+ MenuItem,
+ useDisclosure,
+ VisuallyHidden,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo, useState } from "react";
+import { BsEnvelope, BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Avatar, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Customer } from "~/interfaces/Users/types";
+import { ResendInviteModal, DeactivateUsersModal } from "~/interfaces/Users";
+import { FaBan } from "react-icons/fa";
+
+type CustomerAccountsTableProps = {
+ data: Customer[];
+ count: number;
+ isEditable?: boolean;
+};
+
+const defaultColumnVisibility = {
+ user_firstName: false,
+ user_lastName: false,
+};
+
+const CustomerAccountsTable = memo(
+ ({ data, count, isEditable = false }: CustomerAccountsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
+
+ const deactivateCustomerModal = useDisclosure();
+ const resendInviteModal = useDisclosure();
+
+ const rows = useMemo(
+ () =>
+ data.map((d) => {
+ // we should only have one user and customer per customer id
+ if (
+ d.user === null ||
+ d.customer === null ||
+ Array.isArray(d.user) ||
+ Array.isArray(d.customer)
+ ) {
+ throw new Error("Expected user and customer to be objects");
+ }
+
+ return d;
+ }),
+ [data]
+ );
+
+ const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ return [
+ {
+ header: "User",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <Avatar
+ size="sm"
+ // @ts-ignore
+ name={row.original.user?.fullName}
+ // @ts-ignore
+ path={row.original.user?.avatarUrl}
+ />
+
+ <span>
+ {
+ // @ts-ignore
+ `${row.original.user?.firstName} ${row.original.user?.lastName}`
+ }
+ </span>
+ </HStack>
+ ),
+ },
+
+ {
+ accessorKey: "user.firstName",
+ header: "First Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "user.lastName",
+ header: "Last Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "user.email",
+ header: "Email",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "customer.name",
+ header: "Customer",
+ cell: (item) => item.getValue(),
+ },
+ {
+ header: "Customer Type",
+ cell: ({ row }) => {
+ // @ts-ignore
+ const customerType = row.original.customer?.customerType;
+ return customerType ? customerType.name : "";
+ },
+ },
+ {
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ accessorKey: "user.id",
+ cell: (item) => (
+ <Flex justifyContent="end">
+ {permissions.can("update", "users") && (
+ <ActionMenu>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ onClick={() =>
+ navigate(
+ `/app/users/customers/${
+ item.getValue() as string
+ }?${params.toString()}`
+ )
+ }
+ >
+ Edit Customer
+ </MenuItem>
+ <MenuItem
+ icon={<BsEnvelope />}
+ onClick={() => {
+ setSelectedUserIds([item.getValue() as string]);
+ resendInviteModal.onOpen();
+ }}
+ >
+ Send Account Invite
+ </MenuItem>
+ {
+ // @ts-ignore
+ item.row.original.user?.active === true && (
+ <MenuItem
+ icon={<IoMdTrash />}
+ onClick={(e) => {
+ setSelectedUserIds([item.getValue() as string]);
+ deactivateCustomerModal.onOpen();
+ }}
+ >
+ Deactivate Customer
+ </MenuItem>
+ )
+ }
+ </ActionMenu>
+ )}
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ const actions = useMemo(() => {
+ return [
+ {
+ label: "Send Account Invite",
+ icon: <BsEnvelope />,
+ disabled: !permissions.can("create", "users"),
+ onClick: (selected: typeof rows) => {
+ setSelectedUserIds(
+ selected.reduce<string[]>((acc, row) => {
+ if (row.user && !Array.isArray(row.user)) {
+ acc.push(row.user.id);
+ }
+ return acc;
+ }, [])
+ );
+ resendInviteModal.onOpen();
+ },
+ },
+ {
+ label: "Deactivate Users",
+ icon: <FaBan />,
+ disabled: !permissions.can("delete", "users"),
+ onClick: (selected: typeof rows) => {
+ setSelectedUserIds(
+ selected.reduce<string[]>((acc, row) => {
+ if (row.user && !Array.isArray(row.user)) {
+ acc.push(row.user.id);
+ }
+ return acc;
+ }, [])
+ );
+ deactivateCustomerModal.onOpen();
+ },
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // const editableComponents = useMemo(
+ // () => ({
+ // "user.firstName": EditableName,
+ // "user.lastName": EditableName,
+ // }),
+ // []
+ // );
+
+ return (
+ <>
+ <Table<typeof rows[number]>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ withColumnOrdering
+ withFilters
+ withPagination
+ withSelectableRows={isEditable}
+ />
+
+ {deactivateCustomerModal.isOpen && (
+ <DeactivateUsersModal
+ userIds={selectedUserIds}
+ isOpen={deactivateCustomerModal.isOpen}
+ redirectTo="/app/users/suppliers"
+ onClose={deactivateCustomerModal.onClose}
+ />
+ )}
+ {resendInviteModal.isOpen && (
+ <ResendInviteModal
+ userIds={selectedUserIds}
+ isOpen={resendInviteModal.isOpen}
+ onClose={resendInviteModal.onClose}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+CustomerAccountsTable.displayName = "CustomerTable";
+
+export default CustomerAccountsTable;
diff --git a/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/index.ts b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/index.ts
new file mode 100644
index 0000000000..bb25aef5c5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTable/index.ts
@@ -0,0 +1,3 @@
+import CustomerAccountsTable from "./CustomerAccountsTable";
+
+export default CustomerAccountsTable;
diff --git a/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx
new file mode 100644
index 0000000000..66343dc0c3
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx
@@ -0,0 +1,100 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { CustomerType } from "~/interfaces/Sales/types";
+import { mapRowsToOptions } from "~/utils/form";
+
+type CustomerAccountsTableFiltersProps = {
+ customerTypes: Partial<CustomerType>[];
+};
+
+const CustomerAccountsTableFilters = ({
+ customerTypes,
+}: CustomerAccountsTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const customerTypeOptions = mapRowsToOptions({
+ data: customerTypes,
+ value: "id",
+ label: "name",
+ });
+
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={customerTypeOptions.filter(
+ (type) => type.value === params.get("type")
+ )}
+ isClearable
+ options={customerTypeOptions}
+ onChange={(selected) => {
+ setParams({ type: selected?.value });
+ }}
+ aria-label="Customer Type"
+ minW={180}
+ placeholder="Customer Type"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={
+ params.get("active") === "false"
+ ? { value: "false", label: "Inactive" }
+ : { value: "true", label: "Active" }
+ }
+ options={[
+ {
+ value: "true",
+ label: "Active",
+ },
+ {
+ value: "false",
+ label: "Inactive",
+ },
+ ]}
+ onChange={(selected) => {
+ setParams({ active: selected?.value });
+ }}
+ aria-label="Active"
+ minW={180}
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Customer
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default CustomerAccountsTableFilters;
diff --git a/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/index.ts b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/index.ts
new file mode 100644
index 0000000000..90c5535661
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/CustomerAccountsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import CustomerAccountsTableFilters from "./CustomerAccountsTableFilters";
+
+export default CustomerAccountsTableFilters;
diff --git a/apps/carbon/app/interfaces/Users/Customers/index.ts b/apps/carbon/app/interfaces/Users/Customers/index.ts
new file mode 100644
index 0000000000..aa276fb31c
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Customers/index.ts
@@ -0,0 +1,9 @@
+import CreateCustomerModal from "./CreateCustomerModal";
+import CustomerAccountsTable from "./CustomerAccountsTable";
+import CustomerAccountsTableFilters from "./CustomerAccountsTableFilters";
+
+export {
+ CreateCustomerModal,
+ CustomerAccountsTable,
+ CustomerAccountsTableFilters,
+};
diff --git a/apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/DeactivateEmployeesModal.tsx b/apps/carbon/app/interfaces/Users/DeactivateUsersModal/DeactivateUsersModal.tsx
similarity index 85%
rename from apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/DeactivateEmployeesModal.tsx
rename to apps/carbon/app/interfaces/Users/DeactivateUsersModal/DeactivateUsersModal.tsx
index 0d63b5c861..0c50b7f133 100644
--- a/apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/DeactivateEmployeesModal.tsx
+++ b/apps/carbon/app/interfaces/Users/DeactivateUsersModal/DeactivateUsersModal.tsx
@@ -14,17 +14,19 @@ import { ValidatedForm } from "remix-validated-form";
import { UserSelect } from "~/components/Selectors";
import { deactivateUsersValidator } from "~/services/users";
-type DeactivateEmployeesModalProps = {
+type DeactivateUsersModalProps = {
userIds: string[];
isOpen: boolean;
+ redirectTo?: string;
onClose: () => void;
};
-const DeactivateEmployeesModal = ({
+const DeactivateUsersModal = ({
userIds,
isOpen,
+ redirectTo = "/app/users/employees",
onClose,
-}: DeactivateEmployeesModalProps) => {
+}: DeactivateUsersModalProps) => {
const isSingleUser = userIds.length === 1;
return (
@@ -61,11 +63,7 @@ const DeactivateEmployeesModal = ({
value={id}
/>
))}
- <input
- type="hidden"
- name="redirectTo"
- value="/app/users/employees"
- />
+ <input type="hidden" name="redirectTo" value={redirectTo} />
<Button colorScheme="red" type="submit">
Deactivate
</Button>
@@ -77,4 +75,4 @@ const DeactivateEmployeesModal = ({
);
};
-export default DeactivateEmployeesModal;
+export default DeactivateUsersModal;
diff --git a/apps/carbon/app/interfaces/Users/DeactivateUsersModal/index.ts b/apps/carbon/app/interfaces/Users/DeactivateUsersModal/index.ts
new file mode 100644
index 0000000000..00d765483f
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/DeactivateUsersModal/index.ts
@@ -0,0 +1,3 @@
+import DeactivateUsersModal from "./DeactivateUsersModal";
+
+export default DeactivateUsersModal;
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/DeleteEmployeeTypeModal.tsx b/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/DeleteEmployeeTypeModal.tsx
deleted file mode 100644
index a095a98496..0000000000
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/DeleteEmployeeTypeModal.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import {
- Button,
- Modal,
- ModalBody,
- ModalCloseButton,
- ModalContent,
- ModalFooter,
- ModalHeader,
- ModalOverlay,
-} from "@chakra-ui/react";
-import { Form } from "@remix-run/react";
-import type { EmployeeType } from "../../types";
-
-type DeleteEmployeeTypeModalProps = {
- employeeTypeId: string;
- data: EmployeeType;
- onCancel: () => void;
-};
-
-const DeleteEmployeeTypeModal = ({
- data,
- onCancel,
-}: DeleteEmployeeTypeModalProps) => {
- return (
- <Modal isOpen={true} onClose={onCancel}>
- <ModalOverlay />
- <ModalContent>
- <ModalHeader>Delete {data?.name}</ModalHeader>
- <ModalCloseButton />
- <ModalBody>
- Are you sure you want to delete the {data?.name} employee type? This
- cannot be undone.
- </ModalBody>
-
- <ModalFooter>
- <Button colorScheme="gray" mr={3} onClick={onCancel}>
- Cancel
- </Button>
- <Form method="post">
- <Button colorScheme="red" type="submit">
- Delete
- </Button>
- </Form>
- </ModalFooter>
- </ModalContent>
- </Modal>
- );
-};
-
-export default DeleteEmployeeTypeModal;
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/index.ts b/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/index.ts
deleted file mode 100644
index 51bb69a106..0000000000
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/DeleteEmployeeTypeModal/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DeleteEmployeeTypeModal from "./DeleteEmployeeTypeModal";
-
-export default DeleteEmployeeTypeModal;
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypeForm/EmployeeTypeForm.tsx b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypeForm/EmployeeTypeForm.tsx
index 22c3a346b3..f016ca6e41 100644
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypeForm/EmployeeTypeForm.tsx
+++ b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypeForm/EmployeeTypeForm.tsx
@@ -5,6 +5,7 @@ import {
DrawerBody,
DrawerCloseButton,
DrawerContent,
+ DrawerFooter,
DrawerHeader,
DrawerOverlay,
FormLabel,
@@ -53,23 +54,25 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{isEditing ? "Edit" : "New"} Employee Type</DrawerHeader>
- <DrawerBody pb={8}>
- <ValidatedForm
- validator={employeeTypeValidator}
- method="post"
- action={
- isEditing
- ? `/app/users/employee-types/${initialValues.id}`
- : "/app/users/employee-types/new"
- }
- defaultValues={initialValues}
- >
+ <ValidatedForm
+ validator={employeeTypeValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/users/employee-types/${initialValues.id}`
+ : "/app/users/employee-types/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Employee Type
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
<VStack spacing={4} alignItems="start">
- <Hidden name="id" />
<Input name="name" label="Employee Type" />
<Color name="color" label="Color" />
<Hidden
@@ -78,7 +81,7 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
/>
</VStack>
<VStack spacing={2} alignItems="start">
- <FormLabel>Permissions</FormLabel>
+ <FormLabel>Default Permissions</FormLabel>
{Object.entries(permissions)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([module, data], index) => (
@@ -91,6 +94,8 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
</Box>
))}
</VStack>
+ </DrawerBody>
+ <DrawerFooter>
<HStack spacing={2}>
<Submit>Save</Submit>
<Button
@@ -102,9 +107,9 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
Cancel
</Button>
</HStack>
- </ValidatedForm>
- </DrawerBody>
- </DrawerContent>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
</Drawer>
);
};
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
index ad19302760..52a1a63bb7 100644
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
+++ b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
@@ -6,7 +6,7 @@ import { memo, useMemo } from "react";
import { BsPencilSquare, BsPeopleFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { Table } from "~/components";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
import type { EmployeeType } from "~/interfaces/Users/types";
type EmployeeTypesTableProps = {
@@ -15,6 +15,7 @@ type EmployeeTypesTableProps = {
};
const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
+ const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -59,7 +60,11 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
}
icon={<BsPencilSquare />}
onClick={() => {
- navigate(`/app/users/employee-types/${row.original.id}`);
+ navigate(
+ `/app/users/employee-types/${
+ row.original.id
+ }?${params.toString()}`
+ );
}}
>
Edit Employee Type
@@ -71,7 +76,9 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
icon={<IoMdTrash />}
onClick={() => {
navigate(
- `/app/users/employee-types/delete/${row.original.id}`
+ `/app/users/employee-types/delete/${
+ row.original.id
+ }?${params.toString()}`
);
}}
>
@@ -83,7 +90,7 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [params]);
return (
<Table<typeof data[number]> data={data} columns={columns} count={count} />
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
index 1621a70fb6..3d8447cf72 100644
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
+++ b/apps/carbon/app/interfaces/Users/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
@@ -3,9 +3,10 @@ import { Button, HStack } from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
const EmployeeTypesTableFilters = () => {
+ const [params] = useUrlParams();
const permissions = usePermissions();
const borderColor = useColor("gray.200");
return (
@@ -28,7 +29,12 @@ const EmployeeTypesTableFilters = () => {
</HStack>
<HStack spacing={2}>
{permissions.can("create", "users") && (
- <Button as={Link} to="new" colorScheme="brand" leftIcon={<IoMdAdd />}>
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
New Employee Type
</Button>
)}
diff --git a/apps/carbon/app/interfaces/Users/EmployeeTypes/index.ts b/apps/carbon/app/interfaces/Users/EmployeeTypes/index.ts
index 71521b6580..001dab2c1a 100644
--- a/apps/carbon/app/interfaces/Users/EmployeeTypes/index.ts
+++ b/apps/carbon/app/interfaces/Users/EmployeeTypes/index.ts
@@ -1,11 +1,5 @@
-import DeleteEmployeeTypeModal from "./DeleteEmployeeTypeModal";
import EmployeeTypeForm from "./EmployeeTypeForm";
import EmployeeTypesTable from "./EmployeeTypesTable";
import EmployeeTypesTableFilters from "./EmployeeTypesTableFilters";
-export {
- DeleteEmployeeTypeModal,
- EmployeeTypeForm,
- EmployeeTypesTable,
- EmployeeTypesTableFilters,
-};
+export { EmployeeTypeForm, EmployeeTypesTable, EmployeeTypesTableFilters };
diff --git a/apps/carbon/app/interfaces/Users/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx b/apps/carbon/app/interfaces/Users/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx
index 482cbaf144..6c32b25185 100644
--- a/apps/carbon/app/interfaces/Users/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx
+++ b/apps/carbon/app/interfaces/Users/Employees/CreateEmployeeModal/CreateEmployeeModal.tsx
@@ -40,7 +40,7 @@ const CreateEmployeeModal = () => {
<Modal
initialFocusRef={initialFocusRef}
isOpen={true}
- onClose={() => navigate("/app/users/employees")}
+ onClose={() => navigate(-1)}
>
<ModalOverlay />
<ModalContent>
@@ -54,7 +54,7 @@ const CreateEmployeeModal = () => {
// @ts-ignore
fetcher={formFetcher}
>
- <VStack spacing={4} alignItems="start">
+ <VStack spacing={4} alignItems="start" w="full">
<Input ref={initialFocusRef} name="email" label="Email" />
<Grid templateColumns="1fr 1fr" gap={4}>
<Input name="firstName" label="First Name" />
diff --git a/apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/index.ts b/apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/index.ts
deleted file mode 100644
index e69991d9fa..0000000000
--- a/apps/carbon/app/interfaces/Users/Employees/DeactivateEmployeesModal/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-import DeactivateEmployeesModal from "./DeactivateEmployeesModal";
-export default DeactivateEmployeesModal;
diff --git a/apps/carbon/app/interfaces/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx b/apps/carbon/app/interfaces/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx
index 4c7ed73958..aa5359476c 100644
--- a/apps/carbon/app/interfaces/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx
+++ b/apps/carbon/app/interfaces/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx
@@ -5,6 +5,7 @@ import {
DrawerBody,
DrawerCloseButton,
DrawerContent,
+ DrawerFooter,
DrawerHeader,
DrawerOverlay,
FormLabel,
@@ -60,17 +61,17 @@ const EmployeePermissionsForm = ({
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{name}</DrawerHeader>
- <DrawerBody pb={8}>
- <ValidatedForm
- validator={employeeValidator}
- method="post"
- action={`/app/users/employees/${initialValues.id}`}
- defaultValues={initialValues}
- >
+ <ValidatedForm
+ validator={employeeValidator}
+ method="post"
+ action={`/app/users/employees/${initialValues.id}`}
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{name}</DrawerHeader>
+ <DrawerBody pb={8}>
<VStack spacing={4} alignItems="start">
<Select
name="employeeType"
@@ -94,6 +95,8 @@ const EmployeePermissionsForm = ({
<Hidden name="id" />
<Hidden name="data" value={JSON.stringify(permissions)} />
</VStack>
+ </DrawerBody>
+ <DrawerFooter>
<HStack spacing={2}>
<Submit>Save</Submit>
<Button
@@ -105,9 +108,9 @@ const EmployeePermissionsForm = ({
Cancel
</Button>
</HStack>
- </ValidatedForm>
- </DrawerBody>
- </DrawerContent>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
</Drawer>
);
};
diff --git a/apps/carbon/app/interfaces/Users/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/interfaces/Users/Employees/EmployeesTable/EmployeesTable.tsx
index 01af9062c8..f4574ade33 100644
--- a/apps/carbon/app/interfaces/Users/Employees/EmployeesTable/EmployeesTable.tsx
+++ b/apps/carbon/app/interfaces/Users/Employees/EmployeesTable/EmployeesTable.tsx
@@ -12,13 +12,10 @@ import { memo, useMemo, useState } from "react";
import { BsEnvelope, BsPencilSquare, BsShieldLock } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { Avatar, Table } from "~/components";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
import type { Employee } from "~/interfaces/Users/types";
-import {
- BulkEditPermissionsForm,
- DeactivateEmployeesModal,
- ResendInviteModal,
-} from "~/interfaces/Users/Employees";
+import { BulkEditPermissionsForm } from "~/interfaces/Users/Employees";
+import { ResendInviteModal, DeactivateUsersModal } from "~/interfaces/Users";
import { FaBan } from "react-icons/fa";
type EmployeesTableProps = {
@@ -36,6 +33,7 @@ const EmployeesTable = memo(
({ data, count, isEditable = false }: EmployeesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
+ const [params] = useUrlParams();
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
@@ -116,7 +114,9 @@ const EmployeesTable = memo(
icon={<BsPencilSquare />}
onClick={() =>
navigate(
- `/app/users/employees/${item.getValue() as string}`
+ `/app/users/employees/${
+ item.getValue() as string
+ }?${params.toString()}`
)
}
>
@@ -152,7 +152,7 @@ const EmployeesTable = memo(
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [params]);
const actions = useMemo(() => {
return [
@@ -237,7 +237,7 @@ const EmployeesTable = memo(
/>
)}
{deactivateEmployeeModal.isOpen && (
- <DeactivateEmployeesModal
+ <DeactivateUsersModal
userIds={selectedUserIds}
isOpen={deactivateEmployeeModal.isOpen}
onClose={deactivateEmployeeModal.onClose}
diff --git a/apps/carbon/app/interfaces/Users/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx b/apps/carbon/app/interfaces/Users/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
index 237728d46f..a091f82cc4 100644
--- a/apps/carbon/app/interfaces/Users/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
+++ b/apps/carbon/app/interfaces/Users/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
@@ -1,19 +1,20 @@
import { Select, useColor } from "@carbon/react";
import { Button, HStack } from "@chakra-ui/react";
-import { useNavigate } from "@remix-run/react";
+import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
import type { EmployeeType } from "~/interfaces/Users/types";
import { mapRowsToOptions } from "~/utils/form";
-type EmployeeTypeFiltersProps = {
+type EmployeesTableFiltersProps = {
employeeTypes: Partial<EmployeeType>[];
};
-const EmployeesTableFilters = ({ employeeTypes }: EmployeeTypeFiltersProps) => {
+const EmployeesTableFilters = ({
+ employeeTypes,
+}: EmployeesTableFiltersProps) => {
const [params, setParams] = useUrlParams();
- const navigate = useNavigate();
const permissions = usePermissions();
const employeeTypeOptions = mapRowsToOptions({
data: employeeTypes,
@@ -83,10 +84,9 @@ const EmployeesTableFilters = ({ employeeTypes }: EmployeeTypeFiltersProps) => {
<HStack spacing={2}>
{permissions.can("create", "users") && (
<Button
+ as={Link}
+ to={`new?${params.toString()}`}
colorScheme="brand"
- onClick={() => {
- navigate("new");
- }}
leftIcon={<IoMdAdd />}
>
New Employee
diff --git a/apps/carbon/app/interfaces/Users/Employees/index.ts b/apps/carbon/app/interfaces/Users/Employees/index.ts
index c5242a9bb8..e93d3d9501 100644
--- a/apps/carbon/app/interfaces/Users/Employees/index.ts
+++ b/apps/carbon/app/interfaces/Users/Employees/index.ts
@@ -1,17 +1,13 @@
import CreateEmployeeModal from "./CreateEmployeeModal";
import BulkEditPermissionsForm from "./BulkEditPermissionsForm";
-import DeactivateEmployeesModal from "./DeactivateEmployeesModal";
import EmployeePermissionsForm from "./EmployeePermissionsForm";
import EmployeesTable from "./EmployeesTable";
import EmployeesTableFilters from "./EmployeesTableFilters";
-import ResendInviteModal from "./ResendInviteModal";
export {
CreateEmployeeModal,
BulkEditPermissionsForm,
- DeactivateEmployeesModal,
EmployeePermissionsForm,
EmployeesTable,
EmployeesTableFilters,
- ResendInviteModal,
};
diff --git a/apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/index.ts b/apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/index.ts
deleted file mode 100644
index 71d88bfd36..0000000000
--- a/apps/carbon/app/interfaces/Users/Groups/DeleteGroupsModal/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DeleteGroupModal from "./DeleteGroupsModal";
-
-export default DeleteGroupModal;
diff --git a/apps/carbon/app/interfaces/Users/Groups/GroupsForm/GroupsForm.tsx b/apps/carbon/app/interfaces/Users/Groups/GroupsForm/GroupsForm.tsx
index f790b56b71..75feca47ce 100644
--- a/apps/carbon/app/interfaces/Users/Groups/GroupsForm/GroupsForm.tsx
+++ b/apps/carbon/app/interfaces/Users/Groups/GroupsForm/GroupsForm.tsx
@@ -4,6 +4,7 @@ import {
DrawerBody,
DrawerCloseButton,
DrawerContent,
+ DrawerFooter,
DrawerHeader,
DrawerOverlay,
HStack,
@@ -30,44 +31,46 @@ const GroupForm = ({ initialValues }: GroupFormProps) => {
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{isEditing ? "Edit" : "New"} Group</DrawerHeader>
- <DrawerBody pb={8}>
- <ValidatedForm
- validator={groupValidator}
- method="post"
- action={
- isEditing
- ? `/app/users/groups/${initialValues.id}`
- : "/app/users/groups/new"
- }
- defaultValues={initialValues}
- >
+ <ValidatedForm
+ validator={groupValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/app/users/groups/${initialValues.id}`
+ : "/app/users/groups/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Group</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
<VStack spacing={4} alignItems="start">
- <Hidden name="id" />
<Input name="name" label="Group Name" />
<Users
name="selections"
selectionsMaxHeight={"calc(100vh - 330px)"}
label="Group Members"
/>
- <HStack spacing={2} my={4}>
- <Submit>Save</Submit>
- <Button
- size="md"
- colorScheme="gray"
- variant="solid"
- onClick={onClose}
- >
- Cancel
- </Button>
- </HStack>
</VStack>
- </ValidatedForm>
- </DrawerBody>
- </DrawerContent>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
</Drawer>
);
};
diff --git a/apps/carbon/app/interfaces/Users/Groups/GroupsTable/GroupsTable.tsx b/apps/carbon/app/interfaces/Users/Groups/GroupsTable/GroupsTable.tsx
index b7ed13ea8a..77735c8b72 100644
--- a/apps/carbon/app/interfaces/Users/Groups/GroupsTable/GroupsTable.tsx
+++ b/apps/carbon/app/interfaces/Users/Groups/GroupsTable/GroupsTable.tsx
@@ -22,6 +22,8 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {
id: row.data.id,
name: row.data.name,
isEmployeeTypeGroup: row.data.isEmployeeTypeGroup,
+ isCustomerTypeGroup: row.data.isCustomerTypeGroup,
+ isSupplierTypeGroup: row.data.isSupplierTypeGroup,
members: row.data.users
.map((user) => ({
name: user.fullName,
@@ -84,6 +86,8 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {
<MenuItem
isDisabled={
row.original.isEmployeeTypeGroup ||
+ row.original.isCustomerTypeGroup ||
+ row.original.isSupplierTypeGroup ||
!permissions.can("delete", "users")
}
icon={<IoMdTrash />}
diff --git a/apps/carbon/app/interfaces/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx b/apps/carbon/app/interfaces/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
index b89bdb83ff..bfd68db6e1 100644
--- a/apps/carbon/app/interfaces/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
+++ b/apps/carbon/app/interfaces/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
@@ -3,9 +3,10 @@ import { Button, HStack } from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUrlParams } from "~/hooks";
const GroupsTableFilters = () => {
+ const [params] = useUrlParams();
const permissions = usePermissions();
const borderColor = useColor("gray.200");
return (
@@ -28,7 +29,12 @@ const GroupsTableFilters = () => {
</HStack>
<HStack spacing={2}>
{permissions.can("create", "users") && (
- <Button as={Link} to="new" colorScheme="brand" leftIcon={<IoMdAdd />}>
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
New Group
</Button>
)}
diff --git a/apps/carbon/app/interfaces/Users/Groups/index.ts b/apps/carbon/app/interfaces/Users/Groups/index.ts
index 84b279c042..90d56a4f65 100644
--- a/apps/carbon/app/interfaces/Users/Groups/index.ts
+++ b/apps/carbon/app/interfaces/Users/Groups/index.ts
@@ -1,6 +1,5 @@
-import DeleteGroupModal from "./DeleteGroupsModal";
import GroupForm from "./GroupsForm";
import GroupsTable from "./GroupsTable";
import GroupsTableFilters from "./GroupsTableFilters";
-export { DeleteGroupModal, GroupForm, GroupsTable, GroupsTableFilters };
+export { GroupForm, GroupsTable, GroupsTableFilters };
diff --git a/apps/carbon/app/interfaces/Users/Employees/ResendInviteModal/ResendInviteModal.tsx b/apps/carbon/app/interfaces/Users/ResendInviteModal/ResendInviteModal.tsx
similarity index 100%
rename from apps/carbon/app/interfaces/Users/Employees/ResendInviteModal/ResendInviteModal.tsx
rename to apps/carbon/app/interfaces/Users/ResendInviteModal/ResendInviteModal.tsx
diff --git a/apps/carbon/app/interfaces/Users/Employees/ResendInviteModal/index.ts b/apps/carbon/app/interfaces/Users/ResendInviteModal/index.ts
similarity index 100%
rename from apps/carbon/app/interfaces/Users/Employees/ResendInviteModal/index.ts
rename to apps/carbon/app/interfaces/Users/ResendInviteModal/index.ts
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
new file mode 100644
index 0000000000..dc94af69a0
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
@@ -0,0 +1,117 @@
+import {
+ Grid,
+ HStack,
+ Input,
+ FormControl,
+ FormLabel,
+ Modal,
+ ModalBody,
+ ModalCloseButton,
+ ModalContent,
+ ModalHeader,
+ ModalOverlay,
+ VStack,
+} from "@chakra-ui/react";
+import { useFetcher, useNavigate } from "@remix-run/react";
+import { useRef, useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import { Supplier, Submit, SupplierContact } from "~/components/Form";
+import { useUrlParams } from "~/hooks";
+import { createSupplierValidator } from "~/services/users";
+import type { Result } from "~/types";
+
+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
+ >();
+
+ return (
+ <Modal
+ initialFocusRef={initialFocusRef}
+ isOpen={true}
+ onClose={() => navigate(-1)}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>Create an account</ModalHeader>
+ <ModalCloseButton />
+ <ModalBody pb={6}>
+ <ValidatedForm
+ method="post"
+ action="/app/users/suppliers/new"
+ validator={createSupplierValidator}
+ defaultValues={{
+ id: params.get("id") ?? "",
+ supplier: params.get("supplier") ?? "",
+ }}
+ // @ts-ignore
+ fetcher={formFetcher}
+ >
+ <VStack spacing={4} alignItems="start" w="full">
+ <Supplier
+ name="supplier"
+ label="Supplier"
+ onChange={(newValue) =>
+ setSupplier(newValue?.value as string | undefined)
+ }
+ />
+ <SupplierContact
+ name="id"
+ label="Supplier Contact"
+ supplier={supplier}
+ onChange={(newValue) => {
+ // @ts-ignore
+ setContact(newValue?.contact);
+ }}
+ />
+ <FormControl>
+ <FormLabel>Email</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.email ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ <Grid templateColumns="1fr 1fr" gap={4}>
+ <FormControl>
+ <FormLabel>First Name</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.firstName ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ <FormControl>
+ <FormLabel>Last Name</FormLabel>
+ <Input
+ isReadOnly
+ value={contact?.lastName ?? ""}
+ variant="filled"
+ />
+ </FormControl>
+ </Grid>
+
+ <HStack spacing={4}>
+ <Submit>Create User</Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default CreateSupplierModal;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/index.ts b/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/index.ts
new file mode 100644
index 0000000000..73a63f04f1
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/CreateSupplierModal/index.ts
@@ -0,0 +1,3 @@
+import CreateSupplierModal from "./CreateSupplierModal";
+
+export default CreateSupplierModal;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx
new file mode 100644
index 0000000000..ad1a306820
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx
@@ -0,0 +1,245 @@
+import { ActionMenu } from "@carbon/react";
+import {
+ Flex,
+ HStack,
+ MenuItem,
+ useDisclosure,
+ VisuallyHidden,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo, useState } from "react";
+import { BsEnvelope, BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Avatar, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Supplier } from "~/interfaces/Users/types";
+import { ResendInviteModal, DeactivateUsersModal } from "~/interfaces/Users";
+import { FaBan } from "react-icons/fa";
+
+type SupplierAccountsTableProps = {
+ data: Supplier[];
+ count: number;
+ isEditable?: boolean;
+};
+
+const defaultColumnVisibility = {
+ user_firstName: false,
+ user_lastName: false,
+};
+
+const SupplierAccountsTable = memo(
+ ({ data, count, isEditable = false }: SupplierAccountsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
+
+ const deactivateSupplierModal = useDisclosure();
+ const resendInviteModal = useDisclosure();
+
+ const rows = useMemo(
+ () =>
+ data.map((d) => {
+ // we should only have one user and supplier per supplier id
+ if (
+ d.user === null ||
+ d.supplier === null ||
+ Array.isArray(d.user) ||
+ Array.isArray(d.supplier)
+ ) {
+ throw new Error("Expected user and supplier to be objects");
+ }
+
+ return d;
+ }),
+ [data]
+ );
+
+ const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ return [
+ {
+ header: "User",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <Avatar
+ size="sm"
+ // @ts-ignore
+ name={row.original.user?.fullName}
+ // @ts-ignore
+ path={row.original.user?.avatarUrl}
+ />
+
+ <span>
+ {
+ // @ts-ignore
+ `${row.original.user?.firstName} ${row.original.user?.lastName}`
+ }
+ </span>
+ </HStack>
+ ),
+ },
+
+ {
+ accessorKey: "user.firstName",
+ header: "First Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "user.lastName",
+ header: "Last Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "user.email",
+ header: "Email",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "supplier.name",
+ header: "Supplier",
+ cell: (item) => item.getValue(),
+ },
+ {
+ header: "Supplier Type",
+ cell: ({ row }) => {
+ // @ts-ignore
+ const supplierType = row.original.supplier?.supplierType;
+ return supplierType ? supplierType.name : "";
+ },
+ },
+ {
+ header: () => <VisuallyHidden>Actions</VisuallyHidden>,
+ accessorKey: "user.id",
+ cell: (item) => (
+ <Flex justifyContent="end">
+ {permissions.can("update", "users") && (
+ <ActionMenu>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ onClick={() =>
+ navigate(
+ `/app/users/suppliers/${
+ item.getValue() as string
+ }?${params.toString()}`
+ )
+ }
+ >
+ Edit Supplier
+ </MenuItem>
+ <MenuItem
+ icon={<BsEnvelope />}
+ onClick={() => {
+ setSelectedUserIds([item.getValue() as string]);
+ resendInviteModal.onOpen();
+ }}
+ >
+ Send Account Invite
+ </MenuItem>
+ {
+ // @ts-ignore
+ item.row.original.user?.active === true && (
+ <MenuItem
+ icon={<IoMdTrash />}
+ onClick={(e) => {
+ setSelectedUserIds([item.getValue() as string]);
+ deactivateSupplierModal.onOpen();
+ }}
+ >
+ Deactivate Supplier
+ </MenuItem>
+ )
+ }
+ </ActionMenu>
+ )}
+ </Flex>
+ ),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
+
+ const actions = useMemo(() => {
+ return [
+ {
+ label: "Send Account Invite",
+ icon: <BsEnvelope />,
+ disabled: !permissions.can("create", "users"),
+ onClick: (selected: typeof rows) => {
+ setSelectedUserIds(
+ selected.reduce<string[]>((acc, row) => {
+ if (row.user && !Array.isArray(row.user)) {
+ acc.push(row.user.id);
+ }
+ return acc;
+ }, [])
+ );
+ resendInviteModal.onOpen();
+ },
+ },
+ {
+ label: "Deactivate Users",
+ icon: <FaBan />,
+ disabled: !permissions.can("delete", "users"),
+ onClick: (selected: typeof rows) => {
+ setSelectedUserIds(
+ selected.reduce<string[]>((acc, row) => {
+ if (row.user && !Array.isArray(row.user)) {
+ acc.push(row.user.id);
+ }
+ return acc;
+ }, [])
+ );
+ deactivateSupplierModal.onOpen();
+ },
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // const editableComponents = useMemo(
+ // () => ({
+ // "user.firstName": EditableName,
+ // "user.lastName": EditableName,
+ // }),
+ // []
+ // );
+
+ return (
+ <>
+ <Table<typeof rows[number]>
+ actions={actions}
+ count={count}
+ columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ withColumnOrdering
+ withFilters
+ withPagination
+ withSelectableRows={isEditable}
+ />
+
+ {deactivateSupplierModal.isOpen && (
+ <DeactivateUsersModal
+ userIds={selectedUserIds}
+ isOpen={deactivateSupplierModal.isOpen}
+ redirectTo="/app/users/suppliers"
+ onClose={deactivateSupplierModal.onClose}
+ />
+ )}
+ {resendInviteModal.isOpen && (
+ <ResendInviteModal
+ userIds={selectedUserIds}
+ isOpen={resendInviteModal.isOpen}
+ onClose={resendInviteModal.onClose}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+SupplierAccountsTable.displayName = "SupplierTable";
+
+export default SupplierAccountsTable;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/index.ts b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/index.ts
new file mode 100644
index 0000000000..5906a18fc5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTable/index.ts
@@ -0,0 +1,3 @@
+import SupplierAccountsTable from "./SuppliersAccountsTable";
+
+export default SupplierAccountsTable;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx
new file mode 100644
index 0000000000..3b4c929d50
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx
@@ -0,0 +1,100 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { SupplierType } from "~/interfaces/Purchasing/types";
+import { mapRowsToOptions } from "~/utils/form";
+
+type SupplierAccountsTableFiltersProps = {
+ supplierTypes: Partial<SupplierType>[];
+};
+
+const SupplierAccountsTableFilters = ({
+ supplierTypes,
+}: SupplierAccountsTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const supplierTypeOptions = mapRowsToOptions({
+ data: supplierTypes,
+ value: "id",
+ label: "name",
+ });
+
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={supplierTypeOptions.filter(
+ (type) => type.value === params.get("type")
+ )}
+ isClearable
+ options={supplierTypeOptions}
+ onChange={(selected) => {
+ setParams({ type: selected?.value });
+ }}
+ aria-label="Supplier Type"
+ minW={180}
+ placeholder="Supplier Type"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={
+ params.get("active") === "false"
+ ? { value: "false", label: "Inactive" }
+ : { value: "true", label: "Active" }
+ }
+ options={[
+ {
+ value: "true",
+ label: "Active",
+ },
+ {
+ value: "false",
+ label: "Inactive",
+ },
+ ]}
+ onChange={(selected) => {
+ setParams({ active: selected?.value });
+ }}
+ aria-label="Active"
+ minW={180}
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Supplier
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default SupplierAccountsTableFilters;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/index.ts b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/index.ts
new file mode 100644
index 0000000000..6d9f8687c5
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/SupplierAccountsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import SupplierAccountsTableFilters from "./SupplierAccountsTableFilters";
+
+export default SupplierAccountsTableFilters;
diff --git a/apps/carbon/app/interfaces/Users/Suppliers/index.ts b/apps/carbon/app/interfaces/Users/Suppliers/index.ts
new file mode 100644
index 0000000000..cd470fdd65
--- /dev/null
+++ b/apps/carbon/app/interfaces/Users/Suppliers/index.ts
@@ -0,0 +1,9 @@
+import CreateSupplierModal from "./CreateSupplierModal";
+import SupplierAccountsTable from "./SupplierAccountsTable";
+import SupplierAccountsTableFilters from "./SupplierAccountsTableFilters";
+
+export {
+ CreateSupplierModal,
+ SupplierAccountsTable,
+ SupplierAccountsTableFilters,
+};
diff --git a/apps/carbon/app/interfaces/Users/index.ts b/apps/carbon/app/interfaces/Users/index.ts
index 3b5dbf4b25..7b4d4cb573 100644
--- a/apps/carbon/app/interfaces/Users/index.ts
+++ b/apps/carbon/app/interfaces/Users/index.ts
@@ -1,3 +1,5 @@
+import DeactivateUsersModal from "./DeactivateUsersModal";
+import ResendInviteModal from "./ResendInviteModal";
import useUsersSidebar from "./useUsersSidebar";
-export { useUsersSidebar };
+export { DeactivateUsersModal, ResendInviteModal, useUsersSidebar };
diff --git a/apps/carbon/app/interfaces/Users/types.ts b/apps/carbon/app/interfaces/Users/types.ts
index 16be7f3b6a..5d6de43f61 100644
--- a/apps/carbon/app/interfaces/Users/types.ts
+++ b/apps/carbon/app/interfaces/Users/types.ts
@@ -3,10 +3,12 @@ import type {
getAttribute,
getAttributeCategories,
getAttributeCategory,
+ getCustomers,
getEmployees,
getEmployeeTypes,
getFeatures,
getPermissionsByEmployeeType,
+ getSuppliers,
getUsers,
} from "~/services/users";
@@ -32,6 +34,10 @@ export type AttributeDataType = {
isText: boolean;
};
+export type Customer = NonNullable<
+ Awaited<ReturnType<typeof getCustomers>>["data"]
+>[number];
+
export enum DataType {
Boolean = 1,
Date = 2,
@@ -63,6 +69,10 @@ export type Group = {
data: {
id: string;
isEmployeeTypeGroup: boolean;
+ isCustomerOrgGroup: boolean;
+ isCustomerTypeGroup: boolean;
+ isSupplierOrgGroup: boolean;
+ isSupplierTypeGroup: boolean;
name: string;
users: User[];
};
@@ -76,6 +86,10 @@ export type Permission = {
delete: boolean;
};
+export type Supplier = NonNullable<
+ Awaited<ReturnType<typeof getSuppliers>>["data"]
+>[number];
+
export type User = NonNullable<
Awaited<ReturnType<typeof getUsers>>["data"]
>[number];
diff --git a/apps/carbon/app/queue/bulk-permissions.queue.server.ts b/apps/carbon/app/queues/bulk-permissions.queue.server.ts
similarity index 100%
rename from apps/carbon/app/queue/bulk-permissions.queue.server.ts
rename to apps/carbon/app/queues/bulk-permissions.queue.server.ts
diff --git a/apps/carbon/app/queue/deactivate-users.queue.server.ts b/apps/carbon/app/queues/deactivate-users.queue.server.ts
similarity index 100%
rename from apps/carbon/app/queue/deactivate-users.queue.server.ts
rename to apps/carbon/app/queues/deactivate-users.queue.server.ts
diff --git a/apps/carbon/app/queue/index.ts b/apps/carbon/app/queues/index.ts
similarity index 100%
rename from apps/carbon/app/queue/index.ts
rename to apps/carbon/app/queues/index.ts
diff --git a/apps/carbon/app/queue/resend-invites.queue.server.ts b/apps/carbon/app/queues/resend-invites.queue.server.ts
similarity index 100%
rename from apps/carbon/app/queue/resend-invites.queue.server.ts
rename to apps/carbon/app/queues/resend-invites.queue.server.ts
diff --git a/apps/carbon/app/routes/app.account.tsx b/apps/carbon/app/routes/app.account.tsx
index 68276304a9..3d39489126 100644
--- a/apps/carbon/app/routes/app.account.tsx
+++ b/apps/carbon/app/routes/app.account.tsx
@@ -1,7 +1,6 @@
-import { useColor } from "@carbon/react";
-import { Button, Grid, VStack } from "@chakra-ui/react";
+import { Grid, VStack } from "@chakra-ui/react";
import type { MetaFunction } from "@remix-run/node";
-import { Link, Outlet, useMatches } from "@remix-run/react";
+import { Outlet } from "@remix-run/react";
import { ContentSidebar } from "~/components/Layout/Sidebar";
import { useAccountSidebar } from "~/interfaces/Account";
@@ -11,44 +10,10 @@ export const meta: MetaFunction = () => ({
export default function AccountRoute() {
const { links } = useAccountSidebar();
- const matches = useMatches();
- const borderColor = useColor("gray.200");
return (
<Grid w="full" h="full" templateColumns="auto 1fr">
- <ContentSidebar>
- <VStack spacing={2}>
- <VStack
- spacing={1}
- alignItems="start"
- borderBottomStyle={"solid"}
- borderBottomWidth={1}
- borderBottomColor={borderColor}
- px={2}
- py={4}
- w="full"
- >
- {links.map((route) => {
- const isActive = matches.some((match) =>
- match.pathname.includes(route.to)
- );
- return (
- <Button
- key={route.name}
- as={Link}
- to={route.to}
- variant={isActive ? "solid" : "ghost"}
- fontWeight={isActive ? "bold" : "normal"}
- justifyContent="start"
- w="full"
- >
- {route.name}
- </Button>
- );
- })}
- </VStack>
- </VStack>
- </ContentSidebar>
+ <ContentSidebar links={links} />
<VStack w="full" h="full" spacing={0} p={8}>
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/app.purchasing.index.tsx b/apps/carbon/app/routes/app.purchasing.index.tsx
new file mode 100644
index 0000000000..c1d170d6cb
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.index.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "@remix-run/node";
+
+export async function loader() {
+ return redirect("/app/purchasing/suppliers");
+}
diff --git a/apps/carbon/app/routes/app.purchasing.supplier-types.$supplierTypeId.tsx b/apps/carbon/app/routes/app.purchasing.supplier-types.$supplierTypeId.tsx
new file mode 100644
index 0000000000..f4ff90591c
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.supplier-types.$supplierTypeId.tsx
@@ -0,0 +1,87 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { SupplierTypeForm } from "~/interfaces/Purchasing/SupplierTypes";
+import { requirePermissions } from "~/services/auth";
+import {
+ supplierTypeValidator,
+ getSupplierType,
+ upsertSupplierType,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierTypeId } = params;
+ if (!supplierTypeId) throw notFound("supplierTypeId not found");
+
+ const supplierType = await getSupplierType(client, supplierTypeId);
+
+ if (supplierType?.data?.protected) {
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(request, error(null, "Cannot edit a protected supplier type"))
+ );
+ }
+
+ return json({
+ supplierType,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const validation = await supplierTypeValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, name, color } = validation.data;
+
+ const updateSupplierType = await upsertSupplierType(client, {
+ id,
+ name,
+ color: color || null,
+ });
+
+ if (updateSupplierType.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateSupplierType.error, "Failed to update supplier type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(request, success("Updated supplier type"))
+ );
+}
+
+export default function EditSupplierTypesRoute() {
+ const { supplierType } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: supplierType.data?.id ?? undefined,
+ name: supplierType.data?.name ?? "",
+ color: supplierType.data?.color ?? "#000000",
+ };
+
+ return <SupplierTypeForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.purchasing.supplier-types.delete.$supplierTypeId.tsx b/apps/carbon/app/routes/app.purchasing.supplier-types.delete.$supplierTypeId.tsx
new file mode 100644
index 0000000000..83c5fcc064
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.supplier-types.delete.$supplierTypeId.tsx
@@ -0,0 +1,81 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { requirePermissions } from "~/services/auth";
+import { deleteSupplierType, getSupplierType } from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+ const { supplierTypeId } = params;
+ if (!supplierTypeId) throw notFound("supplierTypeId not found");
+
+ const supplierType = await getSupplierType(client, supplierTypeId);
+ if (supplierType.error) {
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(
+ request,
+ error(supplierType.error, "Failed to get supplier type")
+ )
+ );
+ }
+
+ return json(supplierType);
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { supplierTypeId } = params;
+ if (!supplierTypeId) {
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(request, error(params, "Failed to get an supplier type id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deleteSupplierType(
+ client,
+ supplierTypeId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete supplier type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(request, success("Successfully deleted supplier type"))
+ );
+}
+
+export default function DeleteSupplierTypeRoute() {
+ const { supplierTypeId } = useParams();
+ const { data } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!supplierTypeId || !data) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate("/app/purchasing/supplier-types");
+ return (
+ <ConfirmDelete
+ action={`/app/purchasing/supplier-types/delete/${supplierTypeId}`}
+ name={data.name}
+ text={`Are you sure you want to delete the supplier type: ${data.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.supplier-types.new.tsx b/apps/carbon/app/routes/app.purchasing.supplier-types.new.tsx
new file mode 100644
index 0000000000..30b5c577eb
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.supplier-types.new.tsx
@@ -0,0 +1,77 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { SupplierTypeForm } from "~/interfaces/Purchasing/SupplierTypes";
+import { requirePermissions } from "~/services/auth";
+import {
+ supplierTypeValidator,
+ upsertSupplierType,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await supplierTypeValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { name, color } = validation.data;
+
+ const insertSupplierType = await upsertSupplierType(client, {
+ name,
+ color: color || null,
+ });
+ if (insertSupplierType.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertSupplierType.error, "Failed to insert supplier type")
+ )
+ );
+ }
+
+ const supplierTypeId = insertSupplierType.data[0]?.id;
+ if (!supplierTypeId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertSupplierType, "Failed to insert supplier type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/purchasing/supplier-types",
+ await flash(request, success("Supplier type created"))
+ );
+}
+
+export default function NewSupplierTypesRoute() {
+ const initialValues = {
+ name: "",
+ color: "#000000",
+ };
+
+ return <SupplierTypeForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.purchasing.supplier-types.tsx b/apps/carbon/app/routes/app.purchasing.supplier-types.tsx
new file mode 100644
index 0000000000..02a012597a
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.supplier-types.tsx
@@ -0,0 +1,36 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ SupplierTypesTable,
+ SupplierTypesTableFilters,
+} from "~/interfaces/Purchasing/SupplierTypes";
+import { requirePermissions } from "~/services/auth";
+import { getSupplierTypes } from "~/services/purchasing";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ return json(await getSupplierTypes(client, { name, limit, offset, sorts }));
+}
+
+export default function SupplierTypesRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <SupplierTypesTableFilters />
+ <SupplierTypesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.$supplierContactId.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.$supplierContactId.tsx
new file mode 100644
index 0000000000..cbb04b8862
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.$supplierContactId.tsx
@@ -0,0 +1,57 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ updateSupplierContact,
+ supplierContactValidator,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { supplierId, supplierContactId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierContactId) throw notFound("supplierContactId not found");
+
+ const validation = await supplierContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ if (id !== supplierContactId)
+ throw badRequest("supplierContactId does not match id from form data");
+
+ if (contactId === undefined)
+ throw badRequest("contactId is undefined from form data");
+
+ const update = await updateSupplierContact(client, {
+ contactId,
+ contact,
+ });
+ if (update.error) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(update.error, "Failed to update supplier contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Supplier contact updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.delete.$supplierContactId.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.delete.$supplierContactId.tsx
new file mode 100644
index 0000000000..d93e5bd775
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.delete.$supplierContactId.tsx
@@ -0,0 +1,40 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { deleteSupplierContact } from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { supplierId, supplierContactId } = params;
+ if (!supplierId || !supplierContactId) {
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(request, error(params, "Failed to get a supplier contact id"))
+ );
+ }
+
+ const { error: deleteSupplierContactError } = await deleteSupplierContact(
+ client,
+ supplierId,
+ supplierContactId
+ );
+ if (deleteSupplierContactError) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(deleteSupplierContactError, "Failed to delete supplier contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Successfully deleted supplier contact"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.new.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.new.tsx
new file mode 100644
index 0000000000..14d7b8f478
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.contact.new.tsx
@@ -0,0 +1,50 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ insertSupplierContact,
+ supplierContactValidator,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+
+ const validation = await supplierContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ const createSupplierContact = await insertSupplierContact(client, {
+ supplierId,
+ contact,
+ });
+ if (createSupplierContact.error) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(createSupplierContact.error, "Failed to create supplier contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Supplier contact created"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.$supplierLocationId.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.$supplierLocationId.tsx
new file mode 100644
index 0000000000..6ed4491a78
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.$supplierLocationId.tsx
@@ -0,0 +1,57 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ updateSupplierLocation,
+ supplierLocationValidator,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { supplierId, supplierLocationId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierLocationId) throw notFound("supplierLocationId not found");
+
+ const validation = await supplierLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ if (id !== Number(supplierLocationId))
+ throw badRequest("supplierLocationId does not match id from form data");
+
+ if (addressId === undefined)
+ throw badRequest("addressId is undefined from form data");
+
+ const update = await updateSupplierLocation(client, {
+ addressId,
+ address,
+ });
+ if (update.error) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(update.error, "Failed to update supplier address")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Supplier address updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.delete.$supplierLocationId.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.delete.$supplierLocationId.tsx
new file mode 100644
index 0000000000..d9f7b91467
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.delete.$supplierLocationId.tsx
@@ -0,0 +1,43 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { deleteSupplierLocation } from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { supplierId, supplierLocationId } = params;
+ if (!supplierId || !supplierLocationId) {
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(
+ request,
+ error(params, "Failed to get a supplier location id")
+ )
+ );
+ }
+
+ const { error: deleteSupplierLocationError } = await deleteSupplierLocation(
+ client,
+ supplierId,
+ Number(supplierLocationId)
+ );
+ if (deleteSupplierLocationError) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(deleteSupplierLocationError, "Failed to delete supplier location")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Successfully deleted supplier location"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.new.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.new.tsx
new file mode 100644
index 0000000000..eea7080274
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.location.new.tsx
@@ -0,0 +1,53 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ insertSupplierLocation,
+ supplierLocationValidator,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+
+ const validation = await supplierLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ const createSupplierLocation = await insertSupplierLocation(client, {
+ supplierId,
+ address,
+ });
+ if (createSupplierLocation.error) {
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(
+ request,
+ error(
+ createSupplierLocation.error,
+ "Failed to create supplier location"
+ )
+ )
+ );
+ }
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Supplier location created"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.tsx
new file mode 100644
index 0000000000..ff33fba46f
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.$supplierId.tsx
@@ -0,0 +1,132 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { SupplierForm } from "~/interfaces/Purchasing/Suppliers";
+import { requirePermissions } from "~/services/auth";
+import {
+ getSupplier,
+ getSupplierContacts,
+ getSupplierLocations,
+ supplierValidator,
+ updateSupplier,
+} from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw notFound("supplierTypeId not found");
+
+ const [supplier, contacts, locations] = await Promise.all([
+ getSupplier(client, supplierId),
+ getSupplierContacts(client, supplierId),
+ getSupplierLocations(client, supplierId),
+ ]);
+ if (supplier.error)
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(request, error(supplier.error, "Failed to get supplier"))
+ );
+
+ if (contacts.error)
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(
+ request,
+ error(contacts.error, "Failed to get supplier contacts")
+ )
+ );
+
+ if (locations.error)
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(
+ request,
+ error(locations.error, "Failed to get supplier locations")
+ )
+ );
+
+ return json({
+ supplier: supplier.data,
+ contacts: contacts.data,
+ locations: locations.data,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await supplierValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const {
+ id,
+ name,
+ supplierTypeId,
+ supplierStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ } = validation.data;
+
+ if (!id) {
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(request, error(null, "Failed to update supplier"))
+ );
+ }
+
+ const update = await updateSupplier(client, {
+ id,
+ name,
+ supplierTypeId,
+ supplierStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(request, error(update.error, "Failed to update supplier"))
+ );
+ }
+
+ return json(null, await flash(request, success("Updated supplier")));
+}
+
+export default function SuppliersNewRoute() {
+ const { supplier, contacts, locations } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: supplier.id ?? undefined,
+ name: supplier.name ?? "",
+ supplierTypeId: supplier.supplierTypeId ?? undefined,
+ supplierStatusId: supplier.supplierStatusId ?? undefined,
+ accountManagerId: supplier.accountManagerId ?? undefined,
+ taxId: supplier.taxId ?? "",
+ description: supplier.description ?? "",
+ };
+
+ return (
+ <SupplierForm
+ initialValues={initialValues}
+ contacts={contacts ?? []}
+ locations={locations ?? []}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.new.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.new.tsx
new file mode 100644
index 0000000000..3801ad18f9
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.new.tsx
@@ -0,0 +1,64 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { SupplierForm } from "~/interfaces/Purchasing/Suppliers";
+import { requirePermissions } from "~/services/auth";
+import { insertSupplier, supplierValidator } from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await supplierValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const {
+ name,
+ supplierTypeId,
+ supplierStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ } = validation.data;
+
+ const createSupplier = await insertSupplier(client, {
+ name,
+ supplierTypeId,
+ supplierStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ createdBy: userId,
+ });
+ if (createSupplier.error) {
+ return redirect(
+ "/app/purchasing/suppliers",
+ await flash(
+ request,
+ error(createSupplier.error, "Failed to insert supplier")
+ )
+ );
+ }
+
+ const supplierId = createSupplier.data[0]?.id;
+
+ return redirect(
+ `/app/purchasing/suppliers/${supplierId}`,
+ await flash(request, success("Created supplier"))
+ );
+}
+
+export default function SuppliersNewRoute() {
+ const initialValues = {
+ name: "",
+ };
+ return <SupplierForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.purchasing.suppliers.tsx b/apps/carbon/app/routes/app.purchasing.suppliers.tsx
new file mode 100644
index 0000000000..6737ad284a
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.suppliers.tsx
@@ -0,0 +1,57 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ SuppliersTable,
+ SuppliersTableFilters,
+} from "~/interfaces/Purchasing/Suppliers";
+import { requirePermissions } from "~/services/auth";
+import {
+ getSuppliers,
+ getSupplierStatuses,
+ getSupplierTypes,
+} from "~/services/purchasing";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const type = searchParams.get("type");
+ const status = searchParams.get("status");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [suppliers, supplierTypes, supplierStatuses] = await Promise.all([
+ getSuppliers(client, { name, type, status, limit, offset, sorts, filters }),
+ getSupplierTypes(client),
+ getSupplierStatuses(client),
+ ]);
+
+ return json({ suppliers, supplierTypes, supplierStatuses });
+}
+
+export default function PurchasingSuppliersRoute() {
+ const { suppliers, supplierTypes, supplierStatuses } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <SuppliersTableFilters
+ supplierTypes={supplierTypes.data ?? []}
+ supplierStatuses={supplierStatuses.data ?? []}
+ />
+ <SuppliersTable
+ data={suppliers.data ?? []}
+ count={suppliers.count ?? 0}
+ />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/app.purchasing.tsx b/apps/carbon/app/routes/app.purchasing.tsx
new file mode 100644
index 0000000000..d63c347c68
--- /dev/null
+++ b/apps/carbon/app/routes/app.purchasing.tsx
@@ -0,0 +1,22 @@
+import { Grid, VStack } from "@chakra-ui/react";
+import type { MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
+import { usePurchasingSidebar } from "~/interfaces/Purchasing";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Purchasing",
+});
+
+export default function UsersRoute() {
+ const { links } = usePurchasingSidebar();
+
+ return (
+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
+ <GroupedContentSidebar links={links} />
+ <VStack w="full" h="full" spacing={0}>
+ <Outlet />
+ </VStack>
+ </Grid>
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customer-types.$customerTypeId.tsx b/apps/carbon/app/routes/app.sales.customer-types.$customerTypeId.tsx
new file mode 100644
index 0000000000..dc61814cd4
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customer-types.$customerTypeId.tsx
@@ -0,0 +1,87 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { CustomerTypeForm } from "~/interfaces/Sales/CustomerTypes";
+import { requirePermissions } from "~/services/auth";
+import {
+ customerTypeValidator,
+ getCustomerType,
+ upsertCustomerType,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerTypeId } = params;
+ if (!customerTypeId) throw notFound("customerTypeId not found");
+
+ const customerType = await getCustomerType(client, customerTypeId);
+
+ if (customerType?.data?.protected) {
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(request, error(null, "Cannot edit a protected customer type"))
+ );
+ }
+
+ return json({
+ customerType,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const validation = await customerTypeValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, name, color } = validation.data;
+
+ const updateCustomerType = await upsertCustomerType(client, {
+ id,
+ name,
+ color: color || null,
+ });
+
+ if (updateCustomerType.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateCustomerType.error, "Failed to update customer type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(request, success("Updated customer type"))
+ );
+}
+
+export default function EditCustomerTypesRoute() {
+ const { customerType } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: customerType.data?.id ?? undefined,
+ name: customerType.data?.name ?? "",
+ color: customerType.data?.color ?? "#000000",
+ };
+
+ return <CustomerTypeForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.sales.customer-types.delete.$customerTypeId.tsx b/apps/carbon/app/routes/app.sales.customer-types.delete.$customerTypeId.tsx
new file mode 100644
index 0000000000..2b7acdc31f
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customer-types.delete.$customerTypeId.tsx
@@ -0,0 +1,82 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { requirePermissions } from "~/services/auth";
+import { deleteCustomerType, getCustomerType } from "~/services/sales";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+ const { customerTypeId } = params;
+ if (!customerTypeId) throw notFound("customerTypeId not found");
+
+ const customerType = await getCustomerType(client, customerTypeId);
+ if (customerType.error) {
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(
+ request,
+ error(customerType.error, "Failed to get customer type")
+ )
+ );
+ }
+
+ return json(customerType);
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "sales",
+ });
+
+ const { customerTypeId } = params;
+ if (!customerTypeId) {
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(request, error(params, "Failed to get an customer type id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deleteCustomerType(
+ client,
+ customerTypeId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete customer type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(request, success("Successfully deleted customer type"))
+ );
+}
+
+export default function DeleteCustomerTypeRoute() {
+ const { customerTypeId } = useParams();
+ const { data } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!customerTypeId || !data) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate("/app/sales/customer-types");
+
+ return (
+ <ConfirmDelete
+ action={`/app/sales/customer-types/delete/${customerTypeId}`}
+ name={data.name}
+ text={`Are you sure you want to delete the customer type: ${data.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customer-types.new.tsx b/apps/carbon/app/routes/app.sales.customer-types.new.tsx
new file mode 100644
index 0000000000..c8912cfa9a
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customer-types.new.tsx
@@ -0,0 +1,74 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { CustomerTypeForm } from "~/interfaces/Sales/CustomerTypes";
+import { requirePermissions } from "~/services/auth";
+import { customerTypeValidator, upsertCustomerType } from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ await requirePermissions(request, {
+ create: "sales",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const validation = await customerTypeValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { name, color } = validation.data;
+
+ const insertCustomerType = await upsertCustomerType(client, {
+ name,
+ color: color || null,
+ });
+ if (insertCustomerType.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertCustomerType.error, "Failed to insert customer type")
+ )
+ );
+ }
+
+ const customerTypeId = insertCustomerType.data[0]?.id;
+ if (!customerTypeId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertCustomerType, "Failed to insert customer type")
+ )
+ );
+ }
+
+ return redirect(
+ "/app/sales/customer-types",
+ await flash(request, success("Customer type created"))
+ );
+}
+
+export default function NewCustomerTypesRoute() {
+ const initialValues = {
+ name: "",
+ color: "#000000",
+ };
+
+ return <CustomerTypeForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.sales.customer-types.tsx b/apps/carbon/app/routes/app.sales.customer-types.tsx
new file mode 100644
index 0000000000..a33058134a
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customer-types.tsx
@@ -0,0 +1,36 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ CustomerTypesTable,
+ CustomerTypesTableFilters,
+} from "~/interfaces/Sales/CustomerTypes";
+import { requirePermissions } from "~/services/auth";
+import { getCustomerTypes } from "~/services/sales";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ return json(await getCustomerTypes(client, { name, limit, offset, sorts }));
+}
+
+export default function CustomerTypesRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <CustomerTypesTableFilters />
+ <CustomerTypesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.contact.$customerContactId.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.$customerContactId.tsx
new file mode 100644
index 0000000000..c3d3059a1f
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.$customerContactId.tsx
@@ -0,0 +1,57 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ updateCustomerContact,
+ customerContactValidator,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { customerId, customerContactId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerContactId) throw notFound("customerContactId not found");
+
+ const validation = await customerContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ if (id !== customerContactId)
+ throw badRequest("customerContactId does not match id from form data");
+
+ if (contactId === undefined)
+ throw badRequest("contactId is undefined from form data");
+
+ const update = await updateCustomerContact(client, {
+ contactId,
+ contact,
+ });
+ if (update.error) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(update.error, "Failed to update customer contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Customer contact updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.contact.delete.$customerContactId.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.delete.$customerContactId.tsx
new file mode 100644
index 0000000000..24d5668f4c
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.delete.$customerContactId.tsx
@@ -0,0 +1,40 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { deleteCustomerContact } from "~/services/sales";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "sales",
+ });
+
+ const { customerId, customerContactId } = params;
+ if (!customerId || !customerContactId) {
+ return redirect(
+ "/app/sales/customers",
+ await flash(request, error(params, "Failed to get a customer contact id"))
+ );
+ }
+
+ const { error: deleteCustomerContactError } = await deleteCustomerContact(
+ client,
+ customerId,
+ customerContactId
+ );
+ if (deleteCustomerContactError) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(deleteCustomerContactError, "Failed to delete customer contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Successfully deleted customer contact"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.contact.new.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.new.tsx
new file mode 100644
index 0000000000..0fd4337aa3
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.contact.new.tsx
@@ -0,0 +1,50 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ insertCustomerContact,
+ customerContactValidator,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw notFound("customerId not found");
+
+ const validation = await customerContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ const createCustomerContact = await insertCustomerContact(client, {
+ customerId,
+ contact,
+ });
+ if (createCustomerContact.error) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(createCustomerContact.error, "Failed to create customer contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Customer contact created"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.location.$customerLocationId.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.location.$customerLocationId.tsx
new file mode 100644
index 0000000000..6342a31ae3
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.location.$customerLocationId.tsx
@@ -0,0 +1,57 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ updateCustomerLocation,
+ customerLocationValidator,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { customerId, customerLocationId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerLocationId) throw notFound("customerLocationId not found");
+
+ const validation = await customerLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ if (id !== Number(customerLocationId))
+ throw badRequest("customerLocationId does not match id from form data");
+
+ if (addressId === undefined)
+ throw badRequest("addressId is undefined from form data");
+
+ const update = await updateCustomerLocation(client, {
+ addressId,
+ address,
+ });
+ if (update.error) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(update.error, "Failed to update customer address")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Customer address updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.location.delete.$customerLocationId.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.location.delete.$customerLocationId.tsx
new file mode 100644
index 0000000000..4b396f0138
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.location.delete.$customerLocationId.tsx
@@ -0,0 +1,43 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { deleteCustomerLocation } from "~/services/sales";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "sales",
+ });
+
+ const { customerId, customerLocationId } = params;
+ if (!customerId || !customerLocationId) {
+ return redirect(
+ "/app/sales/customers",
+ await flash(
+ request,
+ error(params, "Failed to get a customer location id")
+ )
+ );
+ }
+
+ const { error: deleteCustomerLocationError } = await deleteCustomerLocation(
+ client,
+ customerId,
+ Number(customerLocationId)
+ );
+ if (deleteCustomerLocationError) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(deleteCustomerLocationError, "Failed to delete customer location")
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Successfully deleted customer location"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.location.new.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.location.new.tsx
new file mode 100644
index 0000000000..a6e0f48800
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.location.new.tsx
@@ -0,0 +1,53 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import {
+ insertCustomerLocation,
+ customerLocationValidator,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw notFound("customerId not found");
+
+ const validation = await customerLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ const createCustomerLocation = await insertCustomerLocation(client, {
+ customerId,
+ address,
+ });
+ if (createCustomerLocation.error) {
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(
+ request,
+ error(
+ createCustomerLocation.error,
+ "Failed to create customer location"
+ )
+ )
+ );
+ }
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Customer location created"))
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.$customerId.tsx b/apps/carbon/app/routes/app.sales.customers.$customerId.tsx
new file mode 100644
index 0000000000..9bd82a2867
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.$customerId.tsx
@@ -0,0 +1,132 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { CustomerForm } from "~/interfaces/Sales/Customers";
+import { requirePermissions } from "~/services/auth";
+import {
+ getCustomer,
+ getCustomerContacts,
+ getCustomerLocations,
+ customerValidator,
+ updateCustomer,
+} from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw notFound("customerTypeId not found");
+
+ const [customer, contacts, locations] = await Promise.all([
+ getCustomer(client, customerId),
+ getCustomerContacts(client, customerId),
+ getCustomerLocations(client, customerId),
+ ]);
+ if (customer.error)
+ return redirect(
+ "/app/sales/customers",
+ await flash(request, error(customer.error, "Failed to get customer"))
+ );
+
+ if (contacts.error)
+ return redirect(
+ "/app/sales/customers",
+ await flash(
+ request,
+ error(contacts.error, "Failed to get customer contacts")
+ )
+ );
+
+ if (locations.error)
+ return redirect(
+ "/app/sales/customers",
+ await flash(
+ request,
+ error(locations.error, "Failed to get customer locations")
+ )
+ );
+
+ return json({
+ customer: customer.data,
+ contacts: contacts.data,
+ locations: locations.data,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const validation = await customerValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const {
+ id,
+ name,
+ customerTypeId,
+ customerStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ } = validation.data;
+
+ if (!id) {
+ return redirect(
+ "/app/sales/customers",
+ await flash(request, error(null, "Failed to update customer"))
+ );
+ }
+
+ const update = await updateCustomer(client, {
+ id,
+ name,
+ customerTypeId,
+ customerStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ return redirect(
+ "/app/sales/customers",
+ await flash(request, error(update.error, "Failed to update customer"))
+ );
+ }
+
+ return json(null, await flash(request, success("Updated customer")));
+}
+
+export default function CustomersNewRoute() {
+ const { customer, contacts, locations } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: customer.id ?? undefined,
+ name: customer.name ?? "",
+ customerTypeId: customer.customerTypeId ?? undefined,
+ customerStatusId: customer.customerStatusId ?? undefined,
+ accountManagerId: customer.accountManagerId ?? undefined,
+ taxId: customer.taxId ?? "",
+ description: customer.description ?? "",
+ };
+
+ return (
+ <CustomerForm
+ initialValues={initialValues}
+ contacts={contacts ?? []}
+ locations={locations ?? []}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.new.tsx b/apps/carbon/app/routes/app.sales.customers.new.tsx
new file mode 100644
index 0000000000..ab4e78264a
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.new.tsx
@@ -0,0 +1,64 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { CustomerForm } from "~/interfaces/Sales/Customers";
+import { requirePermissions } from "~/services/auth";
+import { insertCustomer, customerValidator } from "~/services/sales";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const validation = await customerValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const {
+ name,
+ customerTypeId,
+ customerStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ } = validation.data;
+
+ const createCustomer = await insertCustomer(client, {
+ name,
+ customerTypeId,
+ customerStatusId,
+ accountManagerId,
+ taxId,
+ description,
+ createdBy: userId,
+ });
+ if (createCustomer.error) {
+ return redirect(
+ "/app/sales/customers",
+ await flash(
+ request,
+ error(createCustomer.error, "Failed to insert customer")
+ )
+ );
+ }
+
+ const customerId = createCustomer.data[0]?.id;
+
+ return redirect(
+ `/app/sales/customers/${customerId}`,
+ await flash(request, success("Created customer"))
+ );
+}
+
+export default function CustomersNewRoute() {
+ const initialValues = {
+ name: "",
+ };
+ return <CustomerForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/app.sales.customers.tsx b/apps/carbon/app/routes/app.sales.customers.tsx
new file mode 100644
index 0000000000..e077872550
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.customers.tsx
@@ -0,0 +1,58 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { CustomerSelect } from "~/components/Selectors";
+import {
+ CustomersTable,
+ CustomersTableFilters,
+} from "~/interfaces/Sales/Customers";
+import { requirePermissions } from "~/services/auth";
+import {
+ getCustomers,
+ getCustomerStatuses,
+ getCustomerTypes,
+} from "~/services/sales";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const type = searchParams.get("type");
+ const status = searchParams.get("status");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [customers, customerTypes, customerStatuses] = await Promise.all([
+ getCustomers(client, { name, type, status, limit, offset, sorts, filters }),
+ getCustomerTypes(client),
+ getCustomerStatuses(client),
+ ]);
+
+ return json({ customers, customerTypes, customerStatuses });
+}
+
+export default function SalesCustomersRoute() {
+ const { customers, customerTypes, customerStatuses } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <CustomersTableFilters
+ customerTypes={customerTypes.data ?? []}
+ customerStatuses={customerStatuses.data ?? []}
+ />
+ <CustomersTable
+ data={customers.data ?? []}
+ count={customers.count ?? 0}
+ />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/app.sales.index.tsx b/apps/carbon/app/routes/app.sales.index.tsx
new file mode 100644
index 0000000000..3d5963fe56
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.index.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "@remix-run/node";
+
+export async function loader() {
+ return redirect("/app/sales/customers");
+}
diff --git a/apps/carbon/app/routes/app.sales.tsx b/apps/carbon/app/routes/app.sales.tsx
new file mode 100644
index 0000000000..291d4cbe96
--- /dev/null
+++ b/apps/carbon/app/routes/app.sales.tsx
@@ -0,0 +1,22 @@
+import { Grid, VStack } from "@chakra-ui/react";
+import type { MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
+import { useSalesSidebar } from "~/interfaces/Sales";
+
+export const meta: MetaFunction = () => ({
+ title: "Carbon | Sales",
+});
+
+export default function UsersRoute() {
+ const { links } = useSalesSidebar();
+
+ return (
+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
+ <GroupedContentSidebar links={links} />
+ <VStack w="full" h="full" spacing={0}>
+ <Outlet />
+ </VStack>
+ </Grid>
+ );
+}
diff --git a/apps/carbon/app/routes/app.users.attributes.list.$categoryId.tsx b/apps/carbon/app/routes/app.users.attributes.list.$categoryId.tsx
index c3473ed496..6ff6ff4b1e 100644
--- a/apps/carbon/app/routes/app.users.attributes.list.$categoryId.tsx
+++ b/apps/carbon/app/routes/app.users.attributes.list.$categoryId.tsx
@@ -1,6 +1,7 @@
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData, useNavigate } from "@remix-run/react";
+import { useUrlParams } from "~/hooks";
import { AttributeCategoryDetail } from "~/interfaces/Users/Attributes";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -74,9 +75,9 @@ export async function action({ request }: ActionArgs) {
export default function AttributeCategoryListRoute() {
const { attributeCategory } = useLoaderData<typeof loader>();
-
+ const [params] = useUrlParams();
const navigate = useNavigate();
- const onClose = () => navigate("/app/users/attributes");
+ const onClose = () => navigate(`/app/users/attributes?${params.toString()}`);
return (
<>
diff --git a/apps/carbon/app/routes/app.users.bulk-edit-permissions.tsx b/apps/carbon/app/routes/app.users.bulk-edit-permissions.tsx
index 83121094b4..3c05b336ff 100644
--- a/apps/carbon/app/routes/app.users.bulk-edit-permissions.tsx
+++ b/apps/carbon/app/routes/app.users.bulk-edit-permissions.tsx
@@ -2,8 +2,8 @@ import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import type { Permission } from "~/interfaces/Users/types";
-import type { BulkPermissionsQueueData } from "~/queue";
-import { bulkPermissionsQueue } from "~/queue";
+import type { BulkPermissionsQueueData } from "~/queues";
+import { bulkPermissionsQueue } from "~/queues";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import {
diff --git a/apps/carbon/app/routes/app.users.customers.new.tsx b/apps/carbon/app/routes/app.users.customers.new.tsx
new file mode 100644
index 0000000000..c1071e2486
--- /dev/null
+++ b/apps/carbon/app/routes/app.users.customers.new.tsx
@@ -0,0 +1,38 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import {
+ createCustomerAccount,
+ createCustomerValidator,
+} from "~/services/users";
+import { assertIsPost } from "~/utils/http";
+import { CreateCustomerModal } from "~/interfaces/Users/Customers";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ const validation = await createCustomerValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, customer } = validation.data;
+ const result = await createCustomerAccount(client, {
+ id,
+ customerId: customer,
+ });
+
+ return redirect("/app/users/customers", await flash(request, result));
+}
+
+export default function () {
+ return <CreateCustomerModal />;
+}
diff --git a/apps/carbon/app/routes/app.users.customers.tsx b/apps/carbon/app/routes/app.users.customers.tsx
index 0857abc451..583be12523 100644
--- a/apps/carbon/app/routes/app.users.customers.tsx
+++ b/apps/carbon/app/routes/app.users.customers.tsx
@@ -1,13 +1,52 @@
-import Todo from "~/components/Todo";
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { usePermissions } from "~/hooks";
+import {
+ CustomerAccountsTable,
+ CustomerAccountsTableFilters,
+} from "~/interfaces/Users/Customers";
+import { requirePermissions } from "~/services/auth";
+import { getCustomerTypes } from "~/services/sales";
+import { getCustomers } from "~/services/users";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const type = searchParams.get("type");
+ const active = searchParams.get("active") !== "false";
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [customers, customerTypes] = await Promise.all([
+ getCustomers(client, { name, type, active, limit, offset, sorts, filters }),
+ getCustomerTypes(client),
+ ]);
+
+ return json({ customers, customerTypes });
+}
export default function UsersCustomersRoute() {
+ const { customers, customerTypes } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+
return (
- <Todo
- items={[
- "Add partners so that we can associate a customers with an organization",
- "Add customer account CRUD",
- "Add RLS such that customers can access things related to their orders",
- ]}
- />
+ <VStack w="full" h="full" spacing={0}>
+ <CustomerAccountsTableFilters customerTypes={customerTypes.data ?? []} />
+ <CustomerAccountsTable
+ data={customers.data ?? []}
+ count={customers.count ?? 0}
+ isEditable={permissions.can("update", "users")}
+ />
+ <Outlet />
+ </VStack>
);
}
diff --git a/apps/carbon/app/routes/app.users.deactivate.tsx b/apps/carbon/app/routes/app.users.deactivate.tsx
index 225210945d..2d269bf4b6 100644
--- a/apps/carbon/app/routes/app.users.deactivate.tsx
+++ b/apps/carbon/app/routes/app.users.deactivate.tsx
@@ -1,8 +1,8 @@
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import type { DeactivateUserQueueData } from "~/queue";
-import { deactivateUsersQueue } from "~/queue";
+import type { DeactivateUserQueueData } from "~/queues";
+import { deactivateUsersQueue } from "~/queues";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { deactivateUser, deactivateUsersValidator } from "~/services/users";
diff --git a/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx b/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
index 94f1736636..30d2ccb289 100644
--- a/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
@@ -116,7 +116,7 @@ export async function action({ request }: ActionArgs) {
);
}
-export default function NewEmployeeTypesRoute() {
+export default function EditEmployeeTypesRoute() {
const { employeeType, employeeTypePermissions } =
useLoaderData<typeof loader>();
diff --git a/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx b/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
index ca83aae476..0b703fccc7 100644
--- a/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
@@ -1,7 +1,7 @@
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
-import { DeleteEmployeeTypeModal } from "~/interfaces/Users/EmployeeTypes";
+import { ConfirmDelete } from "~/components/Modals";
import { requirePermissions } from "~/services/auth";
import { deleteEmployeeType, getEmployeeType } from "~/services/users";
import { flash } from "~/services/session";
@@ -74,9 +74,10 @@ export default function DeleteEmployeeTypeRoute() {
const onCancel = () => navigate("/app/users/employee-types");
return (
- <DeleteEmployeeTypeModal
- employeeTypeId={employeeTypeId}
- data={data}
+ <ConfirmDelete
+ action={`/app/users/employee-types/delete/${employeeTypeId}`}
+ name={data.name}
+ text={`Are you sure you want to delete the employee type: ${data.name}? This cannot be undone.`}
onCancel={onCancel}
/>
);
diff --git a/apps/carbon/app/routes/app.users.employee-types.new.tsx b/apps/carbon/app/routes/app.users.employee-types.new.tsx
index 8b271506d9..1870c5055c 100644
--- a/apps/carbon/app/routes/app.users.employee-types.new.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.new.tsx
@@ -7,11 +7,11 @@ import { EmployeeTypeForm } from "~/interfaces/Users/EmployeeTypes";
import { requirePermissions } from "~/services/auth";
import {
employeeTypeValidator,
+ employeeTypePermissionsValidator,
getFeatures,
+ insertEmployeeType,
makeEmptyPermissionsFromFeatures,
- employeeTypePermissionsValidator,
upsertEmployeeTypePermissions,
- createEmployeeType,
} from "~/services/users";
import { flash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
@@ -64,27 +64,27 @@ export async function action({ request }: ActionArgs) {
);
}
- const insertEmployeeType = await createEmployeeType(client, {
+ const createEmployeeType = await insertEmployeeType(client, {
name,
color: color || null,
});
- if (insertEmployeeType.error) {
+ if (createEmployeeType.error) {
return json(
{},
await flash(
request,
- error(insertEmployeeType.error, "Failed to insert employee type")
+ error(createEmployeeType.error, "Failed to insert employee type")
)
);
}
- const employeeTypeId = insertEmployeeType.data[0]?.id;
+ const employeeTypeId = createEmployeeType.data[0]?.id;
if (!employeeTypeId) {
return json(
{},
await flash(
request,
- error(insertEmployeeType, "Failed to insert employee type")
+ error(createEmployeeType, "Failed to insert employee type")
)
);
}
diff --git a/apps/carbon/app/routes/app.users.employees.$employeeId.tsx b/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
index 3655414905..c0c4931ae2 100644
--- a/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
+++ b/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
@@ -9,8 +9,8 @@ import { flash } from "~/services/session";
import {
userPermissionsValidator,
employeeValidator,
- getClaimsById,
- getEmployeeById,
+ getClaims,
+ getEmployee,
makePermissionsFromClaims,
updateEmployee,
} from "~/services/users";
@@ -26,8 +26,8 @@ export async function loader({ request, params }: LoaderArgs) {
if (!employeeId) throw notFound("EmployeeId was not found");
const [claims, employee] = await Promise.all([
- getClaimsById(client, employeeId),
- getEmployeeById(client, employeeId),
+ getClaims(client, employeeId),
+ getEmployee(client, employeeId),
]);
if (claims.error || employee.error || claims.data === null) {
diff --git a/apps/carbon/app/routes/app.users.groups.$groupId.tsx b/apps/carbon/app/routes/app.users.groups.$groupId.tsx
index 682d54d4ea..2198e65211 100644
--- a/apps/carbon/app/routes/app.users.groups.$groupId.tsx
+++ b/apps/carbon/app/routes/app.users.groups.$groupId.tsx
@@ -7,7 +7,7 @@ import { GroupForm } from "~/interfaces/Users/Groups";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import {
- getGroupMembersById,
+ getGroupMembers,
groupValidator,
upsertGroup,
upsertGroupMembers,
@@ -23,7 +23,7 @@ export async function loader({ request, params }: LoaderArgs) {
const { groupId } = params;
if (!groupId) throw notFound("groupId not found");
- const groupWithMembers = await getGroupMembersById(client, groupId);
+ const groupWithMembers = await getGroupMembers(client, groupId);
if (groupWithMembers.error) {
redirect(
diff --git a/apps/carbon/app/routes/app.users.groups.delete.$groupId.tsx b/apps/carbon/app/routes/app.users.groups.delete.$groupId.tsx
index 05d2aae398..d33f51f6f8 100644
--- a/apps/carbon/app/routes/app.users.groups.delete.$groupId.tsx
+++ b/apps/carbon/app/routes/app.users.groups.delete.$groupId.tsx
@@ -1,7 +1,7 @@
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
-import { DeleteGroupModal } from "~/interfaces/Users/Groups";
+import { ConfirmDelete } from "~/components/Modals";
import { requirePermissions } from "~/services/auth";
import { deleteGroup, getGroup } from "~/services/users";
import { flash } from "~/services/session";
@@ -62,5 +62,12 @@ export default function DeleteEmployeeTypeRoute() {
const onCancel = () => navigate("/app/users/groups");
- return <DeleteGroupModal groupId={groupId} data={data} onCancel={onCancel} />;
+ return (
+ <ConfirmDelete
+ action={`/app/users/groups/delete/${groupId}`}
+ name={data.name}
+ text={`Are you sure you want to delete the group: ${data.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
}
diff --git a/apps/carbon/app/routes/app.users.groups.new.tsx b/apps/carbon/app/routes/app.users.groups.new.tsx
index b120a2c15d..46e0512a07 100644
--- a/apps/carbon/app/routes/app.users.groups.new.tsx
+++ b/apps/carbon/app/routes/app.users.groups.new.tsx
@@ -8,7 +8,7 @@ import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
import { requirePermissions } from "~/services/auth";
import {
- createGroup,
+ insertGroup,
deleteGroup,
groupValidator,
upsertGroupMembers,
@@ -28,19 +28,19 @@ export async function action({ request }: ActionArgs) {
const { name, selections } = validation.data;
- const insertGroup = await createGroup(client, { name });
- if (insertGroup.error) {
+ const createGroup = await insertGroup(client, { name });
+ if (createGroup.error) {
return json(
{},
- await flash(request, error(insertGroup.error, "Failed to insert group"))
+ await flash(request, error(createGroup.error, "Failed to insert group"))
);
}
- const groupId = insertGroup.data[0]?.id;
+ const groupId = createGroup.data[0]?.id;
if (!groupId) {
return json(
{},
- await flash(request, error(insertGroup, "Failed to insert group"))
+ await flash(request, error(createGroup, "Failed to insert group"))
);
}
diff --git a/apps/carbon/app/routes/app.users.resend-invite.tsx b/apps/carbon/app/routes/app.users.resend-invite.tsx
index f6558fe418..38aef9e3bf 100644
--- a/apps/carbon/app/routes/app.users.resend-invite.tsx
+++ b/apps/carbon/app/routes/app.users.resend-invite.tsx
@@ -1,8 +1,8 @@
import type { ActionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import type { ResendInvitesQueueData } from "~/queue";
-import { resendInvitesQueue } from "~/queue";
+import type { ResendInvitesQueueData } from "~/queues";
+import { resendInvitesQueue } from "~/queues";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { resendInvite, resendInviteValidator } from "~/services/users";
diff --git a/apps/carbon/app/routes/app.users.suppliers.new.tsx b/apps/carbon/app/routes/app.users.suppliers.new.tsx
new file mode 100644
index 0000000000..d00ee87bd2
--- /dev/null
+++ b/apps/carbon/app/routes/app.users.suppliers.new.tsx
@@ -0,0 +1,38 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import {
+ createSupplierAccount,
+ createSupplierValidator,
+} from "~/services/users";
+import { assertIsPost } from "~/utils/http";
+import { CreateSupplierModal } from "~/interfaces/Users/Suppliers";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ const validation = await createSupplierValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, supplier } = validation.data;
+ const result = await createSupplierAccount(client, {
+ id,
+ supplierId: supplier,
+ });
+
+ return redirect("/app/users/suppliers", await flash(request, result));
+}
+
+export default function () {
+ return <CreateSupplierModal />;
+}
diff --git a/apps/carbon/app/routes/app.users.suppliers.tsx b/apps/carbon/app/routes/app.users.suppliers.tsx
index d1b85f98ab..60fcb5cd40 100644
--- a/apps/carbon/app/routes/app.users.suppliers.tsx
+++ b/apps/carbon/app/routes/app.users.suppliers.tsx
@@ -1,13 +1,52 @@
-import Todo from "~/components/Todo";
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { usePermissions } from "~/hooks";
+import {
+ SupplierAccountsTable,
+ SupplierAccountsTableFilters,
+} from "~/interfaces/Users/Suppliers";
+import { requirePermissions } from "~/services/auth";
+import { getSupplierTypes } from "~/services/purchasing";
+import { getSuppliers } from "~/services/users";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const type = searchParams.get("type");
+ const active = searchParams.get("active") !== "false";
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [suppliers, supplierTypes] = await Promise.all([
+ getSuppliers(client, { name, type, active, limit, offset, sorts, filters }),
+ getSupplierTypes(client),
+ ]);
+
+ return json({ suppliers, supplierTypes });
+}
export default function UsersSuppliersRoute() {
+ const { suppliers, supplierTypes } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+
return (
- <Todo
- items={[
- "Add partners so that we can associate a supplier with an organization",
- "Add supplier account CRUD",
- "Add RLS such that suppliers can access things related to their orders",
- ]}
- />
+ <VStack w="full" h="full" spacing={0}>
+ <SupplierAccountsTableFilters supplierTypes={supplierTypes.data ?? []} />
+ <SupplierAccountsTable
+ data={suppliers.data ?? []}
+ count={suppliers.count ?? 0}
+ isEditable={permissions.can("update", "users")}
+ />
+ <Outlet />
+ </VStack>
);
}
diff --git a/apps/carbon/app/routes/app.users.tsx b/apps/carbon/app/routes/app.users.tsx
index 919b49f62f..e31629ef89 100644
--- a/apps/carbon/app/routes/app.users.tsx
+++ b/apps/carbon/app/routes/app.users.tsx
@@ -1,8 +1,7 @@
-import { useColor } from "@carbon/react";
-import { Button, Grid, Text, VStack } from "@chakra-ui/react";
+import { Grid, VStack } from "@chakra-ui/react";
import type { MetaFunction } from "@remix-run/node";
-import { Link, Outlet, useMatches } from "@remix-run/react";
-import { ContentSidebar } from "~/components/Layout/Sidebar";
+import { Outlet } from "@remix-run/react";
+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useUsersSidebar } from "~/interfaces/Users";
export const meta: MetaFunction = () => ({
@@ -11,53 +10,10 @@ export const meta: MetaFunction = () => ({
export default function UsersRoute() {
const { links } = useUsersSidebar();
- const matches = useMatches();
- const borderColor = useColor("gray.200");
- const labelColor = useColor("gray.500");
return (
<Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">
- <ContentSidebar>
- <VStack spacing={2}>
- {links.map((groups) =>
- Object.entries(groups).map(([group, routes]) => (
- <VStack
- key={group}
- spacing={1}
- alignItems="start"
- borderBottomStyle={"solid"}
- borderBottomWidth={1}
- borderBottomColor={borderColor}
- px={2}
- py={4}
- w="full"
- >
- <Text color={labelColor} fontSize="sm" pl={3} py={1}>
- {group}
- </Text>
- {routes.map((route) => {
- const isActive = matches.some((match) =>
- match.pathname.includes(route.to)
- );
- return (
- <Button
- key={route.name}
- as={Link}
- to={route.to}
- variant={isActive ? "solid" : "ghost"}
- fontWeight={isActive ? "bold" : "normal"}
- justifyContent="start"
- w="full"
- >
- {route.name}
- </Button>
- );
- })}
- </VStack>
- ))
- )}
- </VStack>
- </ContentSidebar>
+ <GroupedContentSidebar links={links} />
<VStack w="full" h="full" spacing={0}>
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/resource.purchasing.supplier-contacts.tsx b/apps/carbon/app/routes/resource.purchasing.supplier-contacts.tsx
new file mode 100644
index 0000000000..62c0f02f2b
--- /dev/null
+++ b/apps/carbon/app/routes/resource.purchasing.supplier-contacts.tsx
@@ -0,0 +1,34 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getSupplierContacts } from "~/services/purchasing";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const supplierId = searchParams.get("supplierId") as string;
+
+ if (!supplierId || supplierId === "undefined")
+ return json({
+ data: [],
+ });
+
+ const contacts = await getSupplierContacts(client, supplierId);
+ if (contacts.error) {
+ return json(
+ contacts,
+ await flash(
+ request,
+ error(contacts.error, "Failed to get supplier contacts")
+ )
+ );
+ }
+
+ return json(contacts);
+}
diff --git a/apps/carbon/app/routes/resource.purchasing.supplier-statuses.tsx b/apps/carbon/app/routes/resource.purchasing.supplier-statuses.tsx
new file mode 100644
index 0000000000..3e625f5662
--- /dev/null
+++ b/apps/carbon/app/routes/resource.purchasing.supplier-statuses.tsx
@@ -0,0 +1,12 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getSupplierStatuses } from "~/services/purchasing";
+import { requirePermissions } from "~/services/auth";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ return json(await getSupplierStatuses(client));
+}
diff --git a/apps/carbon/app/routes/resource.purchasing.supplier-types.ts b/apps/carbon/app/routes/resource.purchasing.supplier-types.ts
new file mode 100644
index 0000000000..ac7da5f3b0
--- /dev/null
+++ b/apps/carbon/app/routes/resource.purchasing.supplier-types.ts
@@ -0,0 +1,12 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getSupplierTypes } from "~/services/purchasing";
+import { requirePermissions } from "~/services/auth";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
+
+ return json(await getSupplierTypes(client));
+}
diff --git a/apps/carbon/app/routes/resource.purchasing.suppliers.tsx b/apps/carbon/app/routes/resource.purchasing.suppliers.tsx
new file mode 100644
index 0000000000..b304df5888
--- /dev/null
+++ b/apps/carbon/app/routes/resource.purchasing.suppliers.tsx
@@ -0,0 +1,12 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getSuppliersList } from "~/services/purchasing";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ return json(await getSuppliersList(client));
+}
diff --git a/apps/carbon/app/routes/resource.sales.customer-contacts.tsx b/apps/carbon/app/routes/resource.sales.customer-contacts.tsx
new file mode 100644
index 0000000000..7c43b88d08
--- /dev/null
+++ b/apps/carbon/app/routes/resource.sales.customer-contacts.tsx
@@ -0,0 +1,34 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getCustomerContacts } from "~/services/sales";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const customerId = searchParams.get("customerId") as string;
+
+ if (!customerId || customerId === "undefined")
+ return json({
+ data: [],
+ });
+
+ const contacts = await getCustomerContacts(client, customerId);
+ if (contacts.error) {
+ return json(
+ contacts,
+ await flash(
+ request,
+ error(contacts.error, "Failed to get customer contacts")
+ )
+ );
+ }
+
+ return json(contacts);
+}
diff --git a/apps/carbon/app/routes/resource.sales.customers.tsx b/apps/carbon/app/routes/resource.sales.customers.tsx
new file mode 100644
index 0000000000..38ebee13bf
--- /dev/null
+++ b/apps/carbon/app/routes/resource.sales.customers.tsx
@@ -0,0 +1,12 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getCustomersList } from "~/services/sales";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ return json(await getCustomersList(client));
+}
diff --git a/apps/carbon/app/services/purchasing/index.ts b/apps/carbon/app/services/purchasing/index.ts
new file mode 100644
index 0000000000..b0d255d9c4
--- /dev/null
+++ b/apps/carbon/app/services/purchasing/index.ts
@@ -0,0 +1,2 @@
+export * from "./purchasing.form";
+export * from "./purchasing.server";
diff --git a/apps/carbon/app/services/purchasing/purchasing.form.ts b/apps/carbon/app/services/purchasing/purchasing.form.ts
new file mode 100644
index 0000000000..83f0a689ae
--- /dev/null
+++ b/apps/carbon/app/services/purchasing/purchasing.form.ts
@@ -0,0 +1,39 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import { address, contact } from "~/types/validators";
+
+export const supplierValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: zfd.text(z.string().optional()),
+ supplierTypeId: zfd.text(z.string().optional()),
+ supplierStatusId: zfd.numeric(z.number().optional()),
+ taxId: zfd.text(z.string().optional()),
+ accountManagerId: zfd.text(z.string().optional()),
+ })
+);
+
+export const supplierContactValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ ...contact,
+ supplierLocationId: zfd.numeric(z.number().optional()),
+ })
+);
+
+export const supplierLocationValidator = withZod(
+ z.object({
+ id: zfd.numeric(z.number().optional()),
+ ...address,
+ })
+);
+
+export const supplierTypeValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ color: z.string(),
+ })
+);
diff --git a/apps/carbon/app/services/purchasing/purchasing.server.ts b/apps/carbon/app/services/purchasing/purchasing.server.ts
new file mode 100644
index 0000000000..d74c67432d
--- /dev/null
+++ b/apps/carbon/app/services/purchasing/purchasing.server.ts
@@ -0,0 +1,348 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
+
+export async function deleteSupplierContact(
+ client: SupabaseClient<Database>,
+ supplierId: string,
+ supplierContactId: string
+) {
+ return client
+ .from("supplierContact")
+ .delete()
+ .eq("supplierId", supplierId)
+ .eq("id", supplierContactId);
+}
+
+export async function deleteSupplierLocation(
+ client: SupabaseClient<Database>,
+ supplierId: string,
+ supplierLocationId: number
+) {
+ return client
+ .from("supplierLocation")
+ .delete()
+ .eq("supplierId", supplierId)
+ .eq("id", supplierLocationId);
+}
+
+export async function deleteSupplierType(
+ client: SupabaseClient<Database>,
+ supplierTypeId: string
+) {
+ return client.from("supplierType").delete().eq("id", supplierTypeId);
+}
+
+export async function getSupplier(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client
+ .from("supplier")
+ .select(
+ "id, name, description, supplierTypeId, supplierStatusId, taxId, accountManagerId"
+ )
+ .eq("id", supplierId)
+ .single();
+}
+
+export async function getSupplierLocations(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client
+ .from("supplierLocation")
+ .select(
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
+ )
+ .eq("supplierId", supplierId);
+}
+
+export async function getSupplierContact(
+ client: SupabaseClient<Database>,
+ supplierContactId: string
+) {
+ return client
+ .from("supplierContact")
+ .select(
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes)"
+ )
+ .eq("id", supplierContactId)
+ .single();
+}
+
+export async function getSupplierContacts(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client
+ .from("supplierContact")
+ .select(
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes), user(id, active)"
+ )
+ .eq("supplierId", supplierId);
+}
+
+export async function getSuppliers(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ type: string | null;
+ status: string | null;
+ }
+) {
+ let query = client
+ .from("supplier")
+ .select("id, name, description, supplierType(name), supplierStatus(name)", {
+ count: "exact",
+ });
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args.type) {
+ query = query.eq("supplierTypeId", args.type);
+ }
+
+ if (args.status) {
+ query = query.eq("supplierStatusId", Number(args.status));
+ }
+
+ query = setGenericQueryFilters(query, args, "name");
+ return query;
+}
+
+export async function getSuppliersList(client: SupabaseClient<Database>) {
+ return client.from("supplier").select("id, name");
+}
+
+export async function getSupplierStatuses(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null }
+) {
+ let query = client
+ .from("supplierStatus")
+ .select("id, name", { count: "exact" });
+
+ if (args?.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "name");
+ }
+
+ return query;
+}
+
+export async function getSupplierType(
+ client: SupabaseClient<Database>,
+ supplierTypeId: string
+) {
+ return client
+ .from("supplierType")
+ .select("id, name, color, protected")
+ .eq("id", supplierTypeId)
+ .single();
+}
+
+export async function getSupplierTypes(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null }
+) {
+ let query = client
+ .from("supplierType")
+ .select("id, name, color, protected", { count: "exact" });
+
+ if (args?.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "name");
+ }
+
+ return query;
+}
+
+export async function insertSupplier(
+ client: SupabaseClient<Database>,
+ supplier: {
+ name: string;
+ supplierTypeId?: string;
+ supplierStatusId?: number;
+ taxId?: string;
+ accountManagerId?: string;
+ description?: string;
+ createdBy: string;
+ }
+) {
+ return client.from("supplier").insert([supplier]).select("id");
+}
+
+export async function insertSupplierContact(
+ client: SupabaseClient<Database>,
+ supplierContact: {
+ supplierId: string;
+ contact: {
+ firstName: string;
+ lastName: string;
+ email: string;
+ mobilePhone?: string;
+ homePhone?: string;
+ workPhone?: string;
+ fax?: string;
+ title?: string;
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ birthday?: string;
+ notes?: string;
+ };
+ }
+) {
+ const insertContact = await client
+ .from("contact")
+ .insert([supplierContact.contact])
+ .select("id");
+ if (insertContact.error) {
+ return insertContact;
+ }
+
+ const contactId = insertContact.data[0].id;
+ if (!contactId) {
+ return { data: null, error: new Error("Contact ID not found") };
+ }
+
+ return client
+ .from("supplierContact")
+ .insert([
+ {
+ supplierId: supplierContact.supplierId,
+ contactId,
+ },
+ ])
+ .select("id");
+}
+
+export async function insertSupplierLocation(
+ client: SupabaseClient<Database>,
+ supplierLocation: {
+ supplierId: string;
+ address: {
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ };
+ }
+) {
+ const insertAddress = await client
+ .from("address")
+ .insert([supplierLocation.address])
+ .select("id");
+ if (insertAddress.error) {
+ return insertAddress;
+ }
+
+ const addressId = insertAddress.data[0].id;
+ if (!addressId) {
+ return { data: null, error: new Error("Address ID not found") };
+ }
+
+ return client
+ .from("supplierLocation")
+ .insert([
+ {
+ supplierId: supplierLocation.supplierId,
+ addressId,
+ },
+ ])
+ .select("id");
+}
+
+export async function updateSupplier(
+ client: SupabaseClient<Database>,
+ supplier: {
+ id: string;
+ name: string;
+ supplierTypeId?: string;
+ supplierStatusId?: number;
+ taxId?: string;
+ accountManagerId?: string;
+ description?: string;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("supplier")
+ .update(supplier)
+ .eq("id", supplier.id)
+ .select("id");
+}
+
+export async function updateSupplierContact(
+ client: SupabaseClient<Database>,
+ supplierContact: {
+ contactId: string;
+ contact: {
+ firstName?: string;
+ lastName?: string;
+ email: string;
+ mobilePhone?: string;
+ homePhone?: string;
+ workPhone?: string;
+ fax?: string;
+ title?: string;
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ birthday?: string;
+ notes?: string;
+ };
+ }
+) {
+ return client
+ .from("contact")
+ .update(supplierContact.contact)
+ .eq("id", supplierContact.contactId)
+ .select("id");
+}
+
+export async function updateSupplierLocation(
+ client: SupabaseClient<Database>,
+ supplierLocation: {
+ addressId: number;
+ address: {
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ };
+ }
+) {
+ return client
+ .from("address")
+ .update(supplierLocation.address)
+ .eq("id", supplierLocation.addressId)
+ .select("id");
+}
+
+export async function upsertSupplierType(
+ client: SupabaseClient<Database>,
+ supplierType: { id?: string; name: string; color: string | null }
+) {
+ return client.from("supplierType").upsert([supplierType]).select("id");
+}
diff --git a/apps/carbon/app/services/sales/index.ts b/apps/carbon/app/services/sales/index.ts
new file mode 100644
index 0000000000..f4b3153c5f
--- /dev/null
+++ b/apps/carbon/app/services/sales/index.ts
@@ -0,0 +1,2 @@
+export * from "./sales.form";
+export * from "./sales.server";
diff --git a/apps/carbon/app/services/sales/sales.form.ts b/apps/carbon/app/services/sales/sales.form.ts
new file mode 100644
index 0000000000..7bc988f25b
--- /dev/null
+++ b/apps/carbon/app/services/sales/sales.form.ts
@@ -0,0 +1,39 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import { address, contact } from "~/types/validators";
+
+export const customerValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: zfd.text(z.string().optional()),
+ customerTypeId: zfd.text(z.string().optional()),
+ customerStatusId: zfd.numeric(z.number().optional()),
+ taxId: zfd.text(z.string().optional()),
+ accountManagerId: zfd.text(z.string().optional()),
+ })
+);
+
+export const customerContactValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ ...contact,
+ customerLocationId: zfd.numeric(z.number().optional()),
+ })
+);
+
+export const customerLocationValidator = withZod(
+ z.object({
+ id: zfd.numeric(z.number().optional()),
+ ...address,
+ })
+);
+
+export const customerTypeValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ color: z.string(),
+ })
+);
diff --git a/apps/carbon/app/services/sales/sales.server.ts b/apps/carbon/app/services/sales/sales.server.ts
new file mode 100644
index 0000000000..39ed580301
--- /dev/null
+++ b/apps/carbon/app/services/sales/sales.server.ts
@@ -0,0 +1,348 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
+
+export async function deleteCustomerContact(
+ client: SupabaseClient<Database>,
+ customerId: string,
+ customerContactId: string
+) {
+ return client
+ .from("customerContact")
+ .delete()
+ .eq("customerId", customerId)
+ .eq("id", customerContactId);
+}
+
+export async function deleteCustomerLocation(
+ client: SupabaseClient<Database>,
+ customerId: string,
+ customerLocationId: number
+) {
+ return client
+ .from("customerLocation")
+ .delete()
+ .eq("customerId", customerId)
+ .eq("id", customerLocationId);
+}
+
+export async function deleteCustomerType(
+ client: SupabaseClient<Database>,
+ customerTypeId: string
+) {
+ return client.from("customerType").delete().eq("id", customerTypeId);
+}
+
+export async function getCustomer(
+ client: SupabaseClient<Database>,
+ customerId: string
+) {
+ return client
+ .from("customer")
+ .select(
+ "id, name, description, customerTypeId, customerStatusId, taxId, accountManagerId"
+ )
+ .eq("id", customerId)
+ .single();
+}
+
+export async function getCustomerLocations(
+ client: SupabaseClient<Database>,
+ customerId: string
+) {
+ return client
+ .from("customerLocation")
+ .select(
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
+ )
+ .eq("customerId", customerId);
+}
+
+export async function getCustomerContact(
+ client: SupabaseClient<Database>,
+ customerContactId: string
+) {
+ return client
+ .from("customerContact")
+ .select(
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes)"
+ )
+ .eq("id", customerContactId)
+ .single();
+}
+
+export async function getCustomerContacts(
+ client: SupabaseClient<Database>,
+ customerId: string
+) {
+ return client
+ .from("customerContact")
+ .select(
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes), user(id, active)"
+ )
+ .eq("customerId", customerId);
+}
+
+export async function getCustomers(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ type: string | null;
+ status: string | null;
+ }
+) {
+ let query = client
+ .from("customer")
+ .select("id, name, description, customerType(name), customerStatus(name)", {
+ count: "exact",
+ });
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args.type) {
+ query = query.eq("customerTypeId", args.type);
+ }
+
+ if (args.status) {
+ query = query.eq("customerStatusId", Number(args.status));
+ }
+
+ query = setGenericQueryFilters(query, args, "name");
+ return query;
+}
+
+export async function getCustomersList(client: SupabaseClient<Database>) {
+ return client.from("customer").select("id, name");
+}
+
+export async function getCustomerStatuses(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null }
+) {
+ let query = client
+ .from("customerStatus")
+ .select("id, name", { count: "exact" });
+
+ if (args?.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "name");
+ }
+
+ return query;
+}
+
+export async function getCustomerType(
+ client: SupabaseClient<Database>,
+ customerTypeId: string
+) {
+ return client
+ .from("customerType")
+ .select("id, name, color, protected")
+ .eq("id", customerTypeId)
+ .single();
+}
+
+export async function getCustomerTypes(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null }
+) {
+ let query = client
+ .from("customerType")
+ .select("id, name, color, protected", { count: "exact" });
+
+ if (args?.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "name");
+ }
+
+ return query;
+}
+
+export async function insertCustomer(
+ client: SupabaseClient<Database>,
+ customer: {
+ name: string;
+ customerTypeId?: string;
+ customerStatusId?: number;
+ taxId?: string;
+ accountManagerId?: string;
+ description?: string;
+ createdBy: string;
+ }
+) {
+ return client.from("customer").insert([customer]).select("id");
+}
+
+export async function insertCustomerContact(
+ client: SupabaseClient<Database>,
+ customerContact: {
+ customerId: string;
+ contact: {
+ firstName: string;
+ lastName: string;
+ email: string;
+ mobilePhone?: string;
+ homePhone?: string;
+ workPhone?: string;
+ fax?: string;
+ title?: string;
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ birthday?: string;
+ notes?: string;
+ };
+ }
+) {
+ const insertContact = await client
+ .from("contact")
+ .insert([customerContact.contact])
+ .select("id");
+ if (insertContact.error) {
+ return insertContact;
+ }
+
+ const contactId = insertContact.data[0].id;
+ if (!contactId) {
+ return { data: null, error: new Error("Contact ID not found") };
+ }
+
+ return client
+ .from("customerContact")
+ .insert([
+ {
+ customerId: customerContact.customerId,
+ contactId,
+ },
+ ])
+ .select("id");
+}
+
+export async function insertCustomerLocation(
+ client: SupabaseClient<Database>,
+ customerLocation: {
+ customerId: string;
+ address: {
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ };
+ }
+) {
+ const insertAddress = await client
+ .from("address")
+ .insert([customerLocation.address])
+ .select("id");
+ if (insertAddress.error) {
+ return insertAddress;
+ }
+
+ const addressId = insertAddress.data[0].id;
+ if (!addressId) {
+ return { data: null, error: new Error("Address ID not found") };
+ }
+
+ return client
+ .from("customerLocation")
+ .insert([
+ {
+ customerId: customerLocation.customerId,
+ addressId,
+ },
+ ])
+ .select("id");
+}
+
+export async function updateCustomer(
+ client: SupabaseClient<Database>,
+ customer: {
+ id: string;
+ name: string;
+ customerTypeId?: string;
+ customerStatusId?: number;
+ taxId?: string;
+ accountManagerId?: string;
+ description?: string;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("customer")
+ .update(customer)
+ .eq("id", customer.id)
+ .select("id");
+}
+
+export async function updateCustomerContact(
+ client: SupabaseClient<Database>,
+ customerContact: {
+ contactId: string;
+ contact: {
+ firstName?: string;
+ lastName?: string;
+ email: string;
+ mobilePhone?: string;
+ homePhone?: string;
+ workPhone?: string;
+ fax?: string;
+ title?: string;
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ birthday?: string;
+ notes?: string;
+ };
+ }
+) {
+ return client
+ .from("contact")
+ .update(customerContact.contact)
+ .eq("id", customerContact.contactId)
+ .select("id");
+}
+
+export async function updateCustomerLocation(
+ client: SupabaseClient<Database>,
+ customerLocation: {
+ addressId: number;
+ address: {
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ state?: string;
+ // countryId: string;
+ postalCode?: string;
+ };
+ }
+) {
+ return client
+ .from("address")
+ .update(customerLocation.address)
+ .eq("id", customerLocation.addressId)
+ .select("id");
+}
+
+export async function upsertCustomerType(
+ client: SupabaseClient<Database>,
+ customerType: { id?: string; name: string; color: string | null }
+) {
+ return client.from("customerType").upsert([customerType]).select("id");
+}
diff --git a/apps/carbon/app/services/users/users.form.ts b/apps/carbon/app/services/users/users.form.ts
index f7f2a7ca81..ecf8401364 100644
--- a/apps/carbon/app/services/users/users.form.ts
+++ b/apps/carbon/app/services/users/users.form.ts
@@ -48,6 +48,13 @@ export const bulkPermissionsValidator = withZod(
})
);
+export const createCustomerValidator = withZod(
+ z.object({
+ id: z.string().min(36, "Customer contact is required"),
+ customer: z.string().min(36, { message: "Customer is required" }),
+ })
+);
+
export const createEmployeeValidator = withZod(
z.object({
email: z
@@ -60,6 +67,13 @@ export const createEmployeeValidator = withZod(
})
);
+export const createSupplierValidator = withZod(
+ z.object({
+ id: z.string().min(36, "Supplier contact is required"),
+ supplier: z.string().min(36, { message: "Supplier is required" }),
+ })
+);
+
export const deactivateUsersValidator = withZod(
z.object({
redirectTo: z.string(),
diff --git a/apps/carbon/app/services/users/users.server.ts b/apps/carbon/app/services/users/users.server.ts
index 11173129eb..ea2d610177 100644
--- a/apps/carbon/app/services/users/users.server.ts
+++ b/apps/carbon/app/services/users/users.server.ts
@@ -11,12 +11,87 @@ import type {
User,
} from "~/interfaces/Users/types";
import { deleteAuthAccount, sendInviteByEmail } from "~/services/auth";
+import { getSupplierContact } from "~/services/purchasing";
+import { getCustomerContact } from "~/services/sales";
import { requireAuthSession, flash } from "~/services/session";
import type { Result } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { error, success } from "~/utils/result";
-import logger from "~/lib/logger";
+
+export async function createCustomerAccount(
+ client: SupabaseClient<Database>,
+ {
+ id,
+ customerId,
+ }: {
+ id: string;
+ customerId: string;
+ }
+): Promise<Result> {
+ const customerContact = await getCustomerContact(client, id);
+ if (
+ customerContact.error ||
+ customerContact.data === null ||
+ Array.isArray(customerContact.data.contact) ||
+ customerContact.data.contact === null
+ ) {
+ return error(customerContact.error, "Failed to get customer contact");
+ }
+
+ const { email, firstName, lastName } = customerContact.data.contact;
+
+ // TODO: can we do this after we've done the other stuff?
+ const invitation = await sendInviteByEmail(email);
+
+ if (invitation.error)
+ return error(invitation.error.message, "Failed to send invitation email");
+
+ const userId = invitation.data.user.id;
+
+ const claims = makeCustomerClaims();
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "customer",
+ ...claims,
+ });
+ if (claimsUpdate.error) {
+ await deleteAuthAccount(userId);
+ return error(claimsUpdate.error, "Failed to set user claims");
+ }
+
+ const insertUser = await createUser(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ });
+
+ if (insertUser.error)
+ return error(insertUser.error, "Failed to create a new user");
+
+ if (!insertUser.data)
+ return error(insertUser, "No data returned from create user");
+
+ const updateContact = await client
+ .from("customerContact")
+ .update({ userId })
+ .eq("id", id);
+ if (updateContact.error) {
+ await deleteAuthAccount(userId);
+ return error(updateContact.error, "Failed to update customer contact");
+ }
+
+ const createCustomerAccount = await insertCustomerAccount(client, {
+ id: insertUser.data[0].id,
+ customerId,
+ });
+
+ if (createCustomerAccount.error)
+ return error(createCustomerAccount.error, "Failed to create an employee");
+
+ return success("Customer account created");
+}
export async function createEmployeeAccount(
client: SupabaseClient<Database>,
@@ -42,7 +117,7 @@ export async function createEmployeeAccount(
"Failed to get employee type permissions"
);
- // TODO: we should only send this after we've done the other stuff
+ // TODO: can we do this after we've done the other stuff?
const invitation = await sendInviteByEmail(email);
if (invitation.error)
@@ -51,7 +126,10 @@ export async function createEmployeeAccount(
const userId = invitation.data.user.id;
const claims = makeClaimsFromEmployeeType(employeeTypePermissions);
- const claimsUpdate = await setUserClaims(userId, claims);
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "employee",
+ ...claims,
+ });
if (claimsUpdate.error) {
await deleteAuthAccount(userId);
return error(claimsUpdate.error, "Failed to set user claims");
@@ -82,18 +160,78 @@ export async function createEmployeeAccount(
return success("Employee account created");
}
-export async function createEmployeeType(
+export async function createSupplierAccount(
client: SupabaseClient<Database>,
- employeeType: { id?: string; name: string; color: string | null }
-) {
- return client.from("employeeType").insert([employeeType]).select("id");
-}
+ {
+ id,
+ supplierId,
+ }: {
+ id: string;
+ supplierId: string;
+ }
+): Promise<Result> {
+ const supplierContact = await getSupplierContact(client, id);
+ if (
+ supplierContact.error ||
+ supplierContact.data === null ||
+ Array.isArray(supplierContact.data.contact) ||
+ supplierContact.data.contact === null
+ ) {
+ return error(supplierContact.error, "Failed to get supplier contact");
+ }
-export async function createGroup(
- client: SupabaseClient<Database>,
- group: { name: string }
-) {
- return client.from("group").insert(group).select("id");
+ const { email, firstName, lastName } = supplierContact.data.contact;
+
+ // TODO: can we do this after we've done the other stuff?
+ const invitation = await sendInviteByEmail(email);
+
+ if (invitation.error)
+ return error(invitation.error.message, "Failed to send invitation email");
+
+ const userId = invitation.data.user.id;
+
+ const claims = makeSupplierClaims();
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "customer",
+ ...claims,
+ });
+ if (claimsUpdate.error) {
+ await deleteAuthAccount(userId);
+ return error(claimsUpdate.error, "Failed to set user claims");
+ }
+
+ const insertUser = await createUser(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ });
+
+ if (insertUser.error)
+ return error(insertUser.error, "Failed to create a new user");
+
+ if (!insertUser.data)
+ return error(insertUser, "No data returned from create user");
+
+ const updateContact = await client
+ .from("supplierContact")
+ .update({ userId })
+ .eq("id", id);
+ if (updateContact.error) {
+ await deleteAuthAccount(userId);
+ return error(updateContact.error, "Failed to update supplier contact");
+ }
+
+ const createSupplierAccount = await insertSupplierAccount(client, {
+ id: insertUser.data[0].id,
+ supplierId,
+ });
+
+ if (createSupplierAccount.error)
+ return error(createSupplierAccount.error, "Failed to create an employee");
+
+ return success("Supplier account created");
}
async function createUser(
@@ -144,7 +282,6 @@ export async function deleteAttributeCategory(
client: SupabaseClient<Database>,
attributeCategoryId: string
) {
- console.log("deleting attribute category", attributeCategoryId);
return client
.from("userAttributeCategory")
.update({ active: false })
@@ -228,14 +365,11 @@ export async function getAttributeDataTypes(client: SupabaseClient<Database>) {
return client.from("attributeDataType").select("*");
}
-export async function getClaimsById(
- client: SupabaseClient<Database>,
- uid: string
-) {
+export async function getClaims(client: SupabaseClient<Database>, uid: string) {
return client.rpc("get_claims", { uid });
}
-export async function getEmployeeById(
+export async function getEmployee(
client: SupabaseClient<Database>,
id: string
) {
@@ -246,6 +380,36 @@ export async function getEmployeeById(
.single();
}
+export async function getSuppliers(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ type: string | null;
+ active: boolean | null;
+ }
+) {
+ let query = client.from("supplierAccount").select(
+ `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
+ supplier!inner(name, supplierType!left(name))`,
+ { count: "exact" }
+ );
+
+ if (args.name) {
+ query = query.ilike("user.fullName", `%${args.name}%`);
+ }
+
+ if (args.type) {
+ query = query.eq("supplier.supplierTypeId", args.type);
+ }
+
+ if (args.active !== null) {
+ query = query.eq("user.active", args.active);
+ }
+
+ query = setGenericQueryFilters(query, args, "user(lastName)");
+ return query;
+}
+
export async function getEmployees(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
@@ -277,6 +441,36 @@ export async function getEmployees(
return query;
}
+export async function getCustomers(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ type: string | null;
+ active: boolean | null;
+ }
+) {
+ let query = client.from("customerAccount").select(
+ `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
+ customer!inner(name, customerType!left(name))`,
+ { count: "exact" }
+ );
+
+ if (args.name) {
+ query = query.ilike("user.fullName", `%${args.name}%`);
+ }
+
+ if (args.type) {
+ query = query.eq("customer.customerTypeId", args.type);
+ }
+
+ if (args.active !== null) {
+ query = query.eq("user.active", args.active);
+ }
+
+ query = setGenericQueryFilters(query, args, "user(lastName)");
+ return query;
+}
+
export async function getEmployeeType(
client: SupabaseClient<Database>,
employeeTypeId: string
@@ -318,7 +512,7 @@ export async function getGroup(
return client.from("group").select("id, name").eq("id", groupId).single();
}
-export async function getGroupMembersById(
+export async function getGroupMembers(
client: SupabaseClient<Database>,
groupId: string
) {
@@ -374,7 +568,7 @@ export async function getPermissions(
} finally {
// if we don't have permissions from redis, get them from the database
if (!permissions) {
- const claims = await getClaimsById(client, userId);
+ const claims = await getClaims(client, userId);
if (claims.error || claims.data === null) {
throw redirect(
"/app",
@@ -489,6 +683,16 @@ export async function insertAttributeCategory(
.select("id");
}
+async function insertCustomerAccount(
+ client: SupabaseClient<Database>,
+ customerAccount: {
+ id: string;
+ customerId: string;
+ }
+) {
+ return client.from("customerAccount").insert(customerAccount).select("id");
+}
+
export async function insertEmployee(
client: SupabaseClient<Database>,
employee: EmployeeRow
@@ -496,6 +700,30 @@ export async function insertEmployee(
return client.from("employee").insert([employee]);
}
+export async function insertEmployeeType(
+ client: SupabaseClient<Database>,
+ employeeType: { id?: string; name: string; color: string | null }
+) {
+ return client.from("employeeType").insert([employeeType]).select("id");
+}
+
+export async function insertGroup(
+ client: SupabaseClient<Database>,
+ group: { name: string }
+) {
+ return client.from("group").insert(group).select("id");
+}
+
+async function insertSupplierAccount(
+ client: SupabaseClient<Database>,
+ supplierAccount: {
+ id: string;
+ supplierId: string;
+ }
+) {
+ return client.from("supplierAccount").insert(supplierAccount).select("id");
+}
+
async function insertUser(
client: SupabaseClient<Database>,
user: Omit<User, "fullName">
@@ -550,6 +778,17 @@ function isClaimPermission(key: string, value: unknown) {
);
}
+function makeCustomerClaims() {
+ // TODO: this should be more dynamic
+ const claims: Record<string, boolean> = {
+ documents_view: true,
+ jobs_view: true,
+ sales_view: true,
+ };
+
+ return claims;
+}
+
export function makeEmptyPermissionsFromFeatures(data: Feature[]) {
return data.reduce<Record<string, { id: string; permission: Permission }>>(
(acc, module) => {
@@ -631,6 +870,17 @@ export function makePermissionsFromEmployeeType(
return result;
}
+function makeSupplierClaims() {
+ // TODO: this should be more dynamic
+ const claims: Record<string, boolean> = {
+ documents_view: true,
+ inventory_view: true,
+ purchasing_view: true,
+ };
+
+ return claims;
+}
+
export async function resendInvite(
client: SupabaseClient<Database>,
userId: string
@@ -654,7 +904,10 @@ export async function resetPassword(userId: string, password: string) {
});
}
-async function setUserClaims(userId: string, claims: Record<string, boolean>) {
+async function setUserClaims(
+ userId: string,
+ claims: Record<string, boolean | string>
+) {
return getSupabaseAdmin().auth.admin.updateUserById(userId, {
app_metadata: claims,
});
@@ -691,16 +944,16 @@ export async function updatePermissions(
}: { id: string; permissions: Record<string, Permission>; addOnly?: boolean }
): Promise<Result> {
if (await client.rpc("is_claims_admin")) {
- const getClaims = await getClaimsById(client, id);
+ const claims = await getClaims(client, id);
- if (getClaims.error) return error(getClaims.error, "Failed to get claims");
+ if (claims.error) return error(claims.error, "Failed to get claims");
const currentClaims =
- typeof getClaims.data !== "object" ||
- Array.isArray(getClaims.data) ||
- getClaims.data === null
+ typeof claims.data !== "object" ||
+ Array.isArray(claims.data) ||
+ claims.data === null
? {}
- : getClaims.data;
+ : claims.data;
const newClaims: Record<string, boolean> = {};
Object.entries(permissions).forEach(([name, permission]) => {
diff --git a/apps/carbon/app/types/validators.ts b/apps/carbon/app/types/validators.ts
new file mode 100644
index 0000000000..a16cd2a335
--- /dev/null
+++ b/apps/carbon/app/types/validators.ts
@@ -0,0 +1,30 @@
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const address = {
+ addressId: zfd.numeric(z.number().optional()),
+ addressLine1: zfd.text(z.string().optional()),
+ addressLine2: zfd.text(z.string().optional()),
+ city: zfd.text(z.string().optional()),
+ state: zfd.text(z.string().optional()),
+ postalCode: zfd.text(z.string().optional()),
+ countryId: zfd.numeric(z.number().optional()),
+ phone: zfd.text(z.string().optional()),
+ fax: zfd.text(z.string().optional()),
+};
+
+export const contact = {
+ contactId: z.string().optional(),
+ firstName: z.string().min(1, "First name is required"),
+ lastName: z.string().min(1, "Last name is required"),
+ title: zfd.text(z.string().optional()),
+ email: z
+ .string()
+ .min(1, { message: "Email is required" })
+ .email("Must be a valid email"),
+ mobilePhone: zfd.text(z.string().optional()),
+ homePhone: zfd.text(z.string().optional()),
+ workPhone: zfd.text(z.string().optional()),
+ birthday: zfd.text(z.string().optional()),
+ ...address,
+};
diff --git a/apps/carbon/app/utils/form.ts b/apps/carbon/app/utils/form.ts
index 0a72d575c3..0e85cfc2d8 100644
--- a/apps/carbon/app/utils/form.ts
+++ b/apps/carbon/app/utils/form.ts
@@ -10,14 +10,14 @@ export const mapRowsToOptions = <T extends Record<string, any>>({
label,
}: {
data: T[] | undefined | null;
- value: keyof T;
+ value: keyof T | ((row: T) => string);
label: keyof T | ((row: T) => string);
}) => {
if (!data) return [];
return data.reduce<{ value: string | number; label: string }[]>(
(acc, row) => {
- const v = row[value];
+ const v = typeof value === "function" ? value(row) : row[value];
const l = typeof label === "function" ? label(row) : row[label];
if (v && l) {
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 1cad254f71..bfcb092939 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -11,28 +11,28 @@
"lint": "TIMING=1 eslint \"app/**/*.ts*\""
},
"dependencies": {
+ "@carbon/database": "*",
+ "@carbon/logger": "*",
+ "@carbon/react": "*",
+ "@carbon/utils": "*",
"@chakra-ui/react": "^2.4.1",
"@chakra-ui/skip-nav": "^2.0.13",
"@emotion/react": "^11.10.4",
"@emotion/server": "^11.10.0",
"@emotion/styled": "^11.10.4",
"@internationalized/date": "^3.0.2",
- "@remix-run/eslint-config": "^1.9.0",
- "@remix-run/node": "^1.9.0",
- "@remix-run/react": "^1.9.0",
- "@remix-run/vercel": "^1.9.0",
+ "@remix-run/eslint-config": "^1.10.1",
+ "@remix-run/node": "^1.10.1",
+ "@remix-run/react": "^1.10.1",
+ "@remix-run/vercel": "^1.10.1",
"@remix-validated-form/with-zod": "^2.0.5",
- "@carbon/database": "*",
- "@carbon/logger": "*",
- "@carbon/react": "*",
- "@carbon/utils": "*",
"@supabase/supabase-js": "^2.2.1",
"@tanstack/react-table": "^8.7.3",
"@vercel/node": "^2.8.0",
"bullmq": "~3.5.1",
"framer-motion": "^7.6.19",
- "lodash.words": "^4.2.0",
"lodash.debounce": "^4.0.8",
+ "lodash.words": "^4.2.0",
"performant-array-to-tree": "1.11.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -45,9 +45,9 @@
"zod-form-data": "1.2.4"
},
"devDependencies": {
- "@remix-run/dev": "^1.8.2",
- "@remix-run/serve": "^1.8.2",
"@carbon/tsconfig": "*",
+ "@remix-run/dev": "^1.10.1",
+ "@remix-run/serve": "^1.10.1",
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"typescript": "^4.9.3"
diff --git a/apps/carbon/public/serviceWorker.js b/apps/carbon/public/serviceWorker.js
index 2cef0ad515..790bcf811a 100644
--- a/apps/carbon/public/serviceWorker.js
+++ b/apps/carbon/public/serviceWorker.js
@@ -7,8 +7,8 @@ self.addEventListener("fetch", (event) => {
// If the request is for the favicons, fonts, or the built files (which are hashed in the name)
if (
- url.pathname.contains("logo") ||
- url.pathname.contains("storage/v1/object/public/avatars")
+ url.pathname.includes("logo") ||
+ url.pathname.includes("storage/v1/object/public/avatars")
) {
event.respondWith(
// we will open the assets cache
diff --git a/package.json b/package.json
index 54b5db1004..a546a94e38 100755
--- a/package.json
+++ b/package.json
@@ -23,7 +23,7 @@
"db:kill:redis": "yarn workspace @carbon/redis db:kill",
"db:types": "yarn workspace @carbon/database db:types",
"db:migrate": "yarn workspace @carbon/database db:migrate",
- "db:migrate:new": "yarn workspace @carbon/database db:migrate:new",
+ "db:migrate:new": "yarn workspace @carbon/database supabase migration new",
"db:push": "turbo run db:push",
"db:pull": "turbo run db:pull",
"db:seed": "turbo run db:seed --no-cache",
diff --git a/packages/carbon-database/package.json b/packages/carbon-database/package.json
index a3b5298142..1f0058d90c 100644
--- a/packages/carbon-database/package.json
+++ b/packages/carbon-database/package.json
@@ -18,7 +18,6 @@
"db:kill": "supabase stop",
"db:types": "supabase gen types typescript --local > src/types.ts",
"db:migrate": "prisma migrate deploy",
- "db:migrate:new": "prisma migrate dev --create-only",
"db:push": "prisma db push",
"db:pull": "prisma db pull",
"db:seed": "tsx src/seed.ts",
diff --git a/packages/carbon-database/prisma/migrations/20221202000000_employee/migration.sql b/packages/carbon-database/prisma/migrations/20221202000000_employee/migration.sql
index 133f69433e..b717377f99 100644
--- a/packages/carbon-database/prisma/migrations/20221202000000_employee/migration.sql
+++ b/packages/carbon-database/prisma/migrations/20221202000000_employee/migration.sql
@@ -3,8 +3,8 @@ CREATE TABLE "employee" (
"employeeTypeId" TEXT NOT NULL,
CONSTRAINT "employee_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "employee_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE NO ACTION ON UPDATE NO ACTION,
- CONSTRAINT "employee_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION
+ CONSTRAINT "employee_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE NO ACTION ON UPDATE CASCADE,
+ CONSTRAINT "employee_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE "employee" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/carbon-database/prisma/migrations/20221208000000_groups/migration.sql b/packages/carbon-database/prisma/migrations/20221208000000_groups/migration.sql
deleted file mode 100644
index a39d7f8b7c..0000000000
--- a/packages/carbon-database/prisma/migrations/20221208000000_groups/migration.sql
+++ /dev/null
@@ -1,244 +0,0 @@
-CREATE TABLE "group" (
- "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
- "name" TEXT NOT NULL,
- "isIdentityGroup" BOOLEAN NOT NULL DEFAULT false,
- "isEmployeeTypeGroup" BOOLEAN NOT NULL DEFAULT false,
- "createdAt" TIMESTAMP(3) DEFAULT now() NOT NULL,
- "updatedAt" TIMESTAMP(3),
-
- CONSTRAINT "group_pkey" PRIMARY KEY ("id")
-);
-
-CREATE TABLE "membership" (
- "id" SERIAL NOT NULL,
- "groupId" TEXT NOT NULL,
- "memberGroupId" TEXT,
- "memberUserId" TEXT,
-
- CONSTRAINT "membership_pkey" PRIMARY KEY ("id"),
- 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_membership
- UNIQUE ( "groupId", "memberGroupId", "memberUserId" ),
-
- CONSTRAINT membership_hasPersonOrGroup
- CHECK (
- ("memberGroupId" IS NULL AND "memberUserId" IS NOT NULL)
- OR
- ("memberGroupId" IS NOT NULL AND "memberUserId" IS NULL)
- )
-);
-
-CREATE INDEX index_membership_groupId ON "membership" ("groupId");
-CREATE INDEX index_membership_memberGroupId ON "membership" ("memberGroupId");
-CREATE INDEX index_membership_memberUserId ON "membership" ("memberUserId");
-
-CREATE FUNCTION public.create_employee_type_group()
-RETURNS TRIGGER AS $$
-BEGIN
- INSERT INTO public."group" ("id", "name", "isEmployeeTypeGroup")
- VALUES (new.id, new.name, TRUE);
-
- INSERT INTO public."membership"("groupId", "memberGroupId")
- VALUES ('00000000-0000-0000-0000-000000000000', new.id);
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-CREATE FUNCTION public.update_employee_type_group()
-RETURNS TRIGGER AS $$
-BEGIN
- UPDATE public."group" SET "name" = new.name
- WHERE "id" = new.id AND "isEmployeeTypeGroup" = TRUE;
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-CREATE FUNCTION public.create_user_identity_group()
-RETURNS TRIGGER AS $$
-BEGIN
- INSERT INTO public."group" ("id", "name", "isIdentityGroup")
- VALUES (new.id, new."fullName", TRUE);
-
- INSERT INTO public."membership"("groupId", "memberUserId")
- VALUES (new.id, new.id);
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-CREATE FUNCTION public.update_user_identity_group()
-RETURNS TRIGGER AS $$
-BEGIN
- update public."group" set "name" = new."fullName"
- where "id" = new.id and "isIdentityGroup" = TRUE;
-
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-
-CREATE FUNCTION public.add_employee_to_employee_type_group()
-RETURNS TRIGGER AS $$
-BEGIN
- INSERT INTO public."membership" ("groupId", "memberUserId")
- VALUES (new."employeeTypeId", new.id);
-
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-CREATE FUNCTION public.update_employee_to_employee_type_group()
-RETURNS TRIGGER AS $$
-BEGIN
- UPDATE public."membership" SET "groupId" = new."employeeTypeId"
- WHERE "groupId" = old."employeeTypeId" AND "memberUserId" = new.id;
-
- RETURN new;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
-
-CREATE TRIGGER on_employee_type_created
- AFTER INSERT on public."employeeType"
- FOR EACH ROW EXECUTE PROCEDURE public.create_employee_type_group();
-
-CREATE TRIGGER on_user_created
- AFTER INSERT on public.user
- FOR EACH ROW EXECUTE PROCEDURE public.create_user_identity_group();
-
-CREATE TRIGGER on_employee_created
- AFTER INSERT on public.employee
- FOR EACH ROW EXECUTE PROCEDURE public.add_employee_to_employee_type_group();
-
-CREATE TRIGGER on_user_updated
- AFTER UPDATE on public.user
- FOR EACH ROW EXECUTE PROCEDURE public.update_user_identity_group();
-
-CREATE TRIGGER on_employee_updated
- AFTER UPDATE on public.employee
- FOR EACH ROW EXECUTE PROCEDURE public.update_employee_to_employee_type_group();
-
-CREATE TRIGGER on_employee_type_updated
- AFTER UPDATE on public."employeeType"
- FOR EACH ROW EXECUTE PROCEDURE public.update_employee_type_group();
-
-
-CREATE VIEW "group_member" AS
- SELECT
- gm.id,
- g.name,
- g."isIdentityGroup",
- g."isEmployeeTypeGroup",
- gm."groupId",
- gm."memberGroupId",
- gm."memberUserId",
- to_jsonb(u) as user
- FROM
- "membership" gm
- INNER JOIN "group" g ON g.id = gm."groupId"
- LEFT OUTER JOIN "user" u ON u.id = gm."memberUserId"
- WHERE u.active = TRUE;
-
-CREATE RECURSIVE VIEW groups_recursive
-(
- "groupId",
- "name",
- "parentId",
- "isIdentityGroup",
- "isEmployeeTypeGroup",
- "user"
-) AS
- SELECT
- "groupId",
- "name",
- NULL AS "parentId",
- "isIdentityGroup",
- "isEmployeeTypeGroup",
- "user"
- FROM group_member
- UNION ALL
- SELECT g2."groupId", g2.name, g1."groupId" AS "parentId", g1."isIdentityGroup", g2."isEmployeeTypeGroup", g2."user"
- FROM group_member g1
- INNER JOIN group_member g2 ON g1."memberGroupId" = g2."groupId";
-
-CREATE VIEW groups_view AS
- SELECT
- "groupId" as "id",
- "isEmployeeTypeGroup",
- "name",
- "parentId",
- coalesce(jsonb_agg("user") filter (where "user" is not null), '[]') as users
- FROM groups_recursive
- WHERE "isIdentityGroup" = false
- GROUP BY "groupId", "name", "parentId", "isEmployeeTypeGroup"
- ORDER BY "isEmployeeTypeGroup" DESC, "name" ASC;
-
-
-CREATE OR REPLACE FUNCTION groups_query(
- _name TEXT DEFAULT '',
- _uid TEXT DEFAULT NULL
-)
-RETURNS TABLE (
- "id" TEXT,
- "name" TEXT,
- "parentId" TEXT,
- "isEmployeeTypeGroup" BOOLEAN,
- "users" JSONB
-) LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
-AS $$
- BEGIN
- RETURN QUERY
- WITH group_ids AS (
- SELECT g."id"
- FROM "group" g
- WHERE g."isIdentityGroup" = false
- AND g."name" ILIKE '%' || _name || '%'
- )
- SELECT
- g."id",
- g."name",
- g."parentId",
- g."isEmployeeTypeGroup",
- g."users"
- FROM groups_view g
- WHERE g."id" IN (SELECT * FROM group_ids)
- OR g."parentId" IN (SELECT * FROM group_ids);
- END;
-$$;
-
-CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: return setof string
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- DECLARE retval jsonb;
- BEGIN
- WITH RECURSIVE "groupsForUser" AS (
- SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
- WHERE "memberUserId" = uid::text
- UNION
- SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
- INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"
- ) SELECT coalesce(jsonb_agg("groupId"), '[]') INTO retval AS groups FROM "groupsForUser";
- RETURN retval;
- END;
-$$;
-
-CREATE OR REPLACE FUNCTION users_for_groups(groups text[]) RETURNS "jsonb"
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- DECLARE retval jsonb;
- BEGIN
- WITH RECURSIVE "usersForGroups" AS (
- SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
- WHERE "groupId" = ANY(groups)
- UNION
- SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
- INNER JOIN "usersForGroups" g2 ON g2."memberGroupId" = g1."groupId"
- ) SELECT coalesce(jsonb_agg("memberUserId"), '[]') AS groups INTO retval FROM "usersForGroups" WHERE "memberUserId" IS NOT NULL;
- RETURN retval;
- END;
-$$;
-
-NOTIFY pgrst, 'reload schema';
-
diff --git a/packages/carbon-database/prisma/migrations/20221227000000_attributes/migration.sql b/packages/carbon-database/prisma/migrations/20221227000000_attributes/migration.sql
index 38486ef777..b50ba51833 100644
--- a/packages/carbon-database/prisma/migrations/20221227000000_attributes/migration.sql
+++ b/packages/carbon-database/prisma/migrations/20221227000000_attributes/migration.sql
@@ -100,7 +100,7 @@ CREATE TABLE "userAttribute" (
"listOptions" TEXT ARRAY,
"canSelfManage" BOOLEAN DEFAULT FALSE,
"active" BOOLEAN DEFAULT TRUE,
- "createdAt" TIMESTAMP(3) DEFAULT now() NOT NULL,
+ "createdAt" TIMESTAMP(3) DEFAULT NOW() NOT NULL,
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3),
"updatedBy" TEXT,
diff --git a/packages/carbon-database/prisma/migrations/20230109000000_organizations/migration.sql b/packages/carbon-database/prisma/migrations/20230109000000_organizations/migration.sql
new file mode 100644
index 0000000000..04dd7f0860
--- /dev/null
+++ b/packages/carbon-database/prisma/migrations/20230109000000_organizations/migration.sql
@@ -0,0 +1,195 @@
+CREATE TABLE "country" (
+ "id" SERIAL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "code" TEXT NOT NULL
+);
+
+CREATE TABLE "contact" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "firstName" TEXT NOT NULL,
+ "lastName" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "title" TEXT,
+ "mobilePhone" TEXT,
+ "homePhone" TEXT,
+ "workPhone" TEXT,
+ "fax" TEXT,
+ "addressLine1" TEXT,
+ "addressLine2" TEXT,
+ "city" TEXT,
+ "state" TEXT,
+ "postalCode" TEXT,
+ "countryId" INTEGER,
+ "birthday" DATE,
+ "notes" TEXT,
+
+ CONSTRAINT "contact_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "contact_countryId_fkey" FOREIGN KEY ("countryId") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+
+
+CREATE TABLE "address" (
+ "id" SERIAL PRIMARY KEY,
+ "addressLine1" TEXT,
+ "addressLine2" TEXT,
+ "city" TEXT,
+ "state" TEXT,
+ "postalCode" TEXT,
+ "countryId" INTEGER,
+ "phone" TEXT,
+ "fax" TEXT,
+
+ CONSTRAINT "address_countryId_fkey" FOREIGN KEY ("countryId") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+
+CREATE TABLE "supplierStatus" (
+ "id" SERIAL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3)
+);
+
+INSERT INTO "supplierStatus" ("name") VALUES ('Active'), ('Inactive'), ('Pending'), ('Rejected');
+
+CREATE TABLE "supplierType" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "name" TEXT NOT NULL,
+ "color" TEXT DEFAULT '#000000',
+ "protected" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3),
+
+ CONSTRAINT "supplierType_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierType_colorCheck" CHECK ("color" is null or "color" ~* '^#[a-f0-9]{6}$')
+);
+
+CREATE TABLE "supplier" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "supplierTypeId" TEXT,
+ "supplierStatusId" INTEGER,
+ "taxId" TEXT,
+ "accountManagerId" TEXT,
+ "logo" TEXT,
+ "createdAt" TIMESTAMP(3) DEFAULT NOW() NOT NULL,
+ "createdBy" TEXT,
+ "updatedAt" TIMESTAMP(3),
+ "updatedBy" TEXT,
+
+ CONSTRAINT "supplier_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplier_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplier_supplierStatusId_fkey" FOREIGN KEY ("supplierStatusId") REFERENCES "supplierStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplier_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplier_name_unique" UNIQUE ("name")
+);
+
+CREATE TABLE "supplierLocation" (
+ "id" SERIAL PRIMARY KEY,
+ "supplierId" TEXT NOT NULL,
+ "addressId" INTEGER NOT NULL,
+
+ CONSTRAINT "supplierLocation_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "supplierLocation_addressId_fkey" FOREIGN KEY ("addressId") REFERENCES "address"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
+
+CREATE TABLE "supplierContact" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "supplierId" TEXT NOT NULL,
+ "contactId" TEXT NOT NULL,
+ "supplierLocationId" INTEGER,
+ "userId" TEXT,
+
+ CONSTRAINT "supplierContact_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierContact_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "supplierContact_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "supplierContact_supplierLocationId_fkey" FOREIGN KEY ("supplierLocationId") REFERENCES "supplierLocation"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "supplierContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL
+);
+
+CREATE TABLE "supplierAccount" (
+ "id" TEXT NOT NULL,
+ "supplierId" TEXT NOT NULL,
+
+ CONSTRAINT "supplierAccount_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierAccount_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "supplierAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE TABLE "customerStatus" (
+ "id" SERIAL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3)
+);
+
+INSERT INTO "customerStatus" ("name") VALUES ('Active'), ('Inactive'), ('Prospect'), ('Lead'), ('On Hold'), ('Cancelled'), ('Archived');
+
+CREATE TABLE "customerType" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "name" TEXT NOT NULL,
+ "color" TEXT DEFAULT '#000000',
+ "protected" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3),
+
+ CONSTRAINT "customerType_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "customerType_colorCheck" CHECK ("color" is null or "color" ~* '^#[a-f0-9]{6}$')
+);
+
+CREATE TABLE "customer" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "customerTypeId" TEXT,
+ "customerStatusId" INTEGER,
+ "taxId" TEXT,
+ "accountManagerId" TEXT,
+ "logo" TEXT,
+ "createdAt" TIMESTAMP(3) DEFAULT NOW() NOT NULL,
+ "createdBy" TEXT,
+ "updatedAt" TIMESTAMP(3),
+ "updatedBy" TEXT,
+
+ CONSTRAINT "customer_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "customer_customerTypeId_fkey" FOREIGN KEY ("customerTypeId") REFERENCES "customerType"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customer_customerStatusId_fkey" FOREIGN KEY ("customerStatusId") REFERENCES "customerStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customer_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customer_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customer_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customer_name_unique" UNIQUE ("name")
+);
+
+CREATE TABLE "customerLocation" (
+ "id" SERIAL PRIMARY KEY,
+ "customerId" TEXT NOT NULL,
+ "addressId" INTEGER NOT NULL,
+
+ CONSTRAINT "customerLocation_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "customerLocation_addressId_fkey" FOREIGN KEY ("addressId") REFERENCES "address"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
+
+CREATE TABLE "customerContact" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "customerId" TEXT NOT NULL,
+ "contactId" TEXT NOT NULL,
+ "customerLocationId" INTEGER,
+ "userId" TEXT,
+
+ CONSTRAINT "customerContact_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "customerContact_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "customerContact_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "customerContact_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "customerContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL
+);
+
+CREATE TABLE "customerAccount" (
+ "id" TEXT NOT NULL,
+ "customerId" TEXT NOT NULL,
+
+ CONSTRAINT "customerAccount_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "customerAccount_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "customerAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
diff --git a/packages/carbon-database/prisma/migrations/20230110000000_groups/migration.sql b/packages/carbon-database/prisma/migrations/20230110000000_groups/migration.sql
new file mode 100644
index 0000000000..6f22b9ab15
--- /dev/null
+++ b/packages/carbon-database/prisma/migrations/20230110000000_groups/migration.sql
@@ -0,0 +1,470 @@
+CREATE TABLE "group" (
+ "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
+ "name" TEXT NOT NULL,
+ "isIdentityGroup" BOOLEAN NOT NULL DEFAULT false,
+ "isEmployeeTypeGroup" BOOLEAN NOT NULL DEFAULT false,
+ "isCustomerOrgGroup" BOOLEAN NOT NULL DEFAULT false,
+ "isCustomerTypeGroup" BOOLEAN NOT NULL DEFAULT false,
+ "isSupplierTypeGroup" BOOLEAN NOT NULL DEFAULT false,
+ "isSupplierOrgGroup" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) DEFAULT now() NOT NULL,
+ "updatedAt" TIMESTAMP(3),
+
+ CONSTRAINT "group_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "membership" (
+ "id" SERIAL NOT NULL,
+ "groupId" TEXT NOT NULL,
+ "memberGroupId" TEXT,
+ "memberUserId" TEXT,
+
+ CONSTRAINT "membership_pkey" PRIMARY KEY ("id"),
+ 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_membership
+ UNIQUE ( "groupId", "memberGroupId", "memberUserId" ),
+
+ CONSTRAINT membership_hasPersonOrGroup
+ CHECK (
+ ("memberGroupId" IS NULL AND "memberUserId" IS NOT NULL)
+ OR
+ ("memberGroupId" IS NOT NULL AND "memberUserId" IS NULL)
+ )
+);
+
+CREATE INDEX index_membership_groupId ON "membership" ("groupId");
+CREATE INDEX index_membership_memberGroupId ON "membership" ("memberGroupId");
+CREATE INDEX index_membership_memberUserId ON "membership" ("memberUserId");
+
+CREATE FUNCTION public.create_employee_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isEmployeeTypeGroup")
+ VALUES (new.id, new.name, TRUE);
+
+ INSERT INTO public."membership"("groupId", "memberGroupId")
+ VALUES ('00000000-0000-0000-0000-000000000000', new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_employee_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ UPDATE public."group" SET "name" = new.name
+ WHERE "id" = new.id AND "isEmployeeTypeGroup" = TRUE;
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.create_user_identity_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isIdentityGroup")
+ VALUES (new.id, new."fullName", TRUE);
+
+ INSERT INTO public."membership"("groupId", "memberUserId")
+ VALUES (new.id, new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_user_identity_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ update public."group" set "name" = new."fullName"
+ where "id" = new.id and "isIdentityGroup" = TRUE;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+
+CREATE FUNCTION public.add_employee_to_employee_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."membership" ("groupId", "memberUserId")
+ VALUES (new."employeeTypeId", new.id);
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_employee_to_employee_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ UPDATE public."membership" SET "groupId" = new."employeeTypeId"
+ WHERE "groupId" = old."employeeTypeId" AND "memberUserId" = new.id;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER on_employee_type_created
+ AFTER INSERT on public."employeeType"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_employee_type_group();
+
+CREATE TRIGGER on_user_created
+ AFTER INSERT on public.user
+ FOR EACH ROW EXECUTE PROCEDURE public.create_user_identity_group();
+
+CREATE TRIGGER on_employee_created
+ AFTER INSERT on public.employee
+ FOR EACH ROW EXECUTE PROCEDURE public.add_employee_to_employee_type_group();
+
+CREATE TRIGGER on_user_updated
+ AFTER UPDATE on public.user
+ FOR EACH ROW EXECUTE PROCEDURE public.update_user_identity_group();
+
+CREATE TRIGGER on_employee_updated
+ AFTER UPDATE on public.employee
+ FOR EACH ROW EXECUTE PROCEDURE public.update_employee_to_employee_type_group();
+
+CREATE TRIGGER on_employee_type_updated
+ AFTER UPDATE on public."employeeType"
+ FOR EACH ROW EXECUTE PROCEDURE public.update_employee_type_group();
+
+CREATE VIEW "group_member" AS
+ SELECT
+ gm.id,
+ g.name,
+ g."isIdentityGroup",
+ g."isEmployeeTypeGroup",
+ g."isCustomerOrgGroup",
+ g."isCustomerTypeGroup",
+ g."isSupplierOrgGroup",
+ g."isSupplierTypeGroup",
+ gm."groupId",
+ gm."memberGroupId",
+ gm."memberUserId",
+ to_jsonb(u) as user
+ FROM
+ "membership" gm
+ INNER 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
+(
+ "groupId",
+ "name",
+ "parentId",
+ "isIdentityGroup",
+ "isEmployeeTypeGroup",
+ "isCustomerOrgGroup",
+ "isCustomerTypeGroup",
+ "isSupplierOrgGroup",
+ "isSupplierTypeGroup",
+ "user"
+) AS
+ SELECT
+ "groupId",
+ "name",
+ NULL AS "parentId",
+ "isIdentityGroup",
+ "isEmployeeTypeGroup",
+ "isCustomerOrgGroup",
+ "isCustomerTypeGroup",
+ "isSupplierOrgGroup",
+ "isSupplierTypeGroup",
+ "user"
+ FROM group_member
+ 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 group_member g1
+ INNER JOIN group_member g2 ON g1."memberGroupId" = g2."groupId";
+
+CREATE VIEW groups_view AS
+ SELECT
+ "groupId" as "id",
+ "isEmployeeTypeGroup",
+ "isCustomerOrgGroup",
+ "isCustomerTypeGroup",
+ "isSupplierOrgGroup",
+ "isSupplierTypeGroup",
+ "name",
+ "parentId",
+ coalesce(jsonb_agg("user") filter (where "user" is not null), '[]') as users
+ FROM groups_recursive
+ WHERE "isIdentityGroup" = false
+ GROUP BY
+ "groupId",
+ "name",
+ "parentId",
+ "isEmployeeTypeGroup",
+ "isCustomerOrgGroup",
+ "isCustomerTypeGroup",
+ "isSupplierOrgGroup",
+ "isSupplierTypeGroup"
+ ORDER BY "isEmployeeTypeGroup" DESC, "isCustomerTypeGroup" DESC, "isSupplierTypeGroup" DESC, "name" ASC;
+
+
+CREATE OR REPLACE FUNCTION groups_query(
+ _name TEXT DEFAULT '',
+ _uid TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "name" TEXT,
+ "parentId" TEXT,
+ "isEmployeeTypeGroup" BOOLEAN,
+ "isCustomerOrgGroup" BOOLEAN,
+ "isCustomerTypeGroup" BOOLEAN,
+ "isSupplierOrgGroup" BOOLEAN,
+ "isSupplierTypeGroup" BOOLEAN,
+ "users" JSONB
+) LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+AS $$
+ BEGIN
+ RETURN QUERY
+ WITH group_ids AS (
+ SELECT g."id"
+ FROM "group" g
+ WHERE g."isIdentityGroup" = false
+ AND g."name" ILIKE '%' || _name || '%'
+ )
+ SELECT
+ g."id",
+ g."name",
+ g."parentId",
+ g."isEmployeeTypeGroup",
+ g."isCustomerOrgGroup",
+ g."isCustomerTypeGroup",
+ g."isSupplierOrgGroup",
+ g."isSupplierTypeGroup",
+ g."users"
+ FROM groups_view g
+ WHERE g."id" IN (SELECT * FROM group_ids)
+ OR g."parentId" IN (SELECT * FROM group_ids);
+ END;
+$$;
+
+CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS "jsonb" -- TODO: return setof string
+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+ AS $$
+ DECLARE retval jsonb;
+ BEGIN
+ WITH RECURSIVE "groupsForUser" AS (
+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
+ WHERE "memberUserId" = uid::text
+ UNION
+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"
+ ) SELECT coalesce(jsonb_agg("groupId"), '[]') INTO retval AS groups FROM "groupsForUser";
+ RETURN retval;
+ END;
+$$;
+
+CREATE OR REPLACE FUNCTION users_for_groups(groups text[]) RETURNS "jsonb"
+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+ AS $$
+ DECLARE retval jsonb;
+ BEGIN
+ WITH RECURSIVE "usersForGroups" AS (
+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
+ WHERE "groupId" = ANY(groups)
+ UNION
+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
+ INNER JOIN "usersForGroups" g2 ON g2."memberGroupId" = g1."groupId"
+ ) SELECT coalesce(jsonb_agg("memberUserId"), '[]') AS groups INTO retval FROM "usersForGroups" WHERE "memberUserId" IS NOT NULL;
+ RETURN retval;
+ END;
+$$;
+
+CREATE FUNCTION public.create_customer_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isCustomerTypeGroup")
+ VALUES (new.id, new.name, TRUE);
+
+ INSERT INTO public."membership"("groupId", "memberGroupId")
+ VALUES ('11111111-1111-1111-1111-111111111111', new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.create_supplier_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isSupplierTypeGroup")
+ VALUES (new.id, new.name, TRUE);
+
+ INSERT INTO public."membership"("groupId", "memberGroupId")
+ VALUES ('22222222-2222-2222-2222-222222222222', new.id);
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.create_customer_org_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isCustomerOrgGroup")
+ VALUES (new.id, new.name, TRUE);
+
+ IF new."customerTypeId" IS NOT NULL THEN
+ INSERT INTO public."membership"("groupId", "memberGroupId")
+ VALUES (new."customerTypeId", new.id);
+ END IF;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.create_supplier_org_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."group" ("id", "name", "isSupplierOrgGroup")
+ VALUES (new.id, new.name, TRUE);
+
+ IF new."supplierTypeId" IS NOT NULL THEN
+ INSERT INTO public."membership"("groupId", "memberGroupId")
+ VALUES (new."supplierTypeId", new.id);
+ END IF;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.add_customer_account_to_customer_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."membership" ("groupId", "memberUserId")
+ VALUES (new."customerId", new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.add_supplier_account_to_supplier_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."membership" ("groupId", "memberUserId")
+ VALUES (new."supplierId", new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_customer_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ UPDATE public."group" SET "name" = new.name
+ WHERE "id" = new.id AND "isCustomerTypeGroup" = TRUE;
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_supplier_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ UPDATE public."group" SET "name" = new.name
+ WHERE "id" = new.id AND "isSupplierTypeGroup" = TRUE;
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_customer_to_customer_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF old."customerTypeId" IS NOT NULL THEN
+ IF new."customerTypeId" IS NOT NULL THEN
+ UPDATE public."membership" SET "groupId" = new."customerTypeId"
+ WHERE "groupId" = old."customerTypeId" AND "memberGroupId" = new.id;
+ ELSE
+ DELETE FROM public."membership" WHERE "groupId" = old."customerTypeId" AND "memberGroupId" = new.id;
+ END IF;
+ ELSE
+ IF new."customerTypeId" IS NOT NULL THEN
+ INSERT INTO public."membership" ("groupId", "memberGroupId")
+ VALUES (new."customerTypeId", new.id);
+ END IF;
+ END IF;
+
+ UPDATE public."group" SET "name" = new.name
+ WHERE "id" = new.id AND "isCustomerOrgGroup" = TRUE;
+ RETURN new;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE FUNCTION public.update_supplier_to_supplier_type_group()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF old."supplierTypeId" IS NOT NULL THEN
+ IF new."supplierTypeId" IS NOT NULL THEN
+ UPDATE public."membership" SET "groupId" = new."supplierTypeId"
+ WHERE "groupId" = old."supplierTypeId" AND "memberGroupId" = new.id;
+ ELSE
+ DELETE FROM public."membership" WHERE "groupId" = old."supplierTypeId" AND "memberGroupId" = new.id;
+ END IF;
+ ELSE
+ IF new."supplierTypeId" IS NOT NULL THEN
+ INSERT INTO public."membership" ("groupId", "memberGroupId")
+ VALUES (new."supplierTypeId", new.id);
+ END IF;
+ END IF;
+
+ UPDATE public."group" SET "name" = new.name
+ WHERE "id" = new.id AND "isSupplierOrgGroup" = TRUE;
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER on_customer_type_created
+ AFTER INSERT on public."customerType"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_customer_type_group();
+
+CREATE TRIGGER on_supplier_type_created
+ AFTER INSERT on public."supplierType"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_supplier_type_group();
+
+CREATE TRIGGER on_customer_org_created
+ AFTER INSERT on public.customer
+ FOR EACH ROW EXECUTE PROCEDURE public.create_customer_org_group();
+
+CREATE TRIGGER on_supplier_org_created
+ AFTER INSERT on public.supplier
+ FOR EACH ROW EXECUTE PROCEDURE public.create_supplier_org_group();
+
+CREATE TRIGGER on_customer_created
+ AFTER INSERT on public."customerAccount"
+ FOR EACH ROW EXECUTE PROCEDURE public.add_customer_account_to_customer_group();
+
+CREATE TRIGGER on_supplier_created
+ AFTER INSERT on public."supplierAccount"
+ FOR EACH ROW EXECUTE PROCEDURE public.add_supplier_account_to_supplier_group();
+
+CREATE TRIGGER on_customer_updated
+ AFTER UPDATE on public.customer
+ FOR EACH ROW EXECUTE PROCEDURE public.update_customer_to_customer_type_group();
+
+CREATE TRIGGER on_supplier_updated
+ AFTER UPDATE on public.supplier
+ FOR EACH ROW EXECUTE PROCEDURE public.update_supplier_to_supplier_type_group();
+
+CREATE TRIGGER on_customer_type_updated
+ AFTER UPDATE on public."customerType"
+ FOR EACH ROW EXECUTE PROCEDURE public.update_customer_type_group();
+
+CREATE TRIGGER on_supplier_type_updated
+ AFTER UPDATE on public."supplierType"
+ FOR EACH ROW EXECUTE PROCEDURE public.update_supplier_type_group();
+
+NOTIFY pgrst, 'reload schema';
+
diff --git a/packages/carbon-database/prisma/schema.prisma b/packages/carbon-database/prisma/schema.prisma
index 68e877b69b..3364d50069 100644
--- a/packages/carbon-database/prisma/schema.prisma
+++ b/packages/carbon-database/prisma/schema.prisma
@@ -8,11 +8,10 @@ datasource db {
}
model employee {
- id String @id
- employeeTypeId String
- employeeType employeeType @relation(fields: [employeeTypeId], references: [id], onDelete: NoAction, onUpdate: NoAction)
- user user @relation(fields: [id], references: [id], onDelete: Cascade, onUpdate: NoAction)
- employeePersonalData employeePersonalData?
+ id String @id
+ employeeTypeId String
+ employeeType employeeType @relation(fields: [employeeTypeId], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ user user @relation(fields: [id], references: [id], onDelete: Cascade, onUpdate: NoAction)
}
model employeeType {
@@ -50,25 +49,28 @@ model feature {
}
model user {
- id String @id
- email String @unique
- firstName String
- lastName String
- fullName String? @default(dbgenerated("((\"firstName\" || ' '::text) || \"lastName\")"))
- about String @default("")
- avatarUrl String?
- emailVerified DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime?
- attribute_attribute_createdByTouser attribute[] @relation("attribute_createdByTouser")
- attribute_attribute_updatedByTouser attribute[] @relation("attribute_updatedByTouser")
- attributeCategory_attributeCategory_createdByTouser attributeCategory[] @relation("attributeCategory_createdByTouser")
- attributeCategory_attributeCategory_updatedByTouser attributeCategory[] @relation("attributeCategory_updatedByTouser")
- attributeValue_attributeValue_createdByTouser attributeValue[] @relation("attributeValue_createdByTouser")
- attributeValue_attributeValue_updatedByTouser attributeValue[] @relation("attributeValue_updatedByTouser")
- attributeValue_attributeValue_userIdTouser attributeValue[] @relation("attributeValue_userIdTouser")
- employee employee?
- membership membership[]
+ id String @id
+ email String @unique
+ firstName String
+ lastName String
+ fullName String? @default(dbgenerated("((\"firstName\" || ' '::text) || \"lastName\")"))
+ about String @default("")
+ avatarUrl String?
+ active Boolean? @default(true)
+ emailVerified DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime?
+ employee employee?
+ membership membership[]
+ supplier supplier[]
+ userAttribute_userTouserAttribute_createdBy userAttribute[] @relation("userTouserAttribute_createdBy")
+ userAttribute_userTouserAttribute_updatedBy userAttribute[] @relation("userTouserAttribute_updatedBy")
+ userAttributeCategory_userTouserAttributeCategory_createdBy userAttributeCategory[] @relation("userTouserAttributeCategory_createdBy")
+ userAttributeCategory_userTouserAttributeCategory_updatedBy userAttributeCategory[] @relation("userTouserAttributeCategory_updatedBy")
+ userAttributeValue_userTouserAttributeValue_createdBy userAttributeValue[] @relation("userTouserAttributeValue_createdBy")
+ userAttributeValue_userTouserAttributeValue_updatedBy userAttributeValue[] @relation("userTouserAttributeValue_updatedBy")
+ userAttributeValue_userTouserAttributeValue_userId userAttributeValue[] @relation("userTouserAttributeValue_userId")
+ userAttributeValue_userTouserAttributeValue_valueUser userAttributeValue[] @relation("userTouserAttributeValue_valueUser")
@@index([fullName], map: "user_fullName_key")
}
@@ -100,72 +102,154 @@ model membership {
}
model attributeDataType {
- id Int @id @default(autoincrement())
- label String
- value String
- isBoolean Boolean @default(false)
- isDate Boolean @default(false)
- isList Boolean @default(false)
- isNumeric Boolean @default(false)
- isText Boolean @default(false)
- attribute attribute[]
-}
-
-model employeePersonalData {
- id String @id
- employee employee @relation(fields: [id], references: [id], onDelete: Cascade, onUpdate: NoAction)
-}
-
-model attribute {
- id Int @id @default(autoincrement())
- label String
- sortOrder Int @default(1)
- attributeCategoryId Int
- attributeDataTypeId Int
- listOptions String[]
- canSelfManage Boolean? @default(false)
- isActive Boolean? @default(true)
- createdAt DateTime @default(now())
- createdBy String
- updatedAt DateTime?
- updatedBy String?
- attributeCategory attributeCategory @relation(fields: [attributeCategoryId], references: [id], onDelete: Cascade)
- attributeDataType attributeDataType @relation(fields: [attributeDataTypeId], references: [id], onDelete: Cascade)
- user_attribute_createdByTouser user @relation("attribute_createdByTouser", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- user_attribute_updatedByTouser user? @relation("attribute_updatedByTouser", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- attributeValue attributeValue[]
-
- @@unique([attributeCategoryId, sortOrder], map: "uq_attributecategory_sortorder")
-}
-
-model attributeCategory {
- id Int @id @default(autoincrement())
- label String
- isActive Boolean? @default(true)
- createdAt DateTime @default(now())
- createdBy String
- updatedAt DateTime?
- updatedBy String?
- user_attributeCategory_createdByTouser user @relation("attributeCategory_createdByTouser", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- user_attributeCategory_updatedByTouser user? @relation("attributeCategory_updatedByTouser", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- attribute attribute[]
-}
-
-model attributeValue {
- id Int @id @default(autoincrement())
- attributeId Int
- userId String
- valueText String?
- valueDate DateTime? @db.Date
- valueNumber Decimal? @db.Decimal
- createdAt DateTime @default(now())
- createdBy String
- updatedAt DateTime?
- updatedBy String?
- attribute attribute @relation(fields: [attributeId], references: [id], onDelete: Cascade, onUpdate: NoAction)
- user_attributeValue_createdByTouser user @relation("attributeValue_createdByTouser", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- user_attributeValue_updatedByTouser user? @relation("attributeValue_updatedByTouser", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
- user_attributeValue_userIdTouser user @relation("attributeValue_userIdTouser", fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction)
-
- @@unique([attributeId, userId], map: "uq_attributeid_userid")
+ id Int @id @default(autoincrement())
+ label String
+ isBoolean Boolean @default(false)
+ isDate Boolean @default(false)
+ isList Boolean @default(false)
+ isNumeric Boolean @default(false)
+ isText Boolean @default(false)
+ isUser Boolean @default(false)
+ userAttribute userAttribute[]
+}
+
+model userAttribute {
+ id Int @id @default(autoincrement())
+ name String
+ sortOrder Int @default(1)
+ userAttributeCategoryId Int
+ attributeDataTypeId Int
+ listOptions String[]
+ canSelfManage Boolean? @default(false)
+ active Boolean? @default(true)
+ createdAt DateTime @default(now())
+ createdBy String
+ updatedAt DateTime?
+ updatedBy String?
+ attributeDataType attributeDataType @relation(fields: [attributeDataTypeId], references: [id], onDelete: Cascade)
+ user_userTouserAttribute_createdBy user @relation("userTouserAttribute_createdBy", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ user_userTouserAttribute_updatedBy user? @relation("userTouserAttribute_updatedBy", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ userAttributeCategory userAttributeCategory @relation(fields: [userAttributeCategoryId], references: [id], onDelete: Cascade)
+ userAttributeValue userAttributeValue[]
+}
+
+model userAttributeCategory {
+ id Int @id @default(autoincrement())
+ name String
+ public Boolean? @default(false)
+ protected Boolean? @default(false)
+ active Boolean? @default(true)
+ createdAt DateTime @default(now())
+ createdBy String
+ updatedAt DateTime?
+ updatedBy String?
+ user_userTouserAttributeCategory_createdBy user @relation("userTouserAttributeCategory_createdBy", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ user_userTouserAttributeCategory_updatedBy user? @relation("userTouserAttributeCategory_updatedBy", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ userAttribute userAttribute[]
+}
+
+model userAttributeValue {
+ id Int @id @default(autoincrement())
+ userAttributeId Int
+ userId String
+ valueBoolean Boolean?
+ valueDate DateTime? @db.Date
+ valueNumeric Decimal? @db.Decimal
+ valueText String?
+ valueUser String?
+ createdAt DateTime @default(now())
+ createdBy String
+ updatedAt DateTime?
+ updatedBy String?
+ user_userTouserAttributeValue_createdBy user @relation("userTouserAttributeValue_createdBy", fields: [createdBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ user_userTouserAttributeValue_updatedBy user? @relation("userTouserAttributeValue_updatedBy", fields: [updatedBy], references: [id], onDelete: NoAction, onUpdate: NoAction)
+ userAttribute userAttribute @relation(fields: [userAttributeId], references: [id], onDelete: Cascade, onUpdate: NoAction)
+ user_userTouserAttributeValue_userId user @relation("userTouserAttributeValue_userId", fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction)
+ user_userTouserAttributeValue_valueUser user? @relation("userTouserAttributeValue_valueUser", fields: [valueUser], references: [id], onDelete: Cascade, onUpdate: NoAction)
+
+ @@unique([userAttributeId, userId], map: "uq_userattributeid_userid")
+}
+
+model address {
+ id Int @id @default(autoincrement())
+ addressLine1 String?
+ addressLine2 String?
+ city String?
+ stateId Int?
+ countryId Int?
+ phone String?
+ fax String?
+ country country? @relation(fields: [countryId], references: [id])
+ state state? @relation(fields: [stateId], references: [id])
+ supplierLocation supplierLocation[]
+}
+
+model country {
+ id Int @id @default(autoincrement())
+ name String
+ code String
+ address address[]
+ state state[]
+}
+
+model state {
+ id Int @id @default(autoincrement())
+ name String
+ countryId Int?
+ country country? @relation(fields: [countryId], references: [id])
+ address address[]
+}
+
+model supplier {
+ id String @id @default(dbgenerated("uuid_generate_v4()"))
+ name String @unique(map: "supplier_name_unique")
+ description String?
+ supplierTypeId Int?
+ supplierStatusId Int?
+ taxId String? @unique(map: "supplier_taxId_unique")
+ taxable Boolean? @default(true)
+ established DateTime? @db.Date
+ accountManagerId String?
+ logo String?
+ website String?
+ twitter String?
+ facebook String?
+ instagram String?
+ linkedin String?
+ github String?
+ youtube String?
+ twitch String?
+ discord String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime?
+ user user? @relation(fields: [accountManagerId], references: [id])
+ supplierStatus supplierStatus? @relation(fields: [supplierStatusId], references: [id])
+ supplierType supplierType? @relation(fields: [supplierTypeId], references: [id])
+ supplierLocation supplierLocation[]
+}
+
+model supplierLocation {
+ id Int @id @default(autoincrement())
+ supplierId String
+ addressId Int
+ address address @relation(fields: [addressId], references: [id], onDelete: Cascade)
+ supplier supplier @relation(fields: [supplierId], references: [id], onDelete: Cascade)
+}
+
+model supplierStatus {
+ id Int @id @default(autoincrement())
+ name String
+ createdAt DateTime @default(now())
+ updatedAt DateTime?
+ supplier supplier[]
+}
+
+model supplierType {
+ id Int @id @default(autoincrement())
+ name String
+ color String? @default("#000000")
+ protected Boolean @default(false)
+ createdAt DateTime @default(now())
+ updatedAt DateTime?
+ supplier supplier[]
}
diff --git a/packages/carbon-database/src/seed.ts b/packages/carbon-database/src/seed.ts
index ac8ed8e294..42bbf35594 100644
--- a/packages/carbon-database/src/seed.ts
+++ b/packages/carbon-database/src/seed.ts
@@ -85,7 +85,23 @@ async function seed() {
{
id: "00000000-0000-0000-0000-000000000000",
name: "All Employees",
+ isCustomerTypeGroup: false,
isEmployeeTypeGroup: true,
+ isSupplierTypeGroup: false,
+ },
+ {
+ id: "11111111-1111-1111-1111-111111111111",
+ name: "All Customers",
+ isCustomerTypeGroup: true,
+ isEmployeeTypeGroup: false,
+ isSupplierTypeGroup: false,
+ },
+ {
+ id: "22222222-2222-2222-2222-222222222222",
+ name: "All Suppliers",
+ isCustomerTypeGroup: false,
+ isEmployeeTypeGroup: false,
+ isSupplierTypeGroup: true,
},
]);
if (insertGroups.error) throw insertGroups.error;
diff --git a/packages/carbon-database/src/seed/employee-types.ts b/packages/carbon-database/src/seed/employee-types.ts
index 11497b0142..b5f28e8c08 100644
--- a/packages/carbon-database/src/seed/employee-types.ts
+++ b/packages/carbon-database/src/seed/employee-types.ts
@@ -1,5 +1,5 @@
import { v4 as uuidv4 } from "uuid";
-import type { Module } from "./features";
+import type { Feature } from "./features";
export const possibleEmployees = ["Admin", "Project Manager", "Sales"] as const;
@@ -22,7 +22,7 @@ export { employeeTypes };
export const employeeTypePermissionsDefinitions: Record<
EmployeeType,
Record<
- Module,
+ Feature,
{ create: boolean; update: boolean; delete: boolean; view: boolean }
>
> = {
@@ -51,7 +51,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: true,
view: true,
},
- Orders: {
+ Sales: {
create: true,
update: true,
delete: true,
@@ -81,7 +81,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: true,
view: true,
},
- Partners: {
+ People: {
create: true,
update: true,
delete: true,
@@ -125,7 +125,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: true,
view: true,
},
- Orders: {
+ Sales: {
create: false,
update: false,
delete: false,
@@ -155,7 +155,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: false,
view: true,
},
- Partners: {
+ People: {
create: true,
update: true,
delete: true,
@@ -199,7 +199,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: false,
view: true,
},
- Orders: {
+ Sales: {
create: true,
update: true,
delete: true,
@@ -229,7 +229,7 @@ export const employeeTypePermissionsDefinitions: Record<
delete: false,
view: false,
},
- Partners: {
+ People: {
create: true,
update: true,
delete: true,
diff --git a/packages/carbon-database/src/seed/features.ts b/packages/carbon-database/src/seed/features.ts
index 3a5211346f..f019565f78 100644
--- a/packages/carbon-database/src/seed/features.ts
+++ b/packages/carbon-database/src/seed/features.ts
@@ -1,18 +1,18 @@
import { v4 as uuidv4 } from "uuid";
const possibleFeatures = [
- "Parts",
- "Jobs",
- "Inventory",
- "Scheduling",
- "Orders",
- "Purchasing",
"Documents",
+ "Inventory",
+ "Jobs",
"Messaging",
+ "Parts",
+ "People",
+ "Purchasing",
+ "Sales",
+ "Scheduling",
+ "Settings",
"Timecards",
- "Partners",
"Users",
- "Settings",
] as const;
export type Feature = typeof possibleFeatures[number];
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index 8ef9edf3e4..ca189b6195 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -41,10 +41,45 @@ export interface Database {
applied_steps_count?: number
}
}
- attributeDataType: {
+ address: {
Row: {
+ addressLine1: string | null
+ addressLine2: string | null
+ city: string | null
+ state: string | null
+ postalCode: string | null
+ countryId: number | null
+ phone: string | null
+ fax: string | null
id: number
+ }
+ Insert: {
+ addressLine1?: string | null
+ addressLine2?: string | null
+ city?: string | null
+ state?: string | null
+ postalCode?: string | null
+ countryId?: number | null
+ phone?: string | null
+ fax?: string | null
+ id?: number
+ }
+ Update: {
+ addressLine1?: string | null
+ addressLine2?: string | null
+ city?: string | null
+ state?: string | null
+ postalCode?: string | null
+ countryId?: number | null
+ phone?: string | null
+ fax?: string | null
+ id?: number
+ }
+ }
+ attributeDataType: {
+ Row: {
label: string
+ id: number
isBoolean: boolean
isDate: boolean
isList: boolean
@@ -53,8 +88,8 @@ export interface Database {
isUser: boolean
}
Insert: {
- id?: number
label: string
+ id?: number
isBoolean?: boolean
isDate?: boolean
isList?: boolean
@@ -63,8 +98,8 @@ export interface Database {
isUser?: boolean
}
Update: {
- id?: number
label?: string
+ id?: number
isBoolean?: boolean
isDate?: boolean
isList?: boolean
@@ -73,6 +108,226 @@ export interface Database {
isUser?: boolean
}
}
+ contact: {
+ Row: {
+ firstName: string
+ lastName: string
+ email: string
+ title: string | null
+ mobilePhone: string | null
+ homePhone: string | null
+ workPhone: string | null
+ fax: string | null
+ addressLine1: string | null
+ addressLine2: string | null
+ city: string | null
+ state: string | null
+ postalCode: string | null
+ countryId: number | null
+ birthday: string | null
+ notes: string | null
+ id: string
+ }
+ Insert: {
+ firstName: string
+ lastName: string
+ email: string
+ title?: string | null
+ mobilePhone?: string | null
+ homePhone?: string | null
+ workPhone?: string | null
+ fax?: string | null
+ addressLine1?: string | null
+ addressLine2?: string | null
+ city?: string | null
+ state?: string | null
+ postalCode?: string | null
+ countryId?: number | null
+ birthday?: string | null
+ notes?: string | null
+ id?: string
+ }
+ Update: {
+ firstName?: string
+ lastName?: string
+ email?: string
+ title?: string | null
+ mobilePhone?: string | null
+ homePhone?: string | null
+ workPhone?: string | null
+ fax?: string | null
+ addressLine1?: string | null
+ addressLine2?: string | null
+ city?: string | null
+ state?: string | null
+ postalCode?: string | null
+ countryId?: number | null
+ birthday?: string | null
+ notes?: string | null
+ id?: string
+ }
+ }
+ country: {
+ Row: {
+ name: string
+ code: string
+ id: number
+ }
+ Insert: {
+ name: string
+ code: string
+ id?: number
+ }
+ Update: {
+ name?: string
+ code?: string
+ id?: number
+ }
+ }
+ customer: {
+ Row: {
+ name: string
+ description: string | null
+ customerTypeId: string | null
+ customerStatusId: number | null
+ taxId: string | null
+ accountManagerId: string | null
+ logo: string | null
+ createdBy: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ id: string
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ description?: string | null
+ customerTypeId?: string | null
+ customerStatusId?: number | null
+ taxId?: string | null
+ accountManagerId?: string | null
+ logo?: string | null
+ createdBy?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ id?: string
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ description?: string | null
+ customerTypeId?: string | null
+ customerStatusId?: number | null
+ taxId?: string | null
+ accountManagerId?: string | null
+ logo?: string | null
+ createdBy?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ id?: string
+ createdAt?: string
+ }
+ }
+ customerAccount: {
+ Row: {
+ id: string
+ customerId: string
+ }
+ Insert: {
+ id: string
+ customerId: string
+ }
+ Update: {
+ id?: string
+ customerId?: string
+ }
+ }
+ customerContact: {
+ Row: {
+ customerId: string
+ contactId: string
+ customerLocationId: number | null
+ userId: string | null
+ id: string
+ }
+ Insert: {
+ customerId: string
+ contactId: string
+ customerLocationId?: number | null
+ userId?: string | null
+ id?: string
+ }
+ Update: {
+ customerId?: string
+ contactId?: string
+ customerLocationId?: number | null
+ userId?: string | null
+ id?: string
+ }
+ }
+ customerLocation: {
+ Row: {
+ customerId: string
+ addressId: number
+ id: number
+ }
+ Insert: {
+ customerId: string
+ addressId: number
+ id?: number
+ }
+ Update: {
+ customerId?: string
+ addressId?: number
+ id?: number
+ }
+ }
+ customerStatus: {
+ Row: {
+ name: string
+ updatedAt: string | null
+ id: number
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ updatedAt?: string | null
+ id?: number
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ updatedAt?: string | null
+ id?: number
+ createdAt?: string
+ }
+ }
+ customerType: {
+ Row: {
+ name: string
+ updatedAt: string | null
+ id: string
+ color: string | null
+ protected: boolean
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ updatedAt?: string | null
+ id?: string
+ color?: string | null
+ protected?: boolean
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ updatedAt?: string | null
+ id?: string
+ color?: string | null
+ protected?: boolean
+ createdAt?: string
+ }
+ }
employee: {
Row: {
id: string
@@ -89,126 +344,282 @@ export interface Database {
}
employeeType: {
Row: {
- id: string
name: string
+ updatedAt: string | null
+ id: string
color: string | null
protected: boolean
createdAt: string
- updatedAt: string | null
}
Insert: {
- id?: string
name: string
+ updatedAt?: string | null
+ id?: string
color?: string | null
protected?: boolean
createdAt?: string
- updatedAt?: string | null
}
Update: {
- id?: string
name?: string
+ updatedAt?: string | null
+ id?: string
color?: string | null
protected?: boolean
createdAt?: string
- updatedAt?: string | null
}
}
employeeTypePermission: {
Row: {
employeeTypeId: string
featureId: string
+ updatedAt: string | null
create: boolean
delete: boolean
update: boolean
view: boolean
createdAt: string
- updatedAt: string | null
}
Insert: {
employeeTypeId: string
featureId: string
+ updatedAt?: string | null
create?: boolean
delete?: boolean
update?: boolean
view?: boolean
createdAt?: string
- updatedAt?: string | null
}
Update: {
employeeTypeId?: string
featureId?: string
+ updatedAt?: string | null
create?: boolean
delete?: boolean
update?: boolean
view?: boolean
createdAt?: string
- updatedAt?: string | null
}
}
feature: {
Row: {
- id: string
name: string
- createdAt: string
updatedAt: string | null
+ id: string
+ createdAt: string
}
Insert: {
- id?: string
name: string
- createdAt?: string
updatedAt?: string | null
+ id?: string
+ createdAt?: string
}
Update: {
- id?: string
name?: string
- createdAt?: string
updatedAt?: string | null
+ id?: string
+ createdAt?: string
}
}
group: {
Row: {
- id: string
name: string
+ updatedAt: string | null
+ id: string
isIdentityGroup: boolean
isEmployeeTypeGroup: boolean
+ isCustomerOrgGroup: boolean
+ isCustomerTypeGroup: boolean
+ isSupplierTypeGroup: boolean
+ isSupplierOrgGroup: boolean
createdAt: string
- updatedAt: string | null
}
Insert: {
- id?: string
name: string
+ updatedAt?: string | null
+ id?: string
isIdentityGroup?: boolean
isEmployeeTypeGroup?: boolean
+ isCustomerOrgGroup?: boolean
+ isCustomerTypeGroup?: boolean
+ isSupplierTypeGroup?: boolean
+ isSupplierOrgGroup?: boolean
createdAt?: string
- updatedAt?: string | null
}
Update: {
- id?: string
name?: string
+ updatedAt?: string | null
+ id?: string
isIdentityGroup?: boolean
isEmployeeTypeGroup?: boolean
+ isCustomerOrgGroup?: boolean
+ isCustomerTypeGroup?: boolean
+ isSupplierTypeGroup?: boolean
+ isSupplierOrgGroup?: boolean
createdAt?: string
- updatedAt?: string | null
}
}
membership: {
Row: {
- id: number
groupId: string
memberGroupId: string | null
memberUserId: string | null
+ id: number
}
Insert: {
- id?: number
groupId: string
memberGroupId?: string | null
memberUserId?: string | null
+ id?: number
}
Update: {
- id?: number
groupId?: string
memberGroupId?: string | null
memberUserId?: string | null
+ id?: number
+ }
+ }
+ supplier: {
+ Row: {
+ name: string
+ description: string | null
+ supplierTypeId: string | null
+ supplierStatusId: number | null
+ taxId: string | null
+ accountManagerId: string | null
+ logo: string | null
+ createdBy: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ id: string
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ description?: string | null
+ supplierTypeId?: string | null
+ supplierStatusId?: number | null
+ taxId?: string | null
+ accountManagerId?: string | null
+ logo?: string | null
+ createdBy?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ id?: string
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ description?: string | null
+ supplierTypeId?: string | null
+ supplierStatusId?: number | null
+ taxId?: string | null
+ accountManagerId?: string | null
+ logo?: string | null
+ createdBy?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ id?: string
+ createdAt?: string
+ }
+ }
+ supplierAccount: {
+ Row: {
+ id: string
+ supplierId: string
+ }
+ Insert: {
+ id: string
+ supplierId: string
+ }
+ Update: {
+ id?: string
+ supplierId?: string
+ }
+ }
+ supplierContact: {
+ Row: {
+ supplierId: string
+ contactId: string
+ supplierLocationId: number | null
+ userId: string | null
+ id: string
+ }
+ Insert: {
+ supplierId: string
+ contactId: string
+ supplierLocationId?: number | null
+ userId?: string | null
+ id?: string
+ }
+ Update: {
+ supplierId?: string
+ contactId?: string
+ supplierLocationId?: number | null
+ userId?: string | null
+ id?: string
+ }
+ }
+ supplierLocation: {
+ Row: {
+ supplierId: string
+ addressId: number
+ id: number
+ }
+ Insert: {
+ supplierId: string
+ addressId: number
+ id?: number
+ }
+ Update: {
+ supplierId?: string
+ addressId?: number
+ id?: number
+ }
+ }
+ supplierStatus: {
+ Row: {
+ name: string
+ updatedAt: string | null
+ id: number
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ updatedAt?: string | null
+ id?: number
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ updatedAt?: string | null
+ id?: number
+ createdAt?: string
+ }
+ }
+ supplierType: {
+ Row: {
+ name: string
+ updatedAt: string | null
+ id: string
+ color: string | null
+ protected: boolean
+ createdAt: string
+ }
+ Insert: {
+ name: string
+ updatedAt?: string | null
+ id?: string
+ color?: string | null
+ protected?: boolean
+ createdAt?: string
+ }
+ Update: {
+ name?: string
+ updatedAt?: string | null
+ id?: string
+ color?: string | null
+ protected?: boolean
+ createdAt?: string
}
}
user: {
@@ -217,123 +628,122 @@ export interface Database {
email: string
firstName: string
lastName: string
+ avatarUrl: string | null
+ emailVerified: string | null
+ updatedAt: string | null
fullName: string | null
about: string
- avatarUrl: string | null
active: boolean | null
- emailVerified: string | null
createdAt: string
- updatedAt: string | null
}
Insert: {
id: string
email: string
firstName: string
lastName: string
+ avatarUrl?: string | null
+ emailVerified?: string | null
+ updatedAt?: string | null
fullName?: string | null
about?: string
- avatarUrl?: string | null
active?: boolean | null
- emailVerified?: string | null
createdAt?: string
- updatedAt?: string | null
}
Update: {
id?: string
email?: string
firstName?: string
lastName?: string
+ avatarUrl?: string | null
+ emailVerified?: string | null
+ updatedAt?: string | null
fullName?: string | null
about?: string
- avatarUrl?: string | null
active?: boolean | null
- emailVerified?: string | null
createdAt?: string
- updatedAt?: string | null
}
}
userAttribute: {
Row: {
- id: number
name: string
- sortOrder: number
userAttributeCategoryId: number
attributeDataTypeId: number
listOptions: string[] | null
- canSelfManage: boolean | null
- active: boolean | null
- createdAt: string
createdBy: string
updatedAt: string | null
updatedBy: string | null
+ id: number
+ sortOrder: number
+ canSelfManage: boolean | null
+ active: boolean | null
+ createdAt: string
}
Insert: {
- id?: number
name: string
- sortOrder?: number
userAttributeCategoryId: number
attributeDataTypeId: number
listOptions?: string[] | null
- canSelfManage?: boolean | null
- active?: boolean | null
- createdAt?: string
createdBy: string
updatedAt?: string | null
updatedBy?: string | null
+ id?: number
+ sortOrder?: number
+ canSelfManage?: boolean | null
+ active?: boolean | null
+ createdAt?: string
}
Update: {
- id?: number
name?: string
- sortOrder?: number
userAttributeCategoryId?: number
attributeDataTypeId?: number
listOptions?: string[] | null
- canSelfManage?: boolean | null
- active?: boolean | null
- createdAt?: string
createdBy?: string
updatedAt?: string | null
updatedBy?: string | null
+ id?: number
+ sortOrder?: number
+ canSelfManage?: boolean | null
+ active?: boolean | null
+ createdAt?: string
}
}
userAttributeCategory: {
Row: {
- id: number
name: string
+ createdBy: string
+ updatedAt: string | null
+ updatedBy: string | null
+ id: number
public: boolean | null
protected: boolean | null
active: boolean | null
createdAt: string
- createdBy: string
- updatedAt: string | null
- updatedBy: string | null
}
Insert: {
- id?: number
name: string
- public?: boolean | null
- protected?: boolean | null
- active?: boolean | null
- createdAt?: string
createdBy: string
updatedAt?: string | null
updatedBy?: string | null
- }
- Update: {
id?: number
- name?: string
public?: boolean | null
protected?: boolean | null
active?: boolean | null
createdAt?: string
+ }
+ Update: {
+ name?: string
createdBy?: string
updatedAt?: string | null
updatedBy?: string | null
+ id?: number
+ public?: boolean | null
+ protected?: boolean | null
+ active?: boolean | null
+ createdAt?: string
}
}
userAttributeValue: {
Row: {
- id: number
userAttributeId: number
userId: string
valueBoolean: boolean | null
@@ -341,13 +751,13 @@ export interface Database {
valueNumeric: number | null
valueText: string | null
valueUser: string | null
- createdAt: string
createdBy: string
updatedAt: string | null
updatedBy: string | null
+ id: number
+ createdAt: string
}
Insert: {
- id?: number
userAttributeId: number
userId: string
valueBoolean?: boolean | null
@@ -355,13 +765,13 @@ export interface Database {
valueNumeric?: number | null
valueText?: string | null
valueUser?: string | null
- createdAt?: string
createdBy: string
updatedAt?: string | null
updatedBy?: string | null
+ id?: number
+ createdAt?: string
}
Update: {
- id?: number
userAttributeId?: number
userId?: string
valueBoolean?: boolean | null
@@ -369,10 +779,11 @@ export interface Database {
valueNumeric?: number | null
valueText?: string | null
valueUser?: string | null
- createdAt?: string
createdBy?: string
updatedAt?: string | null
updatedBy?: string | null
+ id?: number
+ createdAt?: string
}
}
}
@@ -383,6 +794,10 @@ export interface Database {
name: string | null
isIdentityGroup: boolean | null
isEmployeeTypeGroup: boolean | null
+ isCustomerOrgGroup: boolean | null
+ isCustomerTypeGroup: boolean | null
+ isSupplierOrgGroup: boolean | null
+ isSupplierTypeGroup: boolean | null
groupId: string | null
memberGroupId: string | null
memberUserId: string | null
@@ -396,6 +811,10 @@ export interface Database {
parentId: string | null
isIdentityGroup: boolean | null
isEmployeeTypeGroup: boolean | null
+ isCustomerOrgGroup: boolean | null
+ isCustomerTypeGroup: boolean | null
+ isSupplierOrgGroup: boolean | null
+ isSupplierTypeGroup: boolean | null
user: Json | null
}
}
@@ -403,6 +822,10 @@ export interface Database {
Row: {
id: string | null
isEmployeeTypeGroup: boolean | null
+ isCustomerOrgGroup: boolean | null
+ isCustomerTypeGroup: boolean | null
+ isSupplierOrgGroup: boolean | null
+ isSupplierTypeGroup: boolean | null
name: string | null
parentId: string | null
users: Json | null
@@ -441,6 +864,10 @@ export interface Database {
name: string
parentId: string
isEmployeeTypeGroup: boolean
+ isCustomerOrgGroup: boolean
+ isCustomerTypeGroup: boolean
+ isSupplierOrgGroup: boolean
+ isSupplierTypeGroup: boolean
users: Json
}[]
}
diff --git a/packages/carbon-react/src/Inputs/Phone/countries.json b/packages/carbon-react/src/Inputs/Phone/countries.json
new file mode 100644
index 0000000000..994472be45
--- /dev/null
+++ b/packages/carbon-react/src/Inputs/Phone/countries.json
@@ -0,0 +1,473 @@
+[
+ { "name": "Afghanistan", "flag": "🇦🇫", "code": "AF", "dial_code": "+93" },
+ { "name": "Åland Islands", "flag": "🇦🇽", "code": "AX", "dial_code": "+358" },
+ { "name": "Albania", "flag": "🇦🇱", "code": "AL", "dial_code": "+355" },
+ { "name": "Algeria", "flag": "🇩🇿", "code": "DZ", "dial_code": "+213" },
+ {
+ "name": "American Samoa",
+ "flag": "🇦🇸",
+ "code": "AS",
+ "dial_code": "+1684"
+ },
+ { "name": "Andorra", "flag": "🇦🇩", "code": "AD", "dial_code": "+376" },
+ { "name": "Angola", "flag": "🇦🇴", "code": "AO", "dial_code": "+244" },
+ { "name": "Anguilla", "flag": "🇦🇮", "code": "AI", "dial_code": "+1264" },
+ { "name": "Antarctica", "flag": "🇦🇶", "code": "AQ", "dial_code": "+672" },
+ {
+ "name": "Antigua and Barbuda",
+ "flag": "🇦🇬",
+ "code": "AG",
+ "dial_code": "+1268"
+ },
+ { "name": "Argentina", "flag": "🇦🇷", "code": "AR", "dial_code": "+54" },
+ { "name": "Armenia", "flag": "🇦🇲", "code": "AM", "dial_code": "+374" },
+ { "name": "Aruba", "flag": "🇦🇼", "code": "AW", "dial_code": "+297" },
+ { "name": "Australia", "flag": "🇦🇺", "code": "AU", "dial_code": "+61" },
+ { "name": "Austria", "flag": "🇦🇹", "code": "AT", "dial_code": "+43" },
+ { "name": "Azerbaijan", "flag": "🇦🇿", "code": "AZ", "dial_code": "+994" },
+ { "name": "Bahamas", "flag": "🇧🇸", "code": "BS", "dial_code": "+1242" },
+ { "name": "Bahrain", "flag": "🇧🇭", "code": "BH", "dial_code": "+973" },
+ { "name": "Bangladesh", "flag": "🇧🇩", "code": "BD", "dial_code": "+880" },
+ { "name": "Barbados", "flag": "🇧🇧", "code": "BB", "dial_code": "+1246" },
+ { "name": "Belarus", "flag": "🇧🇾", "code": "BY", "dial_code": "+375" },
+ { "name": "Belgium", "flag": "🇧🇪", "code": "BE", "dial_code": "+32" },
+ { "name": "Belize", "flag": "🇧🇿", "code": "BZ", "dial_code": "+501" },
+ { "name": "Benin", "flag": "🇧🇯", "code": "BJ", "dial_code": "+229" },
+ { "name": "Bermuda", "flag": "🇧🇲", "code": "BM", "dial_code": "+1441" },
+ { "name": "Bhutan", "flag": "🇧🇹", "code": "BT", "dial_code": "+975" },
+ {
+ "name": "Bolivia, Plurinational State of bolivia",
+ "flag": "🇧🇴",
+ "code": "BO",
+ "dial_code": "+591"
+ },
+ {
+ "name": "Bosnia and Herzegovina",
+ "flag": "🇧🇦",
+ "code": "BA",
+ "dial_code": "+387"
+ },
+ { "name": "Botswana", "flag": "🇧🇼", "code": "BW", "dial_code": "+267" },
+ { "name": "Bouvet Island", "flag": "🇧🇻", "code": "BV", "dial_code": "+47" },
+ { "name": "Brazil", "flag": "🇧🇷", "code": "BR", "dial_code": "+55" },
+ {
+ "name": "British Indian Ocean Territory",
+ "flag": "🇮🇴",
+ "code": "IO",
+ "dial_code": "+246"
+ },
+ {
+ "name": "Brunei Darussalam",
+ "flag": "🇧🇳",
+ "code": "BN",
+ "dial_code": "+673"
+ },
+ { "name": "Bulgaria", "flag": "🇧🇬", "code": "BG", "dial_code": "+359" },
+ { "name": "Burkina Faso", "flag": "🇧🇫", "code": "BF", "dial_code": "+226" },
+ { "name": "Burundi", "flag": "🇧🇮", "code": "BI", "dial_code": "+257" },
+ { "name": "Cambodia", "flag": "🇰🇭", "code": "KH", "dial_code": "+855" },
+ { "name": "Cameroon", "flag": "🇨🇲", "code": "CM", "dial_code": "+237" },
+ { "name": "Canada", "flag": "🇨🇦", "code": "CA", "dial_code": "+1" },
+ { "name": "Cape Verde", "flag": "🇨🇻", "code": "CV", "dial_code": "+238" },
+ { "name": "Cayman Islands", "flag": "🇰🇾", "code": "KY", "dial_code": "+345" },
+ {
+ "name": "Central African Republic",
+ "flag": "🇨🇫",
+ "code": "CF",
+ "dial_code": "+236"
+ },
+ { "name": "Chad", "flag": "🇹🇩", "code": "TD", "dial_code": "+235" },
+ { "name": "Chile", "flag": "🇨🇱", "code": "CL", "dial_code": "+56" },
+ { "name": "China", "flag": "🇨🇳", "code": "CN", "dial_code": "+86" },
+ {
+ "name": "Christmas Island",
+ "flag": "🇨🇽",
+ "code": "CX",
+ "dial_code": "+61"
+ },
+ {
+ "name": "Cocos (Keeling) Islands",
+ "flag": "🇨🇨",
+ "code": "CC",
+ "dial_code": "+61"
+ },
+ { "name": "Colombia", "flag": "🇨🇴", "code": "CO", "dial_code": "+57" },
+ { "name": "Comoros", "flag": "🇰🇲", "code": "KM", "dial_code": "+269" },
+ { "name": "Congo", "flag": "🇨🇬", "code": "CG", "dial_code": "+242" },
+ {
+ "name": "Congo, The Democratic Republic of the Congo",
+ "flag": "🇨🇩",
+ "code": "CD",
+ "dial_code": "+243"
+ },
+ { "name": "Cook Islands", "flag": "🇨🇰", "code": "CK", "dial_code": "+682" },
+ { "name": "Costa Rica", "flag": "🇨🇷", "code": "CR", "dial_code": "+506" },
+ { "name": "Cote d'Ivoire", "flag": "🇨🇮", "code": "CI", "dial_code": "+225" },
+ { "name": "Croatia", "flag": "🇭🇷", "code": "HR", "dial_code": "+385" },
+ { "name": "Cuba", "flag": "🇨🇺", "code": "CU", "dial_code": "+53" },
+ { "name": "Cyprus", "flag": "🇨🇾", "code": "CY", "dial_code": "+357" },
+ { "name": "Czech Republic", "flag": "🇨🇿", "code": "CZ", "dial_code": "+420" },
+ { "name": "Denmark", "flag": "🇩🇰", "code": "DK", "dial_code": "+45" },
+ { "name": "Djibouti", "flag": "🇩🇯", "code": "DJ", "dial_code": "+253" },
+ { "name": "Dominica", "flag": "🇩🇲", "code": "DM", "dial_code": "+1767" },
+ {
+ "name": "Dominican Republic",
+ "flag": "🇩🇴",
+ "code": "DO",
+ "dial_code": "+1849"
+ },
+ { "name": "Ecuador", "flag": "🇪🇨", "code": "EC", "dial_code": "+593" },
+ { "name": "Egypt", "flag": "🇪🇬", "code": "EG", "dial_code": "+20" },
+ { "name": "El Salvador", "flag": "🇸🇻", "code": "SV", "dial_code": "+503" },
+ {
+ "name": "Equatorial Guinea",
+ "flag": "🇬🇶",
+ "code": "GQ",
+ "dial_code": "+240"
+ },
+ { "name": "Eritrea", "flag": "🇪🇷", "code": "ER", "dial_code": "+291" },
+ { "name": "Estonia", "flag": "🇪🇪", "code": "EE", "dial_code": "+372" },
+ { "name": "Ethiopia", "flag": "🇪🇹", "code": "ET", "dial_code": "+251" },
+ {
+ "name": "Falkland Islands (Malvinas)",
+ "flag": "🇫🇰",
+ "code": "FK",
+ "dial_code": "+500"
+ },
+ { "name": "Faroe Islands", "flag": "🇫🇴", "code": "FO", "dial_code": "+298" },
+ { "name": "Fiji", "flag": "🇫🇯", "code": "FJ", "dial_code": "+679" },
+ { "name": "Finland", "flag": "🇫🇮", "code": "FI", "dial_code": "+358" },
+ { "name": "France", "flag": "🇫🇷", "code": "FR", "dial_code": "+33" },
+ { "name": "French Guiana", "flag": "🇬🇫", "code": "GF", "dial_code": "+594" },
+ {
+ "name": "French Polynesia",
+ "flag": "🇵🇫",
+ "code": "PF",
+ "dial_code": "+689"
+ },
+ {
+ "name": "French Southern Territories",
+ "flag": "🇹🇫",
+ "code": "TF",
+ "dial_code": "+262"
+ },
+ { "name": "Gabon", "flag": "🇬🇦", "code": "GA", "dial_code": "+241" },
+ { "name": "Gambia", "flag": "🇬🇲", "code": "GM", "dial_code": "+220" },
+ { "name": "Georgia", "flag": "🇬🇪", "code": "GE", "dial_code": "+995" },
+ { "name": "Germany", "flag": "🇩🇪", "code": "DE", "dial_code": "+49" },
+ { "name": "Ghana", "flag": "🇬🇭", "code": "GH", "dial_code": "+233" },
+ { "name": "Gibraltar", "flag": "🇬🇮", "code": "GI", "dial_code": "+350" },
+ { "name": "Greece", "flag": "🇬🇷", "code": "GR", "dial_code": "+30" },
+ { "name": "Greenland", "flag": "🇬🇱", "code": "GL", "dial_code": "+299" },
+ { "name": "Grenada", "flag": "🇬🇩", "code": "GD", "dial_code": "+1473" },
+ { "name": "Guadeloupe", "flag": "🇬🇵", "code": "GP", "dial_code": "+590" },
+ { "name": "Guam", "flag": "🇬🇺", "code": "GU", "dial_code": "+1671" },
+ { "name": "Guatemala", "flag": "🇬🇹", "code": "GT", "dial_code": "+502" },
+ { "name": "Guernsey", "flag": "🇬🇬", "code": "GG", "dial_code": "+44" },
+ { "name": "Guinea", "flag": "🇬🇳", "code": "GN", "dial_code": "+224" },
+ { "name": "Guinea-Bissau", "flag": "🇬🇼", "code": "GW", "dial_code": "+245" },
+ { "name": "Guyana", "flag": "🇬🇾", "code": "GY", "dial_code": "+592" },
+ { "name": "Haiti", "flag": "🇭🇹", "code": "HT", "dial_code": "+509" },
+ {
+ "name": "Heard Island and Mcdonald Islands",
+ "flag": "🇭🇲",
+ "code": "HM",
+ "dial_code": "+672"
+ },
+ {
+ "name": "Holy See (Vatican City State)",
+ "flag": "🇻🇦",
+ "code": "VA",
+ "dial_code": "+379"
+ },
+ { "name": "Honduras", "flag": "🇭🇳", "code": "HN", "dial_code": "+504" },
+ { "name": "Hong Kong", "flag": "🇭🇰", "code": "HK", "dial_code": "+852" },
+ { "name": "Hungary", "flag": "🇭🇺", "code": "HU", "dial_code": "+36" },
+ { "name": "Iceland", "flag": "🇮🇸", "code": "IS", "dial_code": "+354" },
+ { "name": "India", "flag": "🇮🇳", "code": "IN", "dial_code": "+91" },
+ { "name": "Indonesia", "flag": "🇮🇩", "code": "ID", "dial_code": "+62" },
+ {
+ "name": "Iran, Islamic Republic of Persian Gulf",
+ "flag": "🇮🇷",
+ "code": "IR",
+ "dial_code": "+98"
+ },
+ { "name": "Iraq", "flag": "🇮🇶", "code": "IQ", "dial_code": "+964" },
+ { "name": "Ireland", "flag": "🇮🇪", "code": "IE", "dial_code": "+353" },
+ { "name": "Isle of Man", "flag": "🇮🇲", "code": "IM", "dial_code": "+44" },
+ { "name": "Israel", "flag": "🇮🇱", "code": "IL", "dial_code": "+972" },
+ { "name": "Italy", "flag": "🇮🇹", "code": "IT", "dial_code": "+39" },
+ { "name": "Jamaica", "flag": "🇯🇲", "code": "JM", "dial_code": "+1876" },
+ { "name": "Japan", "flag": "🇯🇵", "code": "JP", "dial_code": "+81" },
+ { "name": "Jersey", "flag": "🇯🇪", "code": "JE", "dial_code": "+44" },
+ { "name": "Jordan", "flag": "🇯🇴", "code": "JO", "dial_code": "+962" },
+ { "name": "Kazakhstan", "flag": "🇰🇿", "code": "KZ", "dial_code": "+7" },
+ { "name": "Kenya", "flag": "🇰🇪", "code": "KE", "dial_code": "+254" },
+ { "name": "Kiribati", "flag": "🇰🇮", "code": "KI", "dial_code": "+686" },
+ {
+ "name": "Korea, Democratic People's Republic of Korea",
+ "flag": "🇰🇵",
+ "code": "KP",
+ "dial_code": "+850"
+ },
+ {
+ "name": "Korea, Republic of South Korea",
+ "flag": "🇰🇷",
+ "code": "KR",
+ "dial_code": "+82"
+ },
+ { "name": "Kosovo", "flag": "🇽🇰", "code": "XK", "dial_code": "+383" },
+ { "name": "Kuwait", "flag": "🇰🇼", "code": "KW", "dial_code": "+965" },
+ { "name": "Kyrgyzstan", "flag": "🇰🇬", "code": "KG", "dial_code": "+996" },
+ { "name": "Laos", "flag": "🇱🇦", "code": "LA", "dial_code": "+856" },
+ { "name": "Latvia", "flag": "🇱🇻", "code": "LV", "dial_code": "+371" },
+ { "name": "Lebanon", "flag": "🇱🇧", "code": "LB", "dial_code": "+961" },
+ { "name": "Lesotho", "flag": "🇱🇸", "code": "LS", "dial_code": "+266" },
+ { "name": "Liberia", "flag": "🇱🇷", "code": "LR", "dial_code": "+231" },
+ {
+ "name": "Libyan Arab Jamahiriya",
+ "flag": "🇱🇾",
+ "code": "LY",
+ "dial_code": "+218"
+ },
+ { "name": "Liechtenstein", "flag": "🇱🇮", "code": "LI", "dial_code": "+423" },
+ { "name": "Lithuania", "flag": "🇱🇹", "code": "LT", "dial_code": "+370" },
+ { "name": "Luxembourg", "flag": "🇱🇺", "code": "LU", "dial_code": "+352" },
+ { "name": "Macao", "flag": "🇲🇴", "code": "MO", "dial_code": "+853" },
+ { "name": "Macedonia", "flag": "🇲🇰", "code": "MK", "dial_code": "+389" },
+ { "name": "Madagascar", "flag": "🇲🇬", "code": "MG", "dial_code": "+261" },
+ { "name": "Malawi", "flag": "🇲🇼", "code": "MW", "dial_code": "+265" },
+ { "name": "Malaysia", "flag": "🇲🇾", "code": "MY", "dial_code": "+60" },
+ { "name": "Maldives", "flag": "🇲🇻", "code": "MV", "dial_code": "+960" },
+ { "name": "Mali", "flag": "🇲🇱", "code": "ML", "dial_code": "+223" },
+ { "name": "Malta", "flag": "🇲🇹", "code": "MT", "dial_code": "+356" },
+ {
+ "name": "Marshall Islands",
+ "flag": "🇲🇭",
+ "code": "MH",
+ "dial_code": "+692"
+ },
+ { "name": "Martinique", "flag": "🇲🇶", "code": "MQ", "dial_code": "+596" },
+ { "name": "Mauritania", "flag": "🇲🇷", "code": "MR", "dial_code": "+222" },
+ { "name": "Mauritius", "flag": "🇲🇺", "code": "MU", "dial_code": "+230" },
+ { "name": "Mayotte", "flag": "🇾🇹", "code": "YT", "dial_code": "+262" },
+ { "name": "Mexico", "flag": "🇲🇽", "code": "MX", "dial_code": "+52" },
+ {
+ "name": "Micronesia, Federated States of Micronesia",
+ "flag": "🇫🇲",
+ "code": "FM",
+ "dial_code": "+691"
+ },
+ { "name": "Moldova", "flag": "🇲🇩", "code": "MD", "dial_code": "+373" },
+ { "name": "Monaco", "flag": "🇲🇨", "code": "MC", "dial_code": "+377" },
+ { "name": "Mongolia", "flag": "🇲🇳", "code": "MN", "dial_code": "+976" },
+ { "name": "Montenegro", "flag": "🇲🇪", "code": "ME", "dial_code": "+382" },
+ { "name": "Montserrat", "flag": "🇲🇸", "code": "MS", "dial_code": "+1664" },
+ { "name": "Morocco", "flag": "🇲🇦", "code": "MA", "dial_code": "+212" },
+ { "name": "Mozambique", "flag": "🇲🇿", "code": "MZ", "dial_code": "+258" },
+ { "name": "Myanmar", "flag": "🇲🇲", "code": "MM", "dial_code": "+95" },
+ { "name": "Namibia", "flag": "🇳🇦", "code": "NA", "dial_code": "+264" },
+ { "name": "Nauru", "flag": "🇳🇷", "code": "NR", "dial_code": "+674" },
+ { "name": "Nepal", "flag": "🇳🇵", "code": "NP", "dial_code": "+977" },
+ { "name": "Netherlands", "flag": "🇳🇱", "code": "NL", "dial_code": "+31" },
+ {
+ "name": "Netherlands Antilles",
+ "flag": "",
+ "code": "AN",
+ "dial_code": "+599"
+ },
+ { "name": "New Caledonia", "flag": "🇳🇨", "code": "NC", "dial_code": "+687" },
+ { "name": "New Zealand", "flag": "🇳🇿", "code": "NZ", "dial_code": "+64" },
+ { "name": "Nicaragua", "flag": "🇳🇮", "code": "NI", "dial_code": "+505" },
+ { "name": "Niger", "flag": "🇳🇪", "code": "NE", "dial_code": "+227" },
+ { "name": "Nigeria", "flag": "🇳🇬", "code": "NG", "dial_code": "+234" },
+ { "name": "Niue", "flag": "🇳🇺", "code": "NU", "dial_code": "+683" },
+ { "name": "Norfolk Island", "flag": "🇳🇫", "code": "NF", "dial_code": "+672" },
+ {
+ "name": "Northern Mariana Islands",
+ "flag": "🇲🇵",
+ "code": "MP",
+ "dial_code": "+1670"
+ },
+ { "name": "Norway", "flag": "🇳🇴", "code": "NO", "dial_code": "+47" },
+ { "name": "Oman", "flag": "🇴🇲", "code": "OM", "dial_code": "+968" },
+ { "name": "Pakistan", "flag": "🇵🇰", "code": "PK", "dial_code": "+92" },
+ { "name": "Palau", "flag": "🇵🇼", "code": "PW", "dial_code": "+680" },
+ {
+ "name": "Palestinian Territory, Occupied",
+ "flag": "🇵🇸",
+ "code": "PS",
+ "dial_code": "+970"
+ },
+ { "name": "Panama", "flag": "🇵🇦", "code": "PA", "dial_code": "+507" },
+ {
+ "name": "Papua New Guinea",
+ "flag": "🇵🇬",
+ "code": "PG",
+ "dial_code": "+675"
+ },
+ { "name": "Paraguay", "flag": "🇵🇾", "code": "PY", "dial_code": "+595" },
+ { "name": "Peru", "flag": "🇵🇪", "code": "PE", "dial_code": "+51" },
+ { "name": "Philippines", "flag": "🇵🇭", "code": "PH", "dial_code": "+63" },
+ { "name": "Pitcairn", "flag": "🇵🇳", "code": "PN", "dial_code": "+64" },
+ { "name": "Poland", "flag": "🇵🇱", "code": "PL", "dial_code": "+48" },
+ { "name": "Portugal", "flag": "🇵🇹", "code": "PT", "dial_code": "+351" },
+ { "name": "Puerto Rico", "flag": "🇵🇷", "code": "PR", "dial_code": "+1939" },
+ { "name": "Qatar", "flag": "🇶🇦", "code": "QA", "dial_code": "+974" },
+ { "name": "Romania", "flag": "🇷🇴", "code": "RO", "dial_code": "+40" },
+ { "name": "Russia", "flag": "🇷🇺", "code": "RU", "dial_code": "+7" },
+ { "name": "Rwanda", "flag": "🇷🇼", "code": "RW", "dial_code": "+250" },
+ { "name": "Reunion", "flag": "🇷🇪", "code": "RE", "dial_code": "+262" },
+ {
+ "name": "Saint Barthelemy",
+ "flag": "🇧🇱",
+ "code": "BL",
+ "dial_code": "+590"
+ },
+ {
+ "name": "Saint Helena, Ascension and Tristan Da Cunha",
+ "flag": "🇸🇭",
+ "code": "SH",
+ "dial_code": "+290"
+ },
+ {
+ "name": "Saint Kitts and Nevis",
+ "flag": "🇰🇳",
+ "code": "KN",
+ "dial_code": "+1869"
+ },
+ { "name": "Saint Lucia", "flag": "🇱🇨", "code": "LC", "dial_code": "+1758" },
+ { "name": "Saint Martin", "flag": "🇲🇫", "code": "MF", "dial_code": "+590" },
+ {
+ "name": "Saint Pierre and Miquelon",
+ "flag": "🇵🇲",
+ "code": "PM",
+ "dial_code": "+508"
+ },
+ {
+ "name": "Saint Vincent and the Grenadines",
+ "flag": "🇻🇨",
+ "code": "VC",
+ "dial_code": "+1784"
+ },
+ { "name": "Samoa", "flag": "🇼🇸", "code": "WS", "dial_code": "+685" },
+ { "name": "San Marino", "flag": "🇸🇲", "code": "SM", "dial_code": "+378" },
+ {
+ "name": "Sao Tome and Principe",
+ "flag": "🇸🇹",
+ "code": "ST",
+ "dial_code": "+239"
+ },
+ { "name": "Saudi Arabia", "flag": "🇸🇦", "code": "SA", "dial_code": "+966" },
+ { "name": "Senegal", "flag": "🇸🇳", "code": "SN", "dial_code": "+221" },
+ { "name": "Serbia", "flag": "🇷🇸", "code": "RS", "dial_code": "+381" },
+ { "name": "Seychelles", "flag": "🇸🇨", "code": "SC", "dial_code": "+248" },
+ { "name": "Sierra Leone", "flag": "🇸🇱", "code": "SL", "dial_code": "+232" },
+ { "name": "Singapore", "flag": "🇸🇬", "code": "SG", "dial_code": "+65" },
+ { "name": "Slovakia", "flag": "🇸🇰", "code": "SK", "dial_code": "+421" },
+ { "name": "Slovenia", "flag": "🇸🇮", "code": "SI", "dial_code": "+386" },
+ {
+ "name": "Solomon Islands",
+ "flag": "🇸🇧",
+ "code": "SB",
+ "dial_code": "+677"
+ },
+ { "name": "Somalia", "flag": "🇸🇴", "code": "SO", "dial_code": "+252" },
+ { "name": "South Africa", "flag": "🇿🇦", "code": "ZA", "dial_code": "+27" },
+ { "name": "South Sudan", "flag": "🇸🇸", "code": "SS", "dial_code": "+211" },
+ {
+ "name": "South Georgia and the South Sandwich Islands",
+ "flag": "🇬🇸",
+ "code": "GS",
+ "dial_code": "+500"
+ },
+ { "name": "Spain", "flag": "🇪🇸", "code": "ES", "dial_code": "+34" },
+ { "name": "Sri Lanka", "flag": "🇱🇰", "code": "LK", "dial_code": "+94" },
+ { "name": "Sudan", "flag": "🇸🇩", "code": "SD", "dial_code": "+249" },
+ { "name": "Suriname", "flag": "🇸🇷", "code": "SR", "dial_code": "+597" },
+ {
+ "name": "Svalbard and Jan Mayen",
+ "flag": "🇸🇯",
+ "code": "SJ",
+ "dial_code": "+47"
+ },
+ { "name": "Swaziland", "flag": "🇸🇿", "code": "SZ", "dial_code": "+268" },
+ { "name": "Sweden", "flag": "🇸🇪", "code": "SE", "dial_code": "+46" },
+ { "name": "Switzerland", "flag": "🇨🇭", "code": "CH", "dial_code": "+41" },
+ {
+ "name": "Syrian Arab Republic",
+ "flag": "🇸🇾",
+ "code": "SY",
+ "dial_code": "+963"
+ },
+ { "name": "Taiwan", "flag": "🇹🇼", "code": "TW", "dial_code": "+886" },
+ { "name": "Tajikistan", "flag": "🇹🇯", "code": "TJ", "dial_code": "+992" },
+ {
+ "name": "Tanzania, United Republic of Tanzania",
+ "flag": "🇹🇿",
+ "code": "TZ",
+ "dial_code": "+255"
+ },
+ { "name": "Thailand", "flag": "🇹🇭", "code": "TH", "dial_code": "+66" },
+ { "name": "Timor-Leste", "flag": "🇹🇱", "code": "TL", "dial_code": "+670" },
+ { "name": "Togo", "flag": "🇹🇬", "code": "TG", "dial_code": "+228" },
+ { "name": "Tokelau", "flag": "🇹🇰", "code": "TK", "dial_code": "+690" },
+ { "name": "Tonga", "flag": "🇹🇴", "code": "TO", "dial_code": "+676" },
+ {
+ "name": "Trinidad and Tobago",
+ "flag": "🇹🇹",
+ "code": "TT",
+ "dial_code": "+1868"
+ },
+ { "name": "Tunisia", "flag": "🇹🇳", "code": "TN", "dial_code": "+216" },
+ { "name": "Turkey", "flag": "🇹🇷", "code": "TR", "dial_code": "+90" },
+ { "name": "Turkmenistan", "flag": "🇹🇲", "code": "TM", "dial_code": "+993" },
+ {
+ "name": "Turks and Caicos Islands",
+ "flag": "🇹🇨",
+ "code": "TC",
+ "dial_code": "+1649"
+ },
+ { "name": "Tuvalu", "flag": "🇹🇻", "code": "TV", "dial_code": "+688" },
+ { "name": "Uganda", "flag": "🇺🇬", "code": "UG", "dial_code": "+256" },
+ { "name": "Ukraine", "flag": "🇺🇦", "code": "UA", "dial_code": "+380" },
+ {
+ "name": "United Arab Emirates",
+ "flag": "🇦🇪",
+ "code": "AE",
+ "dial_code": "+971"
+ },
+ { "name": "United Kingdom", "flag": "🇬🇧", "code": "GB", "dial_code": "+44" },
+ { "name": "United States", "flag": "🇺🇸", "code": "US", "dial_code": "+1" },
+ { "name": "Uruguay", "flag": "🇺🇾", "code": "UY", "dial_code": "+598" },
+ { "name": "Uzbekistan", "flag": "🇺🇿", "code": "UZ", "dial_code": "+998" },
+ { "name": "Vanuatu", "flag": "🇻🇺", "code": "VU", "dial_code": "+678" },
+ {
+ "name": "Venezuela, Bolivarian Republic of Venezuela",
+ "flag": "🇻🇪",
+ "code": "VE",
+ "dial_code": "+58"
+ },
+ { "name": "Vietnam", "flag": "🇻🇳", "code": "VN", "dial_code": "+84" },
+ {
+ "name": "Virgin Islands, British",
+ "flag": "🇻🇬",
+ "code": "VG",
+ "dial_code": "+1284"
+ },
+ {
+ "name": "Virgin Islands, U.S.",
+ "flag": "🇻🇮",
+ "code": "VI",
+ "dial_code": "+1340"
+ },
+ {
+ "name": "Wallis and Futuna",
+ "flag": "🇼🇫",
+ "code": "WF",
+ "dial_code": "+681"
+ },
+ { "name": "Yemen", "flag": "🇾🇪", "code": "YE", "dial_code": "+967" },
+ { "name": "Zambia", "flag": "🇿🇲", "code": "ZM", "dial_code": "+260" },
+ { "name": "Zimbabwe", "flag": "🇿🇼", "code": "ZW", "dial_code": "+263" }
+]
diff --git a/packages/carbon-react/src/Inputs/Select/components/containers.tsx b/packages/carbon-react/src/Inputs/Select/components/containers.tsx
index 7c47f10a79..1f979a3173 100644
--- a/packages/carbon-react/src/Inputs/Select/components/containers.tsx
+++ b/packages/carbon-react/src/Inputs/Select/components/containers.tsx
@@ -22,7 +22,7 @@ export const SelectContainer = <
isDisabled,
isRtl,
hasValue,
- selectProps: { chakraStyles, borderRadius, maxW, minW },
+ selectProps: { chakraStyles, borderRadius, maxW, minW, w },
} = props;
const initialSx: SystemStyleObject = {
@@ -49,6 +49,7 @@ export const SelectContainer = <
borderRadius={borderRadius}
maxW={maxW}
minW={minW}
+ w={w}
sx={sx}
>
{children}
diff --git a/packages/carbon-react/src/Inputs/Select/index.ts b/packages/carbon-react/src/Inputs/Select/index.ts
index adb0c5acb7..8168a57c5c 100644
--- a/packages/carbon-react/src/Inputs/Select/index.ts
+++ b/packages/carbon-react/src/Inputs/Select/index.ts
@@ -1,3 +1,5 @@
import Select from "./Select";
+import { createFilter } from "react-select";
export default Select;
+export { createFilter };
diff --git a/packages/carbon-react/src/Inputs/Select/react.select.d.ts b/packages/carbon-react/src/Inputs/Select/react.select.d.ts
index 93adc6d2ee..eb6f01e38e 100644
--- a/packages/carbon-react/src/Inputs/Select/react.select.d.ts
+++ b/packages/carbon-react/src/Inputs/Select/react.select.d.ts
@@ -167,12 +167,22 @@ declare module "react-select/dist/declarations/src/Select" {
* If passed, the select will have a max width
* `Select` component
*
- * @defaultValue `full`
+ * @defaultValue undefined
* @see {@link https://github.com/csandman/chakra-react-select#usebasicstyles--default-false}
* @see {@link https://chakra-ui.com/docs/components/select}
*/
maxW?: string | number;
+ /**
+ * If passed, the select will have a max width
+ * `Select` component
+ *
+ * @defaultValue `full`
+ * @see {@link https://github.com/csandman/chakra-react-select#usebasicstyles--default-false}
+ * @see {@link https://chakra-ui.com/docs/components/select}
+ */
+ w?: string | number;
+
/**
* If passed, the select will have a max width
* `Select` component
diff --git a/packages/carbon-react/src/Inputs/Select/useSelect.ts b/packages/carbon-react/src/Inputs/Select/useSelect.ts
index 68f93a241e..5779496d32 100644
--- a/packages/carbon-react/src/Inputs/Select/useSelect.ts
+++ b/packages/carbon-react/src/Inputs/Select/useSelect.ts
@@ -20,6 +20,7 @@ const useSelect = <
isReadOnly,
isRequired,
inputId,
+ w,
maxW = "full",
minW,
tagVariant,
@@ -115,6 +116,7 @@ const useSelect = <
errorBorderColor,
minW,
maxW,
+ w,
// Extract custom props from form control
onFocus: inputProps.onFocus,
onBlur: inputProps.onBlur,
diff --git a/packages/carbon-react/src/Inputs/index.ts b/packages/carbon-react/src/Inputs/index.ts
index 783f116581..73002ee3b0 100644
--- a/packages/carbon-react/src/Inputs/index.ts
+++ b/packages/carbon-react/src/Inputs/index.ts
@@ -5,8 +5,15 @@ import {
DateRangePicker,
TimePicker,
} from "./Date";
-import Select from "./Select";
+import Select, { createFilter } from "./Select";
import type { OptionBase } from "./Select/types";
export type { OptionBase, OptionProps, GroupBase };
-export { DatePicker, DateTimePicker, DateRangePicker, TimePicker, Select };
+export {
+ DatePicker,
+ DateTimePicker,
+ DateRangePicker,
+ TimePicker,
+ Select,
+ createFilter,
+};
diff --git a/packages/carbon-react/src/Theme/theme.ts b/packages/carbon-react/src/Theme/theme.ts
index 4ab6f275af..a626cc19e9 100644
--- a/packages/carbon-react/src/Theme/theme.ts
+++ b/packages/carbon-react/src/Theme/theme.ts
@@ -17,9 +17,7 @@ export const theme = {
components: {
Button: {
baseStyle: {},
- // styles for different sizes ("sm", "md", "lg")
sizes: {},
- // styles for different visual variants ("outline", "solid")
variants: {
solid: (props: { colorScheme: string }) => {
const { colorScheme: c } = props;
@@ -49,6 +47,19 @@ export const theme = {
colorScheme: "blackAlpha",
},
},
+ Drawer: {
+ baseStyle: {
+ overlay: {
+ backdropFilter: "blur(3px)",
+ },
+ footer: {
+ borderColor: "gray.200",
+ borderTopWidth: "1px",
+ borderTopStyle: "solid",
+ },
+ },
+ defaultProps: {},
+ },
Input: {
defaultProps: {
borderRadius: "md",
@@ -59,6 +70,13 @@ export const theme = {
flushed: focusRingFlushed,
},
},
+ Modal: {
+ baseStyle: {
+ overlay: {
+ backdropFilter: "blur(3px)",
+ },
+ },
+ },
Radio: {
defaultProps: {
colorScheme: "blackAlpha",
@@ -79,7 +97,7 @@ export const theme = {
colorScheme: "green",
},
},
- TextArea: {
+ Textarea: {
variants: {
outline: () => focusRingOutlined().field,
filled: () => focusRingFilled().field,
diff --git a/packages/carbon-react/src/hooks/index.ts b/packages/carbon-react/src/hooks/index.ts
index c48acca52a..346cfc979b 100644
--- a/packages/carbon-react/src/hooks/index.ts
+++ b/packages/carbon-react/src/hooks/index.ts
@@ -4,6 +4,7 @@ import useEscape from "./useEscape";
import useHydrated from "./useHydrated";
import useInterval from "./useInterval";
import useKeyboardShortcuts from "./useKeyboardShortcuts";
+import useLocalStorage from "./useLocalStorage";
export {
useColor,
@@ -12,4 +13,5 @@ export {
useHydrated,
useInterval,
useKeyboardShortcuts,
+ useLocalStorage,
};
diff --git a/packages/carbon-react/src/hooks/useLocalStorage.ts b/packages/carbon-react/src/hooks/useLocalStorage.ts
new file mode 100644
index 0000000000..ba6e8c55f1
--- /dev/null
+++ b/packages/carbon-react/src/hooks/useLocalStorage.ts
@@ -0,0 +1,26 @@
+import { useEffect, useState } from "react";
+
+const useLocalStorage = <T>(
+ key: string,
+ initialValue: T
+): [T, (value: T) => void] => {
+ const [storedValue, setStoredValue] = useState(initialValue);
+
+ useEffect(() => {
+ // Retrieve from localStorage
+ const item = window.localStorage.getItem(key);
+ if (item) {
+ setStoredValue(JSON.parse(item));
+ }
+ }, [key]);
+
+ const setValue = (value: T) => {
+ // Save state
+ setStoredValue(value);
+ // Save to localStorage
+ window.localStorage.setItem(key, JSON.stringify(value));
+ };
+ return [storedValue, setValue];
+};
+
+export default useLocalStorage;
diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsx
index f1cf455f04..f69c89eff9 100644
--- a/packages/carbon-react/src/index.tsx
+++ b/packages/carbon-react/src/index.tsx
@@ -5,6 +5,7 @@ import {
DateRangePicker,
TimePicker,
Select,
+ createFilter,
} from "./Inputs";
import Loading from "./Loading";
import { ActionMenu } from "./Overlay";
@@ -32,6 +33,7 @@ export {
Select,
ThemeProvider,
TimePicker,
+ createFilter,
theme,
useColor,
useDebounce,
diff --git a/packages/carbon-react/tsconfig.json b/packages/carbon-react/tsconfig.json
index 0cb23a4674..c101e0fe04 100644
--- a/packages/carbon-react/tsconfig.json
+++ b/packages/carbon-react/tsconfig.json
@@ -1,6 +1,7 @@
{
"compilerOptions": {
- "lib": ["dom", "ES2015"]
+ "lib": ["dom", "ES2015"],
+ "resolveJsonModule": true
},
"extends": "@carbon/tsconfig/react-library.json",
"include": ["src"],
diff --git a/packages/carbon-redis/src/client.ts b/packages/carbon-redis/src/client.ts
index 235212d45e..7376a01fe2 100644
--- a/packages/carbon-redis/src/client.ts
+++ b/packages/carbon-redis/src/client.ts
@@ -1,6 +1,9 @@
+import Logger from "@carbon/logger";
import type { Redis as RedisType, RedisOptions } from "ioredis";
import Redis from "ioredis";
+const logger = Logger.create("redis");
+
const config: RedisOptions = {
enableReadyCheck: false,
maxRetriesPerRequest: null,
@@ -29,4 +32,8 @@ if (process.env.NODE_ENV === "production") {
redis = global.__redis;
}
+redis.on("error", function (e) {
+ logger.error(e);
+});
+
export default redis;
diff --git a/packages/carbon-redis/tsconfig.json b/packages/carbon-redis/tsconfig.json
index 60537146a3..bcf2726028 100644
--- a/packages/carbon-redis/tsconfig.json
+++ b/packages/carbon-redis/tsconfig.json
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"lib": ["ES2015"],
- "module": "CommonJS",
+ "module": "ESNext",
"outDir": "./dist",
"rootDir": "./src"
},
diff --git a/yarn.lock b/yarn.lock
index 2b9ffd2f37..b88f25dfb2 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1016,7 +1016,7 @@
core-js-pure "^3.25.1"
regenerator-runtime "^0.13.4"
-"@babel/runtime@^7.0.0", "@babel/runtime@^7.10.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.12.13", "@babel/runtime@^7.12.5", "@babel/runtime@^7.16.3", "@babel/runtime@^7.18.3", "@babel/runtime@^7.18.9", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7":
+"@babel/runtime@^7.0.0", "@babel/runtime@^7.10.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.12.13", "@babel/runtime@^7.12.5", "@babel/runtime@^7.16.3", "@babel/runtime@^7.18.3", "@babel/runtime@^7.18.9", "@babel/runtime@^7.5.5", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7":
version "7.19.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.19.4.tgz#a42f814502ee467d55b38dd1c256f53a7b885c78"
integrity sha512-EXpLCrk55f+cYqmHsSR+yD/0gAIMxxA9QK9lnQWzhMCvt+YmoBN7Zx94s++Kv0+unHk39vxNO8t+CMA2WSS3wA==
@@ -2016,6 +2016,11 @@
escape-string-regexp "^4.0.0"
rollup-plugin-node-polyfills "^0.2.1"
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.16.3.tgz#6af6d16be6d534d776a51fc215bfd81a68906d2c"
+ integrity sha512-RolFVeinkeraDvN/OoRf1F/lP0KUfGNb5jxy/vkIMeRRChkrX/HTYN6TYZosRJs3a1+8wqpxAo5PI5hFmxyPRg==
+
"@esbuild/[email protected]":
version "0.15.12"
resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.15.12.tgz#e548b10a5e55b9e10537a049ebf0bc72c453b769"
@@ -2026,6 +2031,51 @@
resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.15.15.tgz#35b3cc0f9e69cb53932d44f60b99dd440335d2f0"
integrity sha512-JJjZjJi2eBL01QJuWjfCdZxcIgot+VoK6Fq7eKF9w4YHm9hwl7nhBR1o2Wnt/WcANk5l9SkpvrldW1PLuXxcbw==
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.16.3.tgz#2a091222f3b1928e3246fb3c5202eaca88baab67"
+ integrity sha512-mueuEoh+s1eRbSJqq9KNBQwI4QhQV6sRXIfTyLXSHGMpyew61rOK4qY21uKbXl1iBoMb0AdL1deWFCQVlN2qHA==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.16.3.tgz#a6d749c58b022d371dc40d50ac1bb4aebd1eb953"
+ integrity sha512-SFpTUcIT1bIJuCCBMCQWq1bL2gPTjWoLZdjmIhjdcQHaUfV41OQfho6Ici5uvvkMmZRXIUGpM3GxysP/EU7ifQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.16.3.tgz#92d1826ed2f21dcac5830b70d7215c6afbb744e2"
+ integrity sha512-DO8WykMyB+N9mIDfI/Hug70Dk1KipavlGAecxS3jDUwAbTpDXj0Lcwzw9svkhxfpCagDmpaTMgxWK8/C/XcXvw==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.16.3.tgz#7fc3570c2b16e9ff4fc178593a0a4adb1ae8ea57"
+ integrity sha512-uEqZQ2omc6BvWqdCiyZ5+XmxuHEi1SPzpVxXCSSV2+Sh7sbXbpeNhHIeFrIpRjAs0lI1FmA1iIOxFozKBhKgRQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.16.3.tgz#16735ce16f8c9a4e7289e9e259aa01a8d9874307"
+ integrity sha512-nJansp3sSXakNkOD5i5mIz2Is/HjzIhFs49b1tjrPrpCmwgBmH9SSzhC/Z1UqlkivqMYkhfPwMw1dGFUuwmXhw==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.16.3.tgz#f4edd1464cb072799ed6b8ab5178478e71c13459"
+ integrity sha512-TfoDzLw+QHfc4a8aKtGSQ96Wa+6eimljjkq9HKR0rHlU83vw8aldMOUSJTUDxbcUdcgnJzPaX8/vGWm7vyV7ug==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.16.3.tgz#4b7ae6fe3618d9a40d6ca39c6edc991ac1447203"
+ integrity sha512-7I3RlsnxEFCHVZNBLb2w7unamgZ5sVwO0/ikE2GaYvYuUQs9Qte/w7TqWcXHtCwxvZx/2+F97ndiUQAWs47ZfQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.16.3.tgz#4b3e9f849822e16a76a70844c4db68075b259a58"
+ integrity sha512-VwswmSYwVAAq6LysV59Fyqk3UIjbhuc6wb3vEcJ7HEJUtFuLK9uXWuFoH1lulEbE4+5GjtHi3MHX+w1gNHdOWQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.16.3.tgz#2ff3936b91bfff62f9ecf7f6411ef399b29ed22d"
+ integrity sha512-X8FDDxM9cqda2rJE+iblQhIMYY49LfvW4kaEjoFbTTQ4Go8G96Smj2w3BRTwA8IHGoi9dPOPGAX63dhuv19UqA==
+
"@esbuild/[email protected]":
version "0.15.12"
resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.15.12.tgz#475b33a2631a3d8ca8aa95ee127f9a61d95bf9c1"
@@ -2036,6 +2086,66 @@
resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.15.15.tgz#32c65517a09320b62530867345222fde7794fbe1"
integrity sha512-lhz6UNPMDXUhtXSulw8XlFAtSYO26WmHQnCi2Lg2p+/TMiJKNLtZCYUxV4wG6rZMzXmr8InGpNwk+DLT2Hm0PA==
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.16.3.tgz#ff8aa59f49d9ccbc1ff952ba1f5cd01a534562df"
+ integrity sha512-hIbeejCOyO0X9ujfIIOKjBjNAs9XD/YdJ9JXAy1lHA+8UXuOqbFe4ErMCqMr8dhlMGBuvcQYGF7+kO7waj2KHw==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.16.3.tgz#5dd5e118071c3912df69beedbfd11fb117f0fe5e"
+ integrity sha512-znFRzICT/V8VZQMt6rjb21MtAVJv/3dmKRMlohlShrbVXdBuOdDrGb+C2cZGQAR8RFyRe7HS6klmHq103WpmVw==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.16.3.tgz#36c62e24eae7fa3f0d921506da8fc1e6098a1364"
+ integrity sha512-EV7LuEybxhXrVTDpbqWF2yehYRNz5e5p+u3oQUS2+ZFpknyi1NXxr8URk4ykR8Efm7iu04//4sBg249yNOwy5Q==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.16.3.tgz#f0fec8e7affb5bcc817fefc61a21cbb95539e393"
+ integrity sha512-uDxqFOcLzFIJ+r/pkTTSE9lsCEaV/Y6rMlQjUI9BkzASEChYL/aSQjZjchtEmdnVxDKETnUAmsaZ4pqK1eE5BQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.16.3.tgz#22e10edd6e91f53c2e1f60e46abd453d7794409b"
+ integrity sha512-NbeREhzSxYwFhnCAQOQZmajsPYtX71Ufej3IQ8W2Gxskfz9DK58ENEju4SbpIj48VenktRASC52N5Fhyf/aliQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.16.3.tgz#38388b73fd9eebe45b073d7d8099b9c2e54f7139"
+ integrity sha512-SDiG0nCixYO9JgpehoKgScwic7vXXndfasjnD5DLbp1xltANzqZ425l7LSdHynt19UWOcDjG9wJJzSElsPvk0w==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.16.3.tgz#e0270569567f1530b8dbe6d11d5b4930b9cc71ae"
+ integrity sha512-AzbsJqiHEq1I/tUvOfAzCY15h4/7Ivp3ff/o1GpP16n48JMNAtbW0qui2WCgoIZArEHD0SUQ95gvR0oSO7ZbdA==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.16.3.tgz#3b16642d443848bca605f33ee3978a1890911e6d"
+ integrity sha512-gSABi8qHl8k3Cbi/4toAzHiykuBuWLZs43JomTcXkjMZVkp0gj3gg9mO+9HJW/8GB5H89RX/V0QP4JGL7YEEVg==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.16.3.tgz#a838f247867380f0ae25ce1936dc5ab6f57b7734"
+ integrity sha512-SF9Kch5Ete4reovvRO6yNjMxrvlfT0F0Flm+NPoUw5Z4Q3r1d23LFTgaLwm3Cp0iGbrU/MoUI+ZqwCv5XJijCw==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.16.3.tgz#bedd9bef5fb41f89ce2599f1761973cf6d6a67b6"
+ integrity sha512-u5aBonZIyGopAZyOnoPAA6fGsDeHByZ9CnEzyML9NqntK6D/xl5jteZUKm/p6nD09+v3pTM6TuUIqSPcChk5gg==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.16.3.tgz#49800aa812d8cc35ceef61e8d3b01224684cc0b1"
+ integrity sha512-GlgVq1WpvOEhNioh74TKelwla9KDuAaLZrdxuuUgsP2vayxeLgVc+rbpIv0IYF4+tlIzq2vRhofV+KGLD+37EQ==
+
+"@esbuild/[email protected]":
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.16.3.tgz#94047dae921949cfb308117d993c4b941291ae10"
+ integrity sha512-5/JuTd8OWW8UzEtyf19fbrtMJENza+C9JoPIkvItgTBQ1FO2ZLvjbPO6Xs54vk0s5JB5QsfieUEshRQfu7ZHow==
+
"@eslint/eslintrc@^0.4.3":
version "0.4.3"
resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c"
@@ -2883,10 +2993,10 @@
classcat "^5.0.3"
zustand "^4.1.1"
-"@remix-run/dev@^1.8.2":
- version "1.8.2"
- resolved "https://registry.yarnpkg.com/@remix-run/dev/-/dev-1.8.2.tgz#449c282906493e43ef96a9498416110a8738aedc"
- integrity sha512-hhLOsILCuo8qBqmbc4Aw1Rps+d8VkuxcwEO04ZQPbz3zGVILvuJQ07O02deWfbF/oK71e0OysU/4CpP1wcXxJA==
+"@remix-run/dev@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/dev/-/dev-1.10.1.tgz#1a896ec9bad7943618be5ca1e52da8eec9330664"
+ integrity sha512-cdAseA/b7T+pIaj8M6LEdDL35uD8OysElz36KS5bCaZpLjr7ID2Za4EBDA4weakoaDb1dpQX/MV3tOZ7LKvJqQ==
dependencies:
"@babel/core" "^7.18.6"
"@babel/plugin-syntax-jsx" "^7.18.6"
@@ -2896,13 +3006,13 @@
"@babel/types" "^7.20.2"
"@esbuild-plugins/node-modules-polyfill" "^0.1.4"
"@npmcli/package-json" "^2.0.0"
- "@remix-run/server-runtime" "1.8.2"
+ "@remix-run/server-runtime" "1.10.1"
arg "^5.0.1"
cacache "^15.0.5"
chalk "^4.1.2"
chokidar "^3.5.1"
dotenv "^16.0.0"
- esbuild "0.15.12"
+ esbuild "0.16.3"
execa "5.1.1"
exit-hook "2.2.1"
express "^4.17.1"
@@ -2932,10 +3042,10 @@
ws "^7.4.5"
xdm "^2.0.0"
-"@remix-run/eslint-config@^1.9.0":
- version "1.9.0"
- resolved "https://registry.yarnpkg.com/@remix-run/eslint-config/-/eslint-config-1.9.0.tgz#9a7e35c61f703165657dd3126bc1cb2424989fc6"
- integrity sha512-SPEY+FqvYrlpqYpvPPKd/2dlKzd9Vlxa2HkvKqIHtaiBFUGX9GWnKRro6b5KQ6IU0K5wupCJXG4/bw1CYd8pFg==
+"@remix-run/eslint-config@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/eslint-config/-/eslint-config-1.10.1.tgz#65d153d8848e70daf736cc00d8407d5939654078"
+ integrity sha512-+yLiYkW/yCH1yau6q/R3JBPYBuf3sQ5UIAc2oPrIVw5DDZ46WciLGzVOGOMh+kTgJGjVhpRvINZfTaksJ72GAw==
dependencies:
"@babel/core" "^7.19.1"
"@babel/eslint-parser" "^7.19.1"
@@ -2954,19 +3064,19 @@
eslint-plugin-react-hooks "^4.6.0"
eslint-plugin-testing-library "^5.6.4"
-"@remix-run/[email protected]":
- version "1.8.2"
- resolved "https://registry.yarnpkg.com/@remix-run/express/-/express-1.8.2.tgz#29883e5e9a64eed15d3964561a1275192dc42ac1"
- integrity sha512-9RPOhAy734HXumxk7D5Sw1ulWOD38hhq42Wrj8DA6hmtjzSvbUzEwCss8Hhh5fIhQqUW+tzZ5U9FJ3b8C8rUpg==
+"@remix-run/[email protected]":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/express/-/express-1.10.1.tgz#e53f2b91d91df2606f955d7a16026dbba29879a3"
+ integrity sha512-chmMd7Lb9OJPbykmaDnhi9sVSNsGEow0DNXG67fW+opDfkmno9cKP1ZnDJWwaJtS+cbDJJxba+g0ljMDVSIY6Q==
dependencies:
- "@remix-run/node" "1.8.2"
+ "@remix-run/node" "1.10.1"
-"@remix-run/[email protected]":
- version "1.8.2"
- resolved "https://registry.yarnpkg.com/@remix-run/node/-/node-1.8.2.tgz#7e8effb3df101f7d24b680d6a4a172272d9f23b0"
- integrity sha512-I5quBtYVL9jEuToAIcoL5OsyUyC06pr3v619V8/HgrlufBV6fYW6jV6O6GVEf5wpkwEHiCgZQc73jzW6XzqX2Q==
+"@remix-run/[email protected]", "@remix-run/node@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/node/-/node-1.10.1.tgz#a9aadb2c0f4208542a074eedf66b15b9b42e180f"
+ integrity sha512-MnBkI/peNHs94ipw2SpX5wdY0kQOCtdfufuo9iq7W2zrrUEdRBXJyfkxU/zvzYZbtTwWKwo0g8irZKz88r4oEg==
dependencies:
- "@remix-run/server-runtime" "1.8.2"
+ "@remix-run/server-runtime" "1.10.1"
"@remix-run/web-fetch" "^4.3.2"
"@remix-run/web-file" "^3.0.2"
"@remix-run/web-stream" "^1.0.3"
@@ -2976,80 +3086,48 @@
source-map-support "^0.5.21"
stream-slice "^0.1.2"
-"@remix-run/[email protected]", "@remix-run/node@^1.9.0":
- version "1.9.0"
- resolved "https://registry.yarnpkg.com/@remix-run/node/-/node-1.9.0.tgz#afed6996305e1fb4b524569797214362d8d46955"
- integrity sha512-LKbzMieBEE1oxeEoR3qyAFd29o/dQvRZvxQyB0LLy1IdAfrMTrADCRK8YZ7xVtJeUzWnNpn9abslotQN82Oz7g==
+"@remix-run/react@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/react/-/react-1.10.1.tgz#910dd6c651360cf56a7f0d8f09dd5878700e21bd"
+ integrity sha512-OqCY+cTuLbNOd2xiR6Iij1qiwq2Yeb6dQvHR8gqWrLn/aR4TYVSiJjfAitg/UfZ9mPlNKvyS5eaUAufCODrnIw==
dependencies:
- "@remix-run/server-runtime" "1.9.0"
- "@remix-run/web-fetch" "^4.3.2"
- "@remix-run/web-file" "^3.0.2"
- "@remix-run/web-stream" "^1.0.3"
- "@web3-storage/multipart-parser" "^1.0.0"
- abort-controller "^3.0.0"
- cookie-signature "^1.1.0"
- source-map-support "^0.5.21"
- stream-slice "^0.1.2"
-
-"@remix-run/react@^1.9.0":
- version "1.9.0"
- resolved "https://registry.yarnpkg.com/@remix-run/react/-/react-1.9.0.tgz#e072f2b26df4ecc5b593633e18777bae936a600a"
- integrity sha512-Rtm6qqdKMD0AMsJuzCFwpz40/o6LXQq20smHyyvH8EMHJRPrms44By28uMW0kmc+M9q0wa0gBfMzWFfZnCSFwg==
- dependencies:
- "@remix-run/router" "1.1.0"
- react-router-dom "6.5.0"
-
-"@remix-run/[email protected]":
- version "1.0.5"
- resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.0.5.tgz#d5c65626add4c3c185a89aa5bd38b1e42daec075"
- integrity sha512-my0Mycd+jruq/1lQuO5LBB6WTlL/e8DTCYWp44DfMTDcXz8DcTlgF0ISaLsGewt+ctHN+yA8xMq3q/N7uWJPug==
+ "@remix-run/router" "1.2.1"
+ react-router-dom "6.6.2"
+ use-sync-external-store "1.2.0"
-"@remix-run/[email protected]":
- version "1.1.0"
- resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.1.0.tgz#b48db8148c8a888e50580a8152b6f68161c49406"
- integrity sha512-rGl+jH/7x1KBCQScz9p54p0dtPLNeKGb3e0wD2H5/oZj41bwQUnXdzbj2TbUAFhvD7cp9EyEQA4dEgpUFa1O7Q==
+"@remix-run/[email protected]":
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.2.1.tgz#812edd4104a15a493dda1ccac0b352270d7a188c"
+ integrity sha512-XiY0IsyHR+DXYS5vBxpoBe/8veTeoRpMHP+vDosLZxL5bnpetzI0igkxkLZS235ldLzyfkxF+2divEwWHP3vMQ==
-"@remix-run/serve@^1.8.2":
- version "1.8.2"
- resolved "https://registry.yarnpkg.com/@remix-run/serve/-/serve-1.8.2.tgz#77760d6e9c56e997db2b93982d37cf417716b40c"
- integrity sha512-/baS2B6Edmge1DSY05p8e+7hAimWZzMhVMSz5YV1rCJwqYUMfgm7z1Bp794pJOycA6g5PuzyX1JrVqvqA6/jsw==
+"@remix-run/serve@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/serve/-/serve-1.10.1.tgz#5c031bc90422b6ef63f9b5b451784986455ae67a"
+ integrity sha512-MipLoO6bNCp3+XkQvycYCzF9VGDn0VtYCP2hI57jvLQoLGUjwRovrvQquJ80IsAFfbL1CUEPwTIGfXB0PD6YpA==
dependencies:
- "@remix-run/express" "1.8.2"
+ "@remix-run/express" "1.10.1"
compression "^1.7.4"
express "^4.17.1"
morgan "^1.10.0"
-"@remix-run/[email protected]":
- version "1.8.2"
- resolved "https://registry.yarnpkg.com/@remix-run/server-runtime/-/server-runtime-1.8.2.tgz#87016defd544f936c857fb8fa6236a72e42a474f"
- integrity sha512-6VLootGC4SyhG1qOOVeXsBrJ3/E3GoQ8YJh5W4IRofO5hNWWy5e4dp/z758RCTGFk4pKGjj64KSnh7NBeS0afA==
+"@remix-run/[email protected]":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/server-runtime/-/server-runtime-1.10.1.tgz#3af2399a9adf48a6081f47833c9c656f4a502d93"
+ integrity sha512-TTuaQP0MzoTyX/jaGhLOU5VAlUVBQ7Ke1rF0DnP/2rRHEV1PX9fbNtqpp0AZt9Fw0+nCTYODPgDY77S6PDCvXg==
dependencies:
- "@remix-run/router" "1.0.5"
+ "@remix-run/router" "1.2.1"
"@types/cookie" "^0.4.0"
"@web3-storage/multipart-parser" "^1.0.0"
cookie "^0.4.1"
- react-router-dom "6.3.0"
set-cookie-parser "^2.4.8"
source-map "^0.7.3"
-"@remix-run/[email protected]":
- version "1.9.0"
- resolved "https://registry.yarnpkg.com/@remix-run/server-runtime/-/server-runtime-1.9.0.tgz#b0e1b0431fcd91daa6058691290f8ebb9519d922"
- integrity sha512-HNJGAzdp4JZqBtDqhi9tEtTxWztuQYruuMPyTlJmSWQhK3MdaOs7F9DJtfFKAhy8LBOqniwpE5w27dkCx7trOg==
+"@remix-run/vercel@^1.10.1":
+ version "1.10.1"
+ resolved "https://registry.yarnpkg.com/@remix-run/vercel/-/vercel-1.10.1.tgz#01a239577701cad3c1d437bcd6b99225ee00f9da"
+ integrity sha512-heUbi/0I3oHINb/Y1kN7SMD+jEAuFfBDXI60gCZ26MDxx7iK5rEkTtS9vftHXk/tJa5Hp9WDCqGeuLerNoVN0w==
dependencies:
- "@remix-run/router" "1.1.0"
- "@types/cookie" "^0.4.0"
- "@web3-storage/multipart-parser" "^1.0.0"
- cookie "^0.4.1"
- set-cookie-parser "^2.4.8"
- source-map "^0.7.3"
-
-"@remix-run/vercel@^1.9.0":
- version "1.9.0"
- resolved "https://registry.yarnpkg.com/@remix-run/vercel/-/vercel-1.9.0.tgz#359af372590f44020897b28a66881a372587f983"
- integrity sha512-pNtVUH6T5gJXgGk7UluK9iOwB+5QmB+UXDGMzyPic5ZGxqxWDTetIwqwLXgxV6xZvAfAClFE8Jf1kZXCUfE1HQ==
- dependencies:
- "@remix-run/node" "1.9.0"
+ "@remix-run/node" "1.10.1"
"@remix-run/web-blob@^3.0.3", "@remix-run/web-blob@^3.0.4":
version "3.0.4"
@@ -5864,7 +5942,35 @@ [email protected]:
esbuild-windows-64 "0.14.47"
esbuild-windows-arm64 "0.14.47"
[email protected], esbuild@^0.15.1:
+ version "0.16.3"
+ resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.16.3.tgz#5868632fa23f7a8547f2a4ea359c44e946515c94"
+ integrity sha512-71f7EjPWTiSguen8X/kxEpkAS7BFHwtQKisCDDV3Y4GLGWBaoSCyD5uXkaUew6JDzA9FEN1W23mdnSwW9kqCeg==
+ optionalDependencies:
+ "@esbuild/android-arm" "0.16.3"
+ "@esbuild/android-arm64" "0.16.3"
+ "@esbuild/android-x64" "0.16.3"
+ "@esbuild/darwin-arm64" "0.16.3"
+ "@esbuild/darwin-x64" "0.16.3"
+ "@esbuild/freebsd-arm64" "0.16.3"
+ "@esbuild/freebsd-x64" "0.16.3"
+ "@esbuild/linux-arm" "0.16.3"
+ "@esbuild/linux-arm64" "0.16.3"
+ "@esbuild/linux-ia32" "0.16.3"
+ "@esbuild/linux-loong64" "0.16.3"
+ "@esbuild/linux-mips64el" "0.16.3"
+ "@esbuild/linux-ppc64" "0.16.3"
+ "@esbuild/linux-riscv64" "0.16.3"
+ "@esbuild/linux-s390x" "0.16.3"
+ "@esbuild/linux-x64" "0.16.3"
+ "@esbuild/netbsd-x64" "0.16.3"
+ "@esbuild/openbsd-x64" "0.16.3"
+ "@esbuild/sunos-x64" "0.16.3"
+ "@esbuild/win32-arm64" "0.16.3"
+ "@esbuild/win32-ia32" "0.16.3"
+ "@esbuild/win32-x64" "0.16.3"
+
+esbuild@^0.15.1:
version "0.15.12"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.15.12.tgz#6c8e22d6d3b7430d165c33848298d3fc9a1f251c"
integrity sha512-PcT+/wyDqJQsRVhaE9uX/Oq4XLrFh0ce/bs2TJh4CSaw9xuvI+xFrH2nAYOADbhQjUgAhNWC5LKoUsakm4dxng==
@@ -7221,13 +7327,6 @@ hey-listen@^1.0.8:
resolved "https://registry.yarnpkg.com/hey-listen/-/hey-listen-1.0.8.tgz#8e59561ff724908de1aa924ed6ecc84a56a9aa68"
integrity sha512-COpmrF2NOg4TBWUJ5UVyaCU2A88wEMkUPK4hNqyCkqHbxT92BbvfjoSozkAIIm6XhicGlJHhFdullInrdhwU8Q==
-history@^5.2.0:
- version "5.3.0"
- resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b"
- integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==
- dependencies:
- "@babel/runtime" "^7.7.6"
-
hoist-non-react-statics@^3.3.1:
version "3.3.2"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"
@@ -10303,35 +10402,20 @@ react-remove-scroll@^2.5.4:
use-callback-ref "^1.3.0"
use-sidecar "^1.1.2"
- version "6.3.0"
- resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.3.0.tgz#a0216da813454e521905b5fa55e0e5176123f43d"
- integrity sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw==
- dependencies:
- history "^5.2.0"
- react-router "6.3.0"
-
- version "6.5.0"
- resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.5.0.tgz#3970bdcaa7c710a6e0b478a833ba0b4b8ae61a6f"
- integrity sha512-/XzRc5fq80gW1ctiIGilyKFZC/j4kfe75uivMsTChFbkvrK4ZrF3P3cGIc1f/SSkQ4JiJozPrf+AwUHHWVehVg==
+ version "6.6.2"
+ resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.6.2.tgz#bbf1f9b45855b218d22fc2d294b79408a084740a"
+ integrity sha512-6SCDXxRQqW5af8ImOqKza7icmQ47/EMbz572uFjzvcArg3lZ+04PxSPp8qGs+p2Y+q+b+S/AjXv8m8dyLndIIA==
dependencies:
- "@remix-run/router" "1.1.0"
- react-router "6.5.0"
+ "@remix-run/router" "1.2.1"
+ react-router "6.6.2"
- version "6.3.0"
- resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.3.0.tgz#3970cc64b4cb4eae0c1ea5203a80334fdd175557"
- integrity sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==
- dependencies:
- history "^5.2.0"
-
- version "6.5.0"
- resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.5.0.tgz#b53f15543a60750c925609d2e38037ac5aed6dd3"
- integrity sha512-fqqUSU0NC0tSX0sZbyuxzuAzvGqbjiZItBQnyicWlOUmzhAU8YuLgRbaCL2hf3sJdtRy4LP/WBrWtARkMvdGPQ==
+ version "6.6.2"
+ resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.6.2.tgz#556f7b56cff7fe32c5c02429fef3fcb2ecd08111"
+ integrity sha512-uJPG55Pek3orClbURDvfljhqFvMgJRo59Pktywkk8hUUkTY2aRfza8Yhl/vZQXs+TNQyr6tu+uqz/fLxPICOGQ==
dependencies:
- "@remix-run/router" "1.1.0"
+ "@remix-run/router" "1.2.1"
react-select@^5.5.1:
version "5.5.4"