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: edit views

Brad Barbin4ade1c18fc55
diff --git a/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index 1b4067607b..6d40709fd4 100644
--- a/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -20,7 +20,7 @@ import {
LuEllipsisVertical,
LuGripVertical,
} from "react-icons/lu";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { path } from "~/utils/path";
import { ConfirmDelete } from "~/components/Modals";
@@ -78,11 +78,7 @@ const GroupedContentSidebar = ({
const isActive = exactMatch
? location.pathname === route.to
: location.pathname.includes(route.to) &&
- !route.views?.some((subRoute) =>
- `${location.pathname}${location.search}`.includes(
- subRoute.to
- )
- );
+ !`${location.pathname}${location.search}`.includes("view=");
const hasViews = route.views && route.views.length > 0;
const isExpanded = expandedViews[route.name];
@@ -191,6 +187,16 @@ const ViewsReorderGroup = ({
return [];
});
+ const viewNames = views
+ .map((view) => view.name)
+ .sort()
+ .join(",");
+
+ useEffect(() => {
+ setSortedViews([...views].sort((a, b) => a.sortOrder - b.sortOrder));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [views.length, viewNames]);
+
const debouncedOnReorder = useDebounce(onReorder, 500, true);
return (
@@ -210,7 +216,7 @@ const ViewsReorderGroup = ({
>
{sortedViews.map((view) => {
const isViewActive = `${location.pathname}${location.search}`.includes(
- view.to
+ `view=${view.id}`
);
return (
<Reorder.Item key={view.to} value={view} className="w-full">
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index b92f15f99b..9e90adf4e2 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -44,7 +44,7 @@ import type {
EditableTableCellComponent,
Position,
} from "~/components/Editable";
-import type { fieldMappings, SavedView } from "~/modules/shared";
+import type { fieldMappings } from "~/modules/shared";
import {
IndeterminateCheckbox,
Pagination,
@@ -57,6 +57,7 @@ import type { ColumnFilter } from "./components/Filter/types";
import { useFilters } from "./components/Filter/useFilters";
import type { ColumnSizeMap } from "./types";
import { getAccessorKey, updateNestedProperty } from "./utils";
+import { useSavedViews } from "~/hooks/useSavedViews";
interface TableProps<T extends object> {
columns: ColumnDef<T>[];
@@ -110,7 +111,7 @@ const Table = <T extends object>({
}: TableProps<T>) => {
const tableContainerRef = useRef<HTMLDivElement>(null);
- const savedView = useSavedView();
+ const { currentView, view } = useSavedViews();
/* Data for Optimistic Updates */
const [internalData, setInternalData] = useState<T[]>(data);
@@ -126,12 +127,12 @@ const Table = <T extends object>({
/* Column Visibility */
const [columnVisibility, setColumnVisibility] = useState(
- savedView?.columnVisibility ?? defaultColumnVisibility ?? {}
+ currentView?.columnVisibility ?? defaultColumnVisibility ?? {}
);
/* Column Ordering */
const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(
- savedView?.columnOrder ?? defaultColumnOrder ?? []
+ currentView?.columnOrder ?? defaultColumnOrder ?? []
);
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(() => {
const left: string[] = [];
@@ -142,8 +143,8 @@ const Table = <T extends object>({
if (renderContextMenu) {
right.push("Actions");
}
- if (savedView?.columnPinning) {
- return savedView.columnPinning;
+ if (currentView?.columnPinning) {
+ return currentView.columnPinning;
}
if (
defaultColumnPinning &&
@@ -159,6 +160,41 @@ const Table = <T extends object>({
};
});
+ useEffect(() => {
+ if (currentView) {
+ setColumnVisibility(currentView.columnVisibility);
+ setColumnOrder(currentView.columnOrder);
+ setColumnPinning(currentView.columnPinning);
+ } else {
+ setColumnVisibility(defaultColumnVisibility ?? {});
+ setColumnOrder(defaultColumnOrder ?? []);
+ setColumnPinning(() => {
+ const left: string[] = [];
+ const right: string[] = [];
+ if (withSelectableRows) {
+ left.push("Select");
+ }
+ if (renderContextMenu) {
+ right.push("Actions");
+ }
+
+ if (
+ defaultColumnPinning &&
+ "left" in defaultColumnPinning &&
+ Array.isArray(defaultColumnPinning.left)
+ ) {
+ left.push(...defaultColumnPinning.left);
+ }
+
+ return {
+ left,
+ right,
+ };
+ });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [view]);
+
/* Sorting */
const { isSorted, toggleSortByAscending, toggleSortByDescending } = useSort();
@@ -595,6 +631,7 @@ const Table = <T extends object>({
return (
<VStack
+ key={view ?? tableName ?? ""}
spacing={0}
className={cn(
"h-full bg-card",
@@ -904,8 +941,4 @@ function getActionColumn<T>(
];
}
-function useSavedView(): SavedView | undefined {
- return undefined;
-}
-
export default Table;
diff --git a/apps/erp/app/components/Table/components/Sort/Sort.tsx b/apps/erp/app/components/Table/components/Sort/Sort.tsx
index 956e632314..cb85f09348 100644
--- a/apps/erp/app/components/Table/components/Sort/Sort.tsx
+++ b/apps/erp/app/components/Table/components/Sort/Sort.tsx
@@ -46,7 +46,7 @@ const Sort = ({ columnAccessors }: SortProps) => {
<IconButton
aria-label="Sort"
title="Sort"
- variant={hasNoSorts ? "ghost" : "secondary"}
+ variant={hasNoSorts ? "ghost" : "active"}
icon={<LuArrowUpDown />}
className={cn(hasNoSorts && "!border-dashed border-border")}
/>
diff --git a/apps/erp/app/components/Table/components/TableHeader.tsx b/apps/erp/app/components/Table/components/TableHeader.tsx
index 9eb9c16f95..f579f5a5a4 100644
--- a/apps/erp/app/components/Table/components/TableHeader.tsx
+++ b/apps/erp/app/components/Table/components/TableHeader.tsx
@@ -45,6 +45,7 @@ import type { ColumnFilter } from "./Filter/types";
import type { PaginationProps } from "./Pagination";
import { PaginationButtons } from "./Pagination";
import Sort from "./Sort";
+import { useSavedViews } from "~/hooks/useSavedViews";
type HeaderProps<T> = {
renderActions?: (selectedRows: T[]) => ReactNode;
@@ -98,7 +99,7 @@ const TableHeader = <T extends object>({
withSearch,
withSelectableRows,
}: HeaderProps<T>) => {
- const [params] = useUrlParams();
+ const [params, setParams] = useUrlParams();
const currentFilters = params.getAll("filter").filter(Boolean);
const currentSorts = params.getAll("sort").filter(Boolean);
@@ -112,7 +113,8 @@ const TableHeader = <T extends object>({
const fetcher = useFetcher<typeof savedViewAction>();
useEffect(() => {
- if (fetcher.data?.success) {
+ if (fetcher.data?.success && fetcher.data.id) {
+ setParams({ view: fetcher.data.id });
savedViewDisclosure.onClose();
} else if (fetcher.data?.success === false) {
toast.error(fetcher.data.message);
@@ -120,6 +122,10 @@ const TableHeader = <T extends object>({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetcher.state, fetcher.data?.success]);
+ const { currentView, hasView } = useSavedViews();
+ const viewTitle = currentView?.name ?? title;
+ // const viewDescription = currentView?.description ?? "";
+
return (
<div className={cn("w-full flex flex-col", !compact && "mb-8")}>
{canSaveView && savedViewDisclosure.isOpen ? (
@@ -129,9 +135,11 @@ const TableHeader = <T extends object>({
validator={savedViewValidator}
resetAfterSubmit
className="w-full px-2 md:px-0"
+ defaultValues={currentView ?? {}}
fetcher={fetcher}
>
<Card className="my-4 p-0">
+ <Hidden name="id" value={currentView?.id} />
<Hidden
name="state"
value={JSON.stringify({
@@ -163,7 +171,7 @@ const TableHeader = <T extends object>({
<Button variant="secondary" onClick={savedViewDisclosure.onClose}>
Cancel
</Button>
- <Submit>Save</Submit>
+ <Submit>{hasView ? "Update" : "Save"}</Submit>
</CardFooter>
</Card>
</ValidatedForm>
@@ -177,7 +185,9 @@ const TableHeader = <T extends object>({
>
<HStack spacing={1}>
<CollapsibleSidebarTrigger />
- {title && <Heading size={compact ? "h3" : "h2"}>{title}</Heading>}
+ {viewTitle && (
+ <Heading size={compact ? "h3" : "h2"}>{viewTitle}</Heading>
+ )}
</HStack>
<HStack>
@@ -260,13 +270,15 @@ const TableHeader = <T extends object>({
<TooltipTrigger asChild>
<IconButton
aria-label="Save View"
- variant={savedViewDisclosure.isOpen ? "active" : "ghost"}
+ variant={
+ savedViewDisclosure.isOpen || hasView ? "active" : "ghost"
+ }
icon={<LuLayers />}
onClick={savedViewDisclosure.onToggle}
/>
</TooltipTrigger>
<TooltipContent>
- <p>Save View</p>
+ <p>{hasView ? "Edit View" : "Save View"}</p>
</TooltipContent>
</Tooltip>
)}
diff --git a/apps/erp/app/components/Table/components/Views/useSavedView.tsx b/apps/erp/app/components/Table/components/Views/useSavedView.tsx
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/apps/erp/app/hooks/useSavedViews.tsx b/apps/erp/app/hooks/useSavedViews.tsx
index 5827e71cad..117b82748b 100644
--- a/apps/erp/app/hooks/useSavedViews.tsx
+++ b/apps/erp/app/hooks/useSavedViews.tsx
@@ -1,12 +1,18 @@
-import { useRouteData } from "@carbon/remix";
+import { useRouteData, useUrlParams } from "@carbon/remix";
import { path } from "~/utils/path";
import type { SavedView } from "~/modules/shared/types";
type SavedViews = SavedView[];
export function useSavedViews(): {
+ currentView: SavedView | null;
+ hasView: boolean;
savedViews: SavedViews;
+ view: string | null;
} {
+ const [params] = useUrlParams();
+ const view = params.get("view");
+
const data = useRouteData<{
savedViews: unknown;
}>(path.to.authenticatedRoot);
@@ -14,8 +20,13 @@ export function useSavedViews(): {
const savedViews =
data?.savedViews && isSavedViews(data.savedViews) ? data.savedViews : [];
+ const currentView = savedViews.find((v) => v.id === view) ?? null;
+
return {
+ currentView,
+ hasView: currentView !== null,
savedViews,
+ view,
};
}
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 01d8fc74b6..8f4fef2aa4 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -279,7 +279,9 @@ export async function upsertSavedView(
...data,
updatedBy: userId,
})
- .eq("id", view.id);
+ .eq("id", view.id)
+ .select("id")
+ .single();
}
const { data: maxSortOrderData, error: maxSortOrderError } = await client
@@ -295,11 +297,15 @@ export async function upsertSavedView(
const newSortOrder = maxSortOrderData ? maxSortOrderData.sortOrder + 1 : 1;
- return client.from("tableView").insert({
- ...data,
- createdBy: userId,
- sortOrder: newSortOrder,
- });
+ return client
+ .from("tableView")
+ .insert({
+ ...data,
+ createdBy: userId,
+ sortOrder: newSortOrder,
+ })
+ .select("id")
+ .single();
}
export async function updateSavedViewOrder(
diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.ts
index 270827831c..130f83c280 100644
--- a/apps/erp/app/modules/shared/types.ts
+++ b/apps/erp/app/modules/shared/types.ts
@@ -67,6 +67,7 @@ export type SavedView = {
columnPinning: ColumnPinningState;
columnVisibility: Record<string, boolean>;
name: string;
+ description?: string;
sortOrder: number;
sorts: string[];
filters: string[];
diff --git a/apps/erp/app/routes/x+/shared+/views.tsx b/apps/erp/app/routes/x+/shared+/views.tsx
index e2e07f1a49..d0d24a3d61 100644
--- a/apps/erp/app/routes/x+/shared+/views.tsx
+++ b/apps/erp/app/routes/x+/shared+/views.tsx
@@ -19,6 +19,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (validation.error) {
return json({
success: false,
+ id: null,
message: "Invalid form data",
});
}
@@ -40,17 +41,28 @@ export async function action({ request }: ActionFunctionArgs) {
console.error(result.error);
return json({
success: false,
+ id: null,
message: result.error.message,
});
}
+ if (data.id) {
+ return json({
+ success: true,
+ id: data.id,
+ message: "View updated",
+ });
+ }
+
return json({
success: true,
+ id: result.data.id,
message: "View saved",
});
} catch (error) {
return json({
success: false,
+ id: null,
message: "Invalid state",
});
}