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: job form

Brad Barbin10b9fd5f9de1
diff --git a/apps/carbon/app/components/Assignee.tsx b/apps/carbon/app/components/Assignee.tsx
index 6c9607d777..7f953f1c69 100644
--- a/apps/carbon/app/components/Assignee.tsx
+++ b/apps/carbon/app/components/Assignee.tsx
@@ -106,7 +106,10 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(
)}
</button>
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<Command id="assignee-options">
<CommandInput placeholder="Search..." className="h-9" />
<CommandEmpty>No option found.</CommandEmpty>
diff --git a/apps/carbon/app/components/Form/Item.tsx b/apps/carbon/app/components/Form/Item.tsx
index ebca8ea044..c922e5c63e 100644
--- a/apps/carbon/app/components/Form/Item.tsx
+++ b/apps/carbon/app/components/Form/Item.tsx
@@ -1,8 +1,22 @@
-import type { Database } from "@carbon/database";
import type { ComboboxProps } from "@carbon/form";
-import { CreatableCombobox } from "@carbon/form";
-import { useDisclosure } from "@carbon/react";
-import { useMemo, useRef, useState } from "react";
+import { useControlField, useField } from "@carbon/form";
+import {
+ cn,
+ CreatableCombobox,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+ HStack,
+ IconButton,
+ useDisclosure,
+} from "@carbon/react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
ConsumableForm,
FixtureForm,
@@ -10,22 +24,36 @@ import {
PartForm,
ToolForm,
} from "~/modules/items";
+import {
+ methodItemType,
+ MethodItemTypeIcon,
+ type MethodItemType,
+} from "~/modules/shared";
import { useItems } from "~/stores";
type ItemSelectProps = Omit<ComboboxProps, "options" | "type"> & {
- type: Database["public"]["Enums"]["itemType"];
disabledItems?: string[];
includeInactive?: boolean;
replenishmentSystem?: "Buy" | "Make";
+ type: MethodItemType;
+ typeFieldName?: string;
+ validItemTypes?: MethodItemType[];
+ onTypeChange?: (type: MethodItemType) => void;
};
-const Item = ({ type, ...props }: ItemSelectProps) => {
+const Item = ({
+ name,
+ label,
+ helperText,
+ isOptional = false,
+ type,
+ typeFieldName = "itemType",
+ validItemTypes,
+ onTypeChange,
+ ...props
+}: ItemSelectProps) => {
const [items] = useItems();
- const newItemsModal = useDisclosure();
- const [created, setCreated] = useState<string>("");
- const triggerRef = useRef<HTMLButtonElement>(null);
-
const options = useMemo(() => {
const results =
(props?.replenishmentSystem || props?.includeInactive !== true
@@ -62,19 +90,116 @@ const Item = ({ type, ...props }: ItemSelectProps) => {
type,
]);
+ const newItemsModal = useDisclosure();
+ const [created, setCreated] = useState<string>("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const { getInputProps, error } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ useEffect(() => {
+ if (props.value !== null && props.value !== undefined)
+ setValue(props.value);
+ }, [props.value, setValue]);
+
+ const onChange = (value: string) => {
+ if (value) {
+ props?.onChange?.(options.find((o) => o.value === value) ?? null);
+ } else {
+ props?.onChange?.(null);
+ }
+ };
+
+ const canSwitchItemType = typeof onTypeChange === "function";
+
return (
<>
- <CreatableCombobox
- ref={triggerRef}
- options={options}
- {...props}
- label={props?.label ?? "Item"}
- itemHeight={44}
- onCreateOption={(option) => {
- newItemsModal.onOpen();
- setCreated(option);
- }}
- />
+ <FormControl isInvalid={!!error} className="w-full">
+ {type && (
+ <FormLabel htmlFor={name} isOptional={isOptional}>
+ {type}
+ </FormLabel>
+ )}
+ <input
+ {...getInputProps({
+ id: name,
+ })}
+ type="hidden"
+ name={name}
+ id={name}
+ value={value}
+ />
+ <input
+ type="hidden"
+ name={typeFieldName}
+ id={typeFieldName}
+ value={type}
+ />
+ <HStack className="w-full" spacing={0}>
+ <CreatableCombobox
+ className={cn(
+ "w-full flex-grow",
+ canSwitchItemType && "rounded-r-none"
+ )}
+ ref={triggerRef}
+ options={options}
+ {...props}
+ value={value?.replace(/"/g, '\\"')}
+ onChange={(newValue) => {
+ setValue(newValue?.replace(/"/g, '\\"') ?? "");
+ onChange(newValue?.replace(/"/g, '\\"') ?? "");
+ }}
+ isClearable={isOptional && !props.isReadOnly}
+ label={label}
+ itemHeight={44}
+ onCreateOption={(option) => {
+ newItemsModal.onOpen();
+ setCreated(option);
+ }}
+ />
+ {canSwitchItemType && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Change Type"
+ className="bg-transparent flex-shrink-0 h-10 rounded-l-none border-l-0 shadow-sm"
+ disabled={props.isReadOnly}
+ variant="secondary"
+ size="lg"
+ icon={<MethodItemTypeIcon type={type} />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {Object.values(methodItemType)
+ .filter(
+ (itemType) =>
+ validItemTypes === undefined ||
+ (Array.isArray(validItemTypes) &&
+ validItemTypes.includes(itemType))
+ )
+ .map((itemType) => (
+ <DropdownMenuItem
+ key={itemType}
+ onSelect={() => {
+ if (type !== itemType) onTypeChange?.(itemType);
+ }}
+ >
+ <DropdownMenuIcon
+ icon={<MethodItemTypeIcon type={itemType} />}
+ />
+ <span>{itemType}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </HStack>
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
{type === "Part" && newItemsModal.isOpen && (
<PartForm
type="modal"
diff --git a/apps/carbon/app/components/Form/SequenceOrCustomId.tsx b/apps/carbon/app/components/Form/SequenceOrCustomId.tsx
new file mode 100644
index 0000000000..3fb1f4227a
--- /dev/null
+++ b/apps/carbon/app/components/Form/SequenceOrCustomId.tsx
@@ -0,0 +1,80 @@
+import { useField } from "@carbon/form";
+import type { InputProps } from "@carbon/react";
+import {
+ Button,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+ HStack,
+ IconButton,
+ Input,
+} from "@carbon/react";
+import { forwardRef, useState } from "react";
+import { LuToggleLeft, LuToggleRight } from "react-icons/lu";
+
+type SequenceOrCustomIdProps = InputProps & {
+ name: string;
+ label: string;
+ table: string;
+ isOptional?: boolean;
+ helperText?: string;
+};
+
+const SequenceOrCustomId = forwardRef<
+ HTMLInputElement,
+ SequenceOrCustomIdProps
+>(({ name, label, table, isOptional = false, helperText, ...rest }, ref) => {
+ const [isCustom, setIsCustom] = useState(false);
+ const { getInputProps, error } = useField(name);
+
+ return (
+ <div>
+ <HStack className="justify-between mb-2">
+ <FormControl isInvalid={!!error}>
+ {label && (
+ <FormLabel htmlFor={name} isOptional={isOptional}>
+ {label}
+ </FormLabel>
+ )}
+ <HStack className="w-full" spacing={0}>
+ {isCustom ? (
+ <Input
+ ref={ref}
+ {...getInputProps({
+ id: name,
+ placeholder: `Custom ${label}`,
+ ...rest,
+ })}
+ className="rounded-r-none"
+ />
+ ) : (
+ <Button
+ size="lg"
+ variant="secondary"
+ className="flex-grow bg-muted text-muted-foreground justify-start pl-4 h-10 rounded-r-none"
+ >
+ Next Sequence
+ </Button>
+ )}
+ <IconButton
+ aria-label="Toggle"
+ className="bg-transparent flex-shrink-0 h-10 rounded-l-none border-l-0 shadow-sm"
+ icon={isCustom ? <LuToggleLeft /> : <LuToggleRight />}
+ variant="secondary"
+ size="lg"
+ onClick={() => setIsCustom(!isCustom)}
+ />
+ </HStack>
+
+ {helperText && <FormHelperText>{helperText}</FormHelperText>}
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ </HStack>
+ </div>
+ );
+});
+
+SequenceOrCustomId.displayName = "SequenceOrCustomId";
+
+export default SequenceOrCustomId;
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 48b05fd261..8c320205d1 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -51,6 +51,7 @@ import Process from "./Process";
import Processes from "./Processes";
import RichText from "./RichText";
import Sequence from "./Sequence";
+import SequenceOrCustomId from "./SequenceOrCustomId";
import Service from "./Service";
import Shift from "./Shift";
import ShippingMethod from "./ShippingMethod";
@@ -117,6 +118,7 @@ export {
Select,
SelectControlled,
Sequence,
+ SequenceOrCustomId,
Service,
Shift,
ShippingMethod,
diff --git a/apps/carbon/app/components/Table/components/Filter/Filter.tsx b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
index dd104eaa24..25404f0b2f 100644
--- a/apps/carbon/app/components/Table/components/Filter/Filter.tsx
+++ b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
@@ -144,7 +144,10 @@ const Filter = forwardRef<HTMLButtonElement, FilterProps>(
</Button>
)}
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<Command>
<CommandInput
value={input}
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index e6f07aea9c..4cb5553941 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -39,11 +39,7 @@ import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { MethodItemType, MethodType } from "~/modules/shared";
-import {
- MethodIcon,
- methodItemType,
- MethodItemTypeIcon,
-} from "~/modules/shared";
+import { MethodIcon, MethodItemTypeIcon } from "~/modules/shared";
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
import { methodMaterialValidator } from "../../items.models";
@@ -444,6 +440,7 @@ function MaterialForm({
});
const onTypeChange = (value: MethodItemType) => {
+ if (value === itemType) return;
setItemType(value);
setItemData({
itemId: "",
@@ -514,47 +511,27 @@ function MaterialForm({
<Hidden name="order" />
<VStack className="pt-4">
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <Select
- name="itemType"
- label="Type"
- options={methodItemType.map((value) => ({
- value,
- label: value,
- }))}
- onChange={(value) => {
- onTypeChange(value?.value as MethodItemType);
- }}
- />
<Item
disabledItems={[params.itemId!]}
name="itemId"
label={itemType}
- // @ts-ignore
type={itemType}
onChange={(value) => {
onItemChange(value?.value as string);
}}
+ onTypeChange={onTypeChange}
/>
- <Select
- name="methodOperationId"
- label="Operation"
- isOptional
- options={methodOperations.map((o) => ({
- value: o.id!,
- label: o.description,
- }))}
+ <InputControlled
+ name="description"
+ label="Description"
+ className="col-span-2"
+ isReadOnly
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
/>
- </div>
- <InputControlled
- name="description"
- label="Description"
- isReadOnly
- value={itemData.description}
- onChange={(newValue) => {
- setItemData((d) => ({ ...d, description: newValue }));
- }}
- />
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+
<DefaultMethodType
name="methodType"
label="Method Type"
@@ -572,6 +549,15 @@ function MaterialForm({
}))
}
/>
+ <Select
+ name="methodOperationId"
+ label="Operation"
+ isOptional
+ options={methodOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
</div>
<motion.div
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index a9cc97d648..9837e3442b 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -1,3 +1,7 @@
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import { methodItemType } from "../shared";
+
export const deadlineTypes = [
"No Deadline",
"ASAP",
@@ -12,4 +16,28 @@ export const jobStatus = [
"Paused",
"Completed",
"Cancelled",
-];
+] as const;
+
+export const jobValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ jobId: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ itemType: z.enum(methodItemType).optional(),
+ customerId: zfd.text(z.string().optional()),
+ description: zfd.text(z.string().optional()),
+ dueDate: zfd.text(z.string().optional()),
+ deadlineType: z.enum(deadlineTypes, {
+ errorMap: () => ({ message: "Deadline type is required" }),
+ }),
+ locationId: z.string().min(1, { message: "Location is required" }),
+ quantity: zfd.numeric(z.number().min(0)),
+ status: z
+ .enum(jobStatus, {
+ errorMap: () => ({ message: "Status is required" }),
+ })
+ .optional(),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of measure is required" }),
+ modelUploadId: zfd.text(z.string().optional()),
+});
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 00cd0491c9..f3ec35b6f4 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -1,7 +1,10 @@
-import type { Database } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
+import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
+import type { jobValidator } from "./production.models";
export async function getJob(client: SupabaseClient<Database>, id: string) {
return client.from("jobs").select("*").eq("id", id).single();
@@ -42,3 +45,31 @@ export async function getJobsList(
.eq("companyId", companyId)
.order("jobId");
}
+
+export async function upsertJob(
+ client: SupabaseClient<Database>,
+ job:
+ | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
+ jobId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
+ id: string;
+ jobId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("updatedBy" in job) {
+ return client
+ .from("job")
+ .update(sanitize(job))
+ .eq("id", job.id)
+ .select("id")
+ .single();
+ } else {
+ return client.from("job").insert([job]).select("id").single();
+ }
+}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
new file mode 100644
index 0000000000..d21381a298
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
@@ -0,0 +1,217 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ VStack,
+ cn,
+} from "@carbon/react";
+import { useState } from "react";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Customer,
+ DatePicker,
+ Hidden,
+ Input,
+ InputControlled,
+ Item,
+ Location,
+ NumberControlled,
+ Select,
+ SequenceOrCustomId,
+ Submit,
+ UnitOfMeasure,
+} from "~/components/Form";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { deadlineTypes, jobValidator } from "~/modules/production";
+import { type MethodItemType } from "~/modules/shared";
+
+type JobFormValues = z.infer<typeof jobValidator>;
+
+type JobFormProps = {
+ initialValues: JobFormValues;
+};
+
+const JobForm = ({ initialValues }: JobFormProps) => {
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+ const [type, setType] = useState<MethodItemType>(
+ initialValues.itemType ?? "Part"
+ );
+
+ const [itemData, setItemData] = useState<{
+ itemId: string;
+ description: string;
+ uom: string;
+ quantity: number;
+ modelUploadId: string | null;
+ }>({
+ itemId: initialValues.itemId ?? "",
+ description: initialValues.description ?? "",
+ quantity: initialValues.quantity ?? 0,
+ uom: initialValues.unitOfMeasureCode ?? "",
+ modelUploadId: initialValues.modelUploadId ?? null,
+ });
+
+ const isCustomer = permissions.is("customer");
+ const isEditing = initialValues.id !== undefined;
+
+ const onTypeChange = (t: MethodItemType) => {
+ setType(t);
+ setItemData({
+ itemId: "",
+ description: "",
+ uom: "EA",
+ quantity: 0,
+ modelUploadId: null,
+ });
+ };
+
+ const onItemChange = async (itemId: string) => {
+ if (!itemId) return;
+ if (!supabase || !company.id) return;
+ const [item, manufacturing] = await Promise.all([
+ supabase
+ .from("item")
+ .select(
+ "name, readableId, defaultMethodType, unitOfMeasureCode, modelUploadId"
+ )
+ .eq("id", itemId)
+ .eq("companyId", company.id)
+ .single(),
+ supabase
+ .from("itemReplenishment")
+ .select("lotSize")
+ .eq("itemId", itemId)
+ .single(),
+ ]);
+
+ setItemData({
+ itemId,
+ description: item.data?.name ?? "",
+ uom: item.data?.unitOfMeasureCode ?? "EA",
+ quantity: manufacturing?.data?.lotSize ?? 0,
+ modelUploadId: item.data?.modelUploadId ?? null,
+ });
+ };
+
+ return (
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={jobValidator}
+ defaultValues={initialValues}
+ >
+ <CardHeader>
+ <CardTitle>{isEditing ? "Job" : "New Job"}</CardTitle>
+ {!isEditing && (
+ <CardDescription>
+ A job is a set of work to be done to fulfill an order or increase
+ inventory
+ </CardDescription>
+ )}
+ </CardHeader>
+ <CardContent>
+ <Hidden name="id" />
+ <Hidden
+ name="modelUploadId"
+ value={itemData.modelUploadId ?? undefined}
+ />
+ <VStack>
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-2"
+ )}
+ >
+ {isEditing ? (
+ <Input name="jobId" label="Job ID" isReadOnly />
+ ) : (
+ <SequenceOrCustomId name="jobId" label="Job ID" table="job" />
+ )}
+
+ <Customer
+ autoFocus={!isEditing}
+ name="customerId"
+ label="Customer"
+ isOptional
+ />
+
+ <Item
+ name="itemId"
+ label={type}
+ type={type}
+ value={itemData.itemId}
+ validItemTypes={["Part", "Fixture"]}
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ onTypeChange={onTypeChange}
+ />
+ <Location name="locationId" label="Location" />
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ isReadOnly
+ className="col-span-2"
+ />
+ <NumberControlled
+ name="quantity"
+ label="Quantity"
+ value={itemData.quantity}
+ onChange={(value) =>
+ setItemData((prev) => ({ ...prev, quantity: value }))
+ }
+ minValue={0}
+ />
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ value={itemData.uom}
+ onChange={(value) => {
+ if (value?.value) {
+ setItemData((prev) => ({ ...prev, uom: value.value }));
+ }
+ }}
+ />
+
+ <DatePicker
+ name="dueDate"
+ label="Due Date"
+ isDisabled={isCustomer}
+ />
+ <Select
+ name="deadlineType"
+ label="Deadline Type"
+ options={deadlineTypes.map((d) => ({
+ value: d,
+ label: d,
+ }))}
+ />
+ <CustomFormFields table="job" />
+ </div>
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={
+ isEditing
+ ? !permissions.can("update", "production")
+ : !permissions.can("create", "production")
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+};
+
+export default JobForm;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
index fe708bf64b..6553253a87 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -286,7 +286,7 @@ const JobsTable = memo(({ data, count, locations }: JobsTableProps) => {
count={count ?? 0}
primaryAction={
permissions.can("update", "resources") && (
- <New label="Job" to={`new?${params.toString()}`} />
+ <New label="Job" to={path.to.newJob} />
)
}
renderContextMenu={renderContextMenu}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/index.ts b/apps/carbon/app/modules/production/ui/Jobs/index.ts
index 3f821670fa..8f3f756d4f 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/index.ts
+++ b/apps/carbon/app/modules/production/ui/Jobs/index.ts
@@ -1,5 +1,6 @@
import { getDeadlineIcon, getDeadlineText } from "./Deadline";
+import JobForm from "./JobForm";
import JobsTable from "./JobsTable";
import JobStatus from "./JobStatus";
-export { getDeadlineIcon, getDeadlineText, JobsTable, JobStatus };
+export { getDeadlineIcon, getDeadlineText, JobForm, JobsTable, JobStatus };
diff --git a/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx b/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
index 8263e20b60..8389dc6af3 100644
--- a/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
@@ -1,4 +1,4 @@
-import { LuHammer } from "react-icons/lu";
+import { LuHardHat } from "react-icons/lu";
import type { RouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -8,8 +8,8 @@ const productionRoutes: RouteGroup[] = [
routes: [
{
name: "Jobs",
- to: path.to.abilities,
- icon: <LuHammer />,
+ to: path.to.jobs,
+ icon: <LuHardHat />,
},
],
},
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 8889a1d7dd..f7acb9abee 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -40,11 +40,7 @@ import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { MethodItemType, MethodType } from "~/modules/shared";
-import {
- MethodIcon,
- methodItemType,
- MethodItemTypeIcon,
-} from "~/modules/shared";
+import { MethodIcon, MethodItemTypeIcon } from "~/modules/shared";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
@@ -544,17 +540,6 @@ function MaterialForm({
)}
<VStack className="pt-4">
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <Select
- name="itemType"
- label="Type"
- options={methodItemType.map((value) => ({
- value,
- label: value,
- }))}
- onChange={(value) => {
- onTypeChange(value?.value as MethodItemType);
- }}
- />
<Item
disabledItems={[params.itemId!]}
isReadOnly={isDisabled}
@@ -565,26 +550,18 @@ function MaterialForm({
onChange={(value) => {
onItemChange(value?.value as string);
}}
+ onTypeChange={onTypeChange}
/>
- <Select
- name="quoteOperationId"
- label="Operation"
- isClearable
- options={quoteOperations.map((o) => ({
- value: o.id!,
- label: o.description,
- }))}
+ <InputControlled
+ className="col-span-2"
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
/>
- </div>
- <InputControlled
- name="description"
- label="Description"
- value={itemData.description}
- onChange={(newValue) => {
- setItemData((d) => ({ ...d, description: newValue }));
- }}
- />
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+
<DefaultMethodType
name="methodType"
label="Method Type"
@@ -602,6 +579,15 @@ function MaterialForm({
}))
}
/>
+ <Select
+ name="quoteOperationId"
+ label="Operation"
+ isClearable
+ options={quoteOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
{itemData.methodType !== "Make" && (
<NumberControlled
name="unitCost"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 368a870f4d..8cc98875b6 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -33,7 +33,6 @@ import { useSupabase } from "~/lib/supabase";
import type { quoteOperationValidator } from "~/modules/sales";
import { quoteMaterialValidator } from "~/modules/sales";
import type { MethodItemType, MethodType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
type QuoteMaterialFormProps = {
@@ -193,17 +192,6 @@ const QuoteMaterialForm = ({
<Hidden name="order" />
<VStack className="pt-4">
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <Select
- name="itemType"
- label="Type"
- options={methodItemType.map((value) => ({
- value,
- label: value,
- }))}
- onChange={(value) => {
- onTypeChange(value?.value as MethodItemType);
- }}
- />
<Item
name="itemId"
label={itemType}
@@ -212,6 +200,7 @@ const QuoteMaterialForm = ({
onChange={(value) => {
onItemChange(value?.value as string);
}}
+ onTypeChange={onTypeChange}
/>
<Select
name="quoteOperationId"
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index 9a098ba8ff..28c852c66f 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -36,7 +36,6 @@ import {
Location,
Number,
NumberControlled,
- Select,
SelectControlled,
Submit,
UnitOfMeasure,
@@ -49,7 +48,7 @@ import type {
SalesOrderLine,
SalesOrderLineType,
} from "~/modules/sales";
-import { salesOrderLineType, salesOrderLineValidator } from "~/modules/sales";
+import { salesOrderLineValidator } from "~/modules/sales";
import { methodType } from "~/modules/shared";
import { path } from "~/utils/path";
import DeleteSalesOrderLine from "./DeleteSalesOrderLine";
@@ -122,13 +121,6 @@ const SalesOrderLineForm = ({
const isEditing = initialValues.id !== undefined;
- const salesOrderLineTypeOptions = salesOrderLineType
- .filter((type) => type !== "Fixed Asset")
- .map((type) => ({
- label: type,
- value: type,
- }));
-
const onTypeChange = (t: SalesOrderLineType) => {
// @ts-ignore
setLineType(t);
@@ -278,34 +270,18 @@ const SalesOrderLineForm = ({
/>
<VStack>
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <Select
- name="salesOrderLineType"
- label="Type"
- options={salesOrderLineTypeOptions}
+ <Item
+ name="itemId"
+ label={lineType}
+ type={lineType as "Part"}
+ typeFieldName="salesOrderLineType"
+ value={itemData.itemId}
onChange={(value) => {
- onTypeChange(value?.value as SalesOrderLineType);
+ onChange(value?.value as string);
}}
+ onTypeChange={onTypeChange}
/>
- {[
- "Part",
- "Material",
- "Service",
- "Tool",
- "Fixture",
- "Consumable",
- ].includes(lineType) && (
- <Item
- name="itemId"
- label={lineType}
- type={lineType as "Part"}
- value={itemData.itemId}
- onChange={(value) => {
- onChange(value?.value as string);
- }}
- />
- )}
-
<InputControlled
name="description"
label="Description"
diff --git a/apps/carbon/app/routes/x+/job+/$jobId._index.tsx b/apps/carbon/app/routes/x+/job+/$jobId._index.tsx
new file mode 100644
index 0000000000..1e2928f513
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId._index.tsx
@@ -0,0 +1,9 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+ throw redirect(path.to.jobDetails(jobId));
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
new file mode 100644
index 0000000000..820495ecf2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -0,0 +1,110 @@
+import {
+ ClientOnly,
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+ ScrollArea,
+ VStack,
+} from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useParams } from "@remix-run/react";
+import {
+ getJob,
+ getJobDocuments,
+ getJobMethodTrees,
+ JobBreadcrumbs,
+ JobExplorer,
+ JobHeader,
+} from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Jobs",
+ to: path.to.jobs,
+ module: "production",
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+
+ const [job, methods, files] = await Promise.all([
+ getJob(client, jobId),
+ getJobMethodTrees(client, jobId),
+ getJobDocuments(client, jobId),
+ ]);
+
+ if (job.error) {
+ throw redirect(
+ path.to.jobs,
+ await flash(request, error(job.error, "Failed to load job"))
+ );
+ }
+
+ if (methods.error) {
+ throw redirect(
+ path.to.jobs,
+ await flash(request, error(methods.error, "Failed to load job method"))
+ );
+ }
+
+ return json({
+ job: job.data,
+ methods: methods.data ?? [],
+ files: files.data ?? [],
+ });
+}
+
+export default function JobRoute() {
+ const params = useParams();
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+
+ return (
+ <div className="flex flex-col h-[calc(100vh-49px)] w-full">
+ <JobHeader />
+ <div className="flex h-[calc(100vh-99px)] w-full">
+ <div className="flex h-full w-full overflow-y-auto">
+ <div className="flex flex-grow overflow-hidden">
+ <ClientOnly fallback={null}>
+ {() => (
+ <ResizablePanelGroup direction="horizontal">
+ <ResizablePanel
+ order={1}
+ minSize={10}
+ defaultSize={20}
+ className="bg-card h-full"
+ >
+ <ScrollArea className="h-[calc(100vh-99px)]">
+ <div className="grid w-full h-full overflow-hidden">
+ <JobExplorer />
+ </div>
+ </ScrollArea>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel order={2}>
+ <ScrollArea className="h-[calc(100vh-99px)]">
+ <VStack spacing={2} className="p-2">
+ <JobBreadcrumbs />
+ <Outlet />
+ </VStack>
+ </ScrollArea>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ )}
+ </ClientOnly>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/_layout.tsx b/apps/carbon/app/routes/x+/job+/_layout.tsx
new file mode 100644
index 0000000000..c3b07966e6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/_layout.tsx
@@ -0,0 +1,27 @@
+import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
+import { json, Outlet } from "@remix-run/react";
+import { requirePermissions } from "~/services/auth/auth.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Jobs" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: "Production",
+ to: path.to.production,
+ module: "production",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ view: "production",
+ });
+
+ return json({});
+}
+
+export default function JobRoute() {
+ return <Outlet />;
+}
diff --git a/apps/carbon/app/routes/x+/job+/new.tsx b/apps/carbon/app/routes/x+/job+/new.tsx
new file mode 100644
index 0000000000..1c697eb14f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/new.tsx
@@ -0,0 +1,94 @@
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useUrlParams, useUser } from "~/hooks";
+import { JobForm, jobValidator, upsertJob } from "~/modules/production";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import type { Handle } from "~/utils/handle";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Jobs",
+ to: path.to.jobs,
+ module: "production",
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(jobValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ let jobId = validation.data.jobId;
+ const useNextSequence = !jobId;
+ if (useNextSequence) {
+ const nextSequence = await getNextSequence(client, "job", companyId);
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.newJob,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+ jobId = nextSequence.data;
+ }
+
+ if (!jobId) throw new Error("jobId is not defined");
+
+ const createJob = await upsertJob(client, {
+ ...validation.data,
+ jobId,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createJob.error || !createJob.data) {
+ // TODO: this should be done as a transaction
+ await rollbackNextSequence(client, "job", companyId);
+ throw redirect(
+ path.to.jobs,
+ await flash(request, error(createJob.error, "Failed to insert job"))
+ );
+ }
+
+ throw redirect(path.to.job(createJob.data?.id!));
+}
+
+export default function JobNewRoute() {
+ const { defaults } = useUser();
+ const [params] = useUrlParams();
+ const customerId = params.get("customerId");
+
+ const initialValues = {
+ customerId: customerId ?? "",
+ deadlineType: "No Deadline" as const,
+ dueDate: "",
+ itemId: "",
+ itemType: "Part" as const,
+ jobId: undefined,
+ locationId: defaults?.locationId ?? "",
+ quantity: 0,
+ unitOfMeasureCode: "EA",
+ };
+
+ return (
+ <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <JobForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 42f7ac5917..4cd03acba9 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -352,8 +352,9 @@ export const path = {
itemCostUpdate: (id: string) => generatePath(`${x}/items/cost/${id}`),
itemPostingGroup: (id: string) => generatePath(`${x}/items/groups/${id}`),
itemPostingGroups: `${x}/items/groups`,
- jobs: `${x}/production/jobs`,
job: (id: string) => generatePath(`${x}/job/${id}`),
+ jobDetails: (id: string) => generatePath(`${x}/job/${id}/details`),
+ jobs: `${x}/production/jobs`,
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
locations: `${x}/resources/locations`,
login: "/login",
@@ -433,6 +434,7 @@ export const path = {
generatePath(`${x}/fixture/${id}/purchasing/new`),
newGroup: `${x}/users/groups/new`,
newHoliday: `${x}/people/holidays/new`,
+ newJob: `${x}/job/new`,
newLocation: `${x}/resources/locations/new`,
newMaterial: `${x}/material/new`,
newMethodMaterial: `${x}/items/methods/material/new`,
diff --git a/packages/database/supabase/migrations/20240909194622_jobs.sql b/packages/database/supabase/migrations/20240909194622_jobs.sql
index 4358f89fab..6184766779 100644
--- a/packages/database/supabase/migrations/20240909194622_jobs.sql
+++ b/packages/database/supabase/migrations/20240909194622_jobs.sql
@@ -92,10 +92,7 @@ CREATE TABLE "public"."job" (
"status" "jobStatus" NOT NULL DEFAULT 'Draft',
"dueDate" DATE,
"deadlineType" "deadlineType" NOT NULL DEFAULT 'No Deadline',
- "orderQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
- "inventoryQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
- "productionQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
- "scrapQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "quantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
"quantityComplete" NUMERIC(10, 4) NOT NULL DEFAULT 0,
"quantityShipped" NUMERIC(10, 4) NOT NULL DEFAULT 0,
"quantityReceivedToInventory" NUMERIC(10, 4) NOT NULL DEFAULT 0,
@@ -103,6 +100,7 @@ CREATE TABLE "public"."job" (
"salesOrderLineId" TEXT,
"quoteId" TEXT,
"quoteLineId" TEXT,
+ "modelUploadId" TEXT,
"notes" JSONB DEFAULT '{}'::jsonb,
"assignee" TEXT,
"customFields" JSONB,
@@ -122,6 +120,7 @@ CREATE TABLE "public"."job" (
CONSTRAINT "job_salesOrderLineId_fkey" FOREIGN KEY ("salesOrderLineId") REFERENCES "salesOrderLine" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "job_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "job_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "job_modelUploadId_fkey" FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "job_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "job_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "job_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
@@ -290,4 +289,8 @@ CREATE OR REPLACE VIEW "jobs" WITH(SECURITY_INVOKER=true) AS
INNER JOIN "item" i ON j."itemId" = i."id"
LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
LEFT JOIN "salesOrder" so on j."salesOrderId" = so.id
- LEFT JOIN "quote" qo ON j."quoteId" = qo.id;
\ No newline at end of file
+ LEFT JOIN "quote" qo ON j."quoteId" = qo.id;
+
+
+INSERT INTO "customFieldTable" ("table", "name", "module")
+VALUES ('job', 'Job', 'Production');
\ No newline at end of file
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 54e5db0c48..e5c1e160e5 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -71,7 +71,10 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
)}
</CommandTrigger>
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<VirtualizedCommand
options={options}
value={value}
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index 27cc00bfc3..3e4647623a 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -57,7 +57,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
const [open, setOpen] = useState(false);
return (
- <HStack spacing={1}>
+ <HStack className="w-full" spacing={1}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<CommandTrigger
@@ -77,7 +77,10 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
)}
</CommandTrigger>
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<VirtualizedCommand
options={options}
selected={selected}
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index 359ae03614..5232756536 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -119,7 +119,10 @@ const CreatableMultiSelect = forwardRef<
</div>
</Button>
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<VirtualizedCommand
options={options}
selected={value}
diff --git a/packages/react/src/Date/DatePicker.tsx b/packages/react/src/Date/DatePicker.tsx
index c8f9e45853..d15f99e2f9 100644
--- a/packages/react/src/Date/DatePicker.tsx
+++ b/packages/react/src/Date/DatePicker.tsx
@@ -3,8 +3,9 @@ import { useDatePicker } from "@react-aria/datepicker";
import { useDatePickerState } from "@react-stately/datepicker";
import type { DatePickerProps } from "@react-types/datepicker";
import { useRef } from "react";
-import { MdOutlineCalendarToday, MdOutlineDoNotDisturb } from "react-icons/md";
-import { InputGroup, InputRightElement } from "../Input";
+import { MdOutlineDoNotDisturb } from "react-icons/md";
+import { HStack } from "../HStack";
+import { InputGroup } from "../Input";
import { useOutsideClick } from "../hooks";
import { FieldButton } from "./components/Button";
import { Calendar } from "./components/Calendar";
@@ -26,19 +27,22 @@ const DatePicker = (props: DatePickerProps<CalendarDate>) => {
return (
<div className="relative inline-flex flex-col w-full">
- <InputGroup {...groupProps} ref={ref} className="w-full inline-flex">
- <div className="flex w-full px-4 py-2">
- <DateField {...fieldProps} />
- {state.isInvalid && (
- <MdOutlineDoNotDisturb className="text-destructive-foreground aboslute right-[12px]" />
- )}
- </div>
- <InputRightElement className="pr-1">
- <FieldButton {...buttonProps} isPressed={state.isOpen}>
- <MdOutlineCalendarToday />
- </FieldButton>
- </InputRightElement>
- </InputGroup>
+ <HStack className="w-full" spacing={0}>
+ <InputGroup
+ {...groupProps}
+ ref={ref}
+ className="w-full inline-flex rounded-r-none"
+ >
+ <div className="flex w-full px-4 py-2">
+ <DateField {...fieldProps} />
+ {state.isInvalid && (
+ <MdOutlineDoNotDisturb className="text-destructive-foreground aboslute right-[12px]" />
+ )}
+ </div>
+ </InputGroup>
+
+ <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ </HStack>
{state.isOpen && (
<Popover {...dialogProps} onClose={() => state.setOpen(false)}>
<Calendar {...calendarProps} />
diff --git a/packages/react/src/Date/DateRangePicker.tsx b/packages/react/src/Date/DateRangePicker.tsx
index 488ba607c4..c50a7caf90 100644
--- a/packages/react/src/Date/DateRangePicker.tsx
+++ b/packages/react/src/Date/DateRangePicker.tsx
@@ -2,8 +2,9 @@ import { useDateRangePicker } from "@react-aria/datepicker";
import { useDateRangePickerState } from "@react-stately/datepicker";
import type { DateRangePickerProps, DateValue } from "@react-types/datepicker";
import { useRef } from "react";
-import { MdCalendarToday, MdOutlineDoNotDisturb } from "react-icons/md";
-import { InputGroup, InputRightElement } from "../Input";
+import { MdOutlineDoNotDisturb } from "react-icons/md";
+import { HStack } from "../HStack";
+import { InputGroup } from "../Input";
import TimeField from "./TimePicker";
import { FieldButton } from "./components/Button";
import DateField from "./components/DateField";
@@ -27,23 +28,26 @@ const DateRangePicker = (props: DateRangePickerProps<DateValue>) => {
return (
<div className="relative inline-flex flex-col w-full">
- <InputGroup {...groupProps} ref={ref} className="w-full inline-flex">
- <div className="flex w-auto px-4 py-2">
- <DateField {...startFieldProps} />
- <span aria-hidden="true" className="px-2">
- –
- </span>
- <DateField {...endFieldProps} />
- {state.isInvalid && (
- <MdOutlineDoNotDisturb className="text-destructive-foreground aboslute right-[12px]" />
- )}
- </div>
- <InputRightElement>
- <FieldButton {...buttonProps} isPressed={state.isOpen}>
- <MdCalendarToday />
- </FieldButton>
- </InputRightElement>
- </InputGroup>
+ <HStack className="w-full" spacing={0}>
+ <InputGroup
+ {...groupProps}
+ ref={ref}
+ className="w-full inline-flex rounded-r-none"
+ >
+ <div className="flex w-full px-4 py-2">
+ <DateField {...startFieldProps} />
+ <span aria-hidden="true" className="px-2">
+ –
+ </span>
+ <DateField {...endFieldProps} />
+ {state.isInvalid && (
+ <MdOutlineDoNotDisturb className="text-destructive-foreground absolute right-[12px]" />
+ )}
+ </div>
+ </InputGroup>
+
+ <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ </HStack>
{state.isOpen && (
<Popover
{...dialogProps}
diff --git a/packages/react/src/Date/DateTimePicker.tsx b/packages/react/src/Date/DateTimePicker.tsx
index 08280e0c76..dc79bcbf71 100644
--- a/packages/react/src/Date/DateTimePicker.tsx
+++ b/packages/react/src/Date/DateTimePicker.tsx
@@ -3,9 +3,10 @@ import { useDatePicker } from "@react-aria/datepicker";
import { useDatePickerState } from "@react-stately/datepicker";
import type { DatePickerProps } from "@react-types/datepicker";
import { useRef } from "react";
-import { MdOutlineCalendarToday, MdOutlineDoNotDisturb } from "react-icons/md";
-import { InputGroup, InputRightElement } from "../Input";
-
+import { MdOutlineDoNotDisturb } from "react-icons/md";
+import { HStack } from "../HStack";
+import { InputGroup } from "../Input";
+import { useOutsideClick } from "../hooks";
import TimeField from "./TimePicker";
import { FieldButton } from "./components/Button";
import { Calendar } from "./components/Calendar";
@@ -21,32 +22,31 @@ const DateTimePicker = (props: DatePickerProps<DateValue>) => {
const { groupProps, fieldProps, buttonProps, dialogProps, calendarProps } =
useDatePicker(props, state, ref);
+ useOutsideClick({
+ ref,
+ handler: () => state.setOpen(false),
+ });
+
return (
<div className="relative inline-flex flex-col w-full">
- <InputGroup
- {...groupProps}
- ref={ref}
- width="auto"
- className="w-full inline-flex"
- >
- <div className="flex w-full px-4 py-2">
- <DateField {...fieldProps} />
- {state.isInvalid && (
- <MdOutlineDoNotDisturb className="text-destructive-foreground aboslute right-[12px]" />
- )}
- </div>
- <InputRightElement>
- <FieldButton {...buttonProps} isPressed={state.isOpen}>
- <MdOutlineCalendarToday />
- </FieldButton>
- </InputRightElement>
- </InputGroup>
- {state.isOpen && (
- <Popover
- {...dialogProps}
- isOpen={state.isOpen}
- onClose={() => state.setOpen(false)}
+ <HStack className="w-full" spacing={0}>
+ <InputGroup
+ {...groupProps}
+ ref={ref}
+ className="w-full inline-flex rounded-r-none"
>
+ <div className="flex w-full px-4 py-2">
+ <DateField {...fieldProps} />
+ {state.isInvalid && (
+ <MdOutlineDoNotDisturb className="text-destructive-foreground absolute right-[12px]" />
+ )}
+ </div>
+ </InputGroup>
+
+ <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ </HStack>
+ {state.isOpen && (
+ <Popover {...dialogProps} onClose={() => state.setOpen(false)}>
<Calendar {...calendarProps} />
<TimeField
label="Time"
diff --git a/packages/react/src/Date/components/Button.tsx b/packages/react/src/Date/components/Button.tsx
index 9aa41cbd89..a4517e041d 100644
--- a/packages/react/src/Date/components/Button.tsx
+++ b/packages/react/src/Date/components/Button.tsx
@@ -1,7 +1,7 @@
import { useButton } from "@react-aria/button";
import type { AriaButtonProps } from "@react-types/button";
import { useRef } from "react";
-import { Button } from "../../Button";
+import { LuCalendar } from "react-icons/lu";
import type { IconButtonProps } from "../../IconButton";
import { IconButton } from "../../IconButton";
@@ -21,20 +21,21 @@ export const CalendarButton = (props: AriaButtonProps & IconButtonProps) => {
export interface FieldButtonProps extends AriaButtonProps {
isPressed: boolean;
+ className?: string;
}
export const FieldButton = (props: FieldButtonProps) => {
const ref = useRef<HTMLButtonElement>(null);
const { buttonProps } = useButton(props, ref);
return (
- <Button
- className="rounded-sm"
+ <IconButton
{...buttonProps}
ref={ref}
- isIcon
- variant="solid"
- >
- {props.children}
- </Button>
+ aria-label="Toggle"
+ className="flex-shrink-0 h-10 rounded-l-none border-l-0 shadow-sm"
+ icon={<LuCalendar />}
+ variant="secondary"
+ size="lg"
+ />
);
};
diff --git a/packages/react/src/Input.tsx b/packages/react/src/Input.tsx
index 2c804d44cc..098d707d04 100644
--- a/packages/react/src/Input.tsx
+++ b/packages/react/src/Input.tsx
@@ -195,14 +195,14 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
className={cn(
inputVariants({
size,
- className,
isInputGroup,
isFirstChild,
isLastChild,
isInvalid,
isReadOnly,
isDisabled,
- })
+ }),
+ className
)}
{...props}
disabled={isDisabled}
diff --git a/packages/react/src/MultiSelect.tsx b/packages/react/src/MultiSelect.tsx
index 759f268689..f24acb2651 100644
--- a/packages/react/src/MultiSelect.tsx
+++ b/packages/react/src/MultiSelect.tsx
@@ -113,7 +113,10 @@ const MultiSelect = forwardRef<HTMLButtonElement, MultiSelectProps>(
</div>
</Button>
</PopoverTrigger>
- <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <PopoverContent
+ align="start"
+ className="min-w-[260px] w-[--radix-popover-trigger-width] p-0"
+ >
<VirtualizedCommand
options={options}
value={value}