Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: edit production events

Brad Barbinefa2240cb672
diff --git a/apps/carbon/app/assets/icons/TodoStatusIcon.tsx b/apps/carbon/app/assets/icons/TodoStatusIcon.tsx
index 58458ad63c..839bd62c05 100644
--- a/apps/carbon/app/assets/icons/TodoStatusIcon.tsx
+++ b/apps/carbon/app/assets/icons/TodoStatusIcon.tsx
@@ -6,7 +6,7 @@ export function TodoStatusIcon({ className }: { className?: string }) {
viewBox="0 0 14 14"
fill="none"
color="currentColor"
- className="className"
+ className={className}
>
<circle
cx="7"
diff --git a/apps/carbon/app/components/CustomerAvatar.tsx b/apps/carbon/app/components/CustomerAvatar.tsx
index 83cec88af0..24859eac6c 100644
--- a/apps/carbon/app/components/CustomerAvatar.tsx
+++ b/apps/carbon/app/components/CustomerAvatar.tsx
@@ -24,9 +24,11 @@ const CustomerAvatar = ({
};
return (
- <HStack className="truncate">
+ <HStack className="truncate no-underline hover:no-underline">
<Avatar size={size ?? "xs"} {...props} name={customer?.name ?? ""} />
- <span className={cn("normal-case font-medium", className)}>
+ <span
+ className={cn("normal-case font-normal tracking-normal", className)}
+ >
{customer.name}
</span>
</HStack>
diff --git a/apps/carbon/app/components/DirectionAwareTabs.tsx b/apps/carbon/app/components/DirectionAwareTabs.tsx
index 3255627af7..09f79f1c2f 100644
--- a/apps/carbon/app/components/DirectionAwareTabs.tsx
+++ b/apps/carbon/app/components/DirectionAwareTabs.tsx
@@ -78,7 +78,7 @@ function DirectionAwareTabs({
disabled={tab.disabled}
onClick={() => handleTabClick(tab.id)}
className={cn(
- "relative rounded-md px-3.5 py-1.5 text-xs sm:text-sm font-medium text-foreground/80 transition focus-visible:outline-1 focus-visible:ring-1 focus-visible:outline-none flex gap-2 items-center ",
+ "relative rounded-md px-3.5 py-1.5 text-xs sm:text-sm font-medium text-foreground/80 transition focus-visible:outline-1 focus-visible:ring-2 ring-ring ring-offset-ring focus-visible:outline-none flex gap-2 items-center ",
activeTab === tab.id
? "text-foreground"
: "hover:text-foreground/60 text-foreground/80",
diff --git a/apps/carbon/app/components/Editable/EditableDateTime.tsx b/apps/carbon/app/components/Editable/EditableDateTime.tsx
new file mode 100644
index 0000000000..e7a5fa0ecd
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditableDateTime.tsx
@@ -0,0 +1,59 @@
+/* eslint-disable react/display-name */
+
+import { DateTimePicker } from "@carbon/react";
+import type { DateValue } from "@internationalized/date";
+import { getLocalTimeZone, parseAbsolute } from "@internationalized/date";
+import type { PostgrestSingleResponse } from "@supabase/supabase-js";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+
+const EditableDateTime =
+ <T extends object>(
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: T
+ ) => Promise<PostgrestSingleResponse<unknown>>
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<T>) => {
+ const defaultValue = (
+ typeof value === "string"
+ ? parseAbsolute(value, getLocalTimeZone())
+ : value
+ ) as DateValue | null | undefined;
+
+ const updateDate = async (newValue: DateValue) => {
+ // this is the optimistic update on the FE
+ onUpdate({ [accessorKey]: newValue.toString() });
+
+ // this is the actual update on the BE
+ mutation(accessorKey, newValue.toString(), row)
+ .then(({ error }) => {
+ if (error) {
+ onError();
+ onUpdate({ [accessorKey]: value });
+ }
+ })
+ .catch(() => {
+ onError();
+ onUpdate({ [accessorKey]: value });
+ });
+ };
+
+ return (
+ <DateTimePicker
+ className="w-full rounded-none outline-none border-none focus-visible:ring-0"
+ defaultValue={defaultValue}
+ onChange={updateDate}
+ autoFocus
+ withButton={false}
+ />
+ );
+ };
+
+export default EditableDateTime;
diff --git a/apps/carbon/app/components/Editable/EditableNumber.tsx b/apps/carbon/app/components/Editable/EditableNumber.tsx
index 27c491f075..6702e28e89 100644
--- a/apps/carbon/app/components/Editable/EditableNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableNumber.tsx
@@ -61,10 +61,15 @@ const EditableNumber =
<NumberField {...numberFieldProps} defaultValue={value as number}>
<Input
size="sm"
- className="w-full rounded-none ring-offset-0"
+ className="w-full rounded-none outline-none border-none focus-visible:ring-0 out"
autoFocus
onKeyDown={onKeyDown}
onBlur={onBlur}
+ ref={(input) => {
+ if (input) {
+ input.select();
+ }
+ }}
/>
</NumberField>
);
diff --git a/apps/carbon/app/components/Editable/index.ts b/apps/carbon/app/components/Editable/index.ts
index 3af30890b1..06ada8d376 100644
--- a/apps/carbon/app/components/Editable/index.ts
+++ b/apps/carbon/app/components/Editable/index.ts
@@ -1,3 +1,4 @@
+import EditableDateTime from "./EditableDateTime";
import EditableList from "./EditableList";
import EditableNumber from "./EditableNumber";
import EditablePurchaseInvoiceLineNumber from "./EditablePurchaseInvoiceLineNumber";
@@ -6,6 +7,7 @@ import EditableText from "./EditableText";
export * from "./types";
export {
+ EditableDateTime,
EditableList,
EditableNumber,
EditablePurchaseInvoiceLineNumber,
diff --git a/apps/carbon/app/components/EmployeeAvatar.tsx b/apps/carbon/app/components/EmployeeAvatar.tsx
index 76b36466c0..5909340278 100644
--- a/apps/carbon/app/components/EmployeeAvatar.tsx
+++ b/apps/carbon/app/components/EmployeeAvatar.tsx
@@ -23,10 +23,10 @@ const EmployeeAvatar = ({
if (!person && people.length > 0) {
return (
- <HStack>
+ <HStack className="no-underline">
<Avatar size={"xs"} {...props} />
{withName && (
- <span className="text-muted-foreground normal-case font-medium">
+ <span className="text-muted-foreground normal-case font-normal tracking-normal tracking-normal">
Deactivated user
</span>
)}
@@ -39,14 +39,16 @@ const EmployeeAvatar = ({
}
return (
- <HStack className="truncate">
+ <HStack className="truncate no-underline hover:no-underline">
<Avatar
size={size ?? "xs"}
path={person.avatarUrl ?? undefined}
name={person?.name ?? ""}
/>
{withName && (
- <span className={cn("normal-case font-medium", className)}>
+ <span
+ className={cn("normal-case font-normal tracking-normal", className)}
+ >
{person.name}
</span>
)}
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index bc5301a077..a4e0bbab86 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -7,6 +7,7 @@ import {
CreatableCombobox,
CreatableMultiSelect,
DatePicker,
+ DateTimePicker,
Hidden,
Input,
InputControlled,
@@ -94,6 +95,7 @@ export {
CustomerType,
CustomFormFields,
DatePicker,
+ DateTimePicker,
DefaultMethodType,
Department,
Employee,
diff --git a/apps/carbon/app/components/Grid/components/Cell.tsx b/apps/carbon/app/components/Grid/components/Cell.tsx
index 46a410e3de..e4eaf01aae 100644
--- a/apps/carbon/app/components/Grid/components/Cell.tsx
+++ b/apps/carbon/app/components/Grid/components/Cell.tsx
@@ -50,7 +50,8 @@ const Cell = <T extends object>({
wasEdited && "bg-yellow-100 dark:bg-yellow-900",
!hasEditableTableCellComponent && "bg-muted/50",
hasError && "ring-inset ring-2 ring-red-500",
- isSelected && "ring-inset ring-2 ring-ring"
+ isSelected && "!ring-inset !ring-2 !ring-ring",
+ isSelected && hasEditableTableCellComponent && "!bg-background"
)}
ref={ref}
data-row={cell.row.index}
diff --git a/apps/carbon/app/components/Icons.tsx b/apps/carbon/app/components/Icons.tsx
index 64b4d1dafb..fa1f7f409e 100644
--- a/apps/carbon/app/components/Icons.tsx
+++ b/apps/carbon/app/components/Icons.tsx
@@ -4,6 +4,7 @@ import { FaCodePullRequest } from "react-icons/fa6";
import { HiSquares2X2 } from "react-icons/hi2";
import {
LuAtom,
+ LuCheckCircle,
LuExternalLink,
LuGrip,
LuHammer,
@@ -12,6 +13,7 @@ import {
LuPizza,
LuShoppingCart,
LuTimer,
+ LuXCircle,
} from "react-icons/lu";
import { RxCodesandboxLogo } from "react-icons/rx";
@@ -20,7 +22,11 @@ import { TbTargetArrow, TbTargetOff } from "react-icons/tb";
import { getColor } from "@carbon/utils";
import { Link } from "@remix-run/react";
import type { ReactNode } from "react";
+import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
+import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
+import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
import { useMode } from "~/hooks/useMode";
+import type { JobOperation } from "~/modules/production";
import type { MethodType } from "~/modules/shared";
export const ModuleIcon = ({ icon }: { icon: ReactNode }) => {
@@ -126,10 +132,10 @@ type MethodBadgeProps = {
export function MethodBadge({ type, text, to, className }: MethodBadgeProps) {
const mode = useMode();
- const style = getBadgeColor(type, mode);
+ const style = getReplenishmentBadgeColor(type, mode);
return (
<HStack className="group" spacing={1}>
- <Badge style={style}>
+ <Badge style={style} className={className}>
<MethodIcon type={type} className="w-3 h-3 mr-1 " />
{text}
</Badge>
@@ -144,10 +150,35 @@ export function MethodBadge({ type, text, to, className }: MethodBadgeProps) {
);
}
-function getBadgeColor(type: MethodType, mode: "light" | "dark") {
+function getReplenishmentBadgeColor(type: MethodType, mode: "light" | "dark") {
return type === "Buy"
? getColor("blue", mode)
: type === "Make"
? getColor("green", mode)
: getColor("orange", mode);
}
+
+export function OperationStatusIcon({
+ status,
+ className,
+}: {
+ status: JobOperation["status"];
+ className?: string;
+}) {
+ switch (status) {
+ case "Ready":
+ case "Todo":
+ return <TodoStatusIcon className={cn("text-foreground", className)} />;
+ case "Waiting":
+ case "Canceled":
+ return <LuXCircle className={cn("text-muted-foreground", className)} />;
+ case "Done":
+ return <LuCheckCircle className={cn("text-blue-600", className)} />;
+ case "In Progress":
+ return <AlmostDoneIcon className={className} />;
+ case "Paused":
+ return <InProgressStatusIcon className={className} />;
+ default:
+ return null;
+ }
+}
diff --git a/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
index 8609e331f7..5b87a33298 100644
--- a/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
@@ -42,6 +42,7 @@ export const CollapsibleSidebar = ({
<Button
onClick={sidebar.onToggle}
aria-label="Toggle sidebar"
+ variant="secondary"
className="bg-popover inline-block border border-border border-l-0 absolute top-[calc(100vh-135px)] text-muted-foreground right-[-31px] left-auto rounded-l-none z-[3] hover:bg-popover p-0 shadow-none w-8 h-8"
>
{sidebar.isOpen ? (
diff --git a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
index 965a9d639f..d09dc1076d 100644
--- a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
+++ b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
@@ -43,7 +43,7 @@ const ConfirmDelete = ({
<ModalBody>{text}</ModalBody>
<ModalFooter>
- <Button variant="secondary" className="mr-3" onClick={onCancel}>
+ <Button variant="secondary" onClick={onCancel}>
Cancel
</Button>
<Form method="post" action={action} onSubmit={onSubmit}>
diff --git a/apps/carbon/app/components/SupplierAvatar.tsx b/apps/carbon/app/components/SupplierAvatar.tsx
index 668e357c78..e925e971d5 100644
--- a/apps/carbon/app/components/SupplierAvatar.tsx
+++ b/apps/carbon/app/components/SupplierAvatar.tsx
@@ -24,9 +24,11 @@ const SupplierAvatar = ({
};
return (
- <HStack className="truncate">
+ <HStack className="truncate no-underline hover:no-underline">
<Avatar size={size ?? "xs"} {...props} name={supplier?.name ?? ""} />
- <span className={cn("normal-case font-medium", className)}>
+ <span
+ className={cn("normal-case font-normal tracking-normal", className)}
+ >
{supplier.name}
</span>
</HStack>
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 0ee9e5fbe8..8632e2c49f 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -431,17 +431,10 @@ const Table = <T extends object>({
]
);
- // reset the selected cell when the table data changes
useEffect(() => {
- setSelectedCell(null);
+ if (selectedCell) setSelectedCell(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- editMode,
- pagination.pageIndex,
- pagination.pageSize,
- columnOrder,
- columnVisibility,
- ]);
+ }, [editMode, pagination.pageIndex, pagination.pageSize]);
useMount(() => {
setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
diff --git a/apps/carbon/app/components/Table/components/Cell.tsx b/apps/carbon/app/components/Table/components/Cell.tsx
index 5d07d398e7..32947ef181 100644
--- a/apps/carbon/app/components/Table/components/Cell.tsx
+++ b/apps/carbon/app/components/Table/components/Cell.tsx
@@ -53,12 +53,13 @@ const Cell = <T extends object>({
return (
<Td
className={cn(
- "relative px-4 whitespace-nowrap text-sm outline-none",
+ "relative px-4 py-2 whitespace-nowrap text-sm outline-none",
wasEdited && "bg-yellow-100 dark:bg-yellow-900",
- isEditing && !hasEditableTableCellComponent && "bg-muted/50",
+ isEditMode && !hasEditableTableCellComponent && "bg-muted/50",
isEditMode && "border-border border-r",
hasError && "ring-inset ring-2 ring-red-500",
- isSelected && "ring-inset ring-2 ring-ring"
+ isSelected && "!ring-inset !ring-2 !ring-ring",
+ isSelected && hasEditableTableCellComponent && "!bg-background"
)}
ref={ref}
style={{
diff --git a/apps/carbon/app/components/Table/components/Row.tsx b/apps/carbon/app/components/Table/components/Row.tsx
index 923bd3e49c..fc57ccc87f 100644
--- a/apps/carbon/app/components/Table/components/Row.tsx
+++ b/apps/carbon/app/components/Table/components/Row.tsx
@@ -93,8 +93,7 @@ const MemoizedRow = memo(
next.row.index === prev.selectedCell?.row &&
next.selectedCell?.column === prev.selectedCell?.column &&
next.isEditing === prev.isEditing &&
- next.isEditMode === prev.isEditMode &&
- prev.pinnedColumns === next.pinnedColumns
+ next.isEditMode === prev.isEditMode
) as typeof Row;
export default MemoizedRow;
diff --git a/apps/carbon/app/components/Table/components/TableHeader.tsx b/apps/carbon/app/components/Table/components/TableHeader.tsx
index 03d61089cd..4e936f39a2 100644
--- a/apps/carbon/app/components/Table/components/TableHeader.tsx
+++ b/apps/carbon/app/components/Table/components/TableHeader.tsx
@@ -1,8 +1,7 @@
import { Button, HStack } from "@carbon/react";
import type { Column, ColumnOrderState } from "@tanstack/react-table";
import { type ReactNode } from "react";
-import { BsFillCheckCircleFill } from "react-icons/bs";
-import { MdOutlineEditNote } from "react-icons/md";
+import { LuFileEdit, LuLock } from "react-icons/lu";
import { SearchFilter } from "~/components";
import { useUrlParams } from "~/hooks";
import type { TableAction } from "../types";
@@ -62,6 +61,19 @@ const TableHeader = <T extends object>({
{!!filters?.length && <Filter filters={filters} />}
</HStack>
<HStack>
+ <Sort columnAccessors={columnAccessors} />
+
+ <Columns
+ columnOrder={columnOrder}
+ columns={columns}
+ setColumnOrder={setColumnOrder}
+ withSelectableRows={withSelectableRows}
+ />
+
+ {withPagination &&
+ (pagination.canNextPage || pagination.canPreviousPage) && (
+ <PaginationButtons {...pagination} condensed />
+ )}
{withSelectableRows && actions.length > 0 && (
// TODO: move this to a draggable bar like Linear
<Actions actions={actions} selectedRows={selectedRows} />
@@ -69,33 +81,21 @@ const TableHeader = <T extends object>({
{withInlineEditing &&
(editMode ? (
<Button
- leftIcon={<BsFillCheckCircleFill />}
+ leftIcon={<LuLock />}
+ variant="secondary"
onClick={() => setEditMode(false)}
>
- Finish Editing
+ Lock
</Button>
) : (
<Button
- leftIcon={<MdOutlineEditNote />}
- variant="ghost"
+ leftIcon={<LuFileEdit />}
+ variant="secondary"
onClick={() => setEditMode(true)}
>
Edit
</Button>
))}
- <Sort columnAccessors={columnAccessors} />
-
- <Columns
- columnOrder={columnOrder}
- columns={columns}
- setColumnOrder={setColumnOrder}
- withSelectableRows={withSelectableRows}
- />
-
- {withPagination &&
- (pagination.canNextPage || pagination.canPreviousPage) && (
- <PaginationButtons {...pagination} condensed />
- )}
<>{primaryAction}</>
</HStack>
</HStack>
diff --git a/apps/carbon/app/components/index.ts b/apps/carbon/app/components/index.ts
index 448090ebd4..2105ce5bfd 100644
--- a/apps/carbon/app/components/index.ts
+++ b/apps/carbon/app/components/index.ts
@@ -19,6 +19,7 @@ import {
MethodIcon,
MethodItemTypeIcon,
ModuleIcon,
+ OperationStatusIcon,
TimeTypeIcon,
TrackingTypeIcon,
} from "./Icons";
@@ -58,6 +59,7 @@ export {
MethodItemTypeIcon,
ModuleIcon,
New,
+ OperationStatusIcon,
RealtimeDataProvider,
RichText,
SearchFilter,
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
index c770aee651..d5eab77128 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
@@ -26,6 +26,7 @@ const DocumentCreateForm = () => {
});
if (fileUpload.error) {
+ console.error(fileUpload.error);
toast.error("Failed to upload file");
}
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index 683529866d..5855831026 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -69,7 +69,7 @@ function makeItem(material: Material): ItemWithData {
id: material.id!,
title: (
<VStack spacing={0} className="py-2.5">
- <h4 className="flex font-medium text-sm md:text-base truncate">
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
{material.itemReadableId}
</h4>
{material?.description && (
@@ -525,13 +525,21 @@ function MaterialForm({
<InputControlled
name="description"
label="Description"
- className="col-span-2"
isReadOnly
value={itemData.description}
onChange={(newValue) => {
setItemData((d) => ({ ...d, description: newValue }));
}}
/>
+ <Select
+ name="methodOperationId"
+ label="Operation"
+ isOptional
+ options={methodOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
<DefaultMethodType
name="methodType"
@@ -550,15 +558,6 @@ 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/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 00dfd7e44f..277b14b740 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -12,6 +12,7 @@ import {
CardTitle,
Editor,
HStack,
+ IconButton,
Label,
cn,
generateHTML,
@@ -69,7 +70,11 @@ function makeItems(operations: Operation[]): ItemWithData[] {
function makeItem(operation: Operation): ItemWithData {
return {
id: operation.id!,
- title: operation.description ?? "",
+ title: (
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
+ {operation.description}
+ </h4>
+ ),
checked: false,
order: operation.operationOrder,
details: (
@@ -759,7 +764,15 @@ function OperationForm({
<TimeTypeIcon type="Setup" />
<Label>Setup</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSetup(!showSetup);
+ }}
className={`transition-transform ${
showSetup ? "rotate-180" : ""
}`}
@@ -819,7 +832,15 @@ function OperationForm({
<TimeTypeIcon type="Labor" />
<Label>Labor</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowLabor(!showLabor);
+ }}
className={`transition-transform ${
showLabor ? "rotate-180" : ""
}`}
@@ -878,7 +899,15 @@ function OperationForm({
<TimeTypeIcon type="Machine" />
<Label>Machine</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showMachine ? "Collapse Machine" : "Expand Machine"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowMachine(!showMachine);
+ }}
className={`transition-transform ${
showMachine ? "rotate-180" : ""
}`}
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index beadb97d70..313c2ebe0f 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -24,6 +24,16 @@ export const jobStatus = [
"Cancelled",
] as const;
+export const jobOperationStatus = [
+ "Todo",
+ "Ready",
+ "Waiting",
+ "In Progress",
+ "Paused",
+ "Done",
+ "Canceled",
+] as const;
+
const baseJobValidator = z.object({
id: zfd.text(z.string().optional()),
jobId: zfd.text(z.string().optional()),
@@ -380,3 +390,28 @@ export const getJobMethodValidator = z.object({
// jobMaterialId: z.string().min(1, { message: "Quote Material is required" }),
// itemId: z.string().min(1, { message: "Please select a source method" }),
// });
+
+export const productionEventValidator = z
+ .object({
+ id: z.string().min(0, { message: "ID is required" }),
+ jobOperationId: z.string().min(1, { message: "Operation is required" }),
+ type: z.enum(["Labor", "Machine", "Setup"], {
+ errorMap: () => ({ message: "Event type is required" }),
+ }),
+ employeeId: zfd.text(z.string().optional()),
+ workCenterId: zfd.text(z.string().optional()),
+ startTime: z.string().min(1, { message: "Start time is required" }),
+ endTime: zfd.text(z.string().optional()),
+ })
+ .refine(
+ (data) => {
+ if (data.endTime) {
+ return new Date(data.startTime) < new Date(data.endTime);
+ }
+ return true;
+ },
+ {
+ message: "Start time must be before end time",
+ path: ["endTime"],
+ }
+ );
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 0e30a75627..13a18f0be0 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -7,9 +7,11 @@ import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
jobMaterialValidator,
+ jobOperationStatus,
jobOperationValidator,
jobStatus,
jobValidator,
+ productionEventValidator,
} from "./production.models";
import type { Job } from "./types";
@@ -38,6 +40,23 @@ export async function deleteJobOperation(
return client.from("jobOperation").delete().eq("id", jobOperationId);
}
+export async function deleteProductionEvent(
+ client: SupabaseClient<Database>,
+ productionEventId: string
+) {
+ return client.from("productionEvent").delete().eq("id", productionEventId);
+}
+
+export async function deleteProductionQuantity(
+ client: SupabaseClient<Database>,
+ productionQuantityId: string
+) {
+ return client
+ .from("productionQuantity")
+ .delete()
+ .eq("id", productionQuantityId);
+}
+
export async function getJobDocuments(
client: SupabaseClient<Database>,
companyId: string,
@@ -266,13 +285,24 @@ export async function getJobOperations(
if (args) {
query = setGenericQueryFilters(query, args, [
- { column: "createdAt", ascending: true },
+ { column: "description", ascending: true },
]);
}
return query;
}
+export async function getJobOperationsList(
+ client: SupabaseClient<Database>,
+ jobId: string
+) {
+ return client
+ .from("jobOperation")
+ .select("id, description, order")
+ .eq("jobId", jobId)
+ .order("order", { ascending: true });
+}
+
export async function getJobOperationsByMethodId(
client: SupabaseClient<Database>,
jobMakeMethodId: string
@@ -281,7 +311,43 @@ export async function getJobOperationsByMethodId(
.from("jobOperation")
.select("*")
.eq("jobMakeMethodId", jobMakeMethodId)
- .order("order", { ascending: true });
+ .order("startTime", { ascending: true });
+}
+
+export async function getProductionEvent(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("productionEvent")
+ .select("*, jobOperation(description)")
+ .eq("id", id)
+ .single();
+}
+
+export async function getProductionEvents(
+ client: SupabaseClient<Database>,
+ jobOperationIds: string[],
+ args?: { search: string | null } & GenericQueryFilters
+) {
+ let query = client
+ .from("productionEvent")
+ .select("*, jobOperation(description)", {
+ count: "exact",
+ })
+ .in("jobOperationId", jobOperationIds);
+
+ if (args?.search) {
+ query = query.or(`jobOperation.description.ilike.%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "createdAt", ascending: false },
+ ]);
+ }
+
+ return query;
}
export async function recalculateJobRequirements(
@@ -366,6 +432,47 @@ export async function updateJobOperationOrder(
return Promise.all(updatePromises);
}
+export async function updateJobOperationStatus(
+ client: SupabaseClient<Database>,
+ id: string,
+ status: (typeof jobOperationStatus)[number],
+ updatedBy: string
+) {
+ return client
+ .from("jobOperation")
+ .update({
+ status,
+ updatedBy,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", id)
+ .select()
+ .single();
+}
+
+export async function updateProductionEvent(
+ client: SupabaseClient<Database>,
+ productionEvent: z.infer<typeof productionEventValidator> & {
+ id: string;
+ updatedBy: string;
+ companyId: string;
+ }
+) {
+ const { id, updatedBy, companyId, ...updateData } = productionEvent;
+
+ return client
+ .from("productionEvent")
+ .update({
+ ...sanitize(updateData),
+ updatedBy,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select()
+ .single();
+}
+
export async function upsertJob(
client: SupabaseClient<Database>,
job:
diff --git a/apps/carbon/app/modules/production/types.ts b/apps/carbon/app/modules/production/types.ts
index 738ecaeabc..64932744fa 100644
--- a/apps/carbon/app/modules/production/types.ts
+++ b/apps/carbon/app/modules/production/types.ts
@@ -3,6 +3,7 @@ import type {
getJobMaterials,
getJobMethodTree,
getJobOperations,
+ getProductionEvents,
} from "./production.service";
export type Job = NonNullable<Awaited<ReturnType<typeof getJob>>["data"]>;
@@ -18,3 +19,7 @@ export type JobMethod = NonNullable<
export type JobOperation = NonNullable<
Awaited<ReturnType<typeof getJobOperations>>["data"]
>[number];
+
+export type ProductionEvent = NonNullable<
+ Awaited<ReturnType<typeof getProductionEvents>>["data"]
+>[number];
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 0ed6a8673f..acda10152b 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -69,7 +69,7 @@ function makeItem(material: Material): ItemWithData {
id: material.id!,
title: (
<VStack spacing={0} className="py-2.5">
- <h4 className="flex font-medium text-sm md:text-base truncate">
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
{material.itemReadableId}
</h4>
{material?.description && (
@@ -549,7 +549,6 @@ function MaterialForm({
onTypeChange={onTypeChange}
/>
<InputControlled
- className="col-span-2"
name="description"
label="Description"
value={itemData.description}
@@ -557,6 +556,15 @@ function MaterialForm({
setItemData((d) => ({ ...d, description: newValue }));
}}
/>
+ <Select
+ name="jobOperationId"
+ label="Operation"
+ isClearable
+ options={jobOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
<DefaultMethodType
name="methodType"
@@ -575,15 +583,7 @@ function MaterialForm({
}))
}
/>
- <Select
- name="jobOperationId"
- label="Operation"
- isClearable
- options={jobOperations.map((o) => ({
- value: o.id!,
- label: o.description,
- }))}
- />
+
{itemData.methodType !== "Make" && (
<NumberControlled
name="unitCost"
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 48b566acb0..52eb25d514 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -12,6 +12,7 @@ import {
CardTitle,
Editor,
HStack,
+ IconButton,
Label,
cn,
generateHTML,
@@ -42,15 +43,17 @@ import {
WorkCenter,
getUnitHint,
} from "~/components/Form";
+import { OperationStatusIcon } from "~/components/Icons";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { methodOperationOrders, operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
import { jobOperationValidator } from "../../production.models";
-import type { Job } from "../../types";
+import type { Job, JobOperation } from "../../types";
type Operation = z.infer<typeof jobOperationValidator> & {
+ status: JobOperation["status"];
workInstruction: JSONContent | null;
};
@@ -70,7 +73,14 @@ function makeItems(operations: Operation[]): ItemWithData[] {
function makeItem(operation: Operation): ItemWithData {
return {
id: operation.id!,
- title: operation.description ?? "",
+ title: (
+ <HStack>
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
+ {operation.description}
+ </h4>
+ <OperationStatusIcon status={operation.status} />
+ </HStack>
+ ),
checked: false,
order: operation.operationOrder,
details: (
@@ -116,6 +126,7 @@ const initialOperation: Omit<Operation, "jobMakeMethodId" | "order"> = {
processId: "",
setupTime: 0,
setupUnit: "Total Minutes",
+ status: "Todo",
workCenterId: "",
workInstruction: {},
};
@@ -762,6 +773,7 @@ function OperationForm({
...makeItem({
...values,
workInstruction: i.data.workInstruction,
+ status: i.data.status,
}),
id: item.id,
}
@@ -904,7 +916,15 @@ function OperationForm({
<TimeTypeIcon type="Setup" />
<Label>Setup</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSetup(!showSetup);
+ }}
className={`transition-transform ${
showSetup ? "rotate-180" : ""
}`}
@@ -963,7 +983,15 @@ function OperationForm({
<TimeTypeIcon type="Labor" />
<Label>Labor</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowLabor(!showLabor);
+ }}
className={`transition-transform ${
showLabor ? "rotate-180" : ""
}`}
@@ -1023,7 +1051,15 @@ function OperationForm({
<TimeTypeIcon type="Machine" />
<Label>Machine</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showMachine ? "Collapse Machine" : "Expand Machine"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowMachine(!showMachine);
+ }}
className={`transition-transform ${
showMachine ? "rotate-180" : ""
}`}
@@ -1083,7 +1119,15 @@ function OperationForm({
<LuDollarSign />
<Label>Costing</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showCost ? "Collapse Costing" : "Expand Costing"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowCost(!showCost);
+ }}
className={`transition-transform ${
showCost ? "rotate-180" : ""
}`}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
index eb710689aa..afae81bc37 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
@@ -160,15 +160,6 @@ const JobForm = ({ initialValues }: JobFormProps) => {
<SequenceOrCustomId name="jobId" label="Job ID" table="job" />
)}
- <Customer
- autoFocus={!isEditing}
- name="customerId"
- label="Customer"
- isOptional
- />
-
- {isEditing && <div className="col-span-1" />}
-
<Item
name="itemId"
label={type}
@@ -180,17 +171,6 @@ const JobForm = ({ initialValues }: JobFormProps) => {
}}
onTypeChange={onTypeChange}
/>
- {!isEditing && (
- <UnitOfMeasure
- name="unitOfMeasureCode"
- value={itemData.uom}
- onChange={(value) => {
- if (value?.value) {
- setItemData((prev) => ({ ...prev, uom: value.value }));
- }
- }}
- />
- )}
{isEditing && (
<InputControlled
@@ -198,7 +178,6 @@ const JobForm = ({ initialValues }: JobFormProps) => {
label="Short Description"
value={itemData.description}
isReadOnly
- className="col-span-2"
/>
)}
@@ -229,17 +208,17 @@ const JobForm = ({ initialValues }: JobFormProps) => {
}
minValue={0}
/>
- {isEditing && (
- <UnitOfMeasure
- name="unitOfMeasureCode"
- value={itemData.uom}
- onChange={(value) => {
- if (value?.value) {
- setItemData((prev) => ({ ...prev, uom: value.value }));
- }
- }}
- />
- )}
+
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ value={itemData.uom}
+ onChange={(value) => {
+ if (value?.value) {
+ setItemData((prev) => ({ ...prev, uom: value.value }));
+ }
+ }}
+ />
+ <Location name="locationId" label="Location" />
<DatePicker
name="dueDate"
@@ -254,7 +233,11 @@ const JobForm = ({ initialValues }: JobFormProps) => {
label: d,
}))}
/>
- <Location name="locationId" label="Location" />
+
+ {isEditing && (
+ <Customer name="customerId" label="Customer" isOptional />
+ )}
+
<CustomFormFields table="job" />
</div>
</VStack>
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index 3b9300541f..3657fda6dc 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -22,7 +22,6 @@ import {
import type { FetcherWithComponents } from "@remix-run/react";
import { Link, useFetcher, useNavigate, useParams } from "@remix-run/react";
import {
- LuCheckCheck,
LuChevronDown,
LuClock,
LuHardHat,
@@ -32,6 +31,7 @@ import {
LuPlayCircle,
LuRefreshCw,
LuSettings,
+ LuSigmaSquare,
LuStopCircle,
LuTable,
} from "react-icons/lu";
@@ -70,20 +70,7 @@ const JobHeader = () => {
const statusFetcher = useFetcher<{}>();
const status = routeData?.job?.status;
- const getExplorePath = (type: string) => {
- switch (type) {
- case "materials":
- return path.to.jobMaterials(jobId);
- case "operations":
- return path.to.jobOperations(jobId);
- case "events":
- return path.to.jobProductionEvents(jobId);
- default:
- return path.to.jobDetails(jobId);
- }
- };
-
- const getOptionFromPath = () => {
+ const getOptionFromPath = (jobId: string) => {
if (location.pathname.includes(path.to.jobMaterials(jobId)))
return "materials";
if (location.pathname.includes(path.to.jobOperations(jobId)))
@@ -93,7 +80,7 @@ const JobHeader = () => {
return "details";
};
- const currentValue = getOptionFromPath();
+ const currentValue = getOptionFromPath(jobId);
return (
<>
@@ -130,14 +117,23 @@ const JobHeader = () => {
<DropdownMenuContent className="w-56">
<DropdownMenuRadioGroup
value={currentValue}
- onValueChange={(option) => navigate(getExplorePath(option))}
+ onValueChange={(option) => {
+ navigate(getExplorePath(jobId, option));
+ }}
>
<DropdownMenuRadioItem value="details">
<DropdownMenuIcon icon={getExplorerMenuIcon("details")} />
{getExplorerLabel("details")}
</DropdownMenuRadioItem>
<DropdownMenuSeparator />
- {["materials", "operations", "events"].map((i) => (
+ {["materials", "operations"].map((i) => (
+ <DropdownMenuRadioItem value={i} key={i}>
+ <DropdownMenuIcon icon={getExplorerMenuIcon(i)} />
+ {getExplorerLabel(i)}
+ </DropdownMenuRadioItem>
+ ))}
+ <DropdownMenuSeparator />
+ {["events", "quantities"].map((i) => (
<DropdownMenuRadioItem value={i} key={i}>
<DropdownMenuIcon icon={getExplorerMenuIcon(i)} />
{getExplorerLabel(i)}
@@ -272,16 +268,16 @@ const JobHeader = () => {
(routeData?.job?.quantity === 0 &&
routeData?.job?.scrapQuantity === 0)
}
- leftIcon={<LuCheckCheck />}
+ leftIcon={<LuPlayCircle />}
>
- Release
+ Start
</Button>
</>
)}
</HStack>
</div>
{releaseModal.isOpen && (
- <JobReleaseModal
+ <JobStartModal
job={routeData?.job}
onClose={releaseModal.onClose}
fetcher={statusFetcher}
@@ -301,6 +297,8 @@ function getExplorerLabel(type: string) {
return "Operations";
case "events":
return "Production Events";
+ case "quantities":
+ return "Production Quantities";
default:
return "Job";
}
@@ -314,12 +312,29 @@ function getExplorerMenuIcon(type: string) {
return <LuSettings />;
case "events":
return <LuClock />;
+ case "quantities":
+ return <LuSigmaSquare />;
default:
return <LuHardHat />;
}
}
-function JobReleaseModal({
+const getExplorePath = (jobId: string, type: string) => {
+ switch (type) {
+ case "materials":
+ return path.to.jobMaterials(jobId);
+ case "operations":
+ return path.to.jobOperations(jobId);
+ case "events":
+ return path.to.jobProductionEvents(jobId);
+ case "quantities":
+ return path.to.jobProductionQuantities(jobId);
+ default:
+ return path.to.jobDetails(jobId);
+ }
+};
+
+function JobStartModal({
job,
onClose,
fetcher,
@@ -341,10 +356,10 @@ function JobReleaseModal({
>
<ModalContent>
<ModalHeader>
- <ModalTitle>Release {job?.jobId}</ModalTitle>
+ <ModalTitle>Start {job?.jobId}</ModalTitle>
</ModalHeader>
<ModalBody>
- Are you sure you want to release this job? It will become available to
+ Are you sure you want to start this job? It will become available to
the shop floor.
</ModalBody>
<ModalFooter>
@@ -357,7 +372,7 @@ function JobReleaseModal({
action={path.to.jobStatus(job.id!)}
>
<input type="hidden" name="status" value="Ready" />
- <Button type="submit">Release</Button>
+ <Button type="submit">Start</Button>
</fetcher.Form>
</ModalFooter>
</ModalContent>
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
index aaea41b6d8..d9c70d6545 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -203,6 +203,15 @@ const JobMaterialForm = ({
}}
onTypeChange={onTypeChange}
/>
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
+ />
+
<Select
name="jobOperationId"
label="Operation"
@@ -212,16 +221,7 @@ const JobMaterialForm = ({
label: o.description,
}))}
/>
- </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"
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index 9f202a360c..e2a7bea143 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -1,8 +1,12 @@
-import { Badge, HStack } from "@carbon/react";
-import { useParams } from "@remix-run/react";
+import { useCarbon } from "@carbon/auth";
+import { Badge, Button, HStack } from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useMemo } from "react";
+import { memo, useCallback, useMemo } from "react";
+import { LuRefreshCcwDot } from "react-icons/lu";
import { Hyperlink, MethodIcon, MethodItemTypeIcon, Table } from "~/components";
+import { EditableNumber, EditableText } from "~/components/Editable";
+import { usePermissions, useUser } from "~/hooks";
import { methodItemType, methodType } from "~/modules/shared";
import { path } from "~/utils/path";
import type { JobMaterial } from "../../types";
@@ -16,6 +20,8 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
const { jobId } = useParams();
if (!jobId) throw new Error("Job ID is required");
+ const fetcher = useFetcher<{}>();
+
const columns = useMemo<ColumnDef<JobMaterial>[]>(() => {
return [
{
@@ -110,7 +116,55 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
];
}, [jobId]);
- return <Table<JobMaterial> count={count} columns={columns} data={data} />;
+ const permissions = usePermissions();
+ const { carbon } = useCarbon();
+ const { id: userId } = useUser();
+ const onCellEdit = useCallback(
+ async (id: string, value: unknown, row: JobMaterial) => {
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
+ .from("jobMaterial")
+ .update({
+ [id]: value,
+ updatedBy: userId,
+ })
+ .eq("id", row.id!);
+ },
+ [carbon, userId]
+ );
+
+ const editableComponents = useMemo(() => {
+ return {
+ description: EditableText(onCellEdit),
+ quantity: EditableNumber(onCellEdit),
+ estimatedQuantity: EditableNumber(onCellEdit),
+ };
+ }, [onCellEdit]);
+
+ return (
+ <Table<JobMaterial>
+ count={count}
+ columns={columns}
+ data={data}
+ primaryAction={
+ data.length > 0 && permissions.can("update", "production") ? (
+ <fetcher.Form action={path.to.jobRecalculate(jobId)} method="post">
+ <Button
+ leftIcon={<LuRefreshCcwDot />}
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ type="submit"
+ variant="secondary"
+ >
+ Recalculate
+ </Button>
+ </fetcher.Form>
+ ) : undefined
+ }
+ editableComponents={editableComponents}
+ withInlineEditing={permissions.can("update", "production")}
+ />
+ );
});
JobMaterialsTable.displayName = "JobMaterialsTable";
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
index 91b5a101af..149292ae97 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
@@ -1,16 +1,27 @@
-import { HStack } from "@carbon/react";
-import { useParams } from "@remix-run/react";
+import { useCarbon } from "@carbon/auth";
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+} from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useMemo } from "react";
-import { LuCheckCircle, LuXCircle } from "react-icons/lu";
-import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
-import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
-import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
+import { memo, useCallback, useMemo } from "react";
+import { LuRefreshCcwDot } from "react-icons/lu";
import { Hyperlink, Table } from "~/components";
+import { EditableNumber } from "~/components/Editable";
import { Enumerable } from "~/components/Enumerable";
-import { useRouteData } from "~/hooks";
+import { OperationStatusIcon } from "~/components/Icons";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
+import { jobOperationStatus } from "../../production.models";
import type { Job, JobOperation } from "../../types";
type JobOperationsTableProps = {
@@ -25,6 +36,23 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
const isPaused = routeData?.job?.status === "Paused";
+ const fetcher = useFetcher<{}>();
+ const permissions = usePermissions();
+
+ const onOperationStatusChange = useCallback(
+ async (id: string, status: JobOperation["status"]) => {
+ const formData = new FormData();
+ formData.set("id", id);
+ formData.set("status", status);
+
+ return await fetcher.submit(formData, {
+ method: "post",
+ action: path.to.jobOperationStatus,
+ });
+ },
+ [fetcher]
+ );
+
const columns = useMemo<ColumnDef<JobOperation>[]>(() => {
return [
{
@@ -32,13 +60,44 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
header: "Description",
cell: ({ row }) => (
<HStack className="py-1">
- {getStatusIcon(isPaused ? "Paused" : row.original.status)}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ size="sm"
+ variant="ghost"
+ aria-label="Change status"
+ icon={
+ <OperationStatusIcon
+ status={isPaused ? "Paused" : row.original.status}
+ />
+ }
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuRadioGroup
+ value={row.original.status}
+ onValueChange={(status) =>
+ onOperationStatusChange(
+ row.original.id,
+ status as JobOperation["status"]
+ )
+ }
+ >
+ {jobOperationStatus.map((status) => (
+ <DropdownMenuRadioItem key={status} value={status}>
+ <DropdownMenuIcon
+ icon={<OperationStatusIcon status={status} />}
+ />
+ <span>{status}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
<Hyperlink
- to={path.to.jobMakeMethod(
- jobId,
- "make",
- row.original.jobMakeMethodId!
- )}
+ to={`${path.to.jobProductionEvents(
+ jobId
+ )}?filter=jobOperationId:eq:${row.original.id}`}
className="max-w-[260px] truncate"
>
{row.original.description}
@@ -50,21 +109,7 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
id: "item",
header: "Item",
cell: ({ row }) => {
- return (
- <Hyperlink
- to={
- row.original.jobMakeMethod?.parentMaterialId
- ? path.to.jobMakeMethod(
- jobId,
- row.original.jobMakeMethodId!,
- row.original.jobMakeMethod?.parentMaterialId
- )
- : path.to.jobMethod(jobId, row.original.jobMakeMethodId!)
- }
- >
- {row.original.jobMakeMethod?.item?.readableId}
- </Hyperlink>
- );
+ return row.original.jobMakeMethod?.item?.readableId;
},
},
{
@@ -97,32 +142,65 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
header: "Qty. Scrapped",
cell: (item) => item.getValue(),
},
+ {
+ accessorKey: "quantityReworked",
+ header: "Qty. Reworked",
+ cell: (item) => item.getValue(),
+ },
];
- }, [isPaused, jobId]);
+ }, [isPaused, jobId, onOperationStatusChange]);
+
+ const { carbon } = useCarbon();
+ const { id: userId } = useUser();
+ const onCellEdit = useCallback(
+ async (id: string, value: unknown, row: JobOperation) => {
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
+ .from("jobOperation")
+ .update({
+ [id]: value,
+ updatedBy: userId,
+ })
+ .eq("id", row.id!);
+ },
+ [carbon, userId]
+ );
- return <Table<JobOperation> count={count} columns={columns} data={data} />;
+ const editableComponents = useMemo(() => {
+ return {
+ operationQuantity: EditableNumber(onCellEdit),
+ quantityScrapped: EditableNumber(onCellEdit),
+ quantityComplete: EditableNumber(onCellEdit),
+ quantityReworked: EditableNumber(onCellEdit),
+ };
+ }, [onCellEdit]);
+
+ return (
+ <Table<JobOperation>
+ count={count}
+ columns={columns}
+ data={data}
+ primaryAction={
+ data.length > 0 && permissions.can("update", "production") ? (
+ <fetcher.Form action={path.to.jobRecalculate(jobId)} method="post">
+ <Button
+ leftIcon={<LuRefreshCcwDot />}
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ type="submit"
+ variant="secondary"
+ >
+ Recalculate
+ </Button>
+ </fetcher.Form>
+ ) : undefined
+ }
+ editableComponents={editableComponents}
+ withInlineEditing={permissions.can("update", "production")}
+ />
+ );
});
JobOperationsTable.displayName = "JobOperationsTable";
export default JobOperationsTable;
-
-// TODO: this might be in a shared location since it is used in the MES too
-export function getStatusIcon(status: JobOperation["status"]) {
- switch (status) {
- case "Ready":
- case "Todo":
- return <TodoStatusIcon className="text-foreground" />;
- case "Waiting":
- case "Canceled":
- return <LuXCircle className="text-muted-foreground" />;
- case "Done":
- return <LuCheckCircle className="text-blue-600" />;
- case "In Progress":
- return <AlmostDoneIcon />;
- case "Paused":
- return <InProgressStatusIcon />;
- default:
- return null;
- }
-}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/ProductionEventForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventForm.tsx
new file mode 100644
index 0000000000..c25b7049e4
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventForm.tsx
@@ -0,0 +1,116 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ VStack,
+} from "@carbon/react";
+import type { CalendarDateTime } from "@internationalized/date";
+import {
+ getLocalTimeZone,
+ parseAbsolute,
+ toCalendarDateTime,
+} from "@internationalized/date";
+import { useNavigate } from "@remix-run/react";
+import { useState } from "react";
+import type { z } from "zod";
+import {
+ DateTimePicker,
+ Employee,
+ Hidden,
+ Select,
+ Submit,
+ WorkCenter,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { productionEventValidator } from "~/modules/production";
+
+type ProductionEventFormProps = {
+ initialValues: z.infer<typeof productionEventValidator>;
+};
+
+const ProductionEventForm = ({ initialValues }: ProductionEventFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const [startTime, setStartTime] = useState(
+ toCalendarDateTime(
+ parseAbsolute(initialValues.startTime, getLocalTimeZone())
+ )
+ );
+ const [endTime, setEndTime] = useState<CalendarDateTime | undefined>(
+ initialValues.endTime
+ ? toCalendarDateTime(
+ parseAbsolute(initialValues.endTime, getLocalTimeZone())
+ )
+ : undefined
+ );
+
+ const isDisabled = !permissions.can("update", "production");
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ validator={productionEventValidator}
+ method="post"
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>Edit Production Event</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <Hidden name="jobOperationId" />
+ <VStack spacing={4}>
+ <Employee name="employeeId" label="Employee" />
+ <Select
+ name="type"
+ label="Event Type"
+ options={[
+ { label: "Labor", value: "Labor" },
+ { label: "Machine", value: "Machine" },
+ { label: "Setup", value: "Setup" },
+ ]}
+ />
+ <WorkCenter name="workCenterId" label="Work Center" />
+ <DateTimePicker
+ name="startTime"
+ label="Start Time"
+ maxValue={endTime}
+ onChange={setStartTime}
+ />
+ <DateTimePicker
+ name="endTime"
+ label="End Time"
+ minValue={startTime}
+ onChange={setEndTime}
+ />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default ProductionEventForm;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx
new file mode 100644
index 0000000000..603a16f4d3
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx
@@ -0,0 +1,221 @@
+import { Badge, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
+import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
+import { useNavigate, useParams } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import { LuPencil, LuTrash } from "react-icons/lu";
+import { EmployeeAvatar, Hyperlink, Table, TimeTypeIcon } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { WorkCenter } from "~/modules/resources";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+import type { ProductionEvent } from "../../types";
+
+type ProductionEventsTableProps = {
+ data: ProductionEvent[];
+ count: number;
+ operations: { id: string; description: string | null }[];
+ workCenters: WorkCenter[];
+};
+
+const ProductionEventsTable = memo(
+ ({ data, count, operations, workCenters }: ProductionEventsTableProps) => {
+ const { jobId } = useParams();
+ if (!jobId) throw new Error("Job ID is required");
+ const [people] = usePeople();
+
+ const columns = useMemo<ColumnDef<ProductionEvent>[]>(() => {
+ return [
+ {
+ accessorKey: "jobOperationId",
+ header: "Operation",
+ cell: ({ row }) => (
+ <Hyperlink to={row.original.id}>
+ {row.original.jobOperation?.description ?? null}
+ </Hyperlink>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: operations.map((operation) => ({
+ value: operation.id,
+ label: <Enumerable value={operation.description} />,
+ })),
+ },
+ },
+ },
+
+ {
+ accessorKey: "employeeId",
+ header: "Employee",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.employeeId} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: <Enumerable value={employee.name} />,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) => (
+ <Badge
+ variant={
+ row.original.type === "Labor"
+ ? "green"
+ : row.original.type === "Machine"
+ ? "blue"
+ : "yellow"
+ }
+ >
+ <TimeTypeIcon type={row.original.type ?? ""} className="mr-2" />
+ {row.original.type}
+ </Badge>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: ["Setup", "Labor", "Machine"].map((type) => ({
+ value: type,
+ label: (
+ <Badge
+ variant={
+ type === "Labor"
+ ? "green"
+ : type === "Machine"
+ ? "blue"
+ : "yellow"
+ }
+ >
+ <TimeTypeIcon type={type} className="mr-2" />
+ {type}
+ </Badge>
+ ),
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "duration",
+ header: "Duration",
+ cell: ({ row }) =>
+ row.original.duration
+ ? formatDurationMilliseconds(row.original.duration * 1000)
+ : null,
+ },
+ {
+ accessorKey: "workCenterId",
+ header: "Work Center",
+ cell: ({ row }) => {
+ const workCenter = workCenters.find(
+ (wc) => wc.id === row.original.workCenterId
+ );
+ return <Enumerable value={workCenter?.name ?? null} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: workCenters.map((workCenter) => ({
+ value: workCenter.id!,
+ label: <Enumerable value={workCenter.name} />,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "startTime",
+ header: "Start Time",
+ cell: ({ row }) => formatDateTime(row.original.startTime),
+ },
+ {
+ accessorKey: "endTime",
+ header: "End Time",
+ cell: ({ row }) =>
+ row.original.endTime ? formatDateTime(row.original.endTime) : null,
+ },
+ ];
+ }, [operations, people, workCenters]);
+
+ const permissions = usePermissions();
+
+ const deleteModal = useDisclosure();
+ const [selectedEvent, setSelectedEvent] = useState<ProductionEvent | null>(
+ null
+ );
+
+ const onDelete = (data: ProductionEvent) => {
+ setSelectedEvent(data);
+ deleteModal.onOpen();
+ };
+
+ const onDeleteCancel = () => {
+ setSelectedEvent(null);
+ deleteModal.onClose();
+ };
+
+ const navigate = useNavigate();
+
+ const renderContextMenu = useCallback<
+ (row: ProductionEvent) => JSX.Element
+ >(
+ (row) => (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "production")}
+ onClick={() => navigate(row.id)}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Event
+ </MenuItem>
+ <MenuItem
+ disabled={!permissions.can("delete", "users")}
+ onClick={() => onDelete(row)}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Event
+ </MenuItem>
+ </>
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [permissions]
+ );
+
+ return (
+ <>
+ <Table<ProductionEvent>
+ count={count}
+ columns={columns}
+ data={data}
+ renderContextMenu={renderContextMenu}
+ />
+ {deleteModal.isOpen && selectedEvent && (
+ <ConfirmDelete
+ action={path.to.deleteProductionEvent(selectedEvent.id)}
+ isOpen
+ name={`${
+ selectedEvent.jobOperation?.description ?? "Operation"
+ } by ${
+ people.find((p) => p.id === selectedEvent.employeeId)?.name ??
+ "Unknown Employee"
+ }`}
+ text="Are you sure you want to delete this production event? This action cannot be undone."
+ onCancel={onDeleteCancel}
+ onSubmit={onDeleteCancel}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+ProductionEventsTable.displayName = "ProductionEventsTable";
+
+export default ProductionEventsTable;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/index.ts b/apps/carbon/app/modules/production/ui/Jobs/index.ts
index 8928033dfc..6f43eb159b 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/index.ts
+++ b/apps/carbon/app/modules/production/ui/Jobs/index.ts
@@ -10,6 +10,8 @@ import JobOperationsTable from "./JobOperationsTable";
import JobsTable from "./JobsTable";
import JobStatus from "./JobStatus";
+import ProductionEventForm from "./ProductionEventForm";
+import ProductionEventsTable from "./ProductionEventsTable";
export {
getDeadlineIcon,
@@ -24,4 +26,6 @@ export {
JobOperationsTable,
JobsTable,
JobStatus,
+ ProductionEventForm,
+ ProductionEventsTable,
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index ea3738035a..4ef8f15a7c 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -69,7 +69,7 @@ function makeItem(material: Material): ItemWithData {
id: material.id!,
title: (
<VStack spacing={0} className="py-2.5">
- <h4 className="flex font-medium text-sm md:text-base truncate">
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
{material.itemReadableId}
</h4>
{material?.description && (
@@ -549,7 +549,6 @@ function MaterialForm({
onTypeChange={onTypeChange}
/>
<InputControlled
- className="col-span-2"
name="description"
label="Description"
value={itemData.description}
@@ -558,6 +557,16 @@ function MaterialForm({
}}
/>
+ <Select
+ name="quoteOperationId"
+ label="Operation"
+ isClearable
+ options={quoteOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
+
<DefaultMethodType
name="methodType"
label="Method Type"
@@ -575,15 +584,7 @@ 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/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 45d7e1711e..fa9b040955 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -12,6 +12,7 @@ import {
CardTitle,
Editor,
HStack,
+ IconButton,
Label,
cn,
generateHTML,
@@ -70,7 +71,11 @@ function makeItems(operations: Operation[]): ItemWithData[] {
function makeItem(operation: Operation): ItemWithData {
return {
id: operation.id!,
- title: operation.description ?? "",
+ title: (
+ <h4 className="flex text-xs font-bold uppercase tracking-tighter md:text-sm truncate">
+ {operation.description}
+ </h4>
+ ),
checked: false,
order: operation.operationOrder,
details: (
@@ -903,7 +908,15 @@ function OperationForm({
<TimeTypeIcon type="Setup" />
<Label>Setup</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSetup(!showSetup);
+ }}
className={`transition-transform ${
showSetup ? "rotate-180" : ""
}`}
@@ -962,7 +975,15 @@ function OperationForm({
<TimeTypeIcon type="Labor" />
<Label>Labor</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowLabor(!showLabor);
+ }}
className={`transition-transform ${
showLabor ? "rotate-180" : ""
}`}
@@ -1022,7 +1043,15 @@ function OperationForm({
<TimeTypeIcon type="Machine" />
<Label>Machine</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showMachine ? "Collapse Machine" : "Expand Machine"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowMachine(!showMachine);
+ }}
className={`transition-transform ${
showMachine ? "rotate-180" : ""
}`}
@@ -1082,7 +1111,15 @@ function OperationForm({
<LuDollarSign />
<Label>Costing</Label>
</HStack>
- <LuChevronDown
+ <IconButton
+ icon={<LuChevronDown />}
+ aria-label={showCost ? "Collapse Costing" : "Expand Costing"}
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowCost(!showCost);
+ }}
className={`transition-transform ${
showCost ? "rotate-180" : ""
}`}
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index e65dc07cb3..d7c1fe8e5e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -201,6 +201,14 @@ const QuoteMaterialForm = ({
}}
onTypeChange={onTypeChange}
/>
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
+ />
<Select
name="quoteOperationId"
label="Operation"
@@ -210,16 +218,7 @@ const QuoteMaterialForm = ({
label: o.description,
}))}
/>
- </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"
diff --git a/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx b/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx
index 21399ca93d..f9620ec554 100644
--- a/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/carbon/app/routes/file+/preview+/$bucket.$.tsx
@@ -57,7 +57,7 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
const headers = new Headers({
"Content-Type": contentType,
- "Cache-Control": "public, max-age=31536000", // Cache for a year
+ "Cache-Control": "public, max-age=31536000, immutable", // Cache for a year
});
return new Response(fileData, { status: 200, headers });
};
diff --git a/apps/carbon/app/routes/x+/consumable+/new.tsx b/apps/carbon/app/routes/x+/consumable+/new.tsx
index 3998c6d77f..4ce6a099f5 100644
--- a/apps/carbon/app/routes/x+/consumable+/new.tsx
+++ b/apps/carbon/app/routes/x+/consumable+/new.tsx
@@ -80,7 +80,7 @@ export default function ConsumablesNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<ConsumableForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/customer+/new.tsx b/apps/carbon/app/routes/x+/customer+/new.tsx
index 64a9857ccf..ccc737af0c 100644
--- a/apps/carbon/app/routes/x+/customer+/new.tsx
+++ b/apps/carbon/app/routes/x+/customer+/new.tsx
@@ -70,7 +70,7 @@ export default function CustomersNewRoute() {
name: "",
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<CustomerForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/fixture+/new.tsx b/apps/carbon/app/routes/x+/fixture+/new.tsx
index 4160994e3b..e6c1855bcf 100644
--- a/apps/carbon/app/routes/x+/fixture+/new.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/new.tsx
@@ -75,7 +75,7 @@ export default function FixturesNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<FixtureForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.events.$id.tsx b/apps/carbon/app/routes/x+/job+/$jobId.events.$id.tsx
new file mode 100644
index 0000000000..f25f73faa7
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.events.$id.tsx
@@ -0,0 +1,92 @@
+import { validationError, validator } from "@carbon/form";
+import { useLoaderData } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ ProductionEventForm,
+ getProductionEvent,
+ productionEventValidator,
+ updateProductionEvent,
+} from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const productionEvent = await getProductionEvent(client, id);
+
+ return json({
+ productionEvent: productionEvent?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting",
+ });
+
+ const { jobId } = params;
+ if (!jobId) throw notFound("jobId or id not found");
+
+ const formData = await request.formData();
+ const validation = await validator(productionEventValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const update = await updateProductionEvent(client, {
+ id,
+ ...data,
+ companyId,
+ updatedBy: userId,
+ });
+
+ if (update.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(update.error, "Failed to update production event")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.jobProductionEvents(jobId)}?${getParams(request)}`,
+ await flash(request, success("Updated production event"))
+ );
+}
+
+export default function EditProductionEventRoute() {
+ const { productionEvent } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: productionEvent?.id!,
+ type: productionEvent?.type ?? ("Setup" as "Setup"),
+ jobOperationId: productionEvent?.jobOperationId ?? "",
+ startTime: productionEvent?.startTime ?? "",
+ employeeId: productionEvent?.employeeId ?? "",
+ workCenterId: productionEvent?.workCenterId ?? "",
+ endTime: productionEvent?.endTime ?? "",
+ };
+
+ return (
+ <ProductionEventForm key={initialValues.id} initialValues={initialValues} />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.events.tsx b/apps/carbon/app/routes/x+/job+/$jobId.events.tsx
new file mode 100644
index 0000000000..f5d190117c
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.events.tsx
@@ -0,0 +1,94 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import {
+ getJobOperationsList,
+ getProductionEvents,
+ ProductionEventsTable,
+} from "~/modules/production";
+import { getWorkCentersList } from "~/modules/resources";
+import { path, requestReferrer } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const operations = await getJobOperationsList(client, jobId);
+ if (operations.error) {
+ redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(operations.error, "Failed to fetch job operations")
+ )
+ );
+ }
+
+ if (operations.data?.length === 0) {
+ return json({
+ count: 0,
+ events: [],
+ workCenters: [],
+ operations: [],
+ });
+ }
+
+ const [events, workCenters] = await Promise.all([
+ getProductionEvents(client, operations.data?.map((o) => o.id) ?? [], {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ getWorkCentersList(client, companyId),
+ ]);
+
+ if (events.error) {
+ redirect(
+ path.to.production,
+ await flash(request, error(events.error, "Failed to fetch job events"))
+ );
+ }
+
+ return json({
+ count: events.count ?? 0,
+ events: events.data ?? [],
+ workCenters: workCenters.data ?? [],
+ operations: operations.data ?? [],
+ });
+}
+
+export default function ProductionEventsRoute() {
+ const { count, events, operations, workCenters } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <VStack spacing={0} className="h-[calc(100vh-99px)]">
+ <ProductionEventsTable
+ data={events}
+ count={count}
+ operations={operations}
+ workCenters={workCenters}
+ />
+ </VStack>
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx b/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx
new file mode 100644
index 0000000000..be0d7dffc4
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx
@@ -0,0 +1,72 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import { useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import {
+ getJobOperationsList,
+ getJobQuantities,
+ JobQuantitiesTable,
+} from "~/modules/production";
+import { getWorkCentersList } from "~/modules/resources";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [events, workCenters, operations] = await Promise.all([
+ getJobQuantities(client, jobId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ getWorkCentersList(client, companyId),
+ getJobOperationsList(client, jobId),
+ ]);
+
+ if (events.error) {
+ redirect(
+ path.to.production,
+ await flash(request, error(events.error, "Failed to fetch job events"))
+ );
+ }
+
+ return json({
+ count: events.count ?? 0,
+ events: events.data ?? [],
+ workCenters: workCenters.data ?? [],
+ operations: operations.data ?? [],
+ });
+}
+
+export default function JobQuantitiesRoute() {
+ const { count, events, operations, workCenters } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-[calc(100vh-99px)]">
+ <JobQuantitiesTable
+ data={events}
+ count={count}
+ operations={operations}
+ workCenters={workCenters}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.recalculate.tsx b/apps/carbon/app/routes/x+/job+/$jobId.recalculate.tsx
new file mode 100644
index 0000000000..b7897802ea
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.recalculate.tsx
@@ -0,0 +1,35 @@
+import { error, getCarbonServiceRole, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { recalculateJobRequirements } from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "production",
+ role: "employee",
+ });
+ const { jobId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+
+ const recalculate = await recalculateJobRequirements(getCarbonServiceRole(), {
+ id: jobId,
+ companyId,
+ userId,
+ });
+ if (recalculate.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(recalculate.error, "Failed to recalculate job requirements")
+ )
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(request, success("Updated job"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.status.tsx b/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
index 3e565d3f4f..ef194fab69 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
@@ -34,7 +34,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (data?.item?.itemReplenishment?.manufacturingBlocked) {
throw redirect(
- path.to.job(id),
+ requestReferrer(request) ?? path.to.job(id),
await flash(request, error(null, "Manufacturing is blocked"))
);
}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/event.delete.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/event.delete.$id.tsx
new file mode 100644
index 0000000000..e4c3838006
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/event.delete.$id.tsx
@@ -0,0 +1,29 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { deleteProductionEvent } from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "production",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const deletion = await deleteProductionEvent(client, id);
+ if (deletion.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.jobs,
+ await flash(request, error(deletion.error, "Failed to delete event"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.jobs,
+ await flash(request, success("Successfully deleted event"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/operation.status.tsx b/apps/carbon/app/routes/x+/job+/methods+/operation.status.tsx
new file mode 100644
index 0000000000..4eb175f68a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/operation.status.tsx
@@ -0,0 +1,28 @@
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { JobOperation } from "~/modules/production";
+import { updateJobOperationStatus } from "~/modules/production";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const formData = await request.formData();
+ const id = formData.get("id") as string;
+ const status = formData.get("status") as JobOperation["status"];
+
+ const update = await updateJobOperationStatus(client, id, status, userId);
+ if (update.error) {
+ return json(
+ {},
+ await flash(request, error(update.error, "Failed to update status"))
+ );
+ }
+
+ return json({});
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/quantity.delete.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/quantity.delete.$id.tsx
new file mode 100644
index 0000000000..8c1af79ca1
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/quantity.delete.$id.tsx
@@ -0,0 +1,29 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { deleteProductionQuantity } from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "production",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const deletion = await deleteProductionQuantity(client, id);
+ if (deletion.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.jobs,
+ await flash(request, error(deletion.error, "Failed to delete quantity"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.jobs,
+ await flash(request, success("Successfully deleted quantity"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/new.tsx b/apps/carbon/app/routes/x+/job+/new.tsx
index 8176039164..664dbbc2ea 100644
--- a/apps/carbon/app/routes/x+/job+/new.tsx
+++ b/apps/carbon/app/routes/x+/job+/new.tsx
@@ -125,7 +125,7 @@ export default function JobNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<JobForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/material+/new.tsx b/apps/carbon/app/routes/x+/material+/new.tsx
index 75ce762bbf..2766f530ab 100644
--- a/apps/carbon/app/routes/x+/material+/new.tsx
+++ b/apps/carbon/app/routes/x+/material+/new.tsx
@@ -82,7 +82,7 @@ export default function MaterialsNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<MaterialForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index 731ac99b91..0fce41742d 100644
--- a/apps/carbon/app/routes/x+/part+/new.tsx
+++ b/apps/carbon/app/routes/x+/part+/new.tsx
@@ -70,7 +70,7 @@ export default function PartsNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<PartForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
index 817568af4e..c249cc2ba9 100644
--- a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
@@ -129,7 +129,7 @@ export default function PurchaseInvoiceNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<PurchaseInvoiceForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
index 3645c72836..4935d49c75 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -91,7 +91,7 @@ export default function PurchaseOrderNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<PurchaseOrderForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/quote+/new.tsx b/apps/carbon/app/routes/x+/quote+/new.tsx
index 441491d79a..18754fb87e 100644
--- a/apps/carbon/app/routes/x+/quote+/new.tsx
+++ b/apps/carbon/app/routes/x+/quote+/new.tsx
@@ -80,7 +80,7 @@ export default function QuoteNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<QuoteForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/sales-order+/new.tsx b/apps/carbon/app/routes/x+/sales-order+/new.tsx
index bc4730089c..0c8df0ff52 100644
--- a/apps/carbon/app/routes/x+/sales-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/new.tsx
@@ -85,7 +85,7 @@ export default function SalesOrderNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<SalesOrderForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/new.tsx b/apps/carbon/app/routes/x+/sales-rfq+/new.tsx
index 1ff44bd885..6ef419f54b 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/new.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/new.tsx
@@ -85,7 +85,7 @@ export default function SalesRFQNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<SalesRFQForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/supplier+/new.tsx b/apps/carbon/app/routes/x+/supplier+/new.tsx
index c5dae46ae3..03dae5d489 100644
--- a/apps/carbon/app/routes/x+/supplier+/new.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/new.tsx
@@ -70,7 +70,7 @@ export default function SuppliersNewRoute() {
name: "",
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<SupplierForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/routes/x+/tool+/new.tsx b/apps/carbon/app/routes/x+/tool+/new.tsx
index 12ae24671e..b1bf5a714a 100644
--- a/apps/carbon/app/routes/x+/tool+/new.tsx
+++ b/apps/carbon/app/routes/x+/tool+/new.tsx
@@ -70,7 +70,7 @@ export default function ToolsNewRoute() {
};
return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <div className="max-w-[50rem] w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
<ToolForm initialValues={initialValues} />
</div>
);
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 8235ef2291..6eb0d86507 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -252,6 +252,10 @@ export const path = {
generatePath(`${x}/accounting/payment-terms/delete/${id}`),
deleteProcess: (id: string) =>
generatePath(`${x}/resources/processes/delete/${id}`),
+ deleteProductionEvent: (id: string) =>
+ generatePath(`${x}/job/methods/event/delete/${id}`),
+ deleteProductionQuantity: (id: string) =>
+ generatePath(`${x}/job/methods/quantity/delete/${id}`),
deletePurchaseInvoice: (id: string) =>
generatePath(`${x}/purchase-invoice/delete/${id}`),
deletePurchaseInvoiceLine: (invoiceId: string, lineId: string) =>
@@ -391,8 +395,12 @@ export const path = {
generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),
jobOperationsOrder: `${x}/job/methods/operation/order`,
+ jobOperationStatus: `${x}/job/methods/operation/status`,
jobProductionEvents: (id: string) => generatePath(`${x}/job/${id}/events`),
+ jobProductionQuantities: (id: string) =>
+ generatePath(`${x}/job/${id}/quantities`),
jobs: `${x}/production/jobs`,
+ jobRecalculate: (id: string) => generatePath(`${x}/job/${id}/recalculate`),
jobRelease: (id: string) => generatePath(`${x}/job/${id}/release`),
jobStatus: (id: string) => generatePath(`${x}/job/${id}/status`),
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
diff --git a/apps/mes/app/components/Icons.tsx b/apps/mes/app/components/Icons.tsx
index 0b3f0735f7..1f5baa5d26 100644
--- a/apps/mes/app/components/Icons.tsx
+++ b/apps/mes/app/components/Icons.tsx
@@ -147,7 +147,7 @@ export const MethodItemTypeIcon = ({
return <HiSquares2X2 className={cn("text-muted-foreground", className)} />;
};
-export function StatusIcon({
+export function OperationStatusIcon({
status,
}: {
status: Operation["operationStatus"];
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index cf6d8cb7cd..cb93f117b1 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -55,8 +55,8 @@ import {
DeadlineIcon,
FileIcon,
FilePreview,
+ OperationStatusIcon,
OptionallyFullscreen,
- StatusIcon,
} from "~/components";
import { useRealtime, useUser } from "~/hooks";
import type {
@@ -205,7 +205,7 @@ export const JobOperation = ({
)}
{operation.operationStatus && (
<HStack className="justify-start space-x-2">
- <StatusIcon
+ <OperationStatusIcon
status={
operation.jobStatus === "Paused"
? "Paused"
@@ -1057,13 +1057,13 @@ function WorkTypeToggle({
<ToggleGroup value={value} type="single" onValueChange={onChange}>
{operation.setupDuration > 0 && (
<ToggleGroupItem
- className="w-[110px] relative"
+ className="w-[80px] sm:w-[110px] relative"
value="Setup"
size="lg"
aria-label="Toggle setup"
>
<LuTimer className="h-4 w-4 mr-2 flex-shrink-0" />
- Setup
+ <span className="hidden sm:inline-flex">Setup</span>
{active.setup && (
<span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />
)}
@@ -1071,13 +1071,13 @@ function WorkTypeToggle({
)}
{operation.laborDuration > 0 && (
<ToggleGroupItem
- className="w-[110px] relative"
+ className="w-[80px] sm:w-[110px] relative"
value="Labor"
size="lg"
aria-label="Toggle labor"
>
<LuHardHat className="h-4 w-4 mr-2 flex-shrink-0" />
- Labor
+ <span className="hidden sm:inline-flex">Labor</span>
{active.labor && (
<span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />
)}
@@ -1085,13 +1085,13 @@ function WorkTypeToggle({
)}
{operation.machineDuration > 0 && (
<ToggleGroupItem
- className="w-[110px] relative"
+ className="w-[80px] sm:w-[110px] relative"
value="Machine"
size="lg"
aria-label="Toggle machine"
>
<LuHammer className="h-4 w-4 mr-2 flex-shrink-0" />
- Machine
+ <span className="hidden sm:inline-flex">Machine</span>
{active.machine && (
<span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />
)}
diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsx
index 5456b0aac2..005f2f3df0 100644
--- a/apps/mes/app/components/OperationsList.tsx
+++ b/apps/mes/app/components/OperationsList.tsx
@@ -17,7 +17,7 @@ import {
import { Link, useParams } from "@remix-run/react";
import { LuAlertTriangle, LuClipboardCheck, LuTimer } from "react-icons/lu";
import type { Operation, OperationSettings } from "~/services/jobs.service";
-import { DeadlineIcon, StatusIcon } from "./Icons";
+import { DeadlineIcon, OperationStatusIcon } from "./Icons";
type OperationsListProps = {
operations: Operation[];
@@ -117,7 +117,7 @@ function OperationCard({
)}
{showStatus && operation.operationStatus && (
<HStack className="justify-start space-x-2">
- <StatusIcon status={operation.operationStatus} />
+ <OperationStatusIcon status={operation.operationStatus} />
<span className="text-sm">{operation.operationStatus}</span>
</HStack>
)}
diff --git a/apps/mes/app/components/index.ts b/apps/mes/app/components/index.ts
index 753d015372..5256f254d3 100644
--- a/apps/mes/app/components/index.ts
+++ b/apps/mes/app/components/index.ts
@@ -2,7 +2,7 @@ import Avatar from "./Avatar";
import AvatarMenu from "./AvatarMenu";
import FilePreview from "./FilePreview";
import Hyperlink from "./Hyperlink";
-import { DeadlineIcon, FileIcon, StatusIcon } from "./Icons";
+import { DeadlineIcon, FileIcon, OperationStatusIcon } from "./Icons";
import { JobOperation } from "./JobOperation";
import { Nav } from "./Nav";
import { OperationsList } from "./OperationsList";
@@ -18,6 +18,6 @@ export {
JobOperation,
Nav,
OperationsList,
+ OperationStatusIcon,
OptionallyFullscreen,
- StatusIcon,
};
diff --git a/packages/form/src/components/DatePicker.tsx b/packages/form/src/components/DatePicker.tsx
index c9abccb3c6..325ce5462c 100644
--- a/packages/form/src/components/DatePicker.tsx
+++ b/packages/form/src/components/DatePicker.tsx
@@ -9,16 +9,31 @@ import { parseDate } from "@internationalized/date";
import { useState } from "react";
import { useField } from "../hooks";
-type DatePickerProps = { name: string; label?: string; isDisabled?: boolean };
+type DatePickerProps = {
+ name: string;
+ label?: string;
+ onChange?: (date: CalendarDate) => void;
+ isDisabled?: boolean;
+ minValue?: CalendarDate;
+ maxValue?: CalendarDate;
+};
-const DatePicker = ({ name, label, isDisabled = false }: DatePickerProps) => {
+const DatePicker = ({
+ name,
+ label,
+ isDisabled = false,
+ minValue,
+ maxValue,
+ onChange,
+}: DatePickerProps) => {
const { error, defaultValue, validate } = useField(name);
const [date, setDate] = useState<CalendarDate | undefined>(
defaultValue ? parseDate(defaultValue) : undefined
);
- const onChange = (date: CalendarDate) => {
+ const handleChange = (date: CalendarDate) => {
setDate(date);
+ onChange?.(date);
validate();
};
@@ -28,9 +43,10 @@ const DatePicker = ({ name, label, isDisabled = false }: DatePickerProps) => {
<input type="hidden" name={name} value={date?.toString()} />
<DatePickerBase
value={date}
- //@ts-ignore
- onChange={onChange}
isDisabled={isDisabled}
+ minValue={minValue}
+ maxValue={maxValue}
+ onChange={handleChange}
/>
{error && <FormErrorMessage>{error}</FormErrorMessage>}
</FormControl>
diff --git a/packages/form/src/components/DateTimePicker.tsx b/packages/form/src/components/DateTimePicker.tsx
new file mode 100644
index 0000000000..62259ebaa8
--- /dev/null
+++ b/packages/form/src/components/DateTimePicker.tsx
@@ -0,0 +1,62 @@
+import {
+ DateTimePicker as DateTimePickerBase,
+ FormControl,
+ FormErrorMessage,
+ FormLabel,
+} from "@carbon/react";
+import type { CalendarDateTime, DateValue } from "@internationalized/date";
+import {
+ getLocalTimeZone,
+ parseAbsolute,
+ toCalendarDateTime,
+} from "@internationalized/date";
+import { useState } from "react";
+import { useField } from "../hooks";
+
+type DateTimePickerProps = {
+ name: string;
+ label?: string;
+ isDisabled?: boolean;
+ minValue?: CalendarDateTime;
+ maxValue?: CalendarDateTime;
+ onChange?: (date: CalendarDateTime) => void;
+};
+
+const DateTimePicker = ({
+ name,
+ label,
+ isDisabled = false,
+ minValue,
+ maxValue,
+ onChange,
+}: DateTimePickerProps) => {
+ const { error, defaultValue, validate } = useField(name);
+ const [date, setDate] = useState<CalendarDateTime | undefined>(
+ defaultValue
+ ? toCalendarDateTime(parseAbsolute(defaultValue, getLocalTimeZone()))
+ : undefined
+ );
+
+ const handleChange = (date: DateValue) => {
+ setDate(toCalendarDateTime(date));
+ onChange?.(toCalendarDateTime(date));
+ validate();
+ };
+
+ return (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} value={date?.toString()} />
+ <DateTimePickerBase
+ value={date}
+ onChange={handleChange}
+ isDisabled={isDisabled}
+ minValue={minValue}
+ maxValue={maxValue}
+ />
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ );
+};
+
+export default DateTimePicker;
diff --git a/packages/form/src/components/index.ts b/packages/form/src/components/index.ts
index 9a1eb61115..5de572e6e9 100644
--- a/packages/form/src/components/index.ts
+++ b/packages/form/src/components/index.ts
@@ -9,6 +9,7 @@ import CreatableCombobox from "./CreatableCombobox";
import type { CreatableMultiSelectProps } from "./CreatableMultiSelect";
import CreatableMultiSelect from "./CreatableMultiSelect";
import DatePicker from "./DatePicker";
+import DateTimePicker from "./DateTimePicker";
import Hidden from "./Hidden";
import Input from "./Input";
import InputControlled from "./InputControlled";
@@ -36,6 +37,7 @@ export {
CreatableCombobox,
CreatableMultiSelect,
DatePicker,
+ DateTimePicker,
Hidden,
Input,
InputControlled,
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index fcbacb7ff2..60d6b8518e 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -55,6 +55,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
ref
) => {
const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState("");
return (
<HStack className="w-full" spacing={1}>
@@ -86,10 +87,12 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
options={options}
selected={selected}
value={value}
+ itemHeight={itemHeight}
+ search={search}
onChange={onChange}
onCreateOption={onCreateOption}
- itemHeight={itemHeight}
setOpen={setOpen}
+ setSearch={setSearch}
/>
</PopoverContent>
</Popover>
@@ -115,10 +118,12 @@ type VirtualizedCommandProps = {
selected?: string[];
value?: string;
label?: string;
+ itemHeight: number;
+ search: string;
onChange?: (selected: string) => void;
onCreateOption?: (inputValue: string) => void;
- itemHeight: number;
setOpen: (open: boolean) => void;
+ setSearch: (search: string) => void;
};
function VirtualizedCommand({
@@ -126,12 +131,13 @@ function VirtualizedCommand({
label,
selected,
value,
+ itemHeight,
+ search,
+ setSearch,
onChange,
onCreateOption,
- itemHeight,
setOpen,
}: VirtualizedCommandProps) {
- const [search, setSearch] = useState("");
const parentRef = useRef<HTMLDivElement>(null);
const filteredOptions = useMemo(() => {
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index 58b4683c6b..b490cd00bc 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -64,6 +64,7 @@ const CreatableMultiSelect = forwardRef<
ref
) => {
const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState("");
const id = useId();
@@ -133,6 +134,8 @@ const CreatableMultiSelect = forwardRef<
itemHeight={itemHeight}
setOpen={setOpen}
label={label}
+ search={search}
+ setSearch={setSearch}
/>
</PopoverContent>
</Popover>
@@ -161,6 +164,8 @@ type VirtualizedCommandProps = {
itemHeight: number;
setOpen: (open: boolean) => void;
label?: string;
+ search: string;
+ setSearch: (search: string) => void;
};
function VirtualizedCommand({
@@ -171,8 +176,9 @@ function VirtualizedCommand({
itemHeight,
setOpen,
label,
+ search,
+ setSearch,
}: VirtualizedCommandProps) {
- const [search, setSearch] = useState("");
const parentRef = useRef<HTMLDivElement>(null);
const filteredOptions = useMemo(() => {
diff --git a/packages/react/src/Date/DatePicker.tsx b/packages/react/src/Date/DatePicker.tsx
index d15f99e2f9..3f27295a2d 100644
--- a/packages/react/src/Date/DatePicker.tsx
+++ b/packages/react/src/Date/DatePicker.tsx
@@ -3,7 +3,7 @@ import { useDatePicker } from "@react-aria/datepicker";
import { useDatePickerState } from "@react-stately/datepicker";
import type { DatePickerProps } from "@react-types/datepicker";
import { useRef } from "react";
-import { MdOutlineDoNotDisturb } from "react-icons/md";
+import { LuBan } from "react-icons/lu";
import { HStack } from "../HStack";
import { InputGroup } from "../Input";
import { useOutsideClick } from "../hooks";
@@ -36,7 +36,7 @@ const DatePicker = (props: DatePickerProps<CalendarDate>) => {
<div className="flex w-full px-4 py-2">
<DateField {...fieldProps} />
{state.isInvalid && (
- <MdOutlineDoNotDisturb className="text-destructive-foreground aboslute right-[12px]" />
+ <LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />
)}
</div>
</InputGroup>
diff --git a/packages/react/src/Date/DateTimePicker.tsx b/packages/react/src/Date/DateTimePicker.tsx
index dc79bcbf71..de4471e1d8 100644
--- a/packages/react/src/Date/DateTimePicker.tsx
+++ b/packages/react/src/Date/DateTimePicker.tsx
@@ -3,7 +3,8 @@ import { useDatePicker } from "@react-aria/datepicker";
import { useDatePickerState } from "@react-stately/datepicker";
import type { DatePickerProps } from "@react-types/datepicker";
import { useRef } from "react";
-import { MdOutlineDoNotDisturb } from "react-icons/md";
+import { LuBan } from "react-icons/lu";
+import { cn } from "..";
import { HStack } from "../HStack";
import { InputGroup } from "../Input";
import { useOutsideClick } from "../hooks";
@@ -13,7 +14,12 @@ import { Calendar } from "./components/Calendar";
import DateField from "./components/DateField";
import { Popover } from "./components/Popover";
-const DateTimePicker = (props: DatePickerProps<DateValue>) => {
+const DateTimePicker = (
+ props: DatePickerProps<DateValue> & {
+ className?: string;
+ withButton?: boolean;
+ }
+) => {
const state = useDatePickerState({
...props,
shouldCloseOnSelect: false,
@@ -33,17 +39,18 @@ const DateTimePicker = (props: DatePickerProps<DateValue>) => {
<InputGroup
{...groupProps}
ref={ref}
- className="w-full inline-flex rounded-r-none"
+ className={cn("w-full inline-flex rounded-r-none", props.className)}
>
<div className="flex w-full px-4 py-2">
<DateField {...fieldProps} />
{state.isInvalid && (
- <MdOutlineDoNotDisturb className="text-destructive-foreground absolute right-[12px]" />
+ <LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />
)}
</div>
</InputGroup>
-
- <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ {props.withButton !== false && (
+ <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ )}
</HStack>
{state.isOpen && (
<Popover {...dialogProps} onClose={() => state.setOpen(false)}>
diff --git a/packages/utils/src/date.ts b/packages/utils/src/date.ts
index 87e5806acc..e5a7d376ab 100644
--- a/packages/utils/src/date.ts
+++ b/packages/utils/src/date.ts
@@ -39,7 +39,7 @@ export function formatDate(
try {
const date = new Date(dateString);
return new Intl.DateTimeFormat(
- undefined,
+ undefined, // TODO: use locale
options || defaultFormatOptions
).format(date);
} catch {
@@ -48,6 +48,10 @@ export function formatDate(
}
}
+export function formatDateTime(isoString: string) {
+ return formatDate(isoString, { dateStyle: "short", timeStyle: "short" });
+}
+
export function formatRelativeTime(isoString: string) {
if (new Date(isoString).getTime() > new Date().getTime()) {
return formatTimeFromNow(isoString);