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: get method and save method for items

Brad Barbind2af56ab13d1
diff --git a/apps/carbon/app/components/Form/Item.tsx b/apps/carbon/app/components/Form/Item.tsx
index 128551255e..ebca8ea044 100644
--- a/apps/carbon/app/components/Form/Item.tsx
+++ b/apps/carbon/app/components/Form/Item.tsx
@@ -16,7 +16,7 @@ type ItemSelectProps = Omit<ComboboxProps, "options" | "type"> & {
type: Database["public"]["Enums"]["itemType"];
disabledItems?: string[];
includeInactive?: boolean;
- replenishmentSystem?: string;
+ replenishmentSystem?: "Buy" | "Make";
};
const Item = ({ type, ...props }: ItemSelectProps) => {
@@ -33,7 +33,9 @@ const Item = ({ type, ...props }: ItemSelectProps) => {
(item) =>
item.type === type &&
(props.replenishmentSystem === undefined ||
- item.replenishmentSystem === props.replenishmentSystem) &&
+ item.replenishmentSystem === props.replenishmentSystem ||
+ item.replenishmentSystem === "Buy and Make" ||
+ props.replenishmentSystem === item.replenishmentSystem) &&
(item.active === true || props?.includeInactive === true)
)
: items
@@ -67,6 +69,7 @@ const Item = ({ type, ...props }: ItemSelectProps) => {
options={options}
{...props}
label={props?.label ?? "Item"}
+ itemHeight={44}
onCreateOption={(option) => {
newItemsModal.onOpen();
setCreated(option);
diff --git a/apps/carbon/app/components/SearchFilter.tsx b/apps/carbon/app/components/SearchFilter.tsx
index 94dc4eb74b..c3830e9328 100644
--- a/apps/carbon/app/components/SearchFilter.tsx
+++ b/apps/carbon/app/components/SearchFilter.tsx
@@ -23,7 +23,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {
return (
<InputGroup size={size}>
<InputLeftElement>
- <LuSearch className="text-muted-foreground w-3.5 h-3.5" />
+ <LuSearch className="text-muted-foreground w-3.5 h-3.5 mt-[-2px]" />
</InputLeftElement>
<Input
value={query}
diff --git a/apps/carbon/app/components/SortableList.tsx b/apps/carbon/app/components/SortableList.tsx
index 799ce0bc56..8cff94167a 100644
--- a/apps/carbon/app/components/SortableList.tsx
+++ b/apps/carbon/app/components/SortableList.tsx
@@ -117,7 +117,11 @@ function SortableListItem<T>({
key={`${item.checked}`}
className="px-1 flex flex-grow truncate cursor-pointer"
role="button"
- onClick={() => onSelectItem(item.id)}
+ onClick={(e) => {
+ if (!isDragging) {
+ onSelectItem(item.id);
+ }
+ }}
>
<HStack className="w-full justify-between">
{typeof item.title === "string" ? (
diff --git a/apps/carbon/app/hooks/useNextItemId.tsx b/apps/carbon/app/hooks/useNextItemId.tsx
index b41e19b7ce..acfb811b55 100644
--- a/apps/carbon/app/hooks/useNextItemId.tsx
+++ b/apps/carbon/app/hooks/useNextItemId.tsx
@@ -10,11 +10,12 @@ export function useNextItemId(
const [loading, setLoading] = useState<boolean>(false);
const [id, setId] = useState<string>("");
- const onIdChange = async (newToolId: string) => {
- if (newToolId.endsWith("...") && supabase) {
+ const onIdChange = async (newItemId: string) => {
+ console.log(newItemId);
+ if (newItemId.endsWith("...") && supabase) {
setLoading(true);
- const prefix = newToolId.slice(0, -3);
+ const prefix = newItemId.slice(0, -3);
try {
const { data } = await supabase
?.from("item")
@@ -44,7 +45,7 @@ export function useNextItemId(
setLoading(false);
}
} else {
- setId(newToolId);
+ setId(newItemId);
}
};
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index 66953b89ad..1cab862215 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -8,6 +8,11 @@ import {
standardFactorType,
} from "../shared";
+export const getMethodValidator = z.object({
+ targetId: z.string().min(1, { message: "Please select a target method" }),
+ sourceId: z.string().min(1, { message: "Please select a source method" }),
+});
+
export const itemTrackingTypes = ["Inventory", "Non-Inventory"] as const;
export const itemCostingMethods = [
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 9273122cab..5ae40dfeab 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -11,6 +11,7 @@ import type {
consumableValidator,
customerPartValidator,
fixtureValidator,
+ getMethodValidator,
itemCostValidator,
itemPlanningValidator,
itemPostingGroupValidator,
@@ -30,6 +31,24 @@ import type {
unitOfMeasureValidator,
} from "./items.models";
+export async function copyMakeMethod(
+ client: SupabaseClient<Database>,
+ args: z.infer<typeof getMethodValidator> & {
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("get-method", {
+ body: {
+ type: "itemToItem",
+ sourceId: args.sourceId,
+ targetId: args.targetId,
+ companyId: args.companyId,
+ userId: args.userId,
+ },
+ });
+}
+
export async function deleteItemCustomerPart(
client: SupabaseClient<Database>,
id: string,
diff --git a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
index 2b10075c62..a2c769d545 100644
--- a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx
@@ -178,7 +178,14 @@ const ConsumableProperties = () => {
</HStack>
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Consumable"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
index 0d7c3a06c4..25176c2af2 100644
--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx
@@ -221,7 +221,14 @@ const FixtureProperties = () => {
</HStack>
)}
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Fixture"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index 43bb2f355e..e6f07aea9c 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -72,8 +72,10 @@ function makeItem(material: Material): ItemWithData {
return {
id: material.id!,
title: (
- <VStack spacing={0}>
- <h4 className="font-mono">{material.itemReadableId}</h4>
+ <VStack spacing={0} className="py-2.5">
+ <h4 className="flex tracking-tighter text-base md:text-lg truncate">
+ {material.itemReadableId}
+ </h4>
{material?.description && (
<span className="text-xs text-muted-foreground">
{material.description}{" "}
diff --git a/apps/carbon/app/modules/items/ui/Item/FileBadge.tsx b/apps/carbon/app/modules/items/ui/Item/FileBadge.tsx
index cce53febb5..fbf127bee9 100644
--- a/apps/carbon/app/modules/items/ui/Item/FileBadge.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/FileBadge.tsx
@@ -2,17 +2,24 @@ import { Badge, HStack, cn } from "@carbon/react";
import { LuDownload } from "react-icons/lu";
import { DocumentPreview } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
+import type { MethodItemType } from "~/modules/shared";
import type { ItemFile } from "../../types";
-import { useItemDocuments } from "./ItemDocuments/useItemDocuments";
+import { useItemDocuments } from "./ItemDocuments";
type FileBadgeProps = {
file: ItemFile;
itemId: string;
+ itemType: MethodItemType;
className?: string;
};
-export function FileBadge({ file, itemId, className }: FileBadgeProps) {
- const { getPath, download } = useItemDocuments({ itemId });
+export function FileBadge({
+ file,
+ itemId,
+ itemType,
+ className,
+}: FileBadgeProps) {
+ const { getPath, download } = useItemDocuments({ itemId, type: itemType });
const type = getDocumentType(file.name);
return (
<HStack className="group" spacing={1}>
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
similarity index 52%
rename from apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx
rename to apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
index bb4c99a24b..34689a6fbf 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ File,
HStack,
IconButton,
Table,
@@ -15,17 +16,24 @@ import {
Td,
Th,
Thead,
+ toast,
Tr,
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
-import { LuAxis3D } from "react-icons/lu";
+import { LuAxis3D, LuUpload } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
-import { DocumentPreview, Hyperlink } from "~/components";
+import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile, ModelUpload } from "~/modules/items";
import type { MethodItemType } from "~/modules/shared";
-import ItemDocumentForm from "./ItemDocumentForm";
-import { useItemDocuments } from "./useItemDocuments";
+
+import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import type { ChangeEvent } from "react";
+import { useCallback } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { path } from "~/utils/path";
type ItemDocumentsProps = {
files: ItemFile[];
@@ -40,10 +48,25 @@ const ItemDocuments = ({
modelUpload,
type,
}: ItemDocumentsProps) => {
- const { canDelete, download, deleteFile, deleteModel, getPath, viewModel } =
- useItemDocuments({
- itemId,
- });
+ const {
+ canDelete,
+ download,
+ deleteFile,
+ deleteModel,
+ getPath,
+ viewModel,
+ upload,
+ } = useItemDocuments({
+ itemId,
+ type,
+ });
+
+ const onDrop = useCallback(
+ (acceptedFiles: File[]) => {
+ upload(acceptedFiles);
+ },
+ [upload]
+ );
return (
<Card className="flex-grow">
@@ -61,7 +84,6 @@ const ItemDocuments = ({
<Tr>
<Th>Name</Th>
<Th>Size</Th>
-
<Th></Th>
</Tr>
</Thead>
@@ -81,7 +103,7 @@ const ItemDocuments = ({
</Hyperlink>
</HStack>
</Td>
- <Td>
+ <Td className="text-xs font-mono">
{modelUpload.modelSize
? convertKbToString(
Math.floor((modelUpload.modelSize ?? 0) / 1024)
@@ -183,9 +205,177 @@ const ItemDocuments = ({
)}
</Tbody>
</Table>
+ <FileDropzone onDrop={onDrop} />
</CardContent>
</Card>
);
};
export default ItemDocuments;
+
+type ItemDocumentFormProps = {
+ itemId: string;
+ type: MethodItemType;
+};
+
+const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
+ const permissions = usePermissions();
+ const { upload } = useItemDocuments({ itemId, type });
+
+ const uploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files) {
+ upload(Array.from(e.target.files));
+ }
+ };
+
+ return (
+ <File
+ isDisabled={!permissions.can("update", "parts")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFiles}
+ multiple
+ >
+ New
+ </File>
+ );
+};
+
+type Props = {
+ itemId: string;
+ type: MethodItemType;
+};
+
+export const useItemDocuments = ({ itemId, type }: Props) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const revalidator = useRevalidator();
+ const { supabase } = useSupabase();
+ const { company } = useUser();
+ const submit = useSubmit();
+
+ const canDelete = permissions.can("delete", "parts");
+ const getPath = useCallback(
+ (file: { name: string }) => {
+ return `${company.id}/parts/${itemId}/${file.name}`;
+ },
+ [company.id, itemId]
+ );
+
+ const deleteFile = useCallback(
+ async (file: FileObject) => {
+ const fileDelete = await supabase?.storage
+ .from("private")
+ .remove([getPath(file)]);
+
+ if (!fileDelete || fileDelete.error) {
+ toast.error(fileDelete?.error?.message || "Error deleting file");
+ return;
+ }
+
+ toast.success("File deleted successfully");
+ revalidator.revalidate();
+ },
+ [getPath, supabase?.storage, revalidator]
+ );
+
+ const deleteModel = useCallback(async () => {
+ if (!supabase) return;
+
+ const { error } = await supabase
+ .from("item")
+ .update({ modelUploadId: null })
+ .eq("id", itemId);
+ if (error) {
+ toast.error("Error removing model from item");
+ return;
+ }
+ toast.success("Model removed from item");
+ revalidator.revalidate();
+ }, [supabase, itemId, revalidator]);
+
+ const download = useCallback(
+ async (file: FileObject) => {
+ const result = await supabase?.storage
+ .from("private")
+ .download(getPath(file));
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error downloading file");
+ return;
+ }
+
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ const url = window.URL.createObjectURL(result.data);
+ a.href = url;
+ a.download = file.name;
+ a.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }, 0);
+ },
+ [supabase?.storage, getPath]
+ );
+
+ const viewModel = useCallback(
+ (model: ModelUpload) => {
+ if (!model?.autodeskUrn) {
+ toast.error("Autodesk URN not found");
+ return;
+ }
+ navigate(path.to.file.cadModel(model?.autodeskUrn));
+ },
+ [navigate]
+ );
+
+ const upload = useCallback(
+ async (files: File[]) => {
+ if (!supabase) {
+ toast.error("Supabase client not available");
+ return;
+ }
+
+ for (const file of files) {
+ const fileName = getPath(file);
+
+ const fileUpload = await supabase.storage
+ .from("private")
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ toast.error(`Failed to upload file: ${file.name}`);
+ } else if (fileUpload.data?.path) {
+ toast.success(`Uploaded: ${file.name}`);
+ const formData = new FormData();
+ formData.append("path", fileUpload.data.path);
+ formData.append("name", file.name);
+ formData.append("size", Math.round(file.size / 1024).toString());
+ formData.append("sourceDocument", type);
+ formData.append("sourceDocumentId", itemId);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ });
+ }
+ }
+ revalidator.revalidate();
+ },
+ [getPath, supabase, revalidator, submit, type, itemId]
+ );
+
+ return {
+ canDelete,
+ deleteFile,
+ deleteModel,
+ download,
+ getPath,
+ viewModel,
+ upload,
+ };
+};
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx
deleted file mode 100644
index 1b5ead6235..0000000000
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocumentForm.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { File, toast } from "@carbon/react";
-import { useSubmit } from "@remix-run/react";
-import type { ChangeEvent } from "react";
-import { LuUpload } from "react-icons/lu";
-import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import type { MethodItemType } from "~/modules/shared";
-import { path } from "~/utils/path";
-
-type ItemDocumentFormProps = {
- itemId: string;
- type: MethodItemType;
-};
-
-const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
- const submit = useSubmit();
- const { company } = useUser();
- const { supabase } = useSupabase();
- const permissions = usePermissions();
-
- const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
- const file = e.target.files[0];
- const fileName = `${company.id}/parts/${itemId}/${file.name}`;
-
- const fileUpload = await supabase.storage
- .from("private")
- .upload(fileName, file, {
- cacheControl: `${12 * 60 * 60}`,
- upsert: true,
- });
-
- if (fileUpload.error) {
- toast.error("Failed to upload file");
- }
-
- if (fileUpload.data?.path) {
- toast.success("File uploaded");
- submitFileData({
- path: fileUpload.data.path,
- name: file.name,
- size: file.size,
- });
- }
- }
- };
-
- const submitFileData = ({
- path: filePath,
- name,
- size,
- }: {
- path: string;
- name: string;
- size: number;
- }) => {
- const formData = new FormData();
- formData.append("path", filePath);
- formData.append("name", name);
- formData.append("size", Math.round(size / 1024).toString());
- formData.append("sourceDocument", type);
- formData.append("sourceDocumentId", itemId);
-
- submit(formData, {
- method: "post",
- action: path.to.newDocument,
- });
- };
-
- return (
- <File
- isDisabled={!permissions.can("update", "parts")}
- leftIcon={<LuUpload />}
- onChange={uploadFile}
- >
- New
- </File>
- );
-};
-
-export default ItemDocumentForm;
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/index.ts b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/index.ts
deleted file mode 100644
index 66c31f4e92..0000000000
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import ItemDocuments from "./ItemDocuments";
-
-export default ItemDocuments;
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/useItemDocuments.ts b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/useItemDocuments.ts
deleted file mode 100644
index 4c0e975a8d..0000000000
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/useItemDocuments.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { toast } from "@carbon/react";
-import { useNavigate, useRevalidator } from "@remix-run/react";
-import type { FileObject } from "@supabase/storage-js";
-import { useCallback } from "react";
-import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import type { ModelUpload } from "~/modules/items";
-import { path } from "~/utils/path";
-
-type Props = {
- itemId: string;
-};
-
-export const useItemDocuments = ({ itemId }: Props) => {
- const navigate = useNavigate();
- const permissions = usePermissions();
- const revalidator = useRevalidator();
- const { supabase } = useSupabase();
- const { company } = useUser();
-
- const canDelete = permissions.can("delete", "parts");
- const getPath = useCallback(
- (file: FileObject) => {
- return `${company.id}/parts/${itemId}/${file.name}`;
- },
- [company.id, itemId]
- );
-
- const deleteFile = useCallback(
- async (file: FileObject) => {
- const fileDelete = await supabase?.storage
- .from("private")
- .remove([getPath(file)]);
-
- if (!fileDelete || fileDelete.error) {
- toast.error(fileDelete?.error?.message || "Error deleting file");
- return;
- }
-
- toast.success("File deleted successfully");
- revalidator.revalidate();
- },
- [getPath, supabase?.storage, revalidator]
- );
-
- const deleteModel = useCallback(async () => {
- if (!supabase) return;
-
- const { error } = await supabase
- .from("item")
- .update({ modelUploadId: null })
- .eq("id", itemId);
- if (error) {
- toast.error("Error removing model from item");
- return;
- }
- toast.success("Model removed from item");
- revalidator.revalidate();
- }, [supabase, itemId, revalidator]);
-
- const download = useCallback(
- async (file: FileObject) => {
- const result = await supabase?.storage
- .from("private")
- .download(getPath(file));
-
- if (!result || result.error) {
- toast.error(result?.error?.message || "Error downloading file");
- return;
- }
-
- const a = document.createElement("a");
- document.body.appendChild(a);
- const url = window.URL.createObjectURL(result.data);
- a.href = url;
- a.download = file.name;
- a.click();
-
- setTimeout(() => {
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
- }, 0);
- },
- [supabase?.storage, getPath]
- );
-
- const viewModel = useCallback(
- (model: ModelUpload) => {
- if (!model?.autodeskUrn) {
- toast.error("Autodesk URN not found");
- return;
- }
- navigate(path.to.file.cadModel(model?.autodeskUrn));
- },
- [navigate]
- );
-
- return {
- canDelete,
- deleteFile,
- deleteModel,
- download,
- getPath,
- viewModel,
- };
-};
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemForm.tsx
index df4b2d64a4..efa636feb4 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemForm.tsx
@@ -102,7 +102,7 @@ const ItemForm = ({ initialValues, type }: ItemFormProps) => {
label={`${getLabel(type)} ID`}
/>
- <Input name="name" label="Name" />
+ <Input name="name" label="Short Description" />
<Select
name="itemTrackingType"
label="Tracking Type"
diff --git a/apps/carbon/app/modules/items/ui/Item/MakeMethodBreacrumbs.tsx b/apps/carbon/app/modules/items/ui/Item/MakeMethodBreacrumbs.tsx
new file mode 100644
index 0000000000..c2d1f33aa9
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Item/MakeMethodBreacrumbs.tsx
@@ -0,0 +1,221 @@
+import { Submit, ValidatedForm } from "@carbon/form";
+import {
+ Alert,
+ AlertTitle,
+ Button,
+ Checkbox,
+ HStack,
+ Menubar,
+ MenubarItem,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ VStack,
+ toast,
+ useDisclosure,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { LuAlertTriangle, LuDownload, LuUpload } from "react-icons/lu";
+import { Hidden, Item } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { getMethodValidator } from "~/modules/items";
+import type { MethodItemType } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+type MakeMethodBreadcrumbsProps = {
+ itemId: string;
+ type: MethodItemType;
+};
+
+const MakeMethodBreadcrumbs = ({
+ itemId,
+ type,
+}: MakeMethodBreadcrumbsProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{ error: string | null }>();
+
+ const isGetMethodLoading =
+ fetcher.state !== "idle" && fetcher.formAction === path.to.makeMethodGet;
+ const isSaveMethodLoading =
+ fetcher.state !== "idle" && fetcher.formAction === path.to.makeMethodSave;
+
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error);
+ }
+ }, [fetcher.data?.error]);
+
+ const [includeInactive, setIncludeInactive] = useState<boolean>(true);
+
+ const getMethodModal = useDisclosure();
+ const saveMethodModal = useDisclosure();
+
+ return (
+ <>
+ <Menubar>
+ <HStack className="w-full justify-end">
+ <HStack spacing={0}>
+ <MenubarItem
+ isDisabled={
+ !permissions.can("update", "parts") || isSaveMethodLoading
+ }
+ isLoading={isSaveMethodLoading}
+ leftIcon={<LuUpload />}
+ onClick={saveMethodModal.onOpen}
+ >
+ Save Method
+ </MenubarItem>
+ <MenubarItem
+ isLoading={isGetMethodLoading}
+ isDisabled={
+ !permissions.can("update", "parts") || isGetMethodLoading
+ }
+ leftIcon={<LuDownload />}
+ onClick={getMethodModal.onOpen}
+ >
+ Get Method
+ </MenubarItem>
+ </HStack>
+ </HStack>
+ </Menubar>
+
+ {getMethodModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ getMethodModal.onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ fetcher={fetcher}
+ action={path.to.makeMethodGet}
+ validator={getMethodValidator}
+ onSubmit={getMethodModal.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Get Method</ModalTitle>
+ <ModalDescription>
+ Overwrite the item method with the source method
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="targetId" value={itemId} />
+ <VStack spacing={4}>
+ <Item
+ name="sourceId"
+ label="Source Method"
+ type={type}
+ includeInactive={includeInactive}
+ disabledItems={[itemId]}
+ replenishmentSystem="Make"
+ />
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="include-inactive"
+ checked={includeInactive}
+ onCheckedChange={(checked) =>
+ setIncludeInactive(!!checked)
+ }
+ />
+ <label
+ htmlFor="include-inactive"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Include Inactive
+ </label>
+ </div>
+
+ <Alert variant="destructive">
+ <LuAlertTriangle className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing manufacturing method
+ </AlertTitle>
+ </Alert>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button onClick={getMethodModal.onClose} variant="secondary">
+ Cancel
+ </Button>
+ <Submit variant="destructive">Confirm</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+
+ {saveMethodModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ saveMethodModal.onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ fetcher={fetcher}
+ action={path.to.makeMethodSave}
+ validator={getMethodValidator}
+ onSubmit={saveMethodModal.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Save Method</ModalTitle>
+ <ModalDescription>
+ Overwrite the target manufacturing method with the item method
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="sourceId" value={itemId} />
+ <VStack spacing={4}>
+ <Item
+ name="targetId"
+ label="Target Method"
+ type={type}
+ includeInactive={includeInactive}
+ disabledItems={[itemId]}
+ replenishmentSystem="Make"
+ />
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="include-inactive"
+ checked={includeInactive}
+ onCheckedChange={(checked) =>
+ setIncludeInactive(!!checked)
+ }
+ />
+ <label
+ htmlFor="include-inactive"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Include Inactive
+ </label>
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button onClick={saveMethodModal.onClose} variant="secondary">
+ Cancel
+ </Button>
+ <Submit>Confirm</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+};
+
+export default MakeMethodBreadcrumbs;
diff --git a/apps/carbon/app/modules/items/ui/Item/index.ts b/apps/carbon/app/modules/items/ui/Item/index.ts
index afdc87c2d4..96c8a23fdf 100644
--- a/apps/carbon/app/modules/items/ui/Item/index.ts
+++ b/apps/carbon/app/modules/items/ui/Item/index.ts
@@ -11,7 +11,7 @@ import ItemForm from "./ItemForm";
import ItemPlanningForm from "./ItemPlanningForm";
import ItemPurchasingForm from "./ItemPurchasingForm";
import ItemSalePriceForm from "./ItemSalePriceForm";
-
+import MakeMethodBreadcrumbs from "./MakeMethodBreacrumbs";
import PickMethodForm from "./PickMethodForm";
export {
@@ -28,5 +28,6 @@ export {
ItemPlanningForm,
ItemPurchasingForm,
ItemSalePriceForm,
+ MakeMethodBreadcrumbs,
PickMethodForm,
};
diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
index 95ceaeb24b..29c926b955 100644
--- a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx
@@ -188,7 +188,14 @@ const MaterialProperties = () => {
</HStack>
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Material"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
index aa5dcbec7c..3e53f47471 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
@@ -58,7 +58,8 @@ const PartManufacturingForm = ({
<InputControlled
isReadOnly
name="name"
- label="Name"
+ label="Short Description"
+ className="col-span-2"
value={routeData?.partSummary?.name ?? ""}
/>
<Number name="lotSize" label="Lot Size" />
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
index 1036ba5887..f605985731 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx
@@ -215,7 +215,14 @@ const PartProperties = () => {
</HStack>
)}
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Part"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx b/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx
index 664dd13016..9051ffb8fd 100644
--- a/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx
@@ -142,7 +142,14 @@ const ServiceProperties = () => {
</HStack>
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Service"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
index d495652b1a..4eabd4810c 100644
--- a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
+++ b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx
@@ -176,7 +176,14 @@ const ToolProperties = () => {
</HStack>
{routeData?.files.map((file) => {
- return <FileBadge key={file.id} file={file} itemId={itemId} />;
+ return (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Tool"
+ />
+ );
})}
</VStack>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 001005b01c..8889a1d7dd 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -72,8 +72,10 @@ function makeItem(material: Material): ItemWithData {
return {
id: material.id!,
title: (
- <VStack spacing={0}>
- <h4 className="font-mono">{material.itemReadableId}</h4>
+ <VStack spacing={0} className="py-2.5">
+ <h4 className="flex tracking-tighter text-base md:text-lg truncate">
+ {material.itemReadableId}
+ </h4>
{material?.description && (
<span className="text-xs text-muted-foreground">
{material.description}{" "}
diff --git a/apps/carbon/app/modules/shared/ui/RealtimeDataProvider.tsx b/apps/carbon/app/modules/shared/ui/RealtimeDataProvider.tsx
index 8da2a0f226..cbfbe54219 100644
--- a/apps/carbon/app/modules/shared/ui/RealtimeDataProvider.tsx
+++ b/apps/carbon/app/modules/shared/ui/RealtimeDataProvider.tsx
@@ -136,9 +136,9 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
...i,
readableId: updated.readableId,
name: updated.name,
- replenishmentSystem: inserted.replenishmentSystem,
- type: inserted.type,
- active: inserted.active,
+ replenishmentSystem: updated.replenishmentSystem,
+ type: updated.type,
+ active: updated.active,
};
}
return i;
diff --git a/apps/carbon/app/routes/x+/items+/methods+/get.tsx b/apps/carbon/app/routes/x+/items+/methods+/get.tsx
new file mode 100644
index 0000000000..3dfc7295f9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/methods+/get.tsx
@@ -0,0 +1,35 @@
+import { validationError, validator } from "@carbon/form";
+import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { copyMakeMethod, getMethodValidator } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const serviceRole = getSupabaseServiceRole();
+
+ const validation = await validator(getMethodValidator).validate(
+ await request.formData()
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const upsert = await copyMakeMethod(serviceRole, {
+ ...validation.data,
+ companyId,
+ userId,
+ });
+
+ if (upsert.error) {
+ return json({
+ error: upsert.error ? "Failed to get method" : null,
+ });
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.items);
+}
diff --git a/apps/carbon/app/routes/x+/items+/methods.material.$id.tsx b/apps/carbon/app/routes/x+/items+/methods+/material.$id.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.material.$id.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/material.$id.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.material.delete.$id.tsx b/apps/carbon/app/routes/x+/items+/methods+/material.delete.$id.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.material.delete.$id.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/material.delete.$id.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.material.new.tsx b/apps/carbon/app/routes/x+/items+/methods+/material.new.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.material.new.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/material.new.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.material.order.tsx b/apps/carbon/app/routes/x+/items+/methods+/material.order.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.material.order.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/material.order.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.operation.$id.tsx b/apps/carbon/app/routes/x+/items+/methods+/operation.$id.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.operation.$id.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/operation.$id.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.operation.new.tsx b/apps/carbon/app/routes/x+/items+/methods+/operation.new.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.operation.new.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/operation.new.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods.operation.order.tsx b/apps/carbon/app/routes/x+/items+/methods+/operation.order.tsx
similarity index 100%
rename from apps/carbon/app/routes/x+/items+/methods.operation.order.tsx
rename to apps/carbon/app/routes/x+/items+/methods+/operation.order.tsx
diff --git a/apps/carbon/app/routes/x+/items+/methods+/save.tsx b/apps/carbon/app/routes/x+/items+/methods+/save.tsx
new file mode 100644
index 0000000000..d7223c83a5
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/methods+/save.tsx
@@ -0,0 +1,35 @@
+import { validationError, validator } from "@carbon/form";
+import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { copyMakeMethod, getMethodValidator } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const serviceRole = getSupabaseServiceRole();
+
+ const validation = await validator(getMethodValidator).validate(
+ await request.formData()
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const upsert = await copyMakeMethod(serviceRole, {
+ ...validation.data,
+ companyId,
+ userId,
+ });
+
+ if (upsert.error) {
+ return json({
+ error: upsert.error ? "Failed to save method" : null,
+ });
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.items);
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index a423f07c78..88271a6fa2 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -7,6 +7,7 @@ import {
BillOfMaterial,
BillOfProcess,
ItemForm,
+ MakeMethodBreadcrumbs,
getItem,
getMethodMaterial,
getMethodMaterials,
@@ -107,6 +108,7 @@ export default function MethodMaterialMakePage() {
return (
<VStack spacing={2} className="p-2">
+ <MakeMethodBreadcrumbs itemId={item.id} type="Part" />
<ItemForm
key={`item:${itemId}:${makeMethodId}:${materialId}`}
type={item.type}
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 e624adf996..2c89711001 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -4,11 +4,11 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, useLoaderData, useParams } from "@remix-run/react";
import { redirect } from "remix-typedjson";
import { useRouteData } from "~/hooks";
-
import type { MakeMethod, Material, MethodOperation } from "~/modules/items";
import {
BillOfMaterial,
BillOfProcess,
+ MakeMethodBreadcrumbs,
PartManufacturingForm,
getItemManufacturing,
partManufacturingValidator,
@@ -113,6 +113,7 @@ export default function MakeMethodRoute() {
return (
<VStack spacing={2} className="p-2">
+ <MakeMethodBreadcrumbs itemId={itemId} type="Part" />
<PartManufacturingForm
key={itemId}
initialValues={manufacturingInitialValues}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 5bdeab09fd..32b342cde2 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -356,6 +356,8 @@ export const path = {
locations: `${x}/resources/locations`,
login: "/login",
logout: "/logout",
+ makeMethodGet: `${x}/items/methods/get`,
+ makeMethodSave: `${x}/items/methods/save`,
material: (id: string) => generatePath(`${x}/material/${id}`),
materialCosting: (id: string) =>
generatePath(`${x}/material/${id}/costing`),
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index f7d5ef587a..9f303713ea 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -18,6 +18,7 @@ const db = getDatabaseClient<DB>(pool);
const payloadValidator = z.object({
type: z.enum([
+ "itemToItem",
"itemToQuoteMakeMethod",
"itemToQuoteLine",
"quoteMakeMethodToItem",
@@ -51,6 +52,77 @@ serve(async (req: Request) => {
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
switch (type) {
+ case "itemToItem": {
+ const [sourceMakeMethod, targetMakeMethod] = await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", sourceId).single(),
+ client.from("makeMethod").select("*").eq("itemId", targetId).single(),
+ ]);
+
+ if (sourceMakeMethod.error || targetMakeMethod.error) {
+ throw new Error("Failed to get make methods");
+ }
+
+ const [sourceMaterials, sourceOperations] = await Promise.all([
+ client
+ .from("methodMaterial")
+ .select("*")
+ .eq("makeMethodId", sourceMakeMethod.data.id),
+ client
+ .from("methodOperation")
+ .select("*")
+ .eq("makeMethodId", sourceMakeMethod.data.id),
+ ]);
+
+ if (sourceMaterials.error || sourceOperations.error) {
+ throw new Error("Failed to get source materials or operations");
+ }
+
+ await db.transaction().execute(async (trx) => {
+ // Delete existing materials and operations from target method
+ await Promise.all([
+ trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "=", targetMakeMethod.data.id)
+ .execute(),
+ trx
+ .deleteFrom("methodOperation")
+ .where("makeMethodId", "=", targetMakeMethod.data.id)
+ .execute(),
+ ]);
+
+ // Copy materials from source to target
+ if (sourceMaterials.data && sourceMaterials.data.length > 0) {
+ await trx
+ .insertInto("methodMaterial")
+ .values(
+ sourceMaterials.data.map((material) => ({
+ ...material,
+ id: undefined, // Let the database generate a new ID
+ makeMethodId: targetMakeMethod.data.id,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+ // Copy operations from source to target
+ if (sourceOperations.data && sourceOperations.data.length > 0) {
+ await trx
+ .insertInto("methodOperation")
+ .values(
+ sourceOperations.data.map((operation) => ({
+ ...operation,
+ id: undefined, // Let the database generate a new ID
+ makeMethodId: targetMakeMethod.data.id,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+ });
+
+ break;
+ }
case "itemToQuoteLine": {
const [quoteId, quoteLineId] = (targetId as string).split(":");
if (!quoteId || !quoteLineId) {
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index 576e86ac5f..27cc00bfc3 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -221,7 +221,9 @@ function VirtualizedCommand({
{isCreateOption ? (
<>
<span>Create</span>
- <span className="ml-1 font-bold">{search}</span>
+ <span className="ml-1 font-bold line-clamp-1">
+ {search}
+ </span>
</>
) : item.helper ? (
<div className="flex flex-col">
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index e6c4a76f5a..359ae03614 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -264,7 +264,9 @@ function VirtualizedCommand({
{isCreateOption ? (
<>
<span>Create</span>
- <span className="ml-1 font-bold">{search}</span>
+ <span className="ml-1 font-bold line-clamp-1">
+ {search}
+ </span>
</>
) : item.helper ? (
<div className="flex flex-col">
diff --git a/prompts/migration.md b/prompts/migration.md
new file mode 100644
index 0000000000..35a065a99f
--- /dev/null
+++ b/prompts/migration.md
@@ -0,0 +1,139 @@
+# PostgreSQL SQL Style Guide
+
+## General
+
+- Use uppercase for SQL reserved words to maintain consistency and readability.
+- Employ consistent, descriptive identifiers for tables, columns, and other database objects.
+- Use white space and indentation to enhance the readability of your code.
+- Store dates in ISO 8601 format (`yyyy-mm-ddThh:mm:ss.sssss`).
+- Include comments for complex logic, using '/_ ... _/' for block comments and '--' for line comments.
+
+## Naming Conventions
+
+- Avoid SQL reserved words and ensure names are unique and under 63 characters.
+- Use camelCase for tables and columns.
+- Prefer singular for table names
+- Prefer plural for views
+- Prefer singular names for columns.
+
+## Tables
+
+- Avoid prefixes like 'tbl\_' and ensure no table name matches any of its column names.
+- Always add an `id` column of type `TEXT DEFAULT xid()` unless otherwise specified. Use it as the primary key.
+- Create all tables in the `public` schema unless otherwise specified.
+- Always add the schema to SQL queries for clarity.
+- Always add a `companyId` column of type `TEXT NOT NULL` that references `company("id")` unless othewise specified.
+- Always include a `customFields` column of type `JSONB` unless otherwise specified.
+- Always include a `createdBy`, `createdAt`, `updatedBy` and `updatedAt` column unless otherwise specified.
+
+## Columns
+
+- Use singular names and avoid generic names like 'id'.
+- For references to foreign tables, use the singular of the table name with the `Id` suffix. For example `userId` to reference the `user` table
+- Always use lowercase except in cases involving acronyms or when readability would be enhanced by an exception.
+
+#### Examples:
+
+```sql
+CREATE TABLE "quote" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "quoteId" TEXT NOT NULL,
+ "revisionId" INTEGER NOT NULL DEFAULT 0,
+ "salesRfqId" TEXT,
+ "dueDate" DATE,
+ "expirationDate" DATE,
+ "status" "quoteStatus" NOT NULL DEFAULT 'Draft',
+ "notes" JSON DEFAULT '{}'::json,
+ "salesPersonId" TEXT,
+ "estimatorId" TEXT,
+ "customerId" TEXT NOT NULL,
+ "customerLocationId" TEXT,
+ "customerContactId" TEXT,
+ "customerReference" TEXT,
+ "locationId" TEXT,
+ "assignee" TEXT,
+ "customFields" JSONB,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "quote_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "quote_quoteId_key" UNIQUE ("quoteId", "companyId"),
+ CONSTRAINT "quote_salesRfqId_fkey" FOREIGN KEY ("salesRfqId") REFERENCES "salesRfq" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "quote_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "quote_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quote_customerContactId_fkey" FOREIGN KEY ("customerContactId") REFERENCES "customerContact" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quote_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quote_salesPersonId_fkey" FOREIGN KEY ("salesPersonId") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "quote_estimatorId_fkey" FOREIGN KEY ("estimatorId") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "quote_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "quote_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quote_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quote_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+```
+
+## Queries
+
+- When the query is shorter keep it on just a few lines. As it gets larger start adding newlines for readability
+- Add spaces for readability.
+
+Smaller queries:
+
+```sql
+SELECT *
+FROM "employee"
+WHERE "endDate" IS NULL;
+
+UPDATE "employee"
+SET "endDate" = '2023-12-31'
+WHERE "id" = '1234';
+```
+
+Larger queries:
+
+```sql
+SELECT
+ "firstName",
+ "lastName"
+FROM
+ "employee"
+WHERE
+ "startDate" BETWEEN '2021-01-01' AND '2021-12-31'
+AND
+ "status" = 'employed';
+```
+
+### Joins and Subqueries
+
+- Format joins and subqueries for clarity, aligning them with related SQL clauses.
+- Prefer full table names when referencing tables. This helps for readability.
+
+```sql
+SELECT
+ "employee"."employeeName",
+ "department"."departmentName"
+FROM
+ "employee" e
+JOIN
+ "department" d on e."departmentId" = d."id"
+WHERE
+ "employee"."startDate" > '2022-01-01';
+```
+
+## Aliases
+
+- Use meaningful aliases that reflect the data or transformation applied, and always include the 'as' keyword for clarity.
+
+```sql
+SELECT count(*) AS "totalEmployees"
+FROM "employee"
+WHERE "endDate" IS NULL;
+```
+
+## Complex queries and CTEs
+
+- If a query is extremely complex, prefer a CTE.
+- Make sure the CTE is clear and linear Prefer readability over performance.