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: drag and drop for configuration parameters

Brad Barbin858cfacafbc3
diff --git a/apps/carbon/app/hooks/useFlags.tsx b/apps/carbon/app/hooks/useFlags.tsx
new file mode 100644
index 0000000000..ba1862587c
--- /dev/null
+++ b/apps/carbon/app/hooks/useFlags.tsx
@@ -0,0 +1,12 @@
+import { useUser } from "./useUser";
+
+export function useFlags() {
+ const user = useUser();
+ const isInternal = ["carbon.us.org", "carbonos.dev"].some((email) =>
+ user.email.includes(email)
+ );
+
+ return {
+ isInternal,
+ };
+}
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index 7a3952f07c..dccf465d96 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -74,6 +74,12 @@ export const itemValidator = z.object({
active: zfd.checkbox(),
});
+export const configurationParameterOrderValidator = z.object({
+ id: z.string().min(1, { message: "ID is required" }),
+ sortOrder: zfd.numeric(z.number().min(0)),
+ configurationParameterGroupId: zfd.text(z.string().nullable()),
+});
+
export const configurationParameterValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 8e43b61d8c..a784de8bf8 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -8,6 +8,7 @@ import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type { operationToolValidator } from "../shared";
import type {
+ configurationParameterOrderValidator,
configurationParameterValidator,
consumableValidator,
customerPartValidator,
@@ -1008,6 +1009,22 @@ export async function getUnitOfMeasuresList(
.order("name");
}
+export async function updateConfigurationParameterOrder(
+ client: SupabaseClient<Database>,
+ data: Omit<
+ z.infer<typeof configurationParameterOrderValidator>,
+ "configurationParameterGroupId"
+ > & {
+ configurationParameterGroupId?: string | null;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("configurationParameter")
+ .update(sanitize(data))
+ .eq("id", data.id);
+}
+
export async function updateItemCost(
client: SupabaseClient<Database>,
itemId: string,
@@ -1078,6 +1095,7 @@ export async function upsertConfigurationParameter(
return client.from("configurationParameter").insert({
...data,
+ key: data.key ?? "",
createdBy: userId,
configurationParameterGroupId: data.configurationParameterGroupId,
});
diff --git a/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx b/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx
new file mode 100644
index 0000000000..82c4eb6279
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx
@@ -0,0 +1,1013 @@
+import {
+ Array as ArrayInput,
+ Hidden,
+ Input,
+ Select,
+ Submit,
+ ValidatedForm,
+} from "@carbon/form";
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ ClientOnly,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ toast,
+ useDisclosure,
+ VStack,
+} from "@carbon/react";
+import {
+ useFetcher,
+ useFetchers,
+ useParams,
+ useSubmit,
+} from "@remix-run/react";
+import { cva } from "class-variance-authority";
+import { useEffect, useRef, useState } from "react";
+import {
+ LuGripVertical,
+ LuHash,
+ LuKeySquare,
+ LuList,
+ LuMoreVertical,
+ LuPlusCircle,
+ LuToggleLeft,
+ LuType,
+} from "react-icons/lu";
+import { EmployeeAvatar } from "~/components";
+import type { ConfigurationParameter } from "~/modules/items";
+import {
+ configurationParameterDataTypes,
+ configurationParameterValidator,
+} from "~/modules/items";
+import type { action as configurationParameterAction } from "~/routes/x+/part+/$itemId.parameter";
+import { path } from "~/utils/path";
+import { capitalize } from "~/utils/string";
+
+import { formatRelativeTime } from "@carbon/utils";
+import type {
+ Active,
+ DataRef,
+ DragEndEvent,
+ DragOverEvent,
+ DragStartEvent,
+ DroppableContainer,
+ KeyboardCoordinateGetter,
+ Over,
+} from "@dnd-kit/core";
+import {
+ closestCorners,
+ DndContext,
+ DragOverlay,
+ getFirstCollision,
+ KeyboardCode,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { createPortal } from "react-dom";
+import { ConfirmDelete } from "~/components/Modals";
+
+function useConfigurationParameters(parameter?: ConfigurationParameter) {
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const [key, setKey] = useState(parameter?.key ?? "");
+ const [isList, setIsList] = useState(parameter?.dataType === "list");
+
+ const onChangeCheckForListType = (
+ newValue: {
+ value: string;
+ label: string | JSX.Element;
+ } | null
+ ) => {
+ if (!newValue) return;
+ const type = newValue.value;
+ setIsList(type === "list");
+ };
+
+ const updateKey = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const label = e.target.value;
+ setKey(label.toLowerCase().replace(/ /g, "_"));
+ };
+
+ return {
+ key,
+ isList,
+ itemId,
+ onChangeCheckForListType,
+ setKey,
+ setIsList,
+ updateKey,
+ };
+}
+
+type ConfigurationParameterGroup = {
+ id: string;
+ name: string;
+};
+
+export default function ConfigurationParametersForm({
+ parameters: initialParameters,
+}: {
+ parameters: ConfigurationParameter[];
+}) {
+ const {
+ isList,
+ itemId,
+ key,
+ onChangeCheckForListType,
+ setKey,
+ setIsList,
+ updateKey,
+ } = useConfigurationParameters();
+
+ const submit = useSubmit();
+ const fetcher = useFetcher<typeof configurationParameterAction>();
+
+ useEffect(() => {
+ if (fetcher.data?.success === false) {
+ toast.error("Failed to update configuration parameter");
+ }
+ }, [fetcher.data]);
+
+ // Dummy groups for now - will be replaced with real data later
+ const [groups] = useState<ConfigurationParameterGroup[]>([
+ { id: "null", name: "Ungrouped" },
+ { id: "group1", name: "Group 1" },
+ { id: "group2", name: "Group 2" },
+ ]);
+
+ const [groupOrder, setGroupOrder] = useState<string[]>(() => {
+ return groups.map((group) => group.id);
+ });
+
+ const parametersById = new Map<string, ConfigurationParameter>(
+ initialParameters.map((parameter) => [parameter.id, parameter])
+ );
+
+ const pendingParameters = usePendingParameters({ itemId });
+
+ // merge pending parameters and existing parameters
+ for (let pendingParameter of pendingParameters) {
+ let parameter = parametersById.get(pendingParameter.id);
+ if (parameter) {
+ parametersById.set(pendingParameter.id, {
+ ...parameter,
+ ...pendingParameter,
+ });
+ }
+ }
+
+ const parameters = Array.from(parametersById.values()).sort(
+ (a, b) => a.sortOrder - b.sortOrder
+ );
+
+ const [activeParameter, setActiveParameter] =
+ useState<ConfigurationParameter | null>(null);
+ const [activeGroup, setActiveGroup] =
+ useState<ConfigurationParameterGroup | null>(null);
+
+ const sensors = useSensors(
+ useSensor(MouseSensor),
+ useSensor(TouchSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter,
+ })
+ );
+
+ return (
+ <Card isCollapsible>
+ <CardHeader>
+ <CardTitle>Parameters</CardTitle>
+ </CardHeader>
+
+ <CardContent>
+ <div className="flex flex-col gap-4">
+ <div className="p-6 border rounded-lg">
+ <ValidatedForm
+ action={path.to.configurationParameter(itemId)}
+ method="post"
+ validator={configurationParameterValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onSubmit={() => {
+ setKey("");
+ setIsList(false);
+ }}
+ defaultValues={{
+ itemId: itemId,
+ key: "",
+ label: "",
+ dataType: "numeric",
+ listOptions: [],
+ configurationParameterGroupId: undefined,
+ }}
+ className="w-full"
+ >
+ <Hidden name="id" />
+ <Hidden name="itemId" />
+ <Hidden name="key" value={key} />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
+ <VStack>
+ <Input name="label" label="Label" onChange={updateKey} />
+ {key && (
+ <HStack spacing={1}>
+ <LuKeySquare className="w-3 h-3 text-muted-foreground" />
+ <span className="text-sm text-muted-foreground">
+ {key}
+ </span>
+ </HStack>
+ )}
+ </VStack>
+
+ <Select
+ name="dataType"
+ label="Data Type"
+ options={configurationParameterDataTypes.map((type) => ({
+ label: (
+ <HStack className="w-full">
+ <ConfigurationParameterDataTypeIcon
+ type={type}
+ className="mr-2"
+ />
+ {capitalize(type)}
+ </HStack>
+ ),
+ value: type,
+ }))}
+ onChange={onChangeCheckForListType}
+ />
+ {isList && (
+ <ArrayInput name="listOptions" label="List Parameters" />
+ )}
+ </div>
+
+ <Submit
+ leftIcon={<LuPlusCircle />}
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Add Parameter
+ </Submit>
+ </VStack>
+ </ValidatedForm>
+ </div>
+
+ {parameters.length > 0 && (
+ <DndContext
+ sensors={sensors}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ onDragOver={onDragOver}
+ >
+ <SortableContext items={groupOrder}>
+ <div className="relative"></div>
+ {groups.map((group) => {
+ const groupParameters = parameters.filter(
+ (opt) => `${opt.configurationParameterGroupId}` === group.id
+ );
+
+ return (
+ <div
+ key={group.id}
+ className={cn(
+ "transition-opacity",
+ activeGroup?.id === group.id && "opacity-0"
+ )}
+ >
+ <ParameterGroup
+ group={group}
+ parameters={groupParameters}
+ />
+ </div>
+ );
+ })}
+ </SortableContext>
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay>
+ {activeGroup && (
+ <ParameterGroup
+ group={activeGroup}
+ parameters={parameters.filter(
+ (opt) =>
+ `${opt.configurationParameterGroupId}` ===
+ activeGroup.id
+ )}
+ />
+ )}
+ {activeParameter && (
+ <ConfigurableParameter
+ parameter={activeParameter}
+ isOverlay
+ />
+ )}
+ </DragOverlay>,
+ document.body
+ )
+ }
+ </ClientOnly>
+ </DndContext>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ );
+
+ function onDragStart(event: DragStartEvent) {
+ console.log("onDragStart", event);
+ if (!hasDraggableData(event.active)) return;
+ const data = event.active.data.current;
+ if (data?.type === "group") {
+ setActiveGroup(data.group);
+ return;
+ }
+
+ if (data?.type === "parameter") {
+ setActiveParameter(data.parameter);
+ return;
+ }
+ }
+
+ function onDragEnd(event: DragEndEvent) {
+ console.log("onDragEnd", event);
+ setActiveGroup(null);
+ setActiveParameter(null);
+
+ const { active, over } = event;
+
+ if (!over) return;
+
+ const activeId = active.id;
+ const overId = over.id;
+
+ if (!hasDraggableData(active)) return;
+
+ const activeData = active.data.current;
+
+ if (activeId === overId) return;
+
+ const isActiveAColumn = activeData?.type === "group";
+ if (!isActiveAColumn) return;
+
+ setGroupOrder((prevOrder) => {
+ const activeColumnIndex = prevOrder.findIndex((id) => id === activeId);
+ const overGroupIndex = prevOrder.findIndex((id) => id === overId);
+
+ return arrayMove(prevOrder, activeColumnIndex, overGroupIndex);
+ });
+ }
+
+ function onDragOver(event: DragOverEvent) {
+ console.log("onDragOver", event);
+ const { active, over } = event;
+
+ if (!over) return;
+
+ const activeId = active.id;
+ const overId = over.id;
+
+ if (activeId === overId) return;
+
+ if (!hasDraggableData(active) || !hasDraggableData(over)) return;
+
+ const activeData = active.data.current;
+ const overData = over.data.current;
+ const overGroup =
+ overData?.type === "parameter"
+ ? groups.find(
+ (group) =>
+ group.id === `${overData.parameter.configurationParameterGroupId}`
+ )
+ : overData?.group;
+
+ const isActiveAnParameter = activeData?.type === "parameter";
+ const isOverAnParameter = overData?.type === "parameter";
+
+ const activeParameter = parametersById.get(activeId.toString());
+ const overParameter = parametersById.get(overId.toString());
+
+ if (!isActiveAnParameter) return;
+
+ // Im dropping a Item over another Item
+ if (
+ isActiveAnParameter &&
+ isOverAnParameter &&
+ activeParameter &&
+ overParameter
+ ) {
+ let sortOrderBefore = 0;
+ let sortOrderAfter = 0;
+ if (
+ activeParameter.sortOrder > overParameter.sortOrder ||
+ activeParameter.configurationParameterGroupId !==
+ overParameter.configurationParameterGroupId
+ ) {
+ sortOrderAfter = overParameter.sortOrder;
+
+ for (let i = parameters.length - 1; i >= 0; i--) {
+ const parameter = parameters[i];
+ if (
+ `${parameter.configurationParameterGroupId}` ===
+ `${overParameter.configurationParameterGroupId}` &&
+ parameter.sortOrder < sortOrderAfter
+ ) {
+ sortOrderBefore = parameter.sortOrder ?? 0;
+ break;
+ }
+ }
+ } else {
+ sortOrderBefore = overParameter.sortOrder;
+ sortOrderAfter =
+ parameters.find(
+ (parameter) =>
+ `${parameter.configurationParameterGroupId}` ===
+ `${overParameter.configurationParameterGroupId}` &&
+ parameter.sortOrder > sortOrderBefore
+ )?.sortOrder ?? sortOrderBefore + 1;
+ }
+
+ const newSortOrder = (sortOrderBefore + sortOrderAfter) / 2;
+
+ if (
+ activeParameter.configurationParameterGroupId !==
+ overParameter.configurationParameterGroupId
+ ) {
+ submit(
+ {
+ id: activeParameter.id,
+ configurationParameterGroupId:
+ overParameter.configurationParameterGroupId == "null"
+ ? null
+ : overParameter.configurationParameterGroupId,
+ sortOrder: newSortOrder,
+ },
+ {
+ method: "post",
+ action: path.to.configurationParameterOrder(activeParameter.itemId),
+ navigate: false,
+ fetcherKey: `parameter:${activeParameter.id}`,
+ }
+ );
+ return;
+ }
+
+ if (activeParameter && overParameter) {
+ submit(
+ {
+ id: activeParameter.id,
+ configurationParameterGroupId:
+ overParameter.configurationParameterGroupId == "null"
+ ? null
+ : overParameter.configurationParameterGroupId,
+ sortOrder: newSortOrder,
+ },
+ {
+ method: "post",
+ action: path.to.configurationParameterOrder(activeParameter.itemId),
+ navigate: false,
+ fetcherKey: `parameter:${activeParameter.id}`,
+ }
+ );
+ }
+ return;
+ }
+
+ const isOverAGroup = overData?.type === "group";
+
+ // Im dropping a Item over a column
+ if (isActiveAnParameter && isOverAGroup) {
+ const activeParameter = parametersById.get(activeId.toString());
+ const groupId = overId as string;
+
+ if (activeParameter) {
+ const firstItemInColumn = parameters.find(
+ (parameter) => parameter.configurationParameterGroupId === groupId
+ );
+ const sortOrderBefore = 0;
+ const sortOrderAfter = firstItemInColumn?.sortOrder ?? 1;
+
+ const newSortOrder = (sortOrderBefore + sortOrderAfter) / 2;
+
+ submit(
+ {
+ id: activeParameter.id,
+ configurationParameterGroupId: groupId == "null" ? null : groupId,
+ sortOrder: newSortOrder,
+ },
+ {
+ method: "post",
+ action: path.to.configurationParameter(activeParameter.itemId),
+ navigate: false,
+ fetcherKey: `parameter:${activeParameter.id}`,
+ }
+ );
+ }
+ }
+ }
+}
+
+function ParameterGroup({
+ group,
+ parameters,
+ isOverlay,
+}: {
+ group: ConfigurationParameterGroup;
+ parameters: ConfigurationParameter[];
+ isOverlay?: boolean;
+}) {
+ const parametersIds = parameters.map((parameter) => parameter.id);
+ const {
+ setNodeRef,
+ attributes,
+ listeners,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: group.id,
+ data: { type: "group", group } satisfies GroupData,
+ attributes: {
+ roleDescription: `Group: ${group.name}`,
+ },
+ });
+
+ const style = {
+ transition,
+ transform: CSS.Translate.toString(transform),
+ };
+
+ const variants = cva("border rounded-lg", {
+ variants: {
+ dragging: {
+ default: "",
+ over: "ring-2 opacity-30",
+ overlay: "ring-2 ring-primary",
+ },
+ },
+ });
+
+ return (
+ <div
+ key={group.id}
+ ref={setNodeRef}
+ style={style}
+ className={variants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
+ })}
+ >
+ <div className="p-4 border-b bg-muted/30">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <IconButton
+ aria-label="Reorder Group"
+ icon={<LuGripVertical />}
+ variant="ghost"
+ {...attributes}
+ {...listeners}
+ className="cursor-grab"
+ />
+ <h3 className="font-semibold">{group.name}</h3>
+ </HStack>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Open menu"
+ icon={<LuMoreVertical />}
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem>Edit</DropdownMenuItem>
+ <DropdownMenuItem destructive>Delete</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ </div>
+ <SortableContext items={parameters.map((opt) => opt.id)}>
+ <div className="p-2 flex flex-col gap-2">
+ {parameters.map((parameter) => (
+ <ConfigurableParameter key={parameter.id} parameter={parameter} />
+ ))}
+ </div>
+ </SortableContext>
+ </div>
+ );
+}
+
+function ConfigurableParameter({
+ parameter,
+ className,
+ isOverlay,
+}: {
+ parameter: ConfigurationParameter;
+ className?: string;
+ isOverlay?: boolean;
+}) {
+ const { isList, key, onChangeCheckForListType, updateKey } =
+ useConfigurationParameters(parameter);
+
+ const disclosure = useDisclosure();
+ const deleteModalDisclosure = useDisclosure();
+ const submitted = useRef(false);
+ const fetcher = useFetcher<typeof configurationParameterAction>();
+
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: parameter.id,
+ data: {
+ type: "parameter",
+ parameter,
+ } satisfies ParameterData,
+ attributes: {
+ roleDescription: `Parameter: ${parameter.label}`,
+ },
+ });
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ };
+
+ useEffect(() => {
+ if (submitted.current && fetcher.state === "idle") {
+ disclosure.onClose();
+ submitted.current = false;
+ }
+ }, [fetcher.state]);
+
+ const isUpdated = parameter.updatedBy !== null;
+ const person = isUpdated ? parameter.updatedBy : parameter.createdBy;
+ const date = parameter.updatedAt ?? parameter.createdAt;
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ "border rounded-lg p-4 bg-card",
+ isDragging && "opacity-50",
+ isOverlay && "shadow-lg",
+ className
+ )}
+ >
+ {disclosure.isOpen ? (
+ <ValidatedForm
+ action={path.to.configurationParameter(parameter.itemId)}
+ method="post"
+ validator={configurationParameterValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onSubmit={() => {
+ disclosure.onClose();
+ }}
+ defaultValues={{
+ id: parameter.id,
+ itemId: parameter.itemId,
+ key: parameter.key,
+ label: parameter.label,
+ dataType: parameter.dataType,
+ listOptions: parameter.listOptions ?? [],
+ }}
+ >
+ <Hidden name="id" />
+ <Hidden name="itemId" />
+ <Hidden name="key" value={key} />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
+ <VStack>
+ <Input
+ name="label"
+ label="Label"
+ onChange={updateKey}
+ autoFocus
+ />
+ {key && (
+ <HStack spacing={1}>
+ <LuKeySquare className="w-3 h-3 text-muted-foreground" />
+ <span className="text-sm text-muted-foreground">{key}</span>
+ </HStack>
+ )}
+ </VStack>
+
+ <Select
+ name="dataType"
+ label="Data Type"
+ options={configurationParameterDataTypes.map((type) => ({
+ label: (
+ <HStack className="w-full">
+ <ConfigurationParameterDataTypeIcon
+ type={type}
+ className="mr-2"
+ />
+ {capitalize(type)}
+ </HStack>
+ ),
+ value: type,
+ }))}
+ onChange={onChangeCheckForListType}
+ />
+ {isList && (
+ <ArrayInput name="listOptions" label="List Parameters" />
+ )}
+ </div>
+ <HStack className="w-full justify-end" spacing={2}>
+ <Button variant="secondary" onClick={disclosure.onClose}>
+ Cancel
+ </Button>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Save
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ ) : (
+ <div className="flex flex-1 justify-between items-center w-full">
+ <HStack spacing={2} className="w-1/2">
+ <IconButton
+ aria-label="Reorder"
+ icon={<LuGripVertical />}
+ variant="ghost"
+ {...attributes}
+ {...listeners}
+ className="cursor-grab"
+ />
+ <HStack spacing={4} className="flex-1">
+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">
+ <ConfigurationParameterDataTypeIcon
+ type={parameter.dataType}
+ className="w-4 h-4"
+ />
+ </div>
+ <VStack spacing={0}>
+ <span className="text-sm font-medium">{parameter.label}</span>
+ <span className="text-xs text-muted-foreground">
+ {parameter.key}
+ </span>
+ </VStack>
+ </HStack>
+ </HStack>
+ <div className="flex items-center justify-end gap-2">
+ <HStack spacing={2}>
+ <span className="text-xs text-muted-foreground">
+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
+ </span>
+ <EmployeeAvatar employeeId={person} withName={false} />
+ </HStack>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Open menu"
+ icon={<LuMoreVertical />}
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={disclosure.onOpen}>
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ destructive
+ onClick={deleteModalDisclosure.onOpen}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ )}
+ {deleteModalDisclosure.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteConfigurationParameter(
+ parameter.itemId,
+ parameter.id
+ )}
+ isOpen={deleteModalDisclosure.isOpen}
+ name={parameter.label}
+ text={`Are you sure you want to delete the ${parameter.label} parameter? This will not update any formulas that are using this parameter.`}
+ onCancel={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ConfigurationParameterDataTypeIcon({
+ type,
+ className,
+}: {
+ type: (typeof configurationParameterDataTypes)[number];
+ className?: string;
+}) {
+ switch (type) {
+ case "numeric":
+ return <LuHash className={cn("w-4 h-4 text-blue-600", className)} />;
+ case "text":
+ return <LuType className={cn("w-4 h-4 text-green-600", className)} />;
+ case "boolean":
+ return (
+ <LuToggleLeft className={cn("w-4 h-4 text-purple-600", className)} />
+ );
+ case "list":
+ return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;
+ default:
+ return null;
+ }
+}
+
+function usePendingParameters({ itemId }: { itemId: string }) {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.configurationParameter(itemId);
+ })
+ .map((fetcher) => {
+ let configurationParameterGroupId = String(
+ fetcher.formData.get("configurationParameterGroupId")
+ );
+ let id = String(fetcher.formData.get("id"));
+ let label = String(fetcher.formData.get("label"));
+ let key = String(fetcher.formData.get("key"));
+ let dataType = String(
+ fetcher.formData.get("dataType")
+ ) as ConfigurationParameter["dataType"];
+
+ let item: {
+ id: string;
+ label: string;
+ key: string;
+ dataType: ConfigurationParameter["dataType"];
+ configurationParameterGroupId: string;
+ } = {
+ id,
+ label,
+ key,
+ dataType,
+ configurationParameterGroupId,
+ };
+ return item;
+ });
+}
+
+const directions: string[] = [
+ KeyboardCode.Down,
+ KeyboardCode.Right,
+ KeyboardCode.Up,
+ KeyboardCode.Left,
+];
+
+export const coordinateGetter: KeyboardCoordinateGetter = (
+ event,
+ { context: { active, droppableRects, droppableContainers, collisionRect } }
+) => {
+ if (directions.includes(event.code)) {
+ event.preventDefault();
+
+ if (!active || !collisionRect) {
+ return;
+ }
+
+ const filteredContainers: DroppableContainer[] = [];
+
+ droppableContainers.getEnabled().forEach((entry) => {
+ if (!entry || entry?.disabled) {
+ return;
+ }
+
+ const rect = droppableRects.get(entry.id);
+
+ if (!rect) {
+ return;
+ }
+
+ const data = entry.data.current;
+
+ if (data) {
+ const { type, children } = data;
+
+ if (type === "Group" && children?.length > 0) {
+ if (active.data.current?.type !== "Group") {
+ return;
+ }
+ }
+ }
+
+ switch (event.code) {
+ case KeyboardCode.Down:
+ if (active.data.current?.type === "Group") {
+ return;
+ }
+ if (collisionRect.top < rect.top) {
+ // find all droppable areas below
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Up:
+ if (active.data.current?.type === "Group") {
+ return;
+ }
+ if (collisionRect.top > rect.top) {
+ // find all droppable areas above
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Left:
+ if (collisionRect.left >= rect.left + rect.width) {
+ // find all droppable areas to left
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Right:
+ // find all droppable areas to right
+ if (collisionRect.left + collisionRect.width <= rect.left) {
+ filteredContainers.push(entry);
+ }
+ break;
+ }
+ });
+ const collisions = closestCorners({
+ active,
+ collisionRect: collisionRect,
+ droppableRects,
+ droppableContainers: filteredContainers,
+ pointerCoordinates: null,
+ });
+ const closestId = getFirstCollision(collisions, "id");
+
+ if (closestId != null) {
+ const newDroppable = droppableContainers.get(closestId);
+ const newNode = newDroppable?.node.current;
+ const newRect = newDroppable?.rect.current;
+
+ if (newNode && newRect) {
+ return {
+ x: newRect.left,
+ y: newRect.top,
+ };
+ }
+ }
+ }
+
+ return undefined;
+};
+
+type GroupData = {
+ type: "group";
+ group: ConfigurationParameterGroup;
+};
+
+type ParameterData = {
+ type: "parameter";
+ parameter: ConfigurationParameter;
+};
+
+export type DraggableData = GroupData | ParameterData;
+
+export function hasDraggableData<T extends Active | Over>(
+ entry: T | null | undefined
+): entry is T & {
+ data: DataRef<DraggableData>;
+} {
+ if (!entry) {
+ return false;
+ }
+
+ const data = entry.data.current;
+
+ if (data?.type === "parameter" || data?.type === "group") {
+ return true;
+ }
+
+ return false;
+}
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
index 7bead76a16..4a65141037 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
@@ -16,6 +16,7 @@ import {
Submit,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
+import { useFlags } from "~/hooks/useFlags";
import type { action } from "~/routes/x+/part+/$itemId.manufacturing.method";
import { partManufacturingValidator } from "../../items.models";
@@ -29,6 +30,7 @@ const PartManufacturingForm = ({
const fetcher = useFetcher<typeof action>();
const permissions = usePermissions();
const { itemId } = useParams();
+ const { isInternal } = useFlags();
if (!itemId) throw new Error("Could not find itemId");
return (
@@ -57,9 +59,11 @@ const PartManufacturingForm = ({
name="manufacturingBlocked"
label="Manufacturing Blocked"
/> */}
+
<Boolean
name="requiresConfiguration"
label="Requires Configuration"
+ isDisabled={!isInternal}
/>
<CustomFormFields table="partReplenishment" />
</div>
diff --git a/apps/carbon/app/modules/items/ui/Parts/index.ts b/apps/carbon/app/modules/items/ui/Parts/index.ts
index e5541735be..d6aeb6e9f0 100644
--- a/apps/carbon/app/modules/items/ui/Parts/index.ts
+++ b/apps/carbon/app/modules/items/ui/Parts/index.ts
@@ -1,3 +1,4 @@
+import ConfigurationParametersForm from "./ConfigurationParameters";
import PartForm from "./PartForm";
import PartHeader from "./PartHeader";
import PartManufacturingForm from "./PartManufacturingForm";
@@ -5,6 +6,7 @@ import PartProperties from "./PartProperties";
import PartsTable from "./PartsTable";
export {
+ ConfigurationParametersForm,
PartForm,
PartHeader,
PartManufacturingForm,
diff --git a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
index a567339a0f..479ac4e950 100644
--- a/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
@@ -12,7 +12,6 @@ import { useDndContext } from "@dnd-kit/core";
import { SortableContext, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { cva } from "class-variance-authority";
-import { useMemo } from "react";
import { LuGripVertical } from "react-icons/lu";
import { useUrlParams } from "~/hooks";
import type {
@@ -44,9 +43,7 @@ export function ColumnCard({
}: ColumnCardProps) {
const [params] = useUrlParams();
const currentFilters = params.getAll("filter");
- const itemsIds = useMemo(() => {
- return items.map((item) => item.id);
- }, [items]);
+ const itemsIds = items.map((item) => item.id);
const totalDuration = items.reduce((acc, item) => {
const progress = progressByItemId[item.id]?.progress ?? 0;
@@ -79,7 +76,7 @@ export function ColumnCard({
};
const variants = cva(
- "w-[350px] max-w-full flex flex-col flex-shrink-0 snap-center rounded-none from-card/50 via-card/50 to-card",
+ "w-[350px] max-w-full flex flex-col flex-shrink-0 snap-center rounded-none from-card/50 via-card/50 to-card flex flex-col p-[1px] pt-0",
{
variants: {
dragging: {
@@ -87,6 +84,14 @@ export function ColumnCard({
over: "ring-2 opacity-30",
overlay: "ring-2 ring-primary",
},
+ height: {
+ filtered: "h-[calc(100dvh-135px)]",
+ default: "h-[calc(100dvh-98px)]",
+ },
+ },
+ defaultVariants: {
+ dragging: "default",
+ height: "default",
},
}
);
@@ -97,14 +102,10 @@ export function ColumnCard({
<Card
ref={setNodeRef}
style={style}
- className={cn(
- `${variants({
- dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
- })} flex flex-col p-[1px] pt-0`,
- currentFilters.length > 0
- ? "h-[calc(100dvh-135px)]"
- : "h-[calc(100dvh-98px)]"
- )}
+ className={variants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : "default",
+ height: currentFilters.length > 0 ? "filtered" : "default",
+ })}
>
<CardHeader className="p-4 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 bg-card z-10 border-b">
<div className="flex flex-grow items-start space-x-2">
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
index 96045f55be..fe02e36637 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -1,58 +1,21 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
import {
- Array,
- Hidden,
- Input,
- Select,
- Submit,
- ValidatedForm,
- validationError,
- validator,
-} from "@carbon/form";
-import {
- Button,
Card,
CardContent,
CardHeader,
CardTitle,
- cn,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- HStack,
- IconButton,
- toast,
- useDisclosure,
VStack,
} from "@carbon/react";
-import { Await, useFetcher, useLoaderData, useParams } from "@remix-run/react";
+import { Await, useLoaderData, useParams } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { defer, redirect } from "@vercel/remix";
-import { Suspense, useEffect, useRef, useState } from "react";
-import {
- LuGripVertical,
- LuHash,
- LuKeySquare,
- LuList,
- LuMoreVertical,
- LuPlusCircle,
- LuToggleLeft,
- LuType,
-} from "react-icons/lu";
-import { EmployeeAvatar } from "~/components";
+import { Suspense } from "react";
import { useRouteData } from "~/hooks";
-import type {
- ConfigurationParameter,
- MakeMethod,
- Material,
- MethodOperation,
-} from "~/modules/items";
+import type { MakeMethod, Material, MethodOperation } from "~/modules/items";
import {
- configurationParameterDataTypes,
- configurationParameterValidator,
getConfigurationParameters,
getItemManufacturing,
partManufacturingValidator,
@@ -63,14 +26,13 @@ import {
BillOfProcess,
MakeMethodTools,
} from "~/modules/items/ui/Item";
-import { PartManufacturingForm } from "~/modules/items/ui/Parts";
-import type { action as configurationParameterAction } from "~/routes/x+/part+/$itemId.parameter";
+import {
+ ConfigurationParametersForm,
+ PartManufacturingForm,
+} from "~/modules/items/ui/Parts";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
-import { capitalize } from "~/utils/string";
-import { formatRelativeTime } from "@carbon/utils";
-import { ConfirmDelete } from "~/components/Modals";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "parts",
@@ -177,17 +139,17 @@ export default function MakeMethodRoute() {
fallback={
<Card>
<CardHeader>
- <CardTitle>Options</CardTitle>
+ <CardTitle>Parameters</CardTitle>
</CardHeader>
<CardContent className="min-h-[200px]"></CardContent>
</Card>
}
>
<Await resolve={configurationParameters}>
- {(resolvedOptions) => (
+ {(resolvedParameters) => (
<ConfigurationParametersForm
key={`options:${itemId}`}
- options={resolvedOptions.data ?? []}
+ parameters={resolvedParameters.data ?? []}
/>
)}
</Await>
@@ -211,348 +173,3 @@ export default function MakeMethodRoute() {
</VStack>
);
}
-
-function useConfigurationParameters(option?: ConfigurationParameter) {
- const { itemId } = useParams();
- if (!itemId) throw new Error("Could not find itemId");
- const [key, setKey] = useState(option?.key ?? "");
- const [isList, setIsList] = useState(option?.dataType === "list");
-
- const onChangeCheckForListType = (
- newValue: {
- value: string;
- label: string | JSX.Element;
- } | null
- ) => {
- if (!newValue) return;
- const type = newValue.value;
- setIsList(type === "list");
- };
-
- const updateKey = (e: React.ChangeEvent<HTMLInputElement>) => {
- const label = e.target.value;
- setKey(label.toLowerCase().replace(/ /g, "_"));
- };
-
- return {
- key,
- isList,
- itemId,
- onChangeCheckForListType,
- setKey,
- setIsList,
- updateKey,
- };
-}
-
-function ConfigurationParametersForm({
- options,
-}: {
- options: ConfigurationParameter[];
-}) {
- const {
- isList,
- itemId,
- key,
- onChangeCheckForListType,
- setKey,
- setIsList,
- updateKey,
- } = useConfigurationParameters();
-
- const fetcher = useFetcher<typeof configurationParameterAction>();
- useEffect(() => {
- if (fetcher.data?.success === false) {
- toast.error("Failed to update configuration option");
- }
- }, [fetcher.data]);
- return (
- <Card isCollapsible>
- <CardHeader>
- <CardTitle>Parameters</CardTitle>
- </CardHeader>
-
- <CardContent>
- <div className="flex flex-col gap-6">
- <div className="p-6 border rounded-lg">
- <ValidatedForm
- action={path.to.configurationParameter(itemId)}
- method="post"
- validator={configurationParameterValidator}
- fetcher={fetcher}
- resetAfterSubmit
- onSubmit={() => {
- setKey("");
- setIsList(false);
- }}
- defaultValues={{
- itemId: itemId,
- key: "",
- label: "",
- dataType: "numeric",
- listOptions: [],
- configurationParameterGroupId: undefined,
- }}
- className="w-full"
- >
- <Hidden name="id" />
- <Hidden name="itemId" />
- <Hidden name="key" value={key} />
- <VStack spacing={4}>
- <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
- <VStack>
- <Input name="label" label="Label" onChange={updateKey} />
- {key && (
- <HStack spacing={1}>
- <LuKeySquare className="w-3 h-3 text-muted-foreground" />
- <span className="text-sm text-muted-foreground">
- {key}
- </span>
- </HStack>
- )}
- </VStack>
-
- <Select
- name="dataType"
- label="Data Type"
- options={configurationParameterDataTypes.map((type) => ({
- label: (
- <HStack className="w-full">
- <ConfigurationParameterDataTypeIcon
- type={type}
- className="mr-2"
- />
- {capitalize(type)}
- </HStack>
- ),
- value: type,
- }))}
- onChange={onChangeCheckForListType}
- />
- {isList && <Array name="listOptions" label="List Options" />}
- </div>
-
- <Submit
- leftIcon={<LuPlusCircle />}
- isDisabled={fetcher.state !== "idle"}
- isLoading={fetcher.state !== "idle"}
- >
- Add Option
- </Submit>
- </VStack>
- </ValidatedForm>
- </div>
-
- {options.length > 0 && (
- <div className="border rounded-lg">
- {options.map((option, index) => (
- <ConfigurableOption
- key={option.id}
- option={option}
- className={index === options.length - 1 ? "border-none" : ""}
- />
- ))}
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- );
-}
-
-function ConfigurableOption({
- option,
- className,
-}: {
- option: ConfigurationParameter;
- className?: string;
-}) {
- const { isList, key, onChangeCheckForListType, updateKey } =
- useConfigurationParameters(option);
-
- const disclosure = useDisclosure();
- const deleteModalDisclosure = useDisclosure();
- const submitted = useRef(false);
- const fetcher = useFetcher<typeof configurationParameterAction>();
-
- useEffect(() => {
- if (submitted.current && fetcher.state === "idle") {
- disclosure.onClose();
- submitted.current = false;
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [fetcher.state]);
-
- const isUpdated = option.updatedBy !== null;
- const person = isUpdated ? option.updatedBy : option.createdBy;
- const date = option.updatedAt ?? option.createdAt;
-
- return (
- <div className={cn("border-b p-6", className)}>
- {disclosure.isOpen ? (
- <ValidatedForm
- action={path.to.configurationParameter(option.itemId)}
- method="post"
- validator={configurationParameterValidator}
- fetcher={fetcher}
- resetAfterSubmit
- onSubmit={() => {
- disclosure.onClose();
- }}
- defaultValues={{
- id: option.id,
- itemId: option.itemId,
- key: option.key,
- label: option.label,
- dataType: option.dataType,
- listOptions: option.listOptions ?? [],
- }}
- >
- <Hidden name="id" />
- <Hidden name="itemId" />
- <Hidden name="key" value={key} />
- <VStack spacing={4}>
- <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
- <VStack>
- <Input
- name="label"
- label="Label"
- onChange={updateKey}
- autoFocus
- />
- {key && (
- <HStack spacing={1}>
- <LuKeySquare className="w-3 h-3 text-muted-foreground" />
- <span className="text-sm text-muted-foreground">{key}</span>
- </HStack>
- )}
- </VStack>
-
- <Select
- name="dataType"
- label="Data Type"
- options={configurationParameterDataTypes.map((type) => ({
- label: (
- <HStack className="w-full">
- <ConfigurationParameterDataTypeIcon
- type={type}
- className="mr-2"
- />
- {capitalize(type)}
- </HStack>
- ),
- value: type,
- }))}
- onChange={onChangeCheckForListType}
- />
- {isList && <Array name="listOptions" label="List Options" />}
- </div>
- <HStack className="w-full justify-end" spacing={2}>
- <Button variant="secondary" onClick={disclosure.onClose}>
- Cancel
- </Button>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={fetcher.state !== "idle"}
- >
- Save
- </Submit>
- </HStack>
- </VStack>
- </ValidatedForm>
- ) : (
- <div className="flex flex-1 justify-between items-center w-full">
- <HStack spacing={2} className="w-1/2">
- <IconButton
- aria-label="Reorder"
- icon={<LuGripVertical />}
- variant="ghost"
- />
- <HStack spacing={4} className="flex-1">
- <div className="bg-muted border rounded-full flex items-center justify-center p-2">
- <ConfigurationParameterDataTypeIcon
- type={option.dataType}
- className="w-4 h-4"
- />
- </div>
- <VStack spacing={0}>
- <span className="text-sm font-medium">{option.label}</span>
- <span className="text-xs text-muted-foreground">
- {option.key}
- </span>
- </VStack>
- </HStack>
- </HStack>
- <div className="flex items-center justify-end gap-2">
- <HStack spacing={2}>
- <span className="text-xs text-muted-foreground">
- {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
- </span>
- <EmployeeAvatar employeeId={person} withName={false} />
- </HStack>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="Open menu"
- icon={<LuMoreVertical />}
- variant="ghost"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={disclosure.onOpen}>
- Edit
- </DropdownMenuItem>
- <DropdownMenuItem
- destructive
- onClick={deleteModalDisclosure.onOpen}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- )}
- {deleteModalDisclosure.isOpen && (
- <ConfirmDelete
- action={path.to.deleteConfigurationParameter(
- option.itemId,
- option.id
- )}
- isOpen={deleteModalDisclosure.isOpen}
- name={option.label}
- text={`Are you sure you want to delete the ${option.label} parameter? This will not update any formulas that are using this parameter.`}
- onCancel={() => {
- deleteModalDisclosure.onClose();
- }}
- onSubmit={() => {
- deleteModalDisclosure.onClose();
- }}
- />
- )}
- </div>
- );
-}
-
-function ConfigurationParameterDataTypeIcon({
- type,
- className,
-}: {
- type: (typeof configurationParameterDataTypes)[number];
- className?: string;
-}) {
- switch (type) {
- case "numeric":
- return <LuHash className={cn("w-4 h-4 text-blue-600", className)} />;
- case "text":
- return <LuType className={cn("w-4 h-4 text-green-600", className)} />;
- case "boolean":
- return (
- <LuToggleLeft className={cn("w-4 h-4 text-purple-600", className)} />
- );
- case "list":
- return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;
- default:
- return null;
- }
-}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.parameter.order.tsx b/apps/carbon/app/routes/x+/part+/$itemId.parameter.order.tsx
new file mode 100644
index 0000000000..aa9907f117
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$itemId.parameter.order.tsx
@@ -0,0 +1,51 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import {
+ configurationParameterOrderValidator,
+ updateConfigurationParameterOrder,
+} from "~/modules/items";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(
+ configurationParameterOrderValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return json({
+ success: false,
+ error: "Invalid form data",
+ });
+ }
+
+ const upsert = await updateConfigurationParameterOrder(client, {
+ ...validation.data,
+ configurationParameterGroupId:
+ validation.data.configurationParameterGroupId == "null"
+ ? null
+ : validation.data.configurationParameterGroupId ?? null,
+ updatedBy: userId,
+ });
+
+ if (upsert.error) {
+ console.error(upsert.error);
+ return json({
+ success: false,
+ error: upsert.error.message,
+ });
+ }
+
+ return json({
+ success: true,
+ });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 393fd765b3..04d372c7db 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -142,6 +142,8 @@ export const path = {
generatePath(`${x}/settings/company/switch/${companyId}`),
configurationParameter: (itemId: string) =>
generatePath(`${x}/part/${itemId}/parameter`),
+ configurationParameterOrder: (itemId: string) =>
+ generatePath(`${x}/part/${itemId}/parameter/order`),
contractor: (id: string) =>
generatePath(`${x}/resources/contractors/${id}`),
contractors: `${x}/resources/contractors`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 2b74d76b75..ae147a487a 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -9174,6 +9174,9 @@ export default {
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.name",
},
+ {
+ $ref: "#/parameters/rowFilter.configurationParameterGroup.sortOrder",
+ },
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.companyId",
},
@@ -9245,6 +9248,9 @@ export default {
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.name",
},
+ {
+ $ref: "#/parameters/rowFilter.configurationParameterGroup.sortOrder",
+ },
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.companyId",
},
@@ -9270,6 +9276,9 @@ export default {
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.name",
},
+ {
+ $ref: "#/parameters/rowFilter.configurationParameterGroup.sortOrder",
+ },
{
$ref: "#/parameters/rowFilter.configurationParameterGroup.companyId",
},
@@ -41983,8 +41992,8 @@ export default {
},
sortOrder: {
default: 1,
- format: "integer",
- type: "integer",
+ format: "double precision",
+ type: "number",
},
companyId: {
description:
@@ -45330,7 +45339,7 @@ export default {
type: "object",
},
configurationParameterGroup: {
- required: ["id", "itemId", "name", "companyId"],
+ required: ["id", "itemId", "name", "sortOrder", "companyId"],
properties: {
id: {
default: "public.xid()",
@@ -45348,6 +45357,11 @@ export default {
format: "text",
type: "string",
},
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number",
+ },
companyId: {
description:
"Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
@@ -60205,7 +60219,7 @@ export default {
"rowFilter.configurationParameter.sortOrder": {
name: "sortOrder",
required: false,
- format: "integer",
+ format: "double precision",
in: "query",
type: "string",
},
@@ -64522,6 +64536,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.configurationParameterGroup.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ format: "double precision",
+ in: "query",
+ type: "string",
+ },
"rowFilter.configurationParameterGroup.companyId": {
name: "companyId",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 6cf348176d..c261a2827c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2118,18 +2118,21 @@ export type Database = {
id: string
itemId: string
name: string
+ sortOrder: number
}
Insert: {
companyId: string
id?: string
itemId: string
name: string
+ sortOrder?: number
}
Update: {
companyId?: string
id?: string
itemId?: string
name?: string
+ sortOrder?: number
}
Relationships: [
{
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 6cf348176d..c261a2827c 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2118,18 +2118,21 @@ export type Database = {
id: string
itemId: string
name: string
+ sortOrder: number
}
Insert: {
companyId: string
id?: string
itemId: string
name: string
+ sortOrder?: number
}
Update: {
companyId?: string
id?: string
itemId?: string
name?: string
+ sortOrder?: number
}
Relationships: [
{
diff --git a/packages/database/supabase/migrations/20241217184843_configuration-options.sql b/packages/database/supabase/migrations/20241217184843_configuration-options.sql
index 706104563f..c5bca0cb98 100644
--- a/packages/database/supabase/migrations/20241217184843_configuration-options.sql
+++ b/packages/database/supabase/migrations/20241217184843_configuration-options.sql
@@ -2,6 +2,7 @@ CREATE TABLE IF NOT EXISTS "configurationParameterGroup" (
"id" TEXT NOT NULL DEFAULT xid(),
"itemId" TEXT NOT NULL,
"name" TEXT NOT NULL,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
"companyId" TEXT NOT NULL,
CONSTRAINT "configurationParameterGroup_pkey" PRIMARY KEY ("id"),
CONSTRAINT "configurationParameterGroup_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id"),
@@ -17,7 +18,7 @@ CREATE TABLE IF NOT EXISTS "configurationParameter" (
"dataType" "configurationParameterDataType" NOT NULL,
"listOptions" TEXT[],
"configurationParameterGroupId" TEXT,
- "sortOrder" INTEGER NOT NULL DEFAULT 1,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
"companyId" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
"createdBy" TEXT NOT NULL,
@@ -71,3 +72,27 @@ FOR ALL USING (
has_valid_api_key_for_company("companyId")
);
+-- Find duplicate makeMethodId and description combinations
+-- SELECT c."name", i."readableId"
+-- FROM item i
+-- INNER JOIN "makeMethod" mm ON i.id = mm."itemId"
+-- INNER JOIN
+-- (
+-- SELECT "makeMethodId", "description", COUNT(*)
+-- FROM "methodOperation"
+-- GROUP BY "makeMethodId", "description"
+-- HAVING COUNT(*) > 1
+-- ) dups ON dups."makeMethodId" = mm."id"
+-- INNER JOIN "company" c ON c.id = i."companyId"
+
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'methodOperation_makeMethodId_description_unique'
+ ) THEN
+ ALTER TABLE "methodOperation"
+ ADD CONSTRAINT "methodOperation_makeMethodId_description_unique" UNIQUE ("makeMethodId", "description");
+ END IF;
+END $$;