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.

👻 add support for multiple generic filters on table

Brad Barbin9836bedf2858
diff --git a/apps/carbon/app/components/Data/Table/Table.tsx b/apps/carbon/app/components/Data/Table/Table.tsx
index d2dc9954ec..d46a9ed7b5 100644
--- a/apps/carbon/app/components/Data/Table/Table.tsx
+++ b/apps/carbon/app/components/Data/Table/Table.tsx
@@ -1,38 +1,18 @@
import { useColor } from "@carbon/react";
import type { ThemeTypings } from "@chakra-ui/react";
-import { chakra } from "@chakra-ui/react";
-import { Button } from "@chakra-ui/react";
-import { MenuButton, MenuList } from "@chakra-ui/react";
-import { Menu } from "@chakra-ui/react";
-import { MenuItem } from "@chakra-ui/react";
-import { useDisclosure } from "@chakra-ui/react";
-import { Grid } from "@chakra-ui/react";
-import { IconButton } from "@chakra-ui/react";
-import { HStack } from "@chakra-ui/react";
-import { AnimatePresence, Reorder, motion } from "framer-motion";
-import { List, ListItem } from "@chakra-ui/react";
-import {
- Drawer,
- DrawerBody,
- DrawerCloseButton,
- DrawerContent,
- DrawerHeader,
- DrawerOverlay,
- Text,
-} from "@chakra-ui/react";
-import { Checkbox } from "@chakra-ui/react";
import {
Box,
Flex,
+ Grid,
Table as ChakraTable,
Thead,
Tbody,
Tr as ChakraTr,
Th as ChakraTh,
Td as ChakraTd,
+ chakra,
} from "@chakra-ui/react";
import type {
- Column,
ColumnDef,
ColumnOrderState,
ColumnPinningState,
@@ -43,31 +23,23 @@ import {
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
-import { useEffect, useState } from "react";
+import { AnimatePresence, motion } from "framer-motion";
+import { useEffect, useMemo, useState } from "react";
import { AiFillCaretUp, AiFillCaretDown } from "react-icons/ai";
-import { Pagination, PaginationButtons, usePagination } from "./components";
-import { MdOutlineDragIndicator } from "react-icons/md";
import {
- BsChevronDown,
- BsEyeFill,
- BsEyeSlash,
- BsLayoutThreeColumns,
- BsPin,
- BsPinFill,
-} from "react-icons/bs";
-import { useUrlParams } from "~/hooks";
+ Header,
+ IndeterminateCheckbox,
+ Pagination,
+ usePagination,
+ useSort,
+} from "./components";
+import type { TableAction } from "./types";
-interface Action<T> {
- label: string;
- onClick: (rows: T[]) => void;
- disabled?: boolean;
- icon?: JSX.Element;
-}
interface TableProps<T extends object> {
columns: ColumnDef<T>[];
data: T[];
- actions?: Action<T>[];
+ actions?: TableAction<T>[];
count?: number;
colorScheme?: ThemeTypings["colorSchemes"];
defaultColumnVisibility?: Record<string, boolean>;
@@ -91,52 +63,43 @@ const Table = <T extends object>({
onRowClick,
onSelectedRowsChange,
}: TableProps<T>) => {
- const [params, setParams] = useUrlParams();
-
- const toggleSortBy = (columnId: string) => {
- const existingSort = params.getAll("sort");
- const sortAsc = `${columnId}:asc`;
- const sortDesc = `${columnId}:desc`;
-
- if (existingSort.includes(sortAsc)) {
- setParams({
- sort: existingSort.filter((s) => s !== sortAsc).concat(sortDesc),
- });
- } else if (existingSort.includes(sortDesc)) {
- setParams({ sort: existingSort.filter((s) => s !== sortDesc) });
- } else {
- setParams({ sort: existingSort.concat(sortAsc) });
- }
- };
-
- const isSorted = (columnId: string): -1 | null | 1 => {
- const existingSort = params.getAll("sort");
-
- if (existingSort.includes(`${columnId}:asc`)) return 1;
- if (existingSort.includes(`${columnId}:desc`)) return -1;
- return null;
- };
-
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
- if (withSelectableRows) columns.unshift(getSelectableColumn<T>());
+ if (withSelectableRows) columns.unshift(getRowSelectionColumn<T>());
const pagination = usePagination(count, setRowSelection);
- const columnOrderingDrawer = useDisclosure();
const [columnVisibility, setColumnVisibility] = useState(
defaultColumnVisibility
);
+ const { isSorted, toggleSortBy } = useSort();
const [columnOrder, setColumnOrder] = useState<ColumnOrderState>([]);
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(
withColumnOrdering
? {
left: ["select"],
- // right: ["id"],
}
: {}
);
+ const columnAccessors = useMemo(
+ () =>
+ columns.reduce<Record<string, string>>((acc, column) => {
+ if (
+ column.header &&
+ typeof column.header === "string" &&
+ "accessorKey" in column
+ ) {
+ return {
+ ...acc,
+ [column.accessorKey.toString()]: column.header,
+ };
+ }
+ return acc;
+ }, {}),
+ [columns]
+ );
+
const table = useReactTable({
data,
columns,
@@ -176,58 +139,21 @@ const Table = <T extends object>({
return (
<>
- {(withColumnOrdering || withSelectableRows) && (
- <HStack
- px={4}
- py={3}
- justifyContent="space-between"
- borderBottomColor={borderColor}
- borderBottomStyle="solid"
- borderBottomWidth={1}
- w="full"
- >
- <HStack spacing={2}>
- {withSelectableRows && actions.length > 0 && (
- <Menu isLazy>
- <MenuButton
- as={Button}
- rightIcon={<BsChevronDown />}
- disabled={selectedRows.length === 0}
- colorScheme="gray"
- variant="outline"
- >
- Actions
- </MenuButton>
- <MenuList fontSize="sm" boxShadow="xl">
- {actions.map((action) => (
- <MenuItem
- key={action.label}
- onClick={() => action.onClick(selectedRows)}
- disabled={action.disabled}
- icon={action.icon}
- >
- {action.label}
- </MenuItem>
- ))}
- </MenuList>
- </Menu>
- )}
- </HStack>
- <HStack spacing={2}>
- {withColumnOrdering && (
- <Button
- onClick={columnOrderingDrawer.onOpen}
- variant="ghost"
- leftIcon={<BsLayoutThreeColumns />}
- >
- Columns
- </Button>
- )}
- {withPagination && <PaginationButtons {...pagination} condensed />}
- </HStack>
- </HStack>
- )}
<Box w="full" h="full">
+ {(withColumnOrdering || withSelectableRows) && (
+ <Header
+ actions={actions}
+ columnAccessors={columnAccessors}
+ columnOrder={columnOrder}
+ columns={table.getAllLeafColumns()}
+ selectedRows={selectedRows}
+ setColumnOrder={setColumnOrder}
+ pagination={pagination}
+ withColumnOrdering={withColumnOrdering}
+ withPagination={withPagination}
+ withSelectableRows={withSelectableRows}
+ />
+ )}
<Box h="full" overflow="scroll" style={{ contain: "strict" }}>
<Grid
w="full"
@@ -249,7 +175,8 @@ const Table = <T extends object>({
{headerGroup.headers.map((header) => {
// TODO: improve this
const sortable =
- "accessorKey" in header.column.columnDef;
+ "accessorKey" in header.column.columnDef &&
+ header.column.columnDef.enableSorting !== false;
const sorted = isSorted(
// @ts-ignore
header.column.columnDef?.accessorKey ?? ""
@@ -459,7 +386,7 @@ const Table = <T extends object>({
</Tbody>
</ChakraTable>
- {/* Pinned right columns */}
+ {/* Pinned right columns
{withColumnOrdering ? (
<ChakraTable
bg={defaultBackground}
@@ -537,87 +464,13 @@ const Table = <T extends object>({
</AnimatePresence>
</Tbody>
</ChakraTable>
- ) : null}
+ ) : null} */}
</Grid>
</Box>
</Box>
{withPagination && (
<Pagination {...pagination} colorScheme={colorScheme} />
)}
- {withColumnOrdering && (
- <Drawer
- isOpen={columnOrderingDrawer.isOpen}
- placement="right"
- onClose={columnOrderingDrawer.onClose}
- >
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>Edit columns</DrawerHeader>
-
- <DrawerBody>
- <List
- as={Reorder.Group}
- axis="y"
- values={columnOrder}
- onReorder={(newOrder: ColumnOrderState) => {
- if (withSelectableRows) newOrder.unshift("select");
- setColumnOrder(newOrder);
- }}
- spacing={2}
- >
- {/* TODO: list undraggable pinned columns first */}
- {table
- .getAllLeafColumns()
- .reduce<JSX.Element[]>((acc, column) => {
- if (isColumnToggable(column))
- acc.push(
- <ListItem
- key={column.id}
- as={Reorder.Item}
- value={column.id}
- rounded="lg"
- >
- <HStack>
- <IconButton
- aria-label="Drag handle"
- icon={<MdOutlineDragIndicator />}
- />
- <Text fontSize="small" flexGrow={1}>
- <>{column.columnDef.header}</>
- </Text>
- <IconButton
- aria-label="Toggle column"
- icon={
- column.getIsPinned() ? <BsPinFill /> : <BsPin />
- }
- onClick={() =>
- column.getIsPinned()
- ? column.pin(false)
- : column.pin("left")
- }
- />
- <IconButton
- aria-label="Toggle column"
- icon={
- column.getIsVisible() ? (
- <BsEyeFill />
- ) : (
- <BsEyeSlash />
- )
- }
- onClick={column.getToggleVisibilityHandler()}
- />
- </HStack>
- </ListItem>
- );
- return acc;
- }, [])}
- </List>
- </DrawerBody>
- </DrawerContent>
- </Drawer>
- )}
</>
);
};
@@ -632,31 +485,7 @@ const spring = {
stiffness: 30,
};
-type IndeterminateCheckboxProps = {
- checked: boolean;
- indeterminate: boolean;
- [key: string]: any;
-};
-
-const IndeterminateCheckbox = ({
- indeterminate,
- checked,
- ...rest
-}: IndeterminateCheckboxProps) => {
- return (
- <Checkbox
- colorScheme="blackAlpha"
- isChecked={checked}
- isIndeterminate={indeterminate}
- ml={2}
- {...rest}
- />
- );
-};
-
-IndeterminateCheckbox.displayName = "IndeterminateCheckbox";
-
-function getSelectableColumn<T>(): ColumnDef<T> {
+function getRowSelectionColumn<T>(): ColumnDef<T> {
return {
id: "select",
header: ({ table }) => (
@@ -680,12 +509,4 @@ function getSelectableColumn<T>(): ColumnDef<T> {
};
}
-function isColumnToggable<T>(column: Column<T, unknown>): boolean {
- return (
- column.columnDef.id !== "select" &&
- typeof column.columnDef.header === "string" &&
- column.columnDef.header !== ""
- );
-}
-
export default Table;
diff --git a/apps/carbon/app/components/Data/Table/components/Actions/Actions.tsx b/apps/carbon/app/components/Data/Table/components/Actions/Actions.tsx
new file mode 100644
index 0000000000..c1db3754c9
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Actions/Actions.tsx
@@ -0,0 +1,41 @@
+import { Button, Menu, MenuButton, MenuItem, MenuList } from "@chakra-ui/react";
+import { IoMdCheckboxOutline } from "react-icons/io";
+import type { TableAction } from "../../types";
+
+type ActionsProps<T> = {
+ actions: TableAction<T>[];
+ selectedRows: T[];
+};
+
+const Actions = <T extends Object>({
+ actions,
+ selectedRows,
+}: ActionsProps<T>) => {
+ return (
+ <Menu isLazy>
+ <MenuButton
+ as={Button}
+ leftIcon={<IoMdCheckboxOutline />}
+ disabled={selectedRows.length === 0}
+ colorScheme={selectedRows.length === 0 ? "gray" : "brand"}
+ variant={selectedRows.length === 0 ? "ghost" : "solid"}
+ >
+ Actions
+ </MenuButton>
+ <MenuList fontSize="sm" boxShadow="xl">
+ {actions.map((action) => (
+ <MenuItem
+ key={action.label}
+ onClick={() => action.onClick(selectedRows)}
+ disabled={action.disabled}
+ icon={action.icon}
+ >
+ {action.label}
+ </MenuItem>
+ ))}
+ </MenuList>
+ </Menu>
+ );
+};
+
+export default Actions;
diff --git a/apps/carbon/app/components/Data/Table/components/Actions/index.ts b/apps/carbon/app/components/Data/Table/components/Actions/index.ts
new file mode 100644
index 0000000000..2ced987d3a
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Actions/index.ts
@@ -0,0 +1,3 @@
+import Actions from "./Actions";
+
+export default Actions;
diff --git a/apps/carbon/app/components/Data/Table/components/Columns/Columns.tsx b/apps/carbon/app/components/Data/Table/components/Columns/Columns.tsx
new file mode 100644
index 0000000000..47655e8efa
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Columns/Columns.tsx
@@ -0,0 +1,121 @@
+import {
+ Button,
+ IconButton,
+ HStack,
+ List,
+ ListItem,
+ Popover,
+ PopoverArrow,
+ PopoverBody,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTrigger,
+ Text,
+} from "@chakra-ui/react";
+import type { Column, ColumnOrderState } from "@tanstack/react-table";
+import { Reorder } from "framer-motion";
+import {
+ BsEyeFill,
+ BsEyeSlash,
+ BsLayoutThreeColumns,
+ BsPin,
+ BsPinFill,
+} from "react-icons/bs";
+import { MdOutlineDragIndicator } from "react-icons/md";
+
+type ColumnsProps<T> = {
+ columns: Column<T, unknown>[];
+ columnOrder: ColumnOrderState;
+ withSelectableRows: boolean;
+ setColumnOrder: (newOrder: ColumnOrderState) => void;
+};
+
+const Columns = <T extends object>({
+ columns,
+ columnOrder,
+ withSelectableRows,
+ setColumnOrder,
+}: ColumnsProps<T>) => {
+ return (
+ <Popover placement="bottom">
+ <PopoverTrigger>
+ <Button variant="ghost" leftIcon={<BsLayoutThreeColumns />}>
+ Columns
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent w={360} boxShadow="xl">
+ <PopoverHeader>
+ <Text fontSize="sm">Edit column view</Text>
+ <Text fontSize="xs" color="gray.500">
+ Manage and reorder columns
+ </Text>
+ </PopoverHeader>
+ <PopoverArrow />
+ <PopoverBody maxH="50vh" overflow="auto">
+ <List
+ as={Reorder.Group}
+ axis="y"
+ values={columnOrder}
+ onReorder={(newOrder: ColumnOrderState) => {
+ if (withSelectableRows) newOrder.unshift("select");
+ setColumnOrder(newOrder);
+ }}
+ spacing={2}
+ >
+ {columns.reduce<JSX.Element[]>((acc, column) => {
+ if (isColumnToggable(column))
+ acc.push(
+ <ListItem
+ key={column.id}
+ as={Reorder.Item}
+ value={column.id}
+ rounded="lg"
+ >
+ <HStack>
+ <IconButton
+ aria-label="Drag handle"
+ icon={<MdOutlineDragIndicator />}
+ variant="ghost"
+ />
+ <Text fontSize="small" flexGrow={1}>
+ <>{column.columnDef.header}</>
+ </Text>
+ <IconButton
+ aria-label="Toggle column"
+ icon={column.getIsPinned() ? <BsPinFill /> : <BsPin />}
+ onClick={() =>
+ column.getIsPinned()
+ ? column.pin(false)
+ : column.pin("left")
+ }
+ variant="ghost"
+ />
+ <IconButton
+ aria-label="Toggle column"
+ icon={
+ column.getIsVisible() ? <BsEyeFill /> : <BsEyeSlash />
+ }
+ onClick={column.getToggleVisibilityHandler()}
+ variant="ghost"
+ />
+ </HStack>
+ </ListItem>
+ );
+ return acc;
+ }, [])}
+ </List>
+ </PopoverBody>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+function isColumnToggable<T>(column: Column<T, unknown>): boolean {
+ return (
+ column.columnDef.id !== "select" &&
+ typeof column.columnDef.header === "string" &&
+ column.columnDef.header !== ""
+ );
+}
+
+export default Columns;
diff --git a/apps/carbon/app/components/Data/Table/components/Columns/index.ts b/apps/carbon/app/components/Data/Table/components/Columns/index.ts
new file mode 100644
index 0000000000..739b1c897d
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Columns/index.ts
@@ -0,0 +1,3 @@
+import Columns from "./Columns";
+
+export default Columns;
diff --git a/apps/carbon/app/components/Data/Table/components/Filter/Filter.tsx b/apps/carbon/app/components/Data/Table/components/Filter/Filter.tsx
new file mode 100644
index 0000000000..d8c3a050de
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Filter/Filter.tsx
@@ -0,0 +1,103 @@
+import {
+ Button,
+ List,
+ Popover,
+ PopoverArrow,
+ PopoverBody,
+ PopoverContent,
+ PopoverFooter,
+ PopoverHeader,
+ PopoverTrigger,
+ Text,
+} from "@chakra-ui/react";
+import { BsFilter, BsPlus } from "react-icons/bs";
+import { useUrlParams } from "~/hooks";
+import FilterRow from "./FilterRow";
+
+type FilterProps = {
+ columnAccessors: Record<string, string>;
+};
+
+const Filter = ({ columnAccessors }: FilterProps) => {
+ const [params, setParams] = useUrlParams();
+ const filters = params.getAll("filter");
+
+ const addFilter = () => {
+ const defaultFilter = `${Object.keys(columnAccessors)[0]}:contains:`;
+ setParams({ filter: filters.concat(defaultFilter) });
+ };
+
+ const removeFilter = (filterIndex: number) => {
+ setParams({
+ filter: filters.filter((_, index) => index !== filterIndex),
+ });
+ };
+
+ const updateFilter = (filterIndex: number, newFilter: string) => {
+ setParams({
+ filter: filters.map((filter, index) =>
+ index === filterIndex ? newFilter : filter
+ ),
+ });
+ };
+
+ return (
+ <Popover placement="bottom" closeOnBlur>
+ <PopoverTrigger>
+ <Button
+ colorScheme={filters.length === 0 ? undefined : "brand"}
+ variant={filters.length === 0 ? "ghost" : "solid"}
+ leftIcon={<BsFilter />}
+ >
+ {filters.length === 0 ? "Filter" : "Filtered"}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent w={480} boxShadow="xl">
+ {filters.length === 0 && (
+ <PopoverHeader>
+ <Text fontSize="sm">No filters applied to this view</Text>
+ <Text fontSize="xs" color="gray.500">
+ Add a column below to sort the view
+ </Text>
+ </PopoverHeader>
+ )}
+ <PopoverArrow />
+
+ {filters.length > 0 && (
+ <PopoverBody>
+ <List spacing={2}>
+ {filters.reduce<JSX.Element[]>((acc, filter, index) => {
+ const [column, operator, searchValue] = filter.split(":");
+ if (!column || !operator) return acc;
+ acc.push(
+ <FilterRow
+ key={`filter-${column}-${[index]}`}
+ column={column}
+ columnAccessors={columnAccessors}
+ operator={operator}
+ searchValue={searchValue}
+ onRemove={() => removeFilter(index)}
+ onUpdate={(newFilter) => updateFilter(index, newFilter)}
+ />
+ );
+ return acc;
+ }, [])}
+ </List>
+ </PopoverBody>
+ )}
+ <PopoverFooter>
+ <Button
+ size="sm"
+ variant="outline"
+ leftIcon={<BsPlus />}
+ onClick={addFilter}
+ >
+ Add Filter
+ </Button>
+ </PopoverFooter>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export default Filter;
diff --git a/apps/carbon/app/components/Data/Table/components/Filter/FilterRow.tsx b/apps/carbon/app/components/Data/Table/components/Filter/FilterRow.tsx
new file mode 100644
index 0000000000..a5c3f348f0
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Filter/FilterRow.tsx
@@ -0,0 +1,77 @@
+import { useDebounce } from "@carbon/react";
+import { Grid, IconButton, Input, ListItem, Select } from "@chakra-ui/react";
+import { useEffect, useState } from "react";
+import { IoMdClose } from "react-icons/io";
+import { filterOperatorLabels } from "~/utils/query";
+
+type FilterRowProps = {
+ column: string;
+ columnAccessors: Record<string, string>;
+ operator: string;
+ searchValue: string;
+ onRemove: () => void;
+ onUpdate: (newFilter: string) => void;
+};
+
+const FilterRow = ({
+ column,
+ columnAccessors,
+ operator,
+ searchValue,
+ onRemove,
+ onUpdate,
+}: FilterRowProps) => {
+ const [value, setValue] = useState(searchValue || "");
+ const [debouncedQuery] = useDebounce(value, 500);
+
+ useEffect(() => {
+ const newFilter = `${column}:${operator}:${debouncedQuery}`;
+ onUpdate(newFilter);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedQuery]);
+
+ const onColumnChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
+ const newFilter = `${e.target.value}:${operator}:${searchValue}`;
+ onUpdate(newFilter);
+ };
+
+ const onOperatorChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
+ const newFilter = `${column}:${e.target.value}:${searchValue}`;
+ onUpdate(newFilter);
+ };
+
+ return (
+ <ListItem>
+ <Grid gridColumnGap={2} gridTemplateColumns="1fr 1fr 1fr auto">
+ <Select size="sm" defaultValue={column} onChange={onColumnChange}>
+ {Object.entries(columnAccessors).map(([accessor, title]) => (
+ <option key={accessor} value={accessor}>
+ {title}
+ </option>
+ ))}
+ </Select>
+ <Select size="sm" defaultValue={operator} onChange={onOperatorChange}>
+ {filterOperatorLabels.map(({ operator, label }) => (
+ <option key={operator} value={operator}>
+ {label}
+ </option>
+ ))}
+ </Select>
+ <Input
+ defaultValue={searchValue}
+ onChange={(e) => setValue(e.target.value)}
+ size="sm"
+ placeholder="Enter a value"
+ />
+ <IconButton
+ aria-label="Remove filter"
+ icon={<IoMdClose />}
+ onClick={onRemove}
+ variant="ghost"
+ />
+ </Grid>
+ </ListItem>
+ );
+};
+
+export default FilterRow;
diff --git a/apps/carbon/app/components/Data/Table/components/Filter/index.ts b/apps/carbon/app/components/Data/Table/components/Filter/index.ts
new file mode 100644
index 0000000000..0cea50296e
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Filter/index.ts
@@ -0,0 +1,3 @@
+import Filter from "./Filter";
+
+export default Filter;
diff --git a/apps/carbon/app/components/Data/Table/components/Header/Header.tsx b/apps/carbon/app/components/Data/Table/components/Header/Header.tsx
new file mode 100644
index 0000000000..679f6bfa8b
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Header/Header.tsx
@@ -0,0 +1,72 @@
+import { useColor } from "@carbon/react";
+import { HStack } from "@chakra-ui/react";
+import type { Column, ColumnOrderState } from "@tanstack/react-table";
+import type { TableAction } from "../../types";
+import Actions from "../Actions";
+import Columns from "../Columns";
+import Filter from "../Filter";
+import type { PaginationProps } from "../Pagination";
+import { PaginationButtons } from "../Pagination";
+import Sort from "../Sort";
+
+type HeaderProps<T> = {
+ actions: TableAction<T>[];
+ columnAccessors: Record<string, string>;
+ columnOrder: ColumnOrderState;
+ columns: Column<T, unknown>[];
+ pagination: PaginationProps;
+ selectedRows: T[];
+ setColumnOrder: (newOrder: ColumnOrderState) => void;
+ withColumnOrdering: boolean;
+ withPagination: boolean;
+ withSelectableRows: boolean;
+};
+
+const Header = <T extends object>({
+ actions,
+ columnAccessors,
+ columnOrder,
+ columns,
+ pagination,
+ selectedRows,
+ setColumnOrder,
+ withColumnOrdering,
+ withPagination,
+ withSelectableRows,
+}: HeaderProps<T>) => {
+ 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}>
+ {withSelectableRows && actions.length > 0 && (
+ <Actions actions={actions} selectedRows={selectedRows} />
+ )}
+ </HStack>
+ <HStack spacing={2}>
+ <Filter columnAccessors={columnAccessors} />
+ <Sort columnAccessors={columnAccessors} />
+
+ {withColumnOrdering && (
+ <Columns
+ columnOrder={columnOrder}
+ columns={columns}
+ setColumnOrder={setColumnOrder}
+ withSelectableRows={withSelectableRows}
+ />
+ )}
+ {withPagination && <PaginationButtons {...pagination} condensed />}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default Header;
diff --git a/apps/carbon/app/components/Data/Table/components/Header/index.ts b/apps/carbon/app/components/Data/Table/components/Header/index.ts
new file mode 100644
index 0000000000..0d87fe1295
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Header/index.ts
@@ -0,0 +1,3 @@
+import Header from "./Header";
+
+export default Header;
diff --git a/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/IndeterminateCheckbox.tsx b/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/IndeterminateCheckbox.tsx
new file mode 100644
index 0000000000..55f1acc8c7
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/IndeterminateCheckbox.tsx
@@ -0,0 +1,27 @@
+import { Checkbox } from "@chakra-ui/react";
+
+type IndeterminateCheckboxProps = {
+ checked: boolean;
+ indeterminate: boolean;
+ [key: string]: any;
+};
+
+const IndeterminateCheckbox = ({
+ indeterminate,
+ checked,
+ ...rest
+}: IndeterminateCheckboxProps) => {
+ return (
+ <Checkbox
+ colorScheme="blackAlpha"
+ isChecked={checked}
+ isIndeterminate={indeterminate}
+ ml={2}
+ {...rest}
+ />
+ );
+};
+
+IndeterminateCheckbox.displayName = "IndeterminateCheckbox";
+
+export default IndeterminateCheckbox;
diff --git a/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/index.ts b/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/index.ts
new file mode 100644
index 0000000000..90fece7f0a
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/IndeterminateCheckbox/index.ts
@@ -0,0 +1,3 @@
+import IndeterminateCheckbox from "./IndeterminateCheckbox";
+
+export default IndeterminateCheckbox;
diff --git a/apps/carbon/app/components/Data/Table/components/Pagination.tsx b/apps/carbon/app/components/Data/Table/components/Pagination/Pagination.tsx
similarity index 97%
rename from apps/carbon/app/components/Data/Table/components/Pagination.tsx
rename to apps/carbon/app/components/Data/Table/components/Pagination/Pagination.tsx
index c4dcfe2597..7e05fecb51 100644
--- a/apps/carbon/app/components/Data/Table/components/Pagination.tsx
+++ b/apps/carbon/app/components/Data/Table/components/Pagination/Pagination.tsx
@@ -12,7 +12,7 @@ import {
} from "@chakra-ui/react";
import { BsChevronLeft, BsChevronRight } from "react-icons/bs";
-type PaginationProps = {
+export type PaginationProps = {
count: number;
offset: number;
pageIndex: number;
@@ -53,7 +53,7 @@ const Pagination = (props: PaginationProps) => {
>
<HStack spacing={2}>
<Menu>
- <MenuButton as={Button}>
+ <MenuButton as={Button} variant="ghost">
{pageSize} {pageSizeLabel}
</MenuButton>
<MenuList fontSize="sm" boxShadow="xl" minW={48}>
diff --git a/apps/carbon/app/components/Data/Table/components/Pagination/index.ts b/apps/carbon/app/components/Data/Table/components/Pagination/index.ts
new file mode 100644
index 0000000000..6b12b9ba4d
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Pagination/index.ts
@@ -0,0 +1,6 @@
+import Pagination, { PaginationButtons } from "./Pagination";
+import type { PaginationProps } from "./Pagination";
+import { usePagination } from "./usePagination";
+
+export { Pagination, PaginationButtons, usePagination };
+export type { PaginationProps };
diff --git a/apps/carbon/app/components/Data/Table/components/usePagination.tsx b/apps/carbon/app/components/Data/Table/components/Pagination/usePagination.tsx
similarity index 100%
rename from apps/carbon/app/components/Data/Table/components/usePagination.tsx
rename to apps/carbon/app/components/Data/Table/components/Pagination/usePagination.tsx
diff --git a/apps/carbon/app/components/Data/Table/components/Sort/Sort.tsx b/apps/carbon/app/components/Data/Table/components/Sort/Sort.tsx
new file mode 100644
index 0000000000..07311618cb
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Sort/Sort.tsx
@@ -0,0 +1,146 @@
+import {
+ Button,
+ IconButton,
+ HStack,
+ List,
+ ListItem,
+ Popover,
+ PopoverArrow,
+ PopoverBody,
+ PopoverContent,
+ PopoverFooter,
+ PopoverHeader,
+ PopoverTrigger,
+ Switch,
+ Text,
+ Menu,
+ MenuButton,
+ MenuList,
+ MenuItem,
+} from "@chakra-ui/react";
+import { Reorder } from "framer-motion";
+import { BsChevronDown, BsListUl } from "react-icons/bs";
+import { IoMdClose } from "react-icons/io";
+import { MdOutlineDragIndicator } from "react-icons/md";
+import { useSort } from "./useSort";
+
+type SortProps = {
+ columnAccessors: Record<string, string>;
+};
+
+const Sort = ({ columnAccessors }: SortProps) => {
+ const {
+ sorts,
+ removeSortBy,
+ reorderSorts,
+ toggleSortBy,
+ toggleSortByDirection,
+ } = useSort();
+
+ return (
+ <Popover placement="bottom">
+ <PopoverTrigger>
+ <Button
+ colorScheme={sorts.length === 0 ? undefined : "brand"}
+ variant={sorts.length === 0 ? "ghost" : "solid"}
+ leftIcon={<BsListUl />}
+ >
+ {sorts.length === 0 ? "Sort" : "Sorted"}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent w={420} boxShadow="xl">
+ {sorts.length === 0 && (
+ <PopoverHeader>
+ <Text fontSize="sm">No sorts applied to this view</Text>
+ <Text fontSize="xs" color="gray.500">
+ Add a column below to sort the view
+ </Text>
+ </PopoverHeader>
+ )}
+ <PopoverArrow />
+ {sorts.length > 0 && (
+ <PopoverBody>
+ <List
+ as={Reorder.Group}
+ axis="y"
+ values={sorts}
+ onReorder={reorderSorts}
+ spacing={2}
+ >
+ {sorts.map((sort) => {
+ const [column, direction] = sort.split(":");
+ return (
+ <ListItem
+ key={sort}
+ as={Reorder.Item}
+ value={sort}
+ rounded="lg"
+ >
+ <HStack>
+ <IconButton
+ aria-label="Drag handle"
+ icon={<MdOutlineDragIndicator />}
+ variant="ghost"
+ />
+ <Text fontSize="small" flexGrow={1}>
+ <>{columnAccessors[column] ?? ""}</>
+ </Text>
+ <Switch
+ colorScheme="blackAlpha"
+ isChecked={direction === "asc"}
+ onChange={() => toggleSortByDirection(column)}
+ />
+ <Text fontSize="xs" color="gray.500">
+ Ascending
+ </Text>
+ <IconButton
+ aria-label="Remove sort by column"
+ icon={<IoMdClose />}
+ onClick={() => removeSortBy(sort)}
+ variant="ghost"
+ />
+ </HStack>
+ </ListItem>
+ );
+ })}
+ </List>
+ </PopoverBody>
+ )}
+
+ <PopoverFooter>
+ <Menu isLazy>
+ <MenuButton
+ as={Button}
+ rightIcon={<BsChevronDown />}
+ colorScheme="gray"
+ variant="outline"
+ >
+ Pick a column to sort by
+ </MenuButton>
+ <MenuList fontSize="sm" boxShadow="xl">
+ {Object.keys(columnAccessors)
+ .filter((columnAccessor) => {
+ return !sorts
+ .map((sort) => sort.split(":")[0])
+ .includes(columnAccessor);
+ })
+ .map((columnAccessor) => {
+ return (
+ <MenuItem
+ key={columnAccessor}
+ onClick={() => toggleSortBy(columnAccessor)}
+ icon={<BsListUl />}
+ >
+ {columnAccessors[columnAccessor]}
+ </MenuItem>
+ );
+ })}
+ </MenuList>
+ </Menu>
+ </PopoverFooter>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export default Sort;
diff --git a/apps/carbon/app/components/Data/Table/components/Sort/index.ts b/apps/carbon/app/components/Data/Table/components/Sort/index.ts
new file mode 100644
index 0000000000..684f8ac27f
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Sort/index.ts
@@ -0,0 +1,5 @@
+import Sort from "./Sort";
+import { useSort } from "./useSort";
+
+export default Sort;
+export { useSort };
diff --git a/apps/carbon/app/components/Data/Table/components/Sort/useSort.tsx b/apps/carbon/app/components/Data/Table/components/Sort/useSort.tsx
new file mode 100644
index 0000000000..e136202cfc
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/components/Sort/useSort.tsx
@@ -0,0 +1,61 @@
+import { useUrlParams } from "~/hooks";
+
+export function useSort() {
+ const [params, setParams] = useUrlParams();
+ const sorts = params.getAll("sort");
+
+ const isSorted = (columnId: string): -1 | null | 1 => {
+ if (sorts.includes(`${columnId}:asc`)) return 1;
+ if (sorts.includes(`${columnId}:desc`)) return -1;
+ return null;
+ };
+
+ const reorderSorts = (newOrder: string[]) => {
+ setParams({ sort: newOrder });
+ };
+
+ const removeSortBy = (sort: string) => {
+ setParams({ sort: sorts.filter((s) => s !== sort) });
+ };
+
+ const toggleSortBy = (columnId: string) => {
+ const existingSort = [...sorts];
+ const sortAsc = `${columnId}:asc`;
+ const sortDesc = `${columnId}:desc`;
+
+ if (existingSort.includes(sortAsc)) {
+ setParams({
+ sort: existingSort.filter((s) => s !== sortAsc).concat(sortDesc),
+ });
+ } else if (existingSort.includes(sortDesc)) {
+ setParams({ sort: existingSort.filter((s) => s !== sortDesc) });
+ } else {
+ setParams({ sort: existingSort.concat(sortAsc) });
+ }
+ };
+
+ const toggleSortByDirection = (columnId: string) => {
+ const existingSort = [...sorts];
+ const sortAsc = `${columnId}:asc`;
+ const sortDesc = `${columnId}:desc`;
+
+ if (existingSort.includes(sortAsc)) {
+ setParams({
+ sort: existingSort.filter((s) => s !== sortAsc).concat(sortDesc),
+ });
+ } else if (existingSort.includes(sortDesc)) {
+ setParams({
+ sort: existingSort.filter((s) => s !== sortDesc).concat(sortAsc),
+ });
+ }
+ };
+
+ return {
+ sorts,
+ isSorted,
+ reorderSorts,
+ removeSortBy,
+ toggleSortBy,
+ toggleSortByDirection,
+ };
+}
diff --git a/apps/carbon/app/components/Data/Table/components/index.ts b/apps/carbon/app/components/Data/Table/components/index.ts
index 512fae3a98..f19bbb0f51 100644
--- a/apps/carbon/app/components/Data/Table/components/index.ts
+++ b/apps/carbon/app/components/Data/Table/components/index.ts
@@ -1,4 +1,6 @@
-import Pagination, { PaginationButtons } from "./Pagination";
-import { usePagination } from "./usePagination";
+import Header from "./Header";
+import IndeterminateCheckbox from "./IndeterminateCheckbox";
+import { Pagination, usePagination } from "./Pagination";
+import { useSort } from "./Sort";
-export { Pagination, PaginationButtons, usePagination };
+export { Header, IndeterminateCheckbox, Pagination, usePagination, useSort };
diff --git a/apps/carbon/app/components/Data/Table/types.ts b/apps/carbon/app/components/Data/Table/types.ts
new file mode 100644
index 0000000000..473bbe3da2
--- /dev/null
+++ b/apps/carbon/app/components/Data/Table/types.ts
@@ -0,0 +1,6 @@
+export interface TableAction<T> {
+ label: string;
+ onClick: (rows: T[]) => void;
+ disabled?: boolean;
+ icon?: JSX.Element;
+}
diff --git a/apps/carbon/app/components/Selectors/UserSelect/types.ts b/apps/carbon/app/components/Selectors/UserSelect/types.ts
index 0847a8856b..4d8ae82a36 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/types.ts
+++ b/apps/carbon/app/components/Selectors/UserSelect/types.ts
@@ -33,7 +33,7 @@ export interface UserSelectProps {
label?: string;
placeholder?: string;
showAvatars?: boolean;
- queryFilters?: UserSelectionQueryFilters;
+ queryFilters?: UserSelectionGenericQueryFilters;
readOnly?: boolean;
renderInput?: ReactNode;
resetAfterSelection?: boolean;
@@ -124,7 +124,7 @@ export interface UserTreeSelectProps {
visible?: boolean;
}
-export interface UserSelectionQueryFilters {
+export interface UserSelectionGenericQueryFilters {
excludeSelf?: boolean;
onlyEmployeeTypes?: string[];
allowedIds?: string[];
diff --git a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts
index 90938e4eae..706d432587 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts
+++ b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts
@@ -11,7 +11,7 @@ import type {
OptionGroup,
SelectionItemsById,
SelectionItemInterface,
- UserSelectionQueryFilters,
+ UserSelectionGenericQueryFilters,
UserSelectProps,
TreeNode,
} from "./types";
@@ -25,7 +25,7 @@ const defaultProps = {
innerInputRender: null,
isMulti: false,
placeholder: "",
- queryFilters: {} as UserSelectionQueryFilters,
+ queryFilters: {} as UserSelectionGenericQueryFilters,
readOnly: false,
resetAfterSelection: false,
selections: [] as SelectionItemInterface[],
diff --git a/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx
index e68ee9b6bd..60dce82c1e 100644
--- a/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx
+++ b/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx
@@ -15,27 +15,41 @@ type EmployeesTableProps = {
withSelectableRows?: boolean;
};
+const defaultColumnVisibility = {
+ user_firstName: false,
+ user_lastName: false,
+};
+
const EmployeesTable = memo(
({ data, count, withSelectableRows = false }: EmployeesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const rows = data.map((d) => {
- // we should only have one user and employee per employee id
- if (
- d.user === null ||
- d.employeeType === null ||
- Array.isArray(d.user) ||
- Array.isArray(d.employeeType)
- ) {
- throw new Error("Expected user and employee type to be objects");
- }
+ const rows = useMemo(
+ () =>
+ data.map((d) => {
+ // we should only have one user and employee per employee id
+ if (
+ d.user === null ||
+ d.employeeType === null ||
+ Array.isArray(d.user) ||
+ Array.isArray(d.employeeType)
+ ) {
+ throw new Error("Expected user and employee type to be objects");
+ }
- return d;
- });
+ return d;
+ }),
+ [data]
+ );
const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
return [
+ {
+ accessorKey: "user.fullName",
+ header: "Full Name",
+ cell: (item) => item.getValue(),
+ },
{
accessorKey: "user.firstName",
header: "First Name",
@@ -108,8 +122,9 @@ const EmployeesTable = memo(
<Table<typeof rows[number]>
actions={actions}
count={count}
- data={rows}
columns={columns}
+ data={rows}
+ defaultColumnVisibility={defaultColumnVisibility}
withColumnOrdering
withPagination
withSelectableRows={withSelectableRows}
diff --git a/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx b/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx
index 27455ffa7f..053fda0002 100644
--- a/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx
+++ b/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx
@@ -43,8 +43,8 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {
cell: (item) => item.getValue(),
},
{
- accessorKey: "members",
header: "Members",
+ // accessorKey: undefined, // makes the column unsortable
cell: ({ row }) => (
<AvatarGroup max={5} size="sm" spacing={-2}>
{row.original.members.map((name: string, index: number) => (
diff --git a/apps/carbon/app/modules/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx b/apps/carbon/app/modules/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
index 99873f35b6..b89bdb83ff 100644
--- a/apps/carbon/app/modules/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
+++ b/apps/carbon/app/modules/Users/Groups/GroupsTableFilters/GroupsTableFilters.tsx
@@ -10,12 +10,13 @@ const GroupsTableFilters = () => {
const borderColor = useColor("gray.200");
return (
<HStack
- px={4}
- py={3}
- justifyContent="space-between"
borderBottomColor={borderColor}
borderBottomStyle="solid"
borderBottomWidth={1}
+ justifyContent="space-between"
+ px={4}
+ py={3}
+ w="full"
>
<HStack spacing={2}>
<DebouncedInput
diff --git a/apps/carbon/app/routes/app.users.employee-types.tsx b/apps/carbon/app/routes/app.users.employee-types.tsx
index 961282cda7..53cf4b31ce 100644
--- a/apps/carbon/app/routes/app.users.employee-types.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.tsx
@@ -7,7 +7,7 @@ import {
} from "~/modules/Users/EmployeeTypes";
import { requirePermissions } from "~/services/auth";
import { getEmployeeTypes } from "~/services/users";
-import { getQueryFilters } from "~/utils/http";
+import { getGenericQueryFilters } from "~/utils/query";
export async function loader({ request }: LoaderArgs) {
const { client } = await requirePermissions(request, {
@@ -17,9 +17,9 @@ export async function loader({ request }: LoaderArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const name = searchParams.get("name");
- const { limit, offset } = getQueryFilters(searchParams);
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
- return json(await getEmployeeTypes(client, { name, limit, offset }));
+ return json(await getEmployeeTypes(client, { name, limit, offset, sorts }));
}
export default function EmployeeTypesRoute() {
diff --git a/apps/carbon/app/routes/app.users.employees.tsx b/apps/carbon/app/routes/app.users.employees.tsx
index 856e1cf8cb..0d6ea8f3b0 100644
--- a/apps/carbon/app/routes/app.users.employees.tsx
+++ b/apps/carbon/app/routes/app.users.employees.tsx
@@ -8,7 +8,7 @@ import {
} from "~/modules/Users/Employees";
import { requirePermissions } from "~/services/auth";
import { getEmployees, getEmployeeTypes } from "~/services/users";
-import { getQueryFilters } from "~/utils/http";
+import { getGenericQueryFilters } from "~/utils/query";
export async function loader({ request }: LoaderArgs) {
const { client } = await requirePermissions(request, {
@@ -19,10 +19,11 @@ export async function loader({ request }: LoaderArgs) {
const searchParams = new URLSearchParams(url.search);
const name = searchParams.get("name");
const type = searchParams.get("type");
- const { limit, offset, sorts } = getQueryFilters(searchParams);
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
const [employees, employeeTypes] = await Promise.all([
- getEmployees(client, { name, type, limit, offset, sorts }),
+ getEmployees(client, { name, type, limit, offset, sorts, filters }),
getEmployeeTypes(client),
]);
diff --git a/apps/carbon/app/routes/app.users.groups.tsx b/apps/carbon/app/routes/app.users.groups.tsx
index d5e3856e9e..51530f4d1b 100644
--- a/apps/carbon/app/routes/app.users.groups.tsx
+++ b/apps/carbon/app/routes/app.users.groups.tsx
@@ -7,7 +7,7 @@ import type { Group } from "~/modules/Users/types";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { getGroups } from "~/services/users";
-import { getQueryFilters } from "~/utils/http";
+import { getGenericQueryFilters } from "~/utils/query";
import { error } from "~/utils/result";
export async function loader({ request }: LoaderArgs) {
@@ -19,9 +19,9 @@ export async function loader({ request }: LoaderArgs) {
const searchParams = new URLSearchParams(url.search);
const name = searchParams.get("name");
const uid = searchParams.get("uid");
- const { limit, offset } = getQueryFilters(searchParams);
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
- const groups = await getGroups(client, { name, uid, limit, offset });
+ const groups = await getGroups(client, { name, uid, limit, offset, sorts });
if (groups.error) {
return json(
diff --git a/apps/carbon/app/services/users/users.server.ts b/apps/carbon/app/services/users/users.server.ts
index 1e3ff6354e..d28bda973b 100644
--- a/apps/carbon/app/services/users/users.server.ts
+++ b/apps/carbon/app/services/users/users.server.ts
@@ -13,8 +13,8 @@ import type {
import { deleteAuthAccount, sendInviteByEmail } from "~/services/auth";
import { requireAuthSession, flash } from "~/services/session";
import type { Result } from "~/types";
-import type { PaginationParams } from "~/utils/http";
-import { setQueryFilters } from "~/utils/http";
+import type { GenericQueryFilters } from "~/utils/query";
+import { setGenericQueryFilters } from "~/utils/query";
import { error, success } from "~/utils/result";
export async function createEmployeeAccount(
@@ -141,7 +141,7 @@ export async function getEmployeeById(
export async function getEmployees(
client: SupabaseClient<Database>,
- args: PaginationParams & {
+ args: GenericQueryFilters & {
name: string | null;
type: string | null;
}
@@ -149,7 +149,7 @@ export async function getEmployees(
let query = client
.from("employee")
.select(
- "user!inner(id, firstName, lastName, email), employeeType!inner(name)",
+ "user!inner(id, fullName, firstName, lastName, email), employeeType!inner(name)",
{ count: "exact" }
);
@@ -161,7 +161,7 @@ export async function getEmployees(
query = query.eq("employeeTypeId", args.type);
}
- query = setQueryFilters(query, args, "user(lastName)");
+ query = setGenericQueryFilters(query, args, "user(lastName)");
return query;
}
@@ -178,7 +178,7 @@ export async function getEmployeeType(
export async function getEmployeeTypes(
client: SupabaseClient<Database>,
- args?: PaginationParams & { name: string | null }
+ args?: GenericQueryFilters & { name: string | null }
) {
let query = client
.from("employeeType")
@@ -189,7 +189,7 @@ export async function getEmployeeTypes(
}
if (args) {
- query = setQueryFilters(query, args, "name");
+ query = setGenericQueryFilters(query, args, "name");
}
return query;
@@ -211,19 +211,19 @@ export async function getGroupMembersById(
export async function getGroups(
client: SupabaseClient<Database>,
- args?: {
+ args?: GenericQueryFilters & {
name: string | null;
- limit: number;
- offset: number;
uid: string | null;
}
) {
- return client.rpc("groups_query", {
- _limit: args?.limit ?? 15,
- _offset: args?.offset ?? 0,
+ let query = client.rpc("groups_query", {
+ _uid: args?.uid ?? "",
_name: args?.name ?? "",
- uid: args?.uid ?? "",
});
+
+ if (args) query = setGenericQueryFilters(query, args);
+
+ return query;
}
export async function getPermissionsByEmployeeType(
diff --git a/apps/carbon/app/utils/http.ts b/apps/carbon/app/utils/http.ts
index 0eaaca8595..31cf945c96 100644
--- a/apps/carbon/app/utils/http.ts
+++ b/apps/carbon/app/utils/http.ts
@@ -1,6 +1,3 @@
-import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";
-import type { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types";
-
export function getCurrentPath(request: Request) {
return new URL(request.url).pathname;
}
@@ -34,7 +31,7 @@ function notAllowedMethod(message: string) {
return new Response(message, { status: 405 });
}
-function badRequest(message: string) {
+export function badRequest(message: string) {
return new Response(message, { status: 400 });
}
@@ -106,67 +103,3 @@ export function parseNumberFromUrlParam(
return parsed;
}
-
-export type Sort = {
- sortBy: string;
- sortAsc: boolean;
-};
-
-export interface PaginationParams {
- limit: number;
- offset: number;
- sorts?: Sort[];
-}
-
-export function getQueryFilters(params: URLSearchParams): PaginationParams {
- const limit = parseNumberFromUrlParam(params, "limit", 15);
- const offset = parseNumberFromUrlParam(params, "offset", 0);
-
- const sortParams = params.getAll("sort");
- const sorts: Sort[] =
- sortParams.length > 0
- ? (sortParams
- .map((sort) => {
- const [sortBy, sortDirection] = sort.split(":");
- if (
- !sortBy ||
- !sortDirection ||
- !["asc", "desc"].includes(sortDirection)
- )
- return undefined;
- return { sortBy, sortAsc: sortDirection === "asc" };
- })
- .filter((sort) => sort !== undefined) as Sort[])
- : [];
-
- return { limit, offset, sorts };
-}
-
-export function setQueryFilters<
- T extends GenericSchema,
- U extends Record<string, unknown>,
- V
->(
- query: PostgrestFilterBuilder<T, U, V>,
- args: PaginationParams,
- defaultSort?: string
-): PostgrestFilterBuilder<T, U, V> {
- if (args.sorts && args.sorts.length > 0) {
- args.sorts.forEach((sort) => {
- if (sort.sortBy.includes(".")) {
- const [table, column] = sort.sortBy.split(".");
- query = query.order(`${table}(${column})`, {
- ascending: sort.sortAsc,
- });
- } else {
- query = query.order(sort.sortBy, { ascending: sort.sortAsc });
- }
- });
- } else if (defaultSort) {
- query = query.order(defaultSort, {
- ascending: true,
- });
- }
-
- return query.range(args.offset, args.offset + args.limit - 1);
-}
diff --git a/apps/carbon/app/utils/query.ts b/apps/carbon/app/utils/query.ts
new file mode 100644
index 0000000000..c12bac48a1
--- /dev/null
+++ b/apps/carbon/app/utils/query.ts
@@ -0,0 +1,153 @@
+import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";
+import type { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types";
+import { badRequest, parseNumberFromUrlParam } from "./http";
+
+export type Sort = {
+ sortBy: string;
+ sortAsc: boolean;
+};
+
+export type Filter = {
+ column: string;
+ operator: string;
+ value?: string;
+};
+
+export interface GenericQueryFilters {
+ limit: number;
+ offset: number;
+ sorts?: Sort[];
+ filters?: Filter[];
+}
+
+export function getGenericQueryFilters(
+ params: URLSearchParams
+): GenericQueryFilters {
+ const limit = parseNumberFromUrlParam(params, "limit", 15);
+ const offset = parseNumberFromUrlParam(params, "offset", 0);
+
+ const sortParams = params.getAll("sort");
+ const sorts: Sort[] =
+ sortParams.length > 0
+ ? (sortParams
+ .map((sort) => {
+ const [sortBy, sortDirection] = sort.split(":");
+ if (
+ !sortBy ||
+ !sortDirection ||
+ !["asc", "desc"].includes(sortDirection)
+ )
+ return undefined;
+ return { sortBy, sortAsc: sortDirection === "asc" };
+ })
+ .filter((sort) => sort !== undefined) as Sort[])
+ : [];
+
+ const filterParams = params.getAll("filter");
+ const filters: Filter[] =
+ filterParams.length > 0
+ ? (filterParams
+ .map((filter) => {
+ const [column, operator, value] = filter.split(":");
+ if (!column || !operator || !value) return undefined;
+ return { column, operator, value };
+ })
+ .filter((filter) => filter !== undefined) as Filter[])
+ : [];
+
+ return { limit, offset, sorts, filters };
+}
+
+export function getGenericFilter<
+ T extends GenericSchema,
+ U extends Record<string, unknown>,
+ V
+>(
+ query: PostgrestFilterBuilder<T, U, V>,
+ column: string,
+ operator: string,
+ value: string
+) {
+ switch (operator) {
+ case "eq":
+ return query.eq(column, value);
+ case "neq":
+ return query.neq(column, value);
+ case "gt":
+ return query.gt(column, getSafeNumber(value));
+ case "gte":
+ return query.gte(column, getSafeNumber(value));
+ case "lt":
+ return query.lt(column, getSafeNumber(value));
+ case "lte":
+ return query.lte(column, getSafeNumber(value));
+ case "contains":
+ return query.ilike(column, `%${value}%`);
+ case "startsWith":
+ return query.ilike(column, `${value}%`);
+ default:
+ throw badRequest(`Invalid filter operator: ${operator}`);
+ }
+}
+
+export function setGenericQueryFilters<
+ T extends GenericSchema,
+ U extends Record<string, unknown>,
+ V
+>(
+ query: PostgrestFilterBuilder<T, U, V>,
+ args: GenericQueryFilters,
+ defaultSort?: string
+): PostgrestFilterBuilder<T, U, V> {
+ args.filters?.forEach((filter) => {
+ if (!filter.value) return;
+ query = getGenericFilter(
+ query,
+ filter.column,
+ filter.operator,
+ filter.value
+ );
+ });
+
+ if (args.sorts && args.sorts.length > 0) {
+ args.sorts.forEach((sort) => {
+ if (sort.sortBy.includes(".")) {
+ const [table, column] = sort.sortBy.split(".");
+ query = query.order(`${table}(${column})`, {
+ ascending: sort.sortAsc,
+ });
+ } else {
+ query = query.order(sort.sortBy, { ascending: sort.sortAsc });
+ }
+ });
+ } else if (defaultSort) {
+ query = query.order(defaultSort, {
+ ascending: true,
+ });
+ }
+
+ return query.range(args.offset, args.offset + args.limit - 1);
+}
+
+const getSafeNumber = (value: string) => {
+ const number = Number(value);
+ return Number.isNaN(number) ? value : number;
+};
+
+const filterOperators = {
+ eq: "equals",
+ neq: "not equals",
+ gt: "greater than",
+ gte: "greater than or equal to",
+ lt: "less than",
+ lte: "less than or equal to",
+ contains: "contains",
+ startsWith: "starts with",
+};
+
+export const filterOperatorLabels = Object.entries(filterOperators).map(
+ ([key, value]) => ({
+ operator: key,
+ label: value,
+ })
+);
diff --git a/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql b/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
index 55ef9186e7..b2d0af5f77 100644
--- a/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
+++ b/packages/carbon-database/prisma/migrations/20221208201232_groups/migration.sql
@@ -209,10 +209,8 @@ CREATE VIEW groups_view AS
CREATE OR REPLACE FUNCTION groups_query(
- _limit INTEGER DEFAULT 15,
- _offset INTEGER DEFAULT 0,
_name TEXT DEFAULT '',
- uid TEXT DEFAULT NULL
+ _uid TEXT DEFAULT NULL
)
RETURNS TABLE (
"id" TEXT,
@@ -228,9 +226,7 @@ AS $$
SELECT g."id"
FROM "group" g
WHERE g."isIdentityGroup" = false
- AND g."name" ILIKE '%' || _name || '%'
- LIMIT _limit
- OFFSET _offset
+ AND g."name" ILIKE '%' || _name || '%'
)
SELECT
g."id",
@@ -244,7 +240,6 @@ AS $$
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 $$
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index a0d6a09350..af454aa5b8 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -271,7 +271,7 @@ export interface Database {
Returns: Json
}
groups_query: {
- Args: { _limit: number; _offset: number; _name: string; uid: string }
+ Args: { _name: string; _uid: string }
Returns: {
id: string
name: string