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: create part from part dropdown

Brad Barbinbbe537566ce0
diff --git a/apps/carbon/app/components/CreateableCombobox.tsx b/apps/carbon/app/components/CreateableCombobox.tsx
index a42e92af37..c1633a6156 100644
--- a/apps/carbon/app/components/CreateableCombobox.tsx
+++ b/apps/carbon/app/components/CreateableCombobox.tsx
@@ -25,6 +25,7 @@ export type CreatableComboboxProps = Omit<
options: {
label: string;
value: string;
+ helper?: string;
}[];
selected?: string[];
isClearable?: boolean;
@@ -51,8 +52,10 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
ref
) => {
const [search, setSearch] = useState("");
- const isExactMatch = options.some(
- (option) => option.value.toLowerCase() === search.toLowerCase()
+ const isExactMatch = options.some((option) =>
+ [option.value.toLowerCase(), option.helper?.toLowerCase()].includes(
+ search.toLowerCase()
+ )
);
return (
@@ -84,13 +87,26 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
const isSelected = !!selected?.includes(option.value);
return (
<CommandItem
- value={option.label}
+ value={
+ typeof option.label === "string"
+ ? option.label + option.helper
+ : undefined
+ }
key={option.value}
onSelect={() => {
if (!isSelected) onChange?.(option.value);
}}
>
- {option.label}
+ {option.helper ? (
+ <div className="flex flex-col">
+ <p>{option.label}</p>
+ <p className="text-xs text-muted-foreground">
+ {option.helper}
+ </p>
+ </div>
+ ) : (
+ option.label
+ )}
<RxCheck
className={cn(
"ml-auto h-4 w-4",
diff --git a/apps/carbon/app/components/Form/CreatableCombobox.tsx b/apps/carbon/app/components/Form/CreatableCombobox.tsx
index 0ff67578b7..c657d9cb6d 100644
--- a/apps/carbon/app/components/Form/CreatableCombobox.tsx
+++ b/apps/carbon/app/components/Form/CreatableCombobox.tsx
@@ -4,6 +4,7 @@ import {
FormHelperText,
FormLabel,
} from "@carbon/react";
+import { forwardRef } from "react";
import { useControlField, useField } from "remix-validated-form";
import { CreatableCombobox as CreatableComboboxBase } from "~/components";
@@ -19,53 +20,51 @@ export type CreatableComboboxProps = Omit<
onChange?: (newValue: { value: string; label: string } | null) => void;
};
-const CreatableCombobox = ({
- name,
- label,
- helperText,
- ...props
-}: CreatableComboboxProps) => {
- const { getInputProps, error } = useField(name);
- const [value, setValue] = useControlField<string | undefined>(name);
+const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
+ ({ name, label, helperText, ...props }, ref) => {
+ const { getInputProps, error } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
- const onChange = (value: string) => {
- if (value) {
- props?.onChange?.(props.options.find((o) => o.value === value) ?? null);
- } else {
- props?.onChange?.(null);
- }
- };
+ const onChange = (value: string) => {
+ if (value) {
+ props?.onChange?.(props.options.find((o) => o.value === value) ?? null);
+ } else {
+ props?.onChange?.(null);
+ }
+ };
- return (
- <FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
- <input
- {...getInputProps({
- id: name,
- })}
- type="hidden"
- name={name}
- id={name}
- value={value}
- />
- <CreatableComboboxBase
- {...props}
- value={value}
- onChange={(newValue) => {
- setValue(newValue ?? "");
- onChange(newValue ?? "");
- }}
- className="w-full"
- />
+ return (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input
+ {...getInputProps({
+ id: name,
+ })}
+ type="hidden"
+ name={name}
+ id={name}
+ value={value}
+ />
+ <CreatableComboboxBase
+ ref={ref}
+ {...props}
+ value={value}
+ onChange={(newValue) => {
+ setValue(newValue ?? "");
+ onChange(newValue ?? "");
+ }}
+ className="w-full"
+ />
- {error ? (
- <FormErrorMessage>{error}</FormErrorMessage>
- ) : (
- helperText && <FormHelperText>{helperText}</FormHelperText>
- )}
- </FormControl>
- );
-};
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+ }
+);
CreatableCombobox.displayName = "CreatableCombobox";
diff --git a/apps/carbon/app/components/Form/Part.tsx b/apps/carbon/app/components/Form/Part.tsx
index 56b0723b97..7c0f66ad6f 100644
--- a/apps/carbon/app/components/Form/Part.tsx
+++ b/apps/carbon/app/components/Form/Part.tsx
@@ -1,8 +1,9 @@
-import { useMemo } from "react";
-import { type PartReplenishmentSystem } from "~/modules/parts";
+import { useDisclosure } from "@carbon/react";
+import { useMemo, useRef, useState } from "react";
+import { PartForm, type PartReplenishmentSystem } from "~/modules/parts";
import { useParts } from "~/stores";
import type { ComboboxProps } from "./Combobox";
-import Combobox from "./Combobox";
+import CreatableCombobox from "./CreatableCombobox";
type PartSelectProps = Omit<ComboboxProps, "options"> & {
partReplenishmentSystem?: PartReplenishmentSystem;
@@ -10,6 +11,9 @@ type PartSelectProps = Omit<ComboboxProps, "options"> & {
const Part = ({ partReplenishmentSystem, ...props }: PartSelectProps) => {
const [parts] = useParts();
+ const newPartsModal = useDisclosure();
+ const [createdPart, setCreatedPart] = useState<string>("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
const options = useMemo(
() =>
@@ -32,7 +36,38 @@ const Part = ({ partReplenishmentSystem, ...props }: PartSelectProps) => {
);
return (
- <Combobox options={options} {...props} label={props?.label ?? "Part"} />
+ <>
+ <CreatableCombobox
+ ref={triggerRef}
+ options={options}
+ {...props}
+ label={props?.label ?? "Part"}
+ onCreateOption={(option) => {
+ newPartsModal.onOpen();
+ setCreatedPart(option);
+ }}
+ />
+ {newPartsModal.isOpen && (
+ <PartForm
+ type="modal"
+ onClose={() => {
+ setCreatedPart("");
+ newPartsModal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{
+ id: "",
+ name: createdPart,
+ description: "",
+ partType: "Inventory" as "Inventory",
+ replenishmentSystem: "Buy" as "Buy",
+ unitOfMeasureCode: "EA",
+ blocked: false,
+ active: false,
+ }}
+ />
+ )}
+ </>
);
};
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
index 72ba97421c..089e01a825 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
@@ -1,13 +1,16 @@
import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
+ ModalCard,
+ ModalCardBody,
+ ModalCardContent,
+ ModalCardDescription,
+ ModalCardFooter,
+ ModalCardHeader,
+ ModalCardProvider,
+ ModalCardTitle,
VStack,
cn,
} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
import { useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import {
@@ -32,6 +35,8 @@ import { path } from "~/utils/path";
type PartFormProps = {
initialValues: TypeOfValidator<typeof partValidator>;
+ type?: "card" | "modal";
+ onClose?: () => void;
};
const useNextPartIdShortcut = () => {
@@ -79,12 +84,13 @@ const useNextPartIdShortcut = () => {
return { partId, onPartIdChange, loading };
};
-const PartForm = ({ initialValues }: PartFormProps) => {
+const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
const sharedPartsData = useRouteData<{
partGroups: PartGroupListItem[];
unitOfMeasures: UnitOfMeasureListItem[];
}>(path.to.partRoot);
+ const fetcher = useFetcher();
const { partId, onPartIdChange, loading } = useNextPartIdShortcut();
const permissions = usePermissions();
const isEditing = !!initialValues.id;
@@ -114,86 +120,101 @@ const PartForm = ({ initialValues }: PartFormProps) => {
})) ?? [];
return (
- <ValidatedForm
- method="post"
- validator={partValidator}
- defaultValues={initialValues}
- >
- <Card>
- <CardHeader>
- <CardTitle>{isEditing ? "Part Details" : "New Part"}</CardTitle>
- {!isEditing && (
- <CardDescription>
- A part contains the information about a specific item that can be
- purchased or manufactured.
- </CardDescription>
- )}
- </CardHeader>
- <CardContent>
- <div
- className={cn(
- "grid w-full gap-x-8 gap-y-2",
- isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-1"
- )}
- >
- <VStack>
- {isEditing ? (
- <Input autoFocus name="id" label="Part ID" isReadOnly />
- ) : (
- <InputControlled
- name="id"
- label="Part ID"
- helperText="Use ... to get the next part ID"
- value={partId}
- onChange={onPartIdChange}
- isDisabled={loading}
- />
- )}
-
- <Input name="name" label="Name" />
- <TextArea name="description" label="Description" />
- </VStack>
- <VStack>
- <Select
- name="replenishmentSystem"
- label="Replenishment System"
- options={partReplenishmentSystemOptions}
- />
- <Select
- name="partType"
- label="Part Type"
- options={partTypeOptions}
- />
- <Combobox
- name="unitOfMeasureCode"
- label="Unit of Measure"
- options={unitOfMeasureOptions}
- />
- </VStack>
- <VStack>
- <Combobox
- name="partGroupId"
- label="Part Group"
- options={partGroupOptions}
- />
- <Boolean name="blocked" label="Blocked" />
- {isEditing && <Boolean name="active" label="Active" />}
- </VStack>
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ action={
isEditing
- ? !permissions.can("update", "parts")
- : !permissions.can("create", "parts")
+ ? undefined
+ : type === "card"
+ ? path.to.newPart
+ : path.to.api.newPart
}
+ method="post"
+ validator={partValidator}
+ defaultValues={initialValues}
+ onSubmit={onClose}
+ fetcher={fetcher}
>
- Save
- </Submit>
- </CardFooter>
- </Card>
- </ValidatedForm>
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing ? "Part Details" : "New Part"}
+ </ModalCardTitle>
+ {!isEditing && (
+ <ModalCardDescription>
+ A part contains the information about a specific item that can
+ be purchased or manufactured.
+ </ModalCardDescription>
+ )}
+ </ModalCardHeader>
+ <ModalCardBody>
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-2",
+ isEditing ? "grid-cols-1 md:grid-cols-3" : "grid-cols-1"
+ )}
+ >
+ <VStack>
+ {isEditing ? (
+ <Input name="id" label="Part ID" isReadOnly />
+ ) : (
+ <InputControlled
+ name="id"
+ label="Part ID"
+ helperText="Use ... to get the next part ID"
+ value={partId}
+ onChange={onPartIdChange}
+ isDisabled={loading}
+ />
+ )}
+
+ <Input name="name" label="Name" />
+ <TextArea name="description" label="Description" />
+ </VStack>
+ <VStack>
+ <Select
+ name="replenishmentSystem"
+ label="Replenishment System"
+ options={partReplenishmentSystemOptions}
+ />
+ <Select
+ name="partType"
+ label="Part Type"
+ options={partTypeOptions}
+ />
+ <Combobox
+ name="unitOfMeasureCode"
+ label="Unit of Measure"
+ options={unitOfMeasureOptions}
+ />
+ </VStack>
+ <VStack>
+ <Combobox
+ name="partGroupId"
+ label="Part Group"
+ options={partGroupOptions}
+ />
+ <Boolean name="blocked" label="Blocked" />
+ {isEditing && <Boolean name="active" label="Active" />}
+ </VStack>
+ </div>
+ </ModalCardBody>
+ <ModalCardFooter>
+ <Submit
+ isDisabled={
+ isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts")
+ }
+ >
+ Save
+ </Submit>
+ </ModalCardFooter>
+ </ValidatedForm>
+ </ModalCardContent>
+ </ModalCard>
+ </ModalCardProvider>
);
};
diff --git a/apps/carbon/app/routes/api+/parts.new.ts b/apps/carbon/app/routes/api+/parts.new.ts
new file mode 100644
index 0000000000..5e507fca8e
--- /dev/null
+++ b/apps/carbon/app/routes/api+/parts.new.ts
@@ -0,0 +1,38 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { partValidator, upsertPart } from "~/modules/parts";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const validation = await partValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const createPart = await upsertPart(client, {
+ ...validation.data,
+ active: true,
+ createdBy: userId,
+ });
+ if (createPart.error) {
+ return json(
+ createPart,
+ await flash(request, error(createPart.error, "Failed to insert part"))
+ );
+ }
+
+ const partId = createPart.data?.id;
+ if (!partId) throw new Error("Part ID not found");
+
+ return json(createPart, { status: 201 });
+}
diff --git a/apps/carbon/app/routes/api+/purchasing.suppliers.new.tsx b/apps/carbon/app/routes/api+/purchasing.suppliers.new.tsx
new file mode 100644
index 0000000000..b1eed3a857
--- /dev/null
+++ b/apps/carbon/app/routes/api+/purchasing.suppliers.new.tsx
@@ -0,0 +1,39 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { insertSupplier, supplierValidator } from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await supplierValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createSupplier = await insertSupplier(client, {
+ ...data,
+ createdBy: userId,
+ });
+ if (createSupplier.error) {
+ return json(
+ createSupplier,
+ await flash(
+ request,
+ error(createSupplier.error, "Failed to insert supplier")
+ )
+ );
+ }
+
+ return json(createSupplier);
+}
diff --git a/apps/carbon/app/routes/api+/sales.customers.new.ts b/apps/carbon/app/routes/api+/sales.customers.new.ts
new file mode 100644
index 0000000000..b1d5567cc7
--- /dev/null
+++ b/apps/carbon/app/routes/api+/sales.customers.new.ts
@@ -0,0 +1,39 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { customerValidator, insertCustomer } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const validation = await customerValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createCustomer = await insertCustomer(client, {
+ ...data,
+ createdBy: userId,
+ });
+ if (createCustomer.error) {
+ return json(
+ createCustomer,
+ await flash(
+ request,
+ error(createCustomer.error, "Failed to insert customer")
+ )
+ );
+ }
+
+ return json(createCustomer, { status: 201 });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 02b6e4eb9d..98523fbde4 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -26,6 +26,9 @@ export const path = {
groupsByType: (type?: string) =>
generatePath(`${api}/users/groups?type=${type}`),
locations: `${api}/resources/locations`,
+ newCustomer: `${api}/sales/customers/new`,
+ newPart: `${api}/parts/new`,
+ newSupplier: `${api}/purchasing/suppliers/new`,
rollback: (table: string, id: string) =>
generatePath(
`${api}/settings/sequence/rollback?table=${table}&currentSequence=${id}`
diff --git a/packages/react/src/Command.tsx b/packages/react/src/Command.tsx
index 1ab0aa3b44..14bda67417 100644
--- a/packages/react/src/Command.tsx
+++ b/packages/react/src/Command.tsx
@@ -255,6 +255,7 @@ const CommandTrigger = forwardRef<ElementRef<"button">, CommandTriggerProps>(
({ size, className, children, ...props }, ref) => (
<button
ref={ref}
+ type="button"
className={cn(
commandTriggerVariants({
size,