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.

feat: add and update for custom fields

Brad Barbinf032ab8cb274
diff --git a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
index 332260bc55..5228ad0c75 100644
--- a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
+++ b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
@@ -24,7 +24,7 @@ import {
attributeUserValidator,
deleteUserAttributeValueValidator,
} from "~/modules/account";
-import { DataType } from "~/modules/users";
+import { DataType } from "~/modules/shared";
import { path } from "~/utils/path";
type UserAttributesFormProps = {
@@ -123,21 +123,23 @@ const GenericAttributeRow = (props: GenericAttributeRowProps) => {
);
};
-function renderTypedForm({
- attribute,
- type,
- value,
- updateFetcher,
- userAttributeId,
- userAttributeValueId,
- userId,
- onSubmit,
- onClose,
-}: GenericAttributeRowProps & {
- userId: string;
- onSubmit: (value: string | boolean | number) => void;
- onClose: () => void;
-}) {
+function TypedForm(
+ props: GenericAttributeRowProps & {
+ onSubmit: (value: string | boolean | number) => void;
+ onClose: () => void;
+ }
+) {
+ const {
+ attribute,
+ type,
+ value,
+ updateFetcher,
+ userAttributeId,
+ userAttributeValueId,
+ userId,
+ onSubmit,
+ onClose,
+ } = props;
switch (type) {
case DataType.Boolean:
return (
@@ -354,18 +356,11 @@ function renderTypedForm({
}
}
-function TypedForm(
+function TypedDisplay(
props: GenericAttributeRowProps & {
- onSubmit: (value: string | boolean | number) => void;
- onClose: () => void;
+ onOpen: () => void;
}
) {
- return renderTypedForm({ ...props });
-}
-
-function renderTypedDisplay({
- ...props
-}: GenericAttributeRowProps & { onOpen: () => void }) {
const {
attribute,
displayValue,
@@ -455,14 +450,6 @@ function renderTypedDisplay({
}
}
-function TypedDisplay(
- props: GenericAttributeRowProps & {
- onOpen: () => void;
- }
-) {
- return renderTypedDisplay({ ...props });
-}
-
function getGenericProps(
attribute: NonNullable<PublicAttributes["userAttribute"]>,
optimisticUpdate: string | boolean | number | undefined
diff --git a/apps/carbon/app/modules/resources/resources.models.ts b/apps/carbon/app/modules/resources/resources.models.ts
index 1efcefb0b9..b0c4a8504e 100644
--- a/apps/carbon/app/modules/resources/resources.models.ts
+++ b/apps/carbon/app/modules/resources/resources.models.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
-import { DataType } from "~/modules/users";
+import { DataType } from "~/modules/shared";
export const standardFactorType = [
"Hours/Piece",
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index 9ff28e6d90..37d89c4682 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -1,7 +1,8 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
-import type { DataType, Employee } from "~/modules/users";
+import type { DataType } from "~/modules/shared";
+import type { Employee } from "~/modules/users";
import { getEmployees } from "~/modules/users";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
diff --git a/apps/carbon/app/modules/resources/types.ts b/apps/carbon/app/modules/resources/types.ts
index de2e8ed3ba..aae07998b2 100644
--- a/apps/carbon/app/modules/resources/types.ts
+++ b/apps/carbon/app/modules/resources/types.ts
@@ -77,6 +77,7 @@ export type AttributeDataType = {
isList: boolean;
isNumeric: boolean;
isText: boolean;
+ isUser: boolean;
};
export type Contractor = NonNullable<
diff --git a/apps/carbon/app/modules/resources/ui/Attributes/AttributeForm.tsx b/apps/carbon/app/modules/resources/ui/Attributes/AttributeForm.tsx
index ba220c41c2..046fcc8625 100644
--- a/apps/carbon/app/modules/resources/ui/Attributes/AttributeForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/Attributes/AttributeForm.tsx
@@ -23,7 +23,7 @@ import {
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { attributeValidator } from "~/modules/resources";
-import { DataType } from "~/modules/users";
+import { DataType } from "~/modules/shared";
import { path } from "~/utils/path";
type AttributeFormProps = {
diff --git a/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx b/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
index 9ba59c86ee..d74e644e8c 100644
--- a/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
@@ -6,7 +6,7 @@ import { BsFillPenFill } from "react-icons/bs";
import { Avatar, Table } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import type { AttributeCategory, Person } from "~/modules/resources";
-import { DataType } from "~/modules/users";
+import { DataType } from "~/modules/shared";
import { path } from "~/utils/path";
type PeopleTableProps = {
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index 4a04eb2a12..e4b0360df7 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+import { DataType } from "~/modules/shared";
const company = {
name: z.string().min(1, { message: "Name is required" }),
@@ -22,6 +23,29 @@ export const onboardingCompanyValidator = z.object({
next: z.string().min(1, { message: "Next is required" }),
});
+export const customFieldValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ customFieldTableId: z.string().min(20),
+ dataTypeId: zfd.numeric(
+ z.number().min(1, { message: "Data type is required" })
+ ),
+ listOptions: z.string().min(1).array().optional(),
+ })
+ .refine((input) => {
+ // allows bar to be optional only when foo is 'foo'
+ if (
+ input.dataTypeId === DataType.List &&
+ (input.listOptions === undefined ||
+ input.listOptions.length === 0 ||
+ input.listOptions.some((option) => option.length === 0))
+ )
+ return false;
+
+ return true;
+ });
+
export const sequenceValidator = z.object({
table: z.string().min(1, { message: "Table is required" }),
prefix: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index 2c60f07094..a094eee4b6 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -8,6 +8,7 @@ import { interpolateSequenceDate } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import type {
companyValidator,
+ customFieldValidator,
sequenceValidator,
themeValidator,
} from "./settings.models";
@@ -50,6 +51,40 @@ export async function getCurrentSequence(
};
}
+export async function getCustomField(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("customField").select("*").eq("id", id).single();
+}
+
+export async function getCustomFields(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("customFieldTables").select("*").eq("id", id).single();
+}
+
+export async function getCustomFieldsTables(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ name: string | null;
+ }
+) {
+ let query = client.from("customFieldTables").select("*", {
+ count: "exact",
+ });
+
+ if (args.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true },
+ ]);
+ return query;
+}
+
export async function getIntegration(
client: SupabaseClient<Database>,
id: string
@@ -115,7 +150,9 @@ export async function getSequences(
name: string | null;
}
) {
- let query = client.from("sequence").select("*");
+ let query = client.from("sequence").select("*", {
+ count: "exact",
+ });
if (args.name) {
query = query.ilike("name", `%${args.name}%`);
@@ -145,6 +182,30 @@ export async function insertCompany(
return client.from("company").insert(company);
}
+export async function insertCustomField(
+ client: SupabaseClient<Database>,
+ customField: Omit<z.infer<typeof customFieldValidator>, "id"> & {
+ createdBy: string;
+ }
+) {
+ // TODO: the new version of supabase client has a max function
+ const sortOrders = await client
+ .from("customField")
+ .select("sortOrder")
+ .eq("customFieldTableId", customField.customFieldTableId);
+
+ if (sortOrders.error) return sortOrders;
+ const maxSortOrder = sortOrders.data.reduce((max, item) => {
+ return Math.max(max, item.sortOrder);
+ }, 0);
+
+ return client
+ .from("customField")
+ .upsert([{ ...customField, sortOrder: maxSortOrder + 1 }])
+ .select("id")
+ .single();
+}
+
export async function rollbackNextSequence(
client: SupabaseClient<Database>,
table: string,
@@ -174,6 +235,39 @@ export async function updateCompany(
return client.from("company").update(sanitize(company)).eq("id", true);
}
+export async function updateCustomField(
+ client: SupabaseClient<Database>,
+ customField: Omit<z.infer<typeof customFieldValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ }
+) {
+ if (!customField.id) throw new Error("id is required");
+ return client
+ .from("customField")
+ .update(
+ sanitize({
+ ...customField,
+ updatedBy: customField.updatedBy,
+ })
+ )
+ .eq("id", customField.id);
+}
+
+export async function updateCustomFieldsSortOrder(
+ client: SupabaseClient<Database>,
+ updates: {
+ id: string;
+ sortOrder: number;
+ updatedBy: string;
+ }[]
+) {
+ const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>
+ client.from("customField").update({ sortOrder, updatedBy }).eq("id", id)
+ );
+ return Promise.all(updatePromises);
+}
+
export async function updateIntegration(
client: SupabaseClient<Database>,
update: {
diff --git a/apps/carbon/app/modules/settings/types.ts b/apps/carbon/app/modules/settings/types.ts
index 671261439f..31b7312b3e 100644
--- a/apps/carbon/app/modules/settings/types.ts
+++ b/apps/carbon/app/modules/settings/types.ts
@@ -1,5 +1,7 @@
import type {
getCompany,
+ getCustomField,
+ getCustomFieldsTables,
getIntegrations,
getSequences,
} from "./settings.service";
@@ -8,6 +10,14 @@ export type Company = NonNullable<
Awaited<ReturnType<typeof getCompany>>["data"]
>;
+export type CustomField = NonNullable<
+ Awaited<ReturnType<typeof getCustomField>>["data"]
+>;
+
+export type CustomFieldsTableType = NonNullable<
+ Awaited<ReturnType<typeof getCustomFieldsTables>>["data"]
+>[number];
+
export type Integration = NonNullable<
Awaited<ReturnType<typeof getIntegrations>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx
new file mode 100644
index 0000000000..681d0c3a23
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx
@@ -0,0 +1,120 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ VStack,
+} from "@carbon/react";
+
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import type { z } from "zod";
+import { Array, Hidden, Input, Select, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type { AttributeDataType } from "~/modules/resources";
+import { customFieldValidator } from "~/modules/settings";
+import { DataType } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+type CustomFieldFormProps = {
+ initialValues: z.infer<typeof customFieldValidator>;
+ dataTypes: AttributeDataType[];
+ onClose: () => void;
+};
+
+const CustomFieldForm = ({
+ initialValues,
+ dataTypes,
+ onClose,
+}: CustomFieldFormProps) => {
+ const permissions = usePermissions();
+ const { tableId } = useParams();
+ if (!tableId) throw new Error("tableId is not found");
+
+ const options =
+ dataTypes?.map((dt) => ({
+ value: dt.id.toString(),
+ label: dt.label,
+ })) ?? [];
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "resources")
+ : !permissions.can("create", "resources");
+
+ const [isList, setIsList] = useState(
+ initialValues.dataTypeId === DataType.List
+ );
+
+ const onChangeCheckForListType = (
+ selected: {
+ value: string;
+ label: string;
+ } | null
+ ) => {
+ setIsList(
+ selected === null ? false : Number(selected.value) === DataType.List
+ );
+ };
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ validator={customFieldValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.customField(tableId, initialValues.id!)
+ : path.to.newCustomField(tableId)
+ }
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>{isEditing ? "Edit" : "New"} Custom Field</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Hidden name="customFieldTableId" />
+
+ <Select
+ name="dataTypeId"
+ label="Data Type"
+ isReadOnly={isEditing}
+ helperText={
+ isEditing ? "Data type cannot be changed" : undefined
+ }
+ options={options}
+ onChange={onChangeCheckForListType}
+ />
+ {isList && <Array name="listOptions" label="List Options" />}
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default CustomFieldForm;
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
new file mode 100644
index 0000000000..8e3278803f
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
@@ -0,0 +1,108 @@
+import {
+ Button,
+ Enumerable,
+ Hyperlink,
+ MenuIcon,
+ MenuItem,
+} from "@carbon/react";
+import { Link, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BiAddToQueue } from "react-icons/bi";
+import { BsListUl } from "react-icons/bs";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { CustomFieldsTableType } from "~/modules/settings";
+import { path } from "~/utils/path";
+
+type CustomFieldsTableProps = {
+ data: CustomFieldsTableType[];
+ count: number;
+};
+
+const CustomFieldsTable = memo(({ data, count }: CustomFieldsTableProps) => {
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<CustomFieldsTableType>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Table",
+ cell: ({ row }) => (
+ <Hyperlink onClick={() => navigate(row.original.id!)}>
+ {row.original.name}
+ </Hyperlink>
+ ),
+ },
+ {
+ accessorKey: "module",
+ header: "Module",
+ cell: ({ row }) => <Enumerable value={row.original.module} />,
+ },
+ {
+ header: "Fields",
+ cell: ({ row }) => (
+ <Button variant="secondary" asChild>
+ <Link
+ to={`${path.to.customFieldList(
+ row.original.id!
+ )}?${params?.toString()}`}
+ >
+ {Array.isArray(row.original.fields)
+ ? row.original.fields?.length ?? 0
+ : 0}{" "}
+ Fields
+ </Link>
+ </Button>
+ ),
+ },
+ ];
+ }, [navigate, params]);
+
+ const renderContextMenu = useCallback(
+ (row: (typeof data)[number]) => {
+ return (
+ <>
+ <MenuItem
+ onClick={() => {
+ navigate(
+ `${path.to.newCustomField(row.id!)}?${params?.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<BiAddToQueue />} />
+ New Field
+ </MenuItem>
+ <MenuItem
+ onClick={() => {
+ navigate(
+ `${path.to.customFieldList(row.id!)}?${params?.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<BsListUl />} />
+ View Custom Fields
+ </MenuItem>
+ </>
+ );
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [navigate, params, permissions]
+ );
+
+ return (
+ <>
+ <Table<CustomFieldsTableType>
+ data={data}
+ columns={columns}
+ count={count ?? 0}
+ renderContextMenu={renderContextMenu}
+ />
+ </>
+ );
+});
+
+CustomFieldsTable.displayName = "CustomFieldsTable";
+export default CustomFieldsTable;
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx
new file mode 100644
index 0000000000..2b82281591
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx
@@ -0,0 +1,226 @@
+import {
+ ActionMenu,
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ IconButton,
+ MenuIcon,
+ MenuItem,
+ useDisclosure,
+} from "@carbon/react";
+import { Link, useFetcher } from "@remix-run/react";
+import { Reorder } from "framer-motion";
+import { useCallback, useMemo, useState } from "react";
+import { AiOutlineNumber } from "react-icons/ai";
+import { BiText } from "react-icons/bi";
+import { BsCalendarDate, BsFillPenFill, BsToggleOn } from "react-icons/bs";
+import { CgProfile } from "react-icons/cg";
+import { IoMdTrash } from "react-icons/io";
+import { MdOutlineDragIndicator } from "react-icons/md";
+import { New } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import type { AttributeDataType } from "~/modules/resources";
+import type { CustomField, CustomFieldsTableType } from "~/modules/settings";
+import { path } from "~/utils/path";
+
+type CustomFieldCategoryDetailProps = {
+ customFieldTable: CustomFieldsTableType;
+ dataTypes: AttributeDataType[];
+ onClose: () => void;
+};
+
+type CustomFieldAndDataType = CustomField & {
+ dataType: AttributeDataType;
+};
+
+const CustomFieldCategoryDetail = ({
+ customFieldTable,
+ dataTypes,
+ onClose,
+}: CustomFieldCategoryDetailProps) => {
+ const sortOrderFetcher = useFetcher();
+
+ const getAttributeDataType = useCallback(
+ (id: number) => {
+ return dataTypes.find((dt) => dt.id === id);
+ },
+ [dataTypes]
+ );
+
+ const fieldMap = useMemo(
+ () =>
+ Array.isArray(customFieldTable.fields)
+ ? customFieldTable.fields.reduce<
+ Record<string, CustomFieldAndDataType>
+ // @ts-ignore
+ >((acc, field) => {
+ if (!field) return acc;
+ const customField = field as CustomFieldAndDataType;
+ return {
+ ...acc,
+ [customField.id]: {
+ ...customField,
+ dataType: getAttributeDataType(customField.dataTypeId),
+ },
+ };
+ }, {})
+ : {},
+ [customFieldTable.fields, getAttributeDataType]
+ ) as Record<string, CustomFieldAndDataType>;
+
+ const [sortOrder, setSortOrder] = useState<string[]>(
+ Array.isArray(customFieldTable.fields)
+ ? customFieldTable.fields
+ .sort(
+ (a, b) =>
+ (a as CustomField).sortOrder - (b as CustomField).sortOrder
+ )
+ .map((field) => (field as CustomField).id)
+ : []
+ );
+
+ const onReorder = (newOrder: string[]) => {
+ let updates: Record<string, number> = {};
+ newOrder.forEach((id, index) => {
+ if (id !== sortOrder[index]) {
+ updates[id] = index + 1;
+ }
+ });
+ setSortOrder(newOrder);
+ updateSortOrder(updates);
+ };
+
+ const updateSortOrder = (updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, { method: "post" });
+ };
+
+ const deleteModal = useDisclosure();
+ const [selectedCustomField, setSelectedCustomField] = useState<
+ CustomField | undefined
+ >();
+
+ const onDelete = (data?: CustomField) => {
+ setSelectedCustomField(data);
+ deleteModal.onOpen();
+ };
+
+ const onDeleteCancel = () => {
+ setSelectedCustomField(undefined);
+ deleteModal.onClose();
+ };
+
+ const renderContextMenu = (fieldId: string) => {
+ return (
+ <>
+ <MenuItem asChild>
+ <Link to={fieldId}>
+ <MenuIcon icon={<BsFillPenFill />} />
+ Edit Custom Field
+ </Link>
+ </MenuItem>
+ <MenuItem onClick={() => onDelete(fieldMap[fieldId])}>
+ <MenuIcon icon={<IoMdTrash />} />
+ Delete Custom Field
+ </MenuItem>
+ </>
+ );
+ };
+
+ return (
+ <>
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <DrawerHeader>
+ <DrawerTitle>{customFieldTable.name}</DrawerTitle>
+ <DrawerDescription>{customFieldTable.module}</DrawerDescription>
+ </DrawerHeader>
+ <DrawerBody>
+ {Array.isArray(customFieldTable?.fields) && (
+ <Reorder.Group
+ axis="y"
+ values={sortOrder}
+ onReorder={onReorder}
+ className="space-y-2 w-full"
+ >
+ {sortOrder.map((sortId) => {
+ return (
+ <Reorder.Item
+ key={sortId}
+ value={sortId}
+ className="rounded-lg w-full"
+ >
+ <HStack>
+ <IconButton
+ aria-label="Drag handle"
+ icon={<MdOutlineDragIndicator />}
+ variant="ghost"
+ />
+ <p className="flex-grow text-foreground">
+ {fieldMap[sortId]?.name}
+ </p>
+ <Button
+ isDisabled
+ leftIcon={getIcon(fieldMap[sortId]?.dataType)}
+ variant="ghost"
+ >
+ {fieldMap[sortId]?.dataType?.label ?? "Unknown"}
+ </Button>
+ <ActionMenu>{renderContextMenu(sortId)}</ActionMenu>
+ </HStack>
+ </Reorder.Item>
+ );
+ })}
+ </Reorder.Group>
+ )}
+ </DrawerBody>
+ <DrawerFooter>
+ <Button asChild size="md">
+ <New label="Custom Field" to="new" />
+ </Button>
+ </DrawerFooter>
+ </DrawerContent>
+ </Drawer>
+ {selectedCustomField && selectedCustomField.id && (
+ <ConfirmDelete
+ isOpen={deleteModal.isOpen}
+ action={path.to.deleteCustomField(
+ selectedCustomField.customFieldTableId,
+ selectedCustomField.id
+ )}
+ name={selectedCustomField?.name ?? ""}
+ text={`Are you sure you want to delete the ${selectedCustomField?.name} field?`}
+ onCancel={onDeleteCancel}
+ />
+ )}
+ </>
+ );
+};
+
+function getIcon({
+ isBoolean,
+ isDate,
+ isNumeric,
+ isText,
+ isUser,
+}: AttributeDataType) {
+ if (isBoolean) return <BsToggleOn />;
+ if (isDate) return <BsCalendarDate />;
+ if (isNumeric) return <AiOutlineNumber />;
+ if (isText) return <BiText />;
+ if (isUser) return <CgProfile />;
+}
+
+export default CustomFieldCategoryDetail;
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableFilters.tsx b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableFilters.tsx
new file mode 100644
index 0000000000..1fc80b2a90
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/CustomFieldsTableFilters.tsx
@@ -0,0 +1,15 @@
+import { HStack } from "@carbon/react";
+import { TableFilters } from "~/components/Layout";
+import { DebouncedInput } from "~/components/Search";
+
+const CustomFieldsTableFilters = () => {
+ return (
+ <TableFilters>
+ <HStack>
+ <DebouncedInput param="name" size="sm" placeholder="Search" />
+ </HStack>
+ </TableFilters>
+ );
+};
+
+export default CustomFieldsTableFilters;
diff --git a/apps/carbon/app/modules/settings/ui/CustomFields/index.ts b/apps/carbon/app/modules/settings/ui/CustomFields/index.ts
new file mode 100644
index 0000000000..98db53539f
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/CustomFields/index.ts
@@ -0,0 +1,11 @@
+import CustomFieldForm from "./CustomFieldForm";
+import CustomFieldsTable from "./CustomFieldsTable";
+import CustomFieldsTableDetail from "./CustomFieldsTableDetail";
+import CustomFieldsTableFilters from "./CustomFieldsTableFilters";
+
+export {
+ CustomFieldForm,
+ CustomFieldsTable,
+ CustomFieldsTableDetail,
+ CustomFieldsTableFilters,
+};
diff --git a/apps/carbon/app/modules/settings/ui/index.ts b/apps/carbon/app/modules/settings/ui/index.ts
index 9097bafad3..905b2bcca0 100644
--- a/apps/carbon/app/modules/settings/ui/index.ts
+++ b/apps/carbon/app/modules/settings/ui/index.ts
@@ -1,6 +1,7 @@
import useSettingsSubmodules from "./useSettingsSubmodules";
export * from "./Company";
+export * from "./CustomFields";
export * from "./Integrations";
export * from "./Sequences";
export * from "./Theme";
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
index 7f22340230..dd6d121858 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,6 +1,7 @@
import { BsPaletteFill } from "react-icons/bs";
import { CgSync } from "react-icons/cg";
import { GoNumber } from "react-icons/go";
+import { MdOutlineDashboardCustomize } from "react-icons/md";
import { TbBuildingFactory2 } from "react-icons/tb";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
@@ -21,6 +22,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
{
name: "System",
routes: [
+ {
+ name: "Custom Fields",
+ to: path.to.customFields,
+ role: "employee",
+ icon: <MdOutlineDashboardCustomize />,
+ },
{
name: "Integrations",
to: path.to.integrations,
diff --git a/apps/carbon/app/modules/shared/types.ts b/apps/carbon/app/modules/shared/types.ts
index f521c6ce32..d71ea77bea 100644
--- a/apps/carbon/app/modules/shared/types.ts
+++ b/apps/carbon/app/modules/shared/types.ts
@@ -19,6 +19,15 @@ export type BillOfMaterialNode = {
children?: BillOfMaterialNode[];
};
+export enum DataType {
+ Boolean = 1,
+ Date = 2,
+ List = 3,
+ Numeric = 4,
+ Text = 5,
+ User = 6,
+}
+
export type Note = NonNullable<
Awaited<ReturnType<typeof getNotes>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/users/types.ts b/apps/carbon/app/modules/users/types.ts
index 43828cfa9a..d1dee6069c 100644
--- a/apps/carbon/app/modules/users/types.ts
+++ b/apps/carbon/app/modules/users/types.ts
@@ -13,15 +13,6 @@ export type Customer = NonNullable<
Awaited<ReturnType<typeof getCustomers>>["data"]
>[number];
-export enum DataType {
- Boolean = 1,
- Date = 2,
- List = 3,
- Numeric = 4,
- Text = 5,
- User = 6,
-}
-
export type Employee = NonNullable<
Awaited<ReturnType<typeof getEmployees>>["data"]
>[number];
diff --git a/apps/carbon/app/routes/x+/resources+/attributes.list.$categoryId.new.tsx b/apps/carbon/app/routes/x+/resources+/attributes.list.$categoryId.new.tsx
index 8985bf6296..d97688aa45 100644
--- a/apps/carbon/app/routes/x+/resources+/attributes.list.$categoryId.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/attributes.list.$categoryId.new.tsx
@@ -2,7 +2,7 @@ import { useNavigate, useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type { AttributeDataType } from "~/modules/resources";
import { AttributeForm } from "~/modules/resources";
-import { DataType } from "~/modules/users";
+import { DataType } from "~/modules/shared";
import { path } from "~/utils/path";
export default function NewAttributeRoute() {
diff --git a/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.$id.tsx b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.$id.tsx
new file mode 100644
index 0000000000..6beebdbfaa
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.$id.tsx
@@ -0,0 +1,108 @@
+import {
+ json,
+ redirect,
+ useLoaderData,
+ useNavigate,
+ useParams,
+} from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type { AttributeDataType } from "~/modules/resources";
+import {
+ CustomFieldForm,
+ customFieldValidator,
+ getCustomField,
+ updateCustomField,
+} from "~/modules/settings";
+import { DataType } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee",
+ });
+
+ const { tableId, id } = params;
+ if (!tableId) throw notFound("Invalid tableId");
+ if (!id) throw new Error("id is not found");
+
+ const customField = await getCustomField(client, id);
+ if (customField.error) {
+ return redirect(
+ path.to.customFieldList(tableId),
+ await flash(
+ request,
+ error(customField.error, "Failed to fetch custom fields")
+ )
+ );
+ }
+
+ return json({ customField: customField.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "settings",
+ });
+
+ const { tableId } = params;
+ if (!tableId) throw new Error("tableId is not found");
+
+ const validation = await validator(customFieldValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id is not found");
+
+ const update = await updateCustomField(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ return json(
+ {},
+ await flash(request, error(update.error, "Failed to update custom field"))
+ );
+ }
+
+ return redirect(path.to.customFields);
+}
+
+export default function UpdateCustomFieldRoute() {
+ const { customField } = useLoaderData<typeof loader>();
+ const { tableId } = useParams();
+ if (!tableId) throw new Error("tableId is not found");
+
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+ const routeData = useRouteData<{
+ dataTypes: AttributeDataType[];
+ }>(path.to.customFields);
+
+ return (
+ <CustomFieldForm
+ initialValues={{
+ id: customField.id,
+ name: customField.name,
+ dataTypeId: customField.dataTypeId || DataType.Text,
+ customFieldTableId: tableId,
+ }}
+ dataTypes={routeData?.dataTypes ?? []}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.new.tsx b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.new.tsx
new file mode 100644
index 0000000000..9874c811a9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.new.tsx
@@ -0,0 +1,76 @@
+import { json, redirect, useNavigate, useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type { AttributeDataType } from "~/modules/resources";
+import {
+ CustomFieldForm,
+ customFieldValidator,
+ insertCustomField,
+} from "~/modules/settings";
+import { DataType } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "settings",
+ });
+
+ const { tableId } = params;
+ if (!tableId) throw new Error("tableId is not found");
+
+ const validation = await validator(customFieldValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createCustomField = await insertCustomField(client, {
+ ...data,
+ createdBy: userId,
+ });
+ if (createCustomField.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(createCustomField.error, "Failed to create custom field")
+ )
+ );
+ }
+
+ return redirect(path.to.customFields);
+}
+
+export default function NewCustomFieldRoute() {
+ const { tableId } = useParams();
+ if (!tableId) throw new Error("tableId is not found");
+
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+ const routeData = useRouteData<{
+ dataTypes: AttributeDataType[];
+ }>(path.to.customFields);
+
+ return (
+ <CustomFieldForm
+ initialValues={{
+ name: "",
+ dataTypeId: DataType.Text,
+ customFieldTableId: tableId,
+ }}
+ dataTypes={routeData?.dataTypes ?? []}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.tsx b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.tsx
new file mode 100644
index 0000000000..8fe65a5c70
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/custom-fields.$tableId.tsx
@@ -0,0 +1,95 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData, useNavigate } from "@remix-run/react";
+import { useRouteData, useUrlParams } from "~/hooks";
+import type { AttributeDataType } from "~/modules/resources";
+import {
+ CustomFieldsTableDetail,
+ getCustomFields,
+ updateCustomFieldsSortOrder,
+} from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost, notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee",
+ });
+
+ const { tableId } = params;
+ if (!tableId) throw notFound("Invalid tableId");
+
+ const customFields = await getCustomFields(client, tableId);
+ if (customFields.error) {
+ return redirect(
+ path.to.customFields,
+ await flash(
+ request,
+ error(customFields.error, "Failed to fetch custom fields")
+ )
+ );
+ }
+
+ return json({ customFields: customFields.data });
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "resources",
+ });
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return json(
+ {},
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId,
+ })
+ );
+
+ const updateSortOrders = await updateCustomFieldsSortOrder(client, updates);
+ if (updateSortOrders.some((update) => update.error))
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateSortOrders, "Failed to update sort order")
+ )
+ );
+
+ return null;
+}
+
+export default function CustomFieldsListRoute() {
+ const { customFields } = useLoaderData<typeof loader>();
+ const routeData = useRouteData<{ dataTypes: AttributeDataType[] }>(
+ path.to.customFields
+ );
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const onClose = () =>
+ navigate(`${path.to.customFields}?${params.toString()}`);
+
+ return (
+ <>
+ <CustomFieldsTableDetail
+ customFieldTable={customFields}
+ dataTypes={routeData?.dataTypes ?? []}
+ onClose={onClose}
+ />
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/settings+/custom-fields.tsx b/apps/carbon/app/routes/x+/settings+/custom-fields.tsx
new file mode 100644
index 0000000000..7e8783850f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/custom-fields.tsx
@@ -0,0 +1,63 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { getAttributeDataTypes } from "~/modules/resources";
+import {
+ CustomFieldsTable,
+ CustomFieldsTableFilters,
+ getCustomFieldsTables,
+} from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Custom Fields",
+ to: path.to.customFields,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ const [tables, dataTypes] = await Promise.all([
+ getCustomFieldsTables(client, { name, limit, offset, sorts }),
+ getAttributeDataTypes(client),
+ ]);
+
+ if (tables.error) {
+ redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(tables.error, "Failed to fetch custom fields"))
+ );
+ }
+
+ return json({
+ count: tables.count ?? 0,
+ tables: tables.data ?? [],
+ dataTypes: dataTypes.data ?? [],
+ });
+}
+
+export default function UserAttributesRoute() {
+ const { count, tables } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <CustomFieldsTableFilters />
+ <CustomFieldsTable data={tables} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 7a2af06a36..6c5c8a10b7 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -125,6 +125,11 @@ export const path = {
customerType: (id: string) =>
generatePath(`${x}/sales/customer-types/${id}`),
customerTypes: `${x}/sales/customer-types`,
+ customField: (tableId: string, id: string) =>
+ generatePath(`${x}/settings/custom-fields/${tableId}/${id}`),
+ customFields: `${x}/settings/custom-fields`,
+ customFieldList: (id: string) =>
+ generatePath(`${x}/settings/custom-fields/${id}`),
deactivateUsers: `${x}/users/deactivate`,
deleteAbility: (id: string) =>
generatePath(`${x}/resources/abilities/delete/${id}`),
@@ -150,6 +155,8 @@ export const path = {
generatePath(`${x}/sales/customer-statuses/delete/${id}`),
deleteCustomerType: (id: string) =>
generatePath(`${x}/sales/customer-types/delete/${id}`),
+ deleteCustomField: (tableId: string, id: string) =>
+ generatePath(`${x}/settings/custom-fields/${tableId}/delete/${id}`),
deleteDepartment: (id: string) =>
generatePath(`${x}/resources/departments/delete/${id}`),
deleteDocument: (id: string) => generatePath(`${x}/documents/${id}/delete`),
@@ -274,6 +281,8 @@ export const path = {
generatePath(`${x}/customer/${id}/locations/new`),
newCustomerStatus: `${x}/sales/customer-statuses/new`,
newCustomerType: `${x}/sales/customer-types/new`,
+ newCustomField: (tableId: string) =>
+ generatePath(`${x}/settings/custom-fields/${tableId}/new`),
newDepartment: `${x}/resources/departments/new`,
newDocument: `${x}/documents/new`,
newEmployee: `${x}/users/employees/new`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index c1a4c6e4fb..848fd6207c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2455,10 +2455,10 @@ export type Database = {
customField: {
Row: {
active: boolean | null
- attributeDataTypeId: number
createdAt: string
createdBy: string
customFieldTableId: string
+ dataTypeId: number
id: string
listOptions: string[] | null
name: string
@@ -2468,10 +2468,10 @@ export type Database = {
}
Insert: {
active?: boolean | null
- attributeDataTypeId: number
createdAt?: string
createdBy: string
customFieldTableId: string
+ dataTypeId: number
id?: string
listOptions?: string[] | null
name: string
@@ -2481,10 +2481,10 @@ export type Database = {
}
Update: {
active?: boolean | null
- attributeDataTypeId?: number
createdAt?: string
createdBy?: string
customFieldTableId?: string
+ dataTypeId?: number
id?: string
listOptions?: string[] | null
name?: string
@@ -2493,13 +2493,6 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
- {
- foreignKeyName: "customField_attributeDataTypeId_fkey"
- columns: ["attributeDataTypeId"]
- isOneToOne: false
- referencedRelation: "attributeDataType"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "customField_createdBy_fkey"
columns: ["createdBy"]
@@ -2528,6 +2521,20 @@ export type Database = {
referencedRelation: "customFieldTable"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "customField_customFieldTableId_fkey"
+ columns: ["customFieldTableId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customField_dataTypeId_fkey"
+ columns: ["dataTypeId"]
+ isOneToOne: false
+ referencedRelation: "attributeDataType"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "customField_updatedBy_fkey"
columns: ["updatedBy"]
@@ -2572,122 +2579,6 @@ export type Database = {
}
Relationships: []
}
- customFieldValue: {
- Row: {
- createdAt: string
- createdBy: string
- customFieldId: string
- id: string
- recordId: string
- updatedAt: string | null
- updatedBy: string | null
- valueBoolean: boolean | null
- valueDate: string | null
- valueNumeric: number | null
- valueText: string | null
- valueUser: string | null
- }
- Insert: {
- createdAt?: string
- createdBy: string
- customFieldId: string
- id?: string
- recordId: string
- updatedAt?: string | null
- updatedBy?: string | null
- valueBoolean?: boolean | null
- valueDate?: string | null
- valueNumeric?: number | null
- valueText?: string | null
- valueUser?: string | null
- }
- Update: {
- createdAt?: string
- createdBy?: string
- customFieldId?: string
- id?: string
- recordId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- valueBoolean?: boolean | null
- valueDate?: string | null
- valueNumeric?: number | null
- valueText?: string | null
- valueUser?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customFieldValue_customFieldId_fkey"
- columns: ["customFieldId"]
- isOneToOne: false
- referencedRelation: "customField"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
department: {
Row: {
color: string
@@ -11977,6 +11868,16 @@ export type Database = {
},
]
}
+ customFieldTables: {
+ Row: {
+ fields: Json | null
+ id: string | null
+ module: Database["public"]["Enums"]["module"] | null
+ name: string | null
+ table: string | null
+ }
+ Relationships: []
+ }
documentLabels: {
Row: {
label: string | null
@@ -12653,14 +12554,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index c1a4c6e4fb..848fd6207c 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2455,10 +2455,10 @@ export type Database = {
customField: {
Row: {
active: boolean | null
- attributeDataTypeId: number
createdAt: string
createdBy: string
customFieldTableId: string
+ dataTypeId: number
id: string
listOptions: string[] | null
name: string
@@ -2468,10 +2468,10 @@ export type Database = {
}
Insert: {
active?: boolean | null
- attributeDataTypeId: number
createdAt?: string
createdBy: string
customFieldTableId: string
+ dataTypeId: number
id?: string
listOptions?: string[] | null
name: string
@@ -2481,10 +2481,10 @@ export type Database = {
}
Update: {
active?: boolean | null
- attributeDataTypeId?: number
createdAt?: string
createdBy?: string
customFieldTableId?: string
+ dataTypeId?: number
id?: string
listOptions?: string[] | null
name?: string
@@ -2493,13 +2493,6 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
- {
- foreignKeyName: "customField_attributeDataTypeId_fkey"
- columns: ["attributeDataTypeId"]
- isOneToOne: false
- referencedRelation: "attributeDataType"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "customField_createdBy_fkey"
columns: ["createdBy"]
@@ -2528,6 +2521,20 @@ export type Database = {
referencedRelation: "customFieldTable"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "customField_customFieldTableId_fkey"
+ columns: ["customFieldTableId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "customField_dataTypeId_fkey"
+ columns: ["dataTypeId"]
+ isOneToOne: false
+ referencedRelation: "attributeDataType"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "customField_updatedBy_fkey"
columns: ["updatedBy"]
@@ -2572,122 +2579,6 @@ export type Database = {
}
Relationships: []
}
- customFieldValue: {
- Row: {
- createdAt: string
- createdBy: string
- customFieldId: string
- id: string
- recordId: string
- updatedAt: string | null
- updatedBy: string | null
- valueBoolean: boolean | null
- valueDate: string | null
- valueNumeric: number | null
- valueText: string | null
- valueUser: string | null
- }
- Insert: {
- createdAt?: string
- createdBy: string
- customFieldId: string
- id?: string
- recordId: string
- updatedAt?: string | null
- updatedBy?: string | null
- valueBoolean?: boolean | null
- valueDate?: string | null
- valueNumeric?: number | null
- valueText?: string | null
- valueUser?: string | null
- }
- Update: {
- createdAt?: string
- createdBy?: string
- customFieldId?: string
- id?: string
- recordId?: string
- updatedAt?: string | null
- updatedBy?: string | null
- valueBoolean?: boolean | null
- valueDate?: string | null
- valueNumeric?: number | null
- valueText?: string | null
- valueUser?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customFieldValue_customFieldId_fkey"
- columns: ["customFieldId"]
- isOneToOne: false
- referencedRelation: "customField"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "customFieldValue_valueUser_fkey"
- columns: ["valueUser"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
department: {
Row: {
color: string
@@ -11977,6 +11868,16 @@ export type Database = {
},
]
}
+ customFieldTables: {
+ Row: {
+ fields: Json | null
+ id: string | null
+ module: Database["public"]["Enums"]["module"] | null
+ name: string | null
+ table: string | null
+ }
+ Relationships: []
+ }
documentLabels: {
Row: {
label: string | null
@@ -12653,14 +12554,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/migrations/20240311021818_custom-fields.sql b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
index ad2443c23f..cb613e8fa4 100644
--- a/packages/database/supabase/migrations/20240311021818_custom-fields.sql
+++ b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
@@ -42,7 +42,7 @@ CREATE TABLE "customField" (
"name" TEXT NOT NULL,
"sortOrder" INTEGER NOT NULL DEFAULT 1,
"customFieldTableId" TEXT NOT NULL,
- "attributeDataTypeId" INTEGER NOT NULL,
+ "dataTypeId" INTEGER NOT NULL,
"listOptions" TEXT ARRAY,
"active" BOOLEAN DEFAULT TRUE,
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
@@ -51,8 +51,9 @@ CREATE TABLE "customField" (
"updatedBy" TEXT,
CONSTRAINT "customField_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "customField_customFieldTableId_name_key" UNIQUE ("customFieldTableId", "name"),
CONSTRAINT "customField_customFieldTableId_fkey" FOREIGN KEY ("customFieldTableId") REFERENCES "customFieldTable"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "customField_attributeDataTypeId_fkey" FOREIGN KEY ("attributeDataTypeId") REFERENCES "attributeDataType"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "customField_dataTypeId_fkey" FOREIGN KEY ("dataTypeId") REFERENCES "attributeDataType"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "customField_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,
CONSTRAINT "customField_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE
);
@@ -87,99 +88,27 @@ CREATE POLICY "Employees with settings_delete can delete custom fields" ON "cust
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE TABLE "customFieldValue" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "customFieldId" TEXT NOT NULL,
- "recordId" TEXT NOT NULL,
- "valueBoolean" BOOLEAN,
- "valueDate" DATE,
- "valueNumeric" NUMERIC,
- "valueText" TEXT,
- "valueUser" TEXT,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE,
- "updatedBy" TEXT,
-
- CONSTRAINT "customFieldValue_singleValue"
- CHECK (
- (
- "valueBoolean" IS NOT NULL AND
- "valueDate" IS NULL AND
- "valueNumeric" IS NULL AND
- "valueText" IS NULL AND
- "valueUser" IS NULL
- )
- OR (
- "valueBoolean" IS NULL AND
- "valueDate" IS NULL AND
- "valueNumeric" IS NULL AND
- "valueText" IS NOT NULL AND
- "valueUser" IS NULL
- )
- OR (
- "valueBoolean" IS NULL AND
- "valueDate" IS NOT NULL AND
- "valueNumeric" IS NULL AND
- "valueText" IS NULL AND
- "valueUser" IS NULL
- )
- OR (
- "valueBoolean" IS NULL AND
- "valueDate" IS NULL AND
- "valueNumeric" IS NOT NULL AND
- "valueText" IS NULL AND
- "valueUser" IS NULL
- )
- OR (
- "valueBoolean" IS NULL AND
- "valueDate" IS NULL AND
- "valueNumeric" IS NULL AND
- "valueText" IS NULL AND
- "valueUser" IS NOT NULL
- )
- ),
-
- CONSTRAINT "customFieldValue_customFieldId_fkey" FOREIGN KEY ("customFieldId") REFERENCES "customField"("id") ON DELETE CASCADE,
- CONSTRAINT "customFieldValue_valueUser_fkey" FOREIGN KEY ("valueUser") REFERENCES "user"("id") ON DELETE CASCADE,
- CONSTRAINT "customFieldValue_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
- CONSTRAINT "customFieldValue_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"),
- CONSTRAINT uq_customFieldId_recordId
- UNIQUE ( "customFieldId", "recordId")
-);
-
-CREATE INDEX "customFieldValue_customFieldId_index" ON "customFieldValue" ("customFieldId");
-CREATE INDEX "customFieldValue_recordId_index" ON "customFieldValue" ("recordId");
-
--- TODO: fine-grained control over read/write access to custom field values based on customFieldTable module
-
-ALTER TABLE "customFieldValue" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Employees can view custom field values" ON "customFieldValue"
- FOR SELECT
- USING (
- auth.role() = 'authenticated'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
-
-CREATE POLICY "Employees can insert custom field values" ON "customFieldValue"
- FOR INSERT
- WITH CHECK (
- auth.role() = 'authenticated'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
-
-CREATE POLICY "Employees can update custom field values" ON "customFieldValue"
- FOR UPDATE
- USING (
- auth.role() = 'authenticated'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
-
-CREATE POLICY "Employees can delete custom field values" ON "customFieldValue"
- FOR DELETE
- USING (
- auth.role() = 'authenticated'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
-
+CREATE OR REPLACE VIEW "customFieldTables" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ cft.id,
+ cft.module,
+ cft.table,
+ cft.name,
+ cf.fields
+FROM "customFieldTable" cft
+LEFT JOIN (
+ SELECT cf."customFieldTableId",
+ COALESCE(json_agg(
+ json_build_object(
+ 'id', id,
+ 'name', name,
+ 'sortOrder', "sortOrder",
+ 'dataTypeId', "dataTypeId",
+ 'listOptions', "listOptions",
+ 'active', active
+ )
+ ), '[]') AS fields
+ FROM "customField" cf
+ GROUP BY cf."customFieldTableId"
+) cf
+ON cf."customFieldTableId" = cft.id;
\ No newline at end of file
diff --git a/packages/utils/src/color.ts b/packages/utils/src/color.ts
index ff53d64d0e..bb96db67f0 100644
--- a/packages/utils/src/color.ts
+++ b/packages/utils/src/color.ts
@@ -8,7 +8,7 @@ const colors = [
{ background: "#4ff38c", color: "#000000" },
{ background: "#f4a261", color: "#38210f" },
{ background: "#e76f51", color: "#ffffff" },
- { background: "#8ecae6", color: "#ffffff" },
+ { background: "#8ecae6", color: "#172a33" },
{ background: "#219ebc", color: "#ffffff" },
{ background: "#3a86ff", color: "#ffffff" },
{ background: "#ff006e", color: "#ffffff" },