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: maintenance dispatch details

Brad Barbinaed017e639ce
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 39de01c13d..23fa2c9f79 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -81,7 +81,7 @@ export const maintenanceFrequency = [
export const maintenanceSeverity = [
"Preventive",
- "OPM",
+ "Operator Perfomed",
"Maintenance Required",
"OEM Required"
] as const;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchExplorer.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchExplorer.tsx
index 7b0abee3e9..9bb11868a3 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchExplorer.tsx
@@ -1,35 +1,64 @@
import {
+ DateTimePicker,
+ Hidden,
+ Number,
+ Submit,
+ ValidatedForm
+} from "@carbon/form";
+import {
+ Button,
Count,
cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
IconButton,
Input,
InputGroup,
InputLeftElement,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
ScrollArea,
Skeleton,
+ Textarea,
+ useDisclosure,
VStack
} from "@carbon/react";
-import { useState } from "react";
+import { useEffect, useState } from "react";
+import { flushSync } from "react-dom";
import {
LuBox,
LuChevronRight,
+ LuCirclePlus,
LuClock,
- LuCog,
- LuSearch
+ LuEllipsisVertical,
+ LuSearch,
+ LuTrash
} from "react-icons/lu";
-import { Link } from "react-router";
-import { EmployeeAvatar } from "~/components";
+import { Link, useFetcher, useParams } from "react-router";
+import { Employee, Item, UnitOfMeasure, WorkCenter } from "~/components/Form";
+import { ConfirmDelete } from "~/components/Modals";
import { LevelLine } from "~/components/TreeView";
+import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
+import {
+ maintenanceDispatchEventValidator,
+ maintenanceDispatchItemValidator
+} from "../../production.models";
import type {
MaintenanceDispatchEvent,
- MaintenanceDispatchItem,
- MaintenanceDispatchWorkCenter
+ MaintenanceDispatchItem
} from "../../types";
export type MaintenanceExplorerNode = {
- key: "items" | "events" | "workCenters";
+ key: "items" | "events";
name: string;
pluralName: string;
children: MaintenanceExplorerChild[];
@@ -37,8 +66,7 @@ export type MaintenanceExplorerNode = {
export type MaintenanceExplorerChild =
| (MaintenanceDispatchItem & { type: "item" })
- | (MaintenanceDispatchEvent & { type: "event" })
- | (MaintenanceDispatchWorkCenter & { type: "workCenter" });
+ | (MaintenanceDispatchEvent & { type: "event" });
export function MaintenanceDispatchExplorerSkeleton() {
return (
@@ -52,14 +80,51 @@ export function MaintenanceDispatchExplorerSkeleton() {
export function MaintenanceDispatchExplorer({
items,
- events,
- workCenters
+ events
}: {
items: MaintenanceDispatchItem[];
events: MaintenanceDispatchEvent[];
- workCenters: MaintenanceDispatchWorkCenter[];
}) {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
const [filterText, setFilterText] = useState("");
+ const deleteDisclosure = useDisclosure();
+ const [selectedChild, setSelectedChild] =
+ useState<MaintenanceExplorerChild | null>(null);
+
+ const onDelete = (child: MaintenanceExplorerChild) => {
+ flushSync(() => {
+ setSelectedChild(child);
+ });
+ deleteDisclosure.onOpen();
+ };
+
+ const onDeleteCancel = () => {
+ setSelectedChild(null);
+ deleteDisclosure.onClose();
+ };
+
+ const getDeleteAction = () => {
+ if (!selectedChild) return "";
+ if (selectedChild.type === "item") {
+ return path.to.deleteMaintenanceDispatchItem(
+ dispatchId,
+ selectedChild.id
+ );
+ }
+ return path.to.deleteMaintenanceDispatchEvent(dispatchId, selectedChild.id);
+ };
+
+ const getDeleteName = () => {
+ if (!selectedChild) return "";
+ if (selectedChild.type === "item") {
+ return selectedChild.item?.name ?? "Item";
+ }
+ return selectedChild.startTime
+ ? new Date(selectedChild.startTime).toLocaleString()
+ : "Timecard";
+ };
const tree: MaintenanceExplorerNode[] = [
{
@@ -73,15 +138,6 @@ export function MaintenanceDispatchExplorer({
name: "Timecard",
pluralName: "Timecards",
children: events.map((event) => ({ ...event, type: "event" as const }))
- },
- {
- key: "workCenters",
- name: "Work Center",
- pluralName: "Work Centers",
- children: workCenters.map((wc) => ({
- ...wc,
- type: "workCenter" as const
- }))
}
];
@@ -106,24 +162,42 @@ export function MaintenanceDispatchExplorer({
key={node.key}
node={node}
filterText={filterText}
+ dispatchId={dispatchId}
+ onDelete={onDelete}
/>
))}
</VStack>
</VStack>
+ {deleteDisclosure.isOpen && selectedChild?.id && (
+ <ConfirmDelete
+ action={getDeleteAction()}
+ name={getDeleteName()}
+ text={`Are you sure you want to remove this ${selectedChild.type === "item" ? "item" : "timecard"}?`}
+ isOpen={deleteDisclosure.isOpen}
+ onCancel={onDeleteCancel}
+ onSubmit={onDeleteCancel}
+ />
+ )}
</ScrollArea>
);
}
function MaintenanceExplorerItem({
node,
- filterText
+ filterText,
+ dispatchId,
+ onDelete
}: {
node: MaintenanceExplorerNode;
filterText: string;
+ dispatchId: string;
+ onDelete: (child: MaintenanceExplorerChild) => void;
}) {
const [isExpanded, setIsExpanded] = useState(
node.children.length > 0 && node.children.length < 10
);
+ const newModal = useDisclosure();
+ const permissions = usePermissions();
const filteredChildren = node.children.filter((child) => {
const searchText = getChildSearchText(child);
@@ -152,6 +226,18 @@ function MaintenanceExplorerItem({
)}
</div>
</button>
+ {permissions.can("update", "production") && (
+ <IconButton
+ aria-label="Add"
+ size="sm"
+ variant="ghost"
+ icon={<LuCirclePlus />}
+ className="ml-auto"
+ onClick={() => {
+ newModal.onOpen();
+ }}
+ />
+ )}
</div>
{isExpanded && (
@@ -164,30 +250,49 @@ function MaintenanceExplorerItem({
</div>
</div>
) : (
- filteredChildren.map((child, index) => (
+ filteredChildren.map((child) => (
<MaintenanceExplorerChildItem
key={child.id}
child={child}
nodeKey={node.key}
+ onDelete={onDelete}
/>
))
)}
</div>
)}
+
+ {newModal.isOpen && node.key === "items" && (
+ <NewItemModal
+ open={newModal.isOpen}
+ onClose={newModal.onClose}
+ dispatchId={dispatchId}
+ />
+ )}
+ {newModal.isOpen && node.key === "events" && (
+ <NewTimecardModal
+ open={newModal.isOpen}
+ onClose={newModal.onClose}
+ dispatchId={dispatchId}
+ />
+ )}
</>
);
}
function MaintenanceExplorerChildItem({
child,
- nodeKey
+ nodeKey,
+ onDelete
}: {
child: MaintenanceExplorerChild;
nodeKey: MaintenanceExplorerNode["key"];
+ onDelete: (child: MaintenanceExplorerChild) => void;
}) {
const link = getChildLink(child);
const icon = getNodeIcon(nodeKey);
const label = getChildLabel(child);
+ const permissions = usePermissions();
const content = (
<div className="flex pr-7 h-8 cursor-pointer items-center overflow-hidden rounded-sm px-1 gap-2 text-sm hover:bg-muted/90 w-full font-medium whitespace-nowrap">
@@ -200,15 +305,152 @@ function MaintenanceExplorerChildItem({
</div>
);
- if (link) {
- return (
- <Link to={link} className="flex w-full">
- {content}
- </Link>
- );
- }
+ return (
+ <div className="group/child relative flex w-full">
+ {link ? (
+ <Link to={link} className="flex w-full">
+ {content}
+ </Link>
+ ) : (
+ <div className="flex w-full">{content}</div>
+ )}
+ {permissions.can("delete", "production") && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Options"
+ icon={<LuEllipsisVertical />}
+ variant="ghost"
+ size="sm"
+ className="absolute right-1 top-0 flex-shrink-0 opacity-0 group-hover/child:opacity-100 data-[state=open]:opacity-100 text-foreground/70 hover:text-foreground"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ destructive
+ onSelect={() => {
+ onDelete(child);
+ }}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+}
+
+function NewItemModal({
+ open,
+ onClose,
+ dispatchId
+}: {
+ open: boolean;
+ onClose: () => void;
+ dispatchId: string;
+}) {
+ const fetcher = useFetcher();
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data) {
+ onClose();
+ }
+ }, [fetcher.state, fetcher.data, onClose]);
+
+ return (
+ <Modal
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.newMaintenanceDispatchItem(dispatchId)}
+ validator={maintenanceDispatchItemValidator}
+ fetcher={fetcher}
+ >
+ <ModalHeader>
+ <ModalTitle>Add Item</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="maintenanceDispatchId" value={dispatchId} />
+ <VStack spacing={4}>
+ <Item name="itemId" label="Item" type="Item" />
+ <Number name="quantity" label="Quantity" minValue={1} />
+ <UnitOfMeasure name="unitOfMeasureCode" label="Unit of Measure" />
+ <Number name="unitCost" label="Unit Cost" minValue={0} />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Submit>Add</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+function NewTimecardModal({
+ open,
+ onClose,
+ dispatchId
+}: {
+ open: boolean;
+ onClose: () => void;
+ dispatchId: string;
+}) {
+ const fetcher = useFetcher();
- return <div className="flex w-full">{content}</div>;
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data) {
+ onClose();
+ }
+ }, [fetcher.state, fetcher.data, onClose]);
+
+ return (
+ <Modal
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.newMaintenanceDispatchEvent(dispatchId)}
+ validator={maintenanceDispatchEventValidator}
+ fetcher={fetcher}
+ >
+ <ModalHeader>
+ <ModalTitle>Add Timecard</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="maintenanceDispatchId" value={dispatchId} />
+ <VStack spacing={4}>
+ <Employee name="employeeId" label="Employee" />
+ <WorkCenter name="workCenterId" label="Work Center" />
+ <DateTimePicker name="startTime" label="Start Time" />
+ <DateTimePicker name="endTime" label="End Time" />
+ <Textarea name="notes" label="Notes" />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Submit>Add</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
}
function getNodeIcon(key: MaintenanceExplorerNode["key"]) {
@@ -217,8 +459,6 @@ function getNodeIcon(key: MaintenanceExplorerNode["key"]) {
return <LuBox className="text-blue-500" />;
case "events":
return <LuClock className="text-green-500" />;
- case "workCenters":
- return <LuCog className="text-amber-500" />;
default:
return null;
}
@@ -231,9 +471,7 @@ function getChildLabel(child: MaintenanceExplorerChild): string {
case "event":
return child.startTime
? new Date(child.startTime).toLocaleString()
- : "Event";
- case "workCenter":
- return child.workCenter?.name ?? child.workCenterId;
+ : "Timecard";
default:
return "";
}
@@ -245,8 +483,6 @@ function getChildSearchText(child: MaintenanceExplorerChild): string {
return child.item?.name ?? child.itemId;
case "event":
return child.notes ?? new Date(child.startTime).toLocaleString();
- case "workCenter":
- return child.workCenter?.name ?? child.workCenterId;
default:
return "";
}
@@ -255,9 +491,7 @@ function getChildSearchText(child: MaintenanceExplorerChild): string {
function getChildLink(child: MaintenanceExplorerChild): string | null {
switch (child.type) {
case "item":
- return path.to.item(child.itemId);
- case "workCenter":
- return path.to.workCenter(child.workCenterId);
+ return path.to.part(child.itemId);
default:
return null;
}
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx
index 0c6d32e748..ca26cd4f36 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx
@@ -20,14 +20,16 @@ import type { z } from "zod/v3";
import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
-import { Hidden, Submit, WorkCenter } from "~/components/Form";
+import { Employee, Hidden, Submit, WorkCenter } from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
import {
maintenanceDispatchPriority,
maintenanceDispatchValidator,
+ maintenanceSeverity,
maintenanceSource
} from "../../production.models";
+import MaintenanceSeverity from "./MaintenanceSeverity";
import MaintenanceSource from "./MaintenanceSource";
function getPriorityIcon(
@@ -135,6 +137,14 @@ const MaintenanceDispatchForm = ({
label: <MaintenanceSource source={source} />
}))}
/>
+ <Select
+ name="severity"
+ label="Severity"
+ options={maintenanceSeverity.map((severity) => ({
+ value: severity,
+ label: <MaintenanceSeverity severity={severity} />
+ }))}
+ />
<WorkCenter name="workCenterId" label="Work Center" />
<Select
name="suspectedFailureModeId"
@@ -145,6 +155,7 @@ const MaintenanceDispatchForm = ({
}))}
isClearable
/>
+ <Employee name="assignee" label="Assignee" />
<DateTimePicker
name="plannedStartTime"
label="Planned Start Time"
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx
index 0b0f53095e..ce6fcb7b95 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx
@@ -46,11 +46,11 @@ const MaintenanceDispatchHeader = () => {
<HStack>
<Link to={path.to.maintenanceDispatch(dispatchId)}>
<Heading size="h4" className="flex items-center gap-2">
- <span>{routeData?.dispatch?.id}</span>
+ <span>{routeData?.dispatch?.maintenanceDispatchId}</span>
</Heading>
</Link>
<MaintenanceStatus status={status} />
- <Copy text={routeData?.dispatch?.id ?? ""} />
+ <Copy text={routeData?.dispatch?.maintenanceDispatchId ?? ""} />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
@@ -80,7 +80,7 @@ const MaintenanceDispatchHeader = () => {
<HStack>
<statusFetcher.Form
method="post"
- action={path.to.maintenanceDispatchProperties(dispatchId)}
+ action={path.to.maintenanceDispatchStatus(dispatchId)}
>
<input type="hidden" name="status" value="In Progress" />
<Button
@@ -107,7 +107,7 @@ const MaintenanceDispatchHeader = () => {
<statusFetcher.Form
method="post"
- action={path.to.maintenanceDispatchProperties(dispatchId)}
+ action={path.to.maintenanceDispatchStatus(dispatchId)}
>
<input type="hidden" name="status" value="Completed" />
<Button
@@ -130,7 +130,7 @@ const MaintenanceDispatchHeader = () => {
<statusFetcher.Form
method="post"
- action={path.to.maintenanceDispatchProperties(dispatchId)}
+ action={path.to.maintenanceDispatchStatus(dispatchId)}
>
<input type="hidden" name="status" value="Open" />
<Button
@@ -152,7 +152,7 @@ const MaintenanceDispatchHeader = () => {
<ConfirmDelete
action={path.to.deleteMaintenanceDispatch(dispatchId)}
isOpen={deleteModal.isOpen}
- name={routeData?.dispatch?.id!}
+ name={routeData?.dispatch?.maintenanceDispatchId!}
text={`Are you sure you want to delete this maintenance dispatch? This cannot be undone.`}
onCancel={() => {
deleteModal.onClose();
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchNotes.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchNotes.tsx
index 2d345e153c..2ea7190dd7 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchNotes.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchNotes.tsx
@@ -1,23 +1,44 @@
import { useCarbon } from "@carbon/auth";
import {
Card,
+ CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ File,
generateHTML,
+ HStack,
+ IconButton,
type JSONContent,
+ Skeleton,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
toast,
useDebounce
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
+import { convertKbToString } from "@carbon/utils";
+import type { FileObject } from "@supabase/storage-js";
import { nanoid } from "nanoid";
-import { Suspense, useState } from "react";
-import { Await } from "react-router";
-import { Files, FilesSkeleton } from "~/components";
+import { type ChangeEvent, Suspense, useCallback, useState } from "react";
+import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
+import { Await, useRevalidator } from "react-router";
+import { DocumentPreview, FileDropzone } from "~/components";
+import DocumentIcon from "~/components/DocumentIcon";
import { usePermissions, useUser } from "~/hooks";
+import { getDocumentType } from "~/modules/shared";
import type { StorageItem } from "~/types";
-import { getPrivateUrl } from "~/utils/path";
+import { getPrivateUrl, path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
export function MaintenanceDispatchNotes({
id,
@@ -104,12 +125,34 @@ export function MaintenanceDispatchNotes({
);
}
+export function MaintenanceDispatchFilesSkeleton() {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ <CardDescription>
+ Attachments and documents related to this dispatch
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-3/4" />
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
export function MaintenanceDispatchFiles({
- id,
- files
+ dispatchId,
+ files,
+ isDisabled
}: {
- id: string;
+ dispatchId: string;
files: Promise<StorageItem[]>;
+ isDisabled: boolean;
}) {
const permissions = usePermissions();
@@ -122,14 +165,15 @@ export function MaintenanceDispatchFiles({
</CardDescription>
</CardHeader>
<CardContent>
- <Suspense fallback={<FilesSkeleton />}>
+ <Suspense fallback={<MaintenanceDispatchFilesSkeleton />}>
<Await resolve={files}>
{(resolvedFiles) => (
- <Files
- bucket="private"
- path={id}
- files={resolvedFiles}
- isReadOnly={!permissions.can("update", "production")}
+ <MaintenanceFilesContent
+ dispatchId={dispatchId}
+ files={resolvedFiles ?? []}
+ isReadOnly={
+ !permissions.can("update", "production") || isDisabled
+ }
/>
)}
</Await>
@@ -139,4 +183,215 @@ export function MaintenanceDispatchFiles({
);
}
+function MaintenanceFilesContent({
+ dispatchId,
+ files,
+ isReadOnly
+}: {
+ dispatchId: string;
+ files: StorageItem[];
+ isReadOnly: boolean;
+}) {
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const revalidator = useRevalidator();
+
+ const getFilePath = useCallback(
+ (fileName: string) => {
+ return `${company.id}/maintenance/${dispatchId}/${stripSpecialCharacters(fileName)}`;
+ },
+ [company.id, dispatchId]
+ );
+
+ const upload = useCallback(
+ async (filesToUpload: File[]) => {
+ if (!carbon) {
+ toast.error("Carbon client not available");
+ return;
+ }
+
+ for (const file of filesToUpload) {
+ const filePath = getFilePath(file.name);
+
+ const result = await carbon.storage
+ .from("private")
+ .upload(filePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true
+ });
+
+ if (result.error) {
+ toast.error(`Failed to upload file: ${file.name}`);
+ } else {
+ toast.success(`${file.name} uploaded successfully`);
+ }
+ }
+ revalidator.revalidate();
+ },
+ [carbon, getFilePath, revalidator]
+ );
+
+ const download = useCallback(
+ async (file: FileObject) => {
+ const filePath = getFilePath(file.name);
+ const url = path.to.file.previewFile(`private/${filePath}`);
+ try {
+ const response = await fetch(url);
+ const blob = await response.blob();
+ const blobUrl = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ a.href = blobUrl;
+ a.download = file.name;
+ a.click();
+ window.URL.revokeObjectURL(blobUrl);
+ document.body.removeChild(a);
+ } catch (error) {
+ toast.error("Error downloading file");
+ console.error(error);
+ }
+ },
+ [getFilePath]
+ );
+
+ const deleteFile = useCallback(
+ async (file: FileObject) => {
+ if (!carbon) {
+ toast.error("Carbon client not available");
+ return;
+ }
+
+ const filePath = getFilePath(file.name);
+ const result = await carbon.storage.from("private").remove([filePath]);
+
+ if (result.error) {
+ toast.error(result.error.message || "Error deleting file");
+ return;
+ }
+
+ toast.success(`${file.name} deleted successfully`);
+ revalidator.revalidate();
+ },
+ [carbon, getFilePath, revalidator]
+ );
+
+ const onDrop = useCallback(
+ (acceptedFiles: File[]) => {
+ upload(acceptedFiles);
+ },
+ [upload]
+ );
+
+ const uploadFiles = (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files) {
+ upload(Array.from(e.target.files));
+ }
+ };
+
+ return (
+ <>
+ {!isReadOnly && (
+ <div className="flex justify-end mb-4">
+ <File leftIcon={<LuUpload />} onChange={uploadFiles} multiple>
+ Upload
+ </File>
+ </div>
+ )}
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ <Th />
+ </Tr>
+ </Thead>
+ <Tbody>
+ {files.map((file) => {
+ const type = getDocumentType(file.name);
+ return (
+ <Tr key={file.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <span
+ className="font-medium cursor-pointer"
+ onClick={() => {
+ if (["PDF", "Image"].includes(type)) {
+ window.open(
+ path.to.file.previewFile(
+ `private/${getFilePath(file.name)}`
+ ),
+ "_blank"
+ );
+ } else {
+ download(file);
+ }
+ }}
+ >
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getFilePath(file.name)}
+ // @ts-ignore
+ type={type}
+ >
+ {file.name}
+ </DocumentPreview>
+ ) : (
+ file.name
+ )}
+ </span>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((file.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem onClick={() => download(file)}>
+ Download
+ </DropdownMenuItem>
+ {!isReadOnly && (
+ <DropdownMenuItem
+ destructive
+ onClick={() => deleteFile(file)}
+ >
+ Delete
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ );
+ })}
+ {files.length === 0 && (
+ <Tr>
+ <Td
+ colSpan={3}
+ className="py-8 text-muted-foreground text-center"
+ >
+ No files uploaded
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ {!isReadOnly && <FileDropzone onDrop={onDrop} />}
+ </>
+ );
+}
+
export default MaintenanceDispatchNotes;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx
index ae4a9a0063..3770bfc6f5 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx
@@ -1,4 +1,4 @@
-import { DatePicker, Select, Switch, ValidatedForm } from "@carbon/form";
+import { Boolean, DatePicker, Select, ValidatedForm } from "@carbon/form";
import {
Button,
HStack,
@@ -28,6 +28,8 @@ import {
} from "../../production.models";
import type { MaintenanceDispatchDetail } from "../../types";
import MaintenancePriority from "./MaintenancePriority";
+import MaintenanceSeverity from "./MaintenanceSeverity";
+import MaintenanceSource from "./MaintenanceSource";
import MaintenanceStatus from "./MaintenanceStatus";
const MaintenanceDispatchProperties = () => {
@@ -62,11 +64,12 @@ const MaintenanceDispatchProperties = () => {
const onUpdate = useCallback(
(field: string, value: string | null) => {
const formData = new FormData();
+ formData.append("ids", dispatchId);
formData.append("field", field);
formData.append("value", value?.toString() ?? "");
fetcher.submit(formData, {
method: "post",
- action: path.to.maintenanceDispatchProperties(dispatchId)
+ action: path.to.maintenanceDispatchUpdate
});
},
[dispatchId, fetcher]
@@ -127,7 +130,11 @@ const MaintenanceDispatchProperties = () => {
aria-label="Copy"
size="sm"
className="p-1"
- onClick={() => copyToClipboard(routeData?.dispatch?.id ?? "")}
+ onClick={() =>
+ copyToClipboard(
+ routeData?.dispatch?.maintenanceDispatchId ?? ""
+ )
+ }
>
<LuCopy className="w-3 h-3" />
</Button>
@@ -139,7 +146,7 @@ const MaintenanceDispatchProperties = () => {
</HStack>
</HStack>
<span className="text-sm tracking-tight">
- {routeData?.dispatch?.id}
+ {routeData?.dispatch?.maintenanceDispatchId}
</span>
</VStack>
@@ -173,7 +180,14 @@ const MaintenanceDispatchProperties = () => {
isReadOnly={!permissions.can("update", "production")}
label="Work Center"
name="workCenterId"
- inline
+ inline={(value) => {
+ return (
+ <span>
+ {workCenterOptions.find((option) => option.value === value)
+ ?.label ?? ""}
+ </span>
+ );
+ }}
isClearable
onChange={(value) => {
onUpdate("workCenterId", value?.value ?? null);
@@ -234,7 +248,13 @@ const MaintenanceDispatchProperties = () => {
isReadOnly={!permissions.can("update", "production")}
label="Severity"
name="severity"
- inline
+ inline={(value) => {
+ return (
+ <MaintenanceSeverity
+ severity={value as (typeof maintenanceSeverity)[number]}
+ />
+ );
+ }}
onChange={(value) => {
if (value) {
onUpdate("severity", value.value);
@@ -260,7 +280,13 @@ const MaintenanceDispatchProperties = () => {
isReadOnly={!permissions.can("update", "production")}
label="Source"
name="source"
- inline
+ inline={(value) => {
+ return (
+ <MaintenanceSource
+ source={value as (typeof maintenanceSource)[number]}
+ />
+ );
+ }}
onChange={(value) => {
if (value) {
onUpdate("source", value.value);
@@ -318,9 +344,10 @@ const MaintenanceDispatchProperties = () => {
})}
className="w-full"
>
- <Switch
+ <Boolean
name="isFailure"
- label="Is Failure"
+ label="Failure"
+ variant="small"
isDisabled={!permissions.can("update", "production")}
onChange={(checked) => {
onUpdate("isFailure", checked.toString());
@@ -346,7 +373,14 @@ const MaintenanceDispatchProperties = () => {
isReadOnly={!permissions.can("update", "production")}
label="Suspected Failure Mode"
name="suspectedFailureModeId"
- inline
+ inline={(value) => {
+ return (
+ <span>
+ {routeData?.failureModes.find((mode) => mode.id === value)
+ ?.name ?? ""}
+ </span>
+ );
+ }}
isClearable
onChange={(value) => {
onUpdate("suspectedFailureModeId", value?.value ?? null);
@@ -371,7 +405,14 @@ const MaintenanceDispatchProperties = () => {
isReadOnly={!permissions.can("update", "production")}
label="Actual Failure Mode"
name="actualFailureModeId"
- inline
+ inline={(value) => {
+ return (
+ <span>
+ {routeData?.failureModes.find((mode) => mode.id === value)
+ ?.name ?? ""}
+ </span>
+ );
+ }}
isClearable
onChange={(value) => {
onUpdate("actualFailureModeId", value?.value ?? null);
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx
index 37876edaa3..e7d3dfee88 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx
@@ -1,4 +1,7 @@
-import { Status } from "@carbon/react";
+import { BsExclamationSquareFill } from "react-icons/bs";
+import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
+import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
+import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import type { maintenanceDispatchPriority } from "../../production.models";
type MaintenancePriorityProps = {
@@ -13,27 +16,31 @@ function MaintenancePriority({
switch (priority) {
case "Low":
return (
- <Status color="gray" className={className}>
- {priority}
- </Status>
+ <div className={`flex gap-1 items-center ${className ?? ""}`}>
+ <LowPriorityIcon />
+ <span>{priority}</span>
+ </div>
);
case "Medium":
return (
- <Status color="yellow" className={className}>
- {priority}
- </Status>
+ <div className={`flex gap-1 items-center ${className ?? ""}`}>
+ <MediumPriorityIcon />
+ <span>{priority}</span>
+ </div>
);
case "High":
return (
- <Status color="orange" className={className}>
- {priority}
- </Status>
+ <div className={`flex gap-1 items-center ${className ?? ""}`}>
+ <HighPriorityIcon />
+ <span>{priority}</span>
+ </div>
);
case "Critical":
return (
- <Status color="red" className={className}>
- {priority}
- </Status>
+ <div className={`flex gap-1 items-center ${className ?? ""}`}>
+ <BsExclamationSquareFill className="text-red-500" />
+ <span>{priority}</span>
+ </div>
);
default:
return null;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSeverity.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSeverity.tsx
new file mode 100644
index 0000000000..9431f5749e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSeverity.tsx
@@ -0,0 +1,65 @@
+import { Badge, cn } from "@carbon/react";
+import {
+ LuSettings,
+ LuSquareUser,
+ LuTriangleAlert,
+ LuWrench
+} from "react-icons/lu";
+import type { maintenanceSeverity } from "../../production.models";
+
+type MaintenanceSeverityProps = {
+ severity?: (typeof maintenanceSeverity)[number] | null;
+ className?: string;
+};
+
+function MaintenanceSeverity({
+ severity,
+ className
+}: MaintenanceSeverityProps) {
+ switch (severity) {
+ case "Preventive":
+ return (
+ <Badge
+ variant="outline"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuSettings />
+ {severity}
+ </Badge>
+ );
+ case "Operator Perfomed":
+ return (
+ <Badge
+ variant="blue"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuSquareUser />
+ {severity}
+ </Badge>
+ );
+ case "Maintenance Required":
+ return (
+ <Badge
+ variant="yellow"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuWrench />
+ {severity}
+ </Badge>
+ );
+ case "OEM Required":
+ return (
+ <Badge
+ variant="red"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuTriangleAlert />
+ {severity}
+ </Badge>
+ );
+ default:
+ return null;
+ }
+}
+
+export default MaintenanceSeverity;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/index.ts b/apps/erp/app/modules/production/ui/Maintenance/index.ts
index 9a0303b31c..a4b2774428 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/index.ts
+++ b/apps/erp/app/modules/production/ui/Maintenance/index.ts
@@ -7,6 +7,7 @@ export { default as MaintenanceDispatchForm } from "./MaintenanceDispatchForm";
export { default as MaintenanceDispatchHeader } from "./MaintenanceDispatchHeader";
export {
MaintenanceDispatchFiles,
+ MaintenanceDispatchFilesSkeleton,
MaintenanceDispatchNotes
} from "./MaintenanceDispatchNotes";
export { default as MaintenanceDispatchProperties } from "./MaintenanceDispatchProperties";
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx
deleted file mode 100644
index 090fed14c4..0000000000
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- HStack,
- VStack
-} from "@carbon/react";
-import { useParams } from "react-router";
-import { EmployeeAvatar } from "~/components";
-import { useRouteData } from "~/hooks";
-import type { MaintenanceDispatchDetail } from "~/modules/production/types";
-import {
- MaintenancePriority,
- MaintenanceStatus
-} from "~/modules/production/ui/Maintenance";
-import { path } from "~/utils/path";
-
-export default function MaintenanceDispatchOverview() {
- const { dispatchId } = useParams();
- if (!dispatchId) throw new Error("dispatchId not found");
-
- const routeData = useRouteData<{
- dispatch: MaintenanceDispatchDetail;
- }>(path.to.maintenanceDispatch(dispatchId));
-
- const dispatch = routeData?.dispatch;
-
- return (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <Card>
- <CardHeader>
- <CardTitle>Status</CardTitle>
- </CardHeader>
- <CardContent>
- <VStack spacing={4}>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Status</span>
- <MaintenanceStatus status={dispatch?.status} />
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Priority</span>
- <MaintenancePriority priority={dispatch?.priority} />
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Severity</span>
- <span>{dispatch?.severity ?? "-"}</span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Source</span>
- <span>{dispatch?.source ?? "-"}</span>
- </HStack>
- </VStack>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Timing</CardTitle>
- </CardHeader>
- <CardContent>
- <VStack spacing={4}>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Planned Start</span>
- <span>
- {dispatch?.plannedStartTime
- ? new Date(dispatch.plannedStartTime).toLocaleString()
- : "-"}
- </span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Planned End</span>
- <span>
- {dispatch?.plannedEndTime
- ? new Date(dispatch.plannedEndTime).toLocaleString()
- : "-"}
- </span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Actual Start</span>
- <span>
- {dispatch?.actualStartTime
- ? new Date(dispatch.actualStartTime).toLocaleString()
- : "-"}
- </span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Actual End</span>
- <span>
- {dispatch?.actualEndTime
- ? new Date(dispatch.actualEndTime).toLocaleString()
- : "-"}
- </span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Duration</span>
- <span>
- {dispatch?.duration ? `${dispatch.duration} min` : "-"}
- </span>
- </HStack>
- </VStack>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Assignment</CardTitle>
- </CardHeader>
- <CardContent>
- <VStack spacing={4}>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Assignee</span>
- {dispatch?.assignee ? (
- <EmployeeAvatar employeeId={dispatch.assignee} size="xs" />
- ) : (
- <span>Unassigned</span>
- )}
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Created By</span>
- {dispatch?.createdBy ? (
- <EmployeeAvatar employeeId={dispatch.createdBy} size="xs" />
- ) : (
- <span>-</span>
- )}
- </HStack>
- </VStack>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Failure Analysis</CardTitle>
- </CardHeader>
- <CardContent>
- <VStack spacing={4}>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Is Failure</span>
- <span>{dispatch?.isFailure ? "Yes" : "No"}</span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">
- Suspected Failure Mode
- </span>
- <span>{dispatch?.suspectedFailureMode?.name ?? "-"}</span>
- </HStack>
- <HStack className="justify-between w-full">
- <span className="text-muted-foreground">Actual Failure Mode</span>
- <span>{dispatch?.actualFailureMode?.name ?? "-"}</span>
- </HStack>
- </VStack>
- </CardContent>
- </Card>
- </div>
- );
-}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx
new file mode 100644
index 0000000000..f9213ebade
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx
@@ -0,0 +1,32 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { deleteMaintenanceDispatchEvent } 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 { dispatchId, eventId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+ if (!eventId) throw new Error("Could not find eventId");
+
+ const result = await deleteMaintenanceDispatchEvent(client, eventId);
+
+ if (result.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(result.error, "Failed to delete timecard"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, success("Timecard removed successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx
new file mode 100644
index 0000000000..959281d51d
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx
@@ -0,0 +1,59 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import {
+ maintenanceDispatchEventValidator,
+ upsertMaintenanceDispatchEvent
+} from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+
+ const formData = await request.formData();
+ const validation = await validator(
+ maintenanceDispatchEventValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(validation.error, "Invalid form data"))
+ );
+ }
+
+ const { employeeId, workCenterId, startTime, endTime, notes } =
+ validation.data;
+
+ const result = await upsertMaintenanceDispatchEvent(client, {
+ maintenanceDispatchId: dispatchId,
+ employeeId,
+ workCenterId,
+ startTime,
+ endTime: endTime ?? null,
+ notes: notes ?? null,
+ companyId,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(result.error, "Failed to add timecard"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, success("Timecard added successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.$itemId.delete.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.$itemId.delete.tsx
new file mode 100644
index 0000000000..9d094d7fb8
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.$itemId.delete.tsx
@@ -0,0 +1,32 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { deleteMaintenanceDispatchItem } 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 { dispatchId, itemId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const result = await deleteMaintenanceDispatchItem(client, itemId);
+
+ if (result.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(result.error, "Failed to delete item"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, success("Item removed successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.new.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.new.tsx
new file mode 100644
index 0000000000..f2be445fa2
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.item.new.tsx
@@ -0,0 +1,57 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import {
+ maintenanceDispatchItemValidator,
+ upsertMaintenanceDispatchItem
+} from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+
+ const formData = await request.formData();
+ const validation = await validator(maintenanceDispatchItemValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(validation.error, "Invalid form data"))
+ );
+ }
+
+ const { itemId, quantity, unitOfMeasureCode, unitCost } = validation.data;
+
+ const result = await upsertMaintenanceDispatchItem(client, {
+ maintenanceDispatchId: dispatchId,
+ itemId,
+ quantity,
+ unitOfMeasureCode,
+ unitCost: unitCost ?? 0,
+ companyId,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(result.error, "Failed to add item"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, success("Item added successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx
deleted file mode 100644
index 2e9d9f1726..0000000000
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { upsertMaintenanceDispatch } from "~/modules/production";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- update: "production"
- });
-
- const { dispatchId } = params;
- if (!dispatchId) throw new Error("dispatchId not found");
-
- const formData = await request.formData();
- const field = formData.get("field") as string;
- const value = formData.get("value") as string | null;
- const status = formData.get("status") as string | null;
-
- // Handle status update from header buttons
- if (status) {
- const updateDispatch = await upsertMaintenanceDispatch(client, {
- id: dispatchId,
- status: status as
- | "Open"
- | "Assigned"
- | "In Progress"
- | "Completed"
- | "Cancelled",
- updatedBy: userId,
- ...(status === "In Progress" && {
- actualStartTime: new Date().toISOString()
- }),
- ...(status === "Completed" && { actualEndTime: new Date().toISOString() })
- });
-
- if (updateDispatch.error) {
- return data(
- { error: updateDispatch.error },
- await flash(
- request,
- error(updateDispatch.error, "Failed to update status")
- )
- );
- }
-
- return data(
- {},
- await flash(request, success(`Status updated to ${status}`))
- );
- }
-
- // Handle field update from properties sidebar
- if (!field) {
- return data(
- { error: { message: "Field is required" } },
- await flash(request, error(null, "Field is required"))
- );
- }
-
- const updateData: Record<string, unknown> = {
- id: dispatchId,
- updatedBy: userId
- };
-
- // Handle different field types
- switch (field) {
- case "priority":
- case "severity":
- case "source":
- case "suspectedFailureModeId":
- case "actualFailureModeId":
- case "workCenterId":
- updateData[field] = value || null;
- break;
- case "plannedStartTime":
- case "plannedEndTime":
- updateData[field] = value ? new Date(value).toISOString() : null;
- break;
- case "isFailure":
- updateData[field] = value === "true";
- break;
- default:
- return data(
- { error: { message: `Unknown field: ${field}` } },
- await flash(request, error(null, `Unknown field: ${field}`))
- );
- }
-
- const updateDispatch = await upsertMaintenanceDispatch(
- client,
- updateData as Parameters<typeof upsertMaintenanceDispatch>[1]
- );
-
- if (updateDispatch.error) {
- return data(
- { error: updateDispatch.error },
- await flash(request, error(updateDispatch.error, "Failed to update"))
- );
- }
-
- return data({}, await flash(request, success("Updated successfully")));
-}
-
-export default function MaintenanceDispatchPropertiesRoute() {
- return null;
-}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx
new file mode 100644
index 0000000000..33b7bea120
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx
@@ -0,0 +1,54 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import {
+ maintenanceDispatchStatus,
+ upsertMaintenanceDispatch
+} from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+
+ const formData = await request.formData();
+ const status = formData.get(
+ "status"
+ ) as (typeof maintenanceDispatchStatus)[number];
+
+ if (!status || !maintenanceDispatchStatus.includes(status)) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await upsertMaintenanceDispatch(client, {
+ id: dispatchId,
+ status,
+ assignee: ["Completed", "Cancelled"].includes(status) ? null : undefined,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(
+ request,
+ error(update.error, "Failed to update dispatch status")
+ )
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
+ await flash(request, success("Updated dispatch status"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
index fa3bf11db5..2426247773 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
@@ -10,11 +10,11 @@ import {
getMaintenanceDispatch,
getMaintenanceDispatchComments,
getMaintenanceDispatchEvents,
- getMaintenanceDispatchItems,
- getMaintenanceDispatchWorkCenters
+ getMaintenanceDispatchItems
} from "~/modules/production";
import {
MaintenanceDispatchExplorer,
+ MaintenanceDispatchFiles,
MaintenanceDispatchHeader,
MaintenanceDispatchNotes,
MaintenanceDispatchProperties
@@ -28,6 +28,17 @@ export const handle: Handle = {
module: "production"
};
+async function getMaintenanceDispatchFiles(
+ client: Parameters<typeof getMaintenanceDispatch>[0],
+ companyId: string,
+ dispatchId: string
+) {
+ const result = await client.storage
+ .from("private")
+ .list(`${companyId}/maintenance/${dispatchId}`);
+ return result.data || [];
+}
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "production"
@@ -36,15 +47,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { dispatchId } = params;
if (!dispatchId) throw new Error("Could not find dispatchId");
- const [dispatch, events, items, workCenters, comments, failureModes] =
- await Promise.all([
- getMaintenanceDispatch(client, dispatchId),
- getMaintenanceDispatchEvents(client, dispatchId),
- getMaintenanceDispatchItems(client, dispatchId),
- getMaintenanceDispatchWorkCenters(client, dispatchId),
- getMaintenanceDispatchComments(client, dispatchId),
- getFailureModesList(client, companyId)
- ]);
+ const [dispatch, events, items, comments, failureModes] = await Promise.all([
+ getMaintenanceDispatch(client, dispatchId),
+ getMaintenanceDispatchEvents(client, dispatchId),
+ getMaintenanceDispatchItems(client, dispatchId),
+ getMaintenanceDispatchComments(client, dispatchId),
+ getFailureModesList(client, companyId)
+ ]);
if (dispatch.error) {
throw redirect(
@@ -60,16 +69,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
dispatch: dispatch.data,
events: events.data ?? [],
items: items.data ?? [],
- workCenters: workCenters.data ?? [],
comments: comments.data ?? [],
- failureModes: failureModes.data ?? []
+ failureModes: failureModes.data ?? [],
+ files: getMaintenanceDispatchFiles(client, companyId, dispatchId)
};
}
export default function MaintenanceDispatchRoute() {
const { dispatchId } = useParams();
- const { dispatch, events, items, workCenters } =
- useLoaderData<typeof loader>();
+ const { dispatch, events, items, files } = useLoaderData<typeof loader>();
if (!dispatchId) throw new Error("Could not find dispatchId");
@@ -83,11 +91,7 @@ export default function MaintenanceDispatchRoute() {
<div className="flex flex-grow overflow-hidden">
<ResizablePanels
explorer={
- <MaintenanceDispatchExplorer
- items={items}
- events={events}
- workCenters={workCenters}
- />
+ <MaintenanceDispatchExplorer items={items} events={events} />
}
content={
<div className="h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
@@ -97,6 +101,11 @@ export default function MaintenanceDispatchRoute() {
content={(dispatch?.content ?? {}) as JSONContent}
isDisabled={isCompleted}
/>
+ <MaintenanceDispatchFiles
+ dispatchId={dispatchId}
+ files={files}
+ isDisabled={isCompleted}
+ />
<Outlet />
</VStack>
</div>
diff --git a/apps/erp/app/routes/x+/maintenance+/new.tsx b/apps/erp/app/routes/x+/maintenance+/new.tsx
index e4da6f9569..ef86daf4ef 100644
--- a/apps/erp/app/routes/x+/maintenance+/new.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/new.tsx
@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
+import { useUser } from "~/hooks";
import {
getFailureModesList,
maintenanceDispatchValidator,
@@ -70,13 +71,13 @@ export async function action({ request }: ActionFunctionArgs) {
maintenanceDispatchId: nextSequence.data,
status: validation.data.status,
priority: validation.data.priority,
- severity: validation.data.severity || null,
+ severity: validation.data.severity || "Maintenance Required",
source: validation.data.source || "Reactive",
- workCenterId: validation.data.workCenterId || null,
- assignee: validation.data.assignee || null,
- suspectedFailureModeId: validation.data.suspectedFailureModeId || null,
- plannedStartTime: validation.data.plannedStartTime || null,
- plannedEndTime: validation.data.plannedEndTime || null,
+ workCenterId: validation.data.workCenterId || undefined,
+ assignee: validation.data.assignee || undefined,
+ suspectedFailureModeId: validation.data.suspectedFailureModeId || undefined,
+ plannedStartTime: validation.data.plannedStartTime || undefined,
+ plannedEndTime: validation.data.plannedEndTime || undefined,
content,
companyId,
createdBy: userId
@@ -109,10 +110,14 @@ export async function action({ request }: ActionFunctionArgs) {
export default function NewMaintenanceDispatchRoute() {
const { failureModes } = useLoaderData<typeof loader>();
+ const { id: userId } = useUser();
+
const initialValues = {
status: "Open" as const,
priority: "Medium" as const,
- source: "Reactive" as const
+ source: "Reactive" as const,
+ severity: "Maintenance Required" as const,
+ assignee: userId
};
return (
diff --git a/apps/erp/app/routes/x+/maintenance+/update.tsx b/apps/erp/app/routes/x+/maintenance+/update.tsx
new file mode 100644
index 0000000000..8cf4e57ae8
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/update.tsx
@@ -0,0 +1,80 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { type ActionFunctionArgs } from "react-router";
+import { upsertMaintenanceDispatch } from "~/modules/production";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const formData = await request.formData();
+ const ids = formData.getAll("ids");
+ const field = formData.get("field");
+ const value = formData.get("value");
+
+ if (
+ typeof field !== "string" ||
+ (typeof value !== "string" && value !== null)
+ ) {
+ return { error: { message: "Invalid form data" }, data: null };
+ }
+
+ const updateData: Record<string, unknown> = {
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ };
+
+ switch (field) {
+ case "priority":
+ case "severity":
+ case "source":
+ case "status":
+ case "suspectedFailureModeId":
+ case "actualFailureModeId":
+ case "workCenterId":
+ updateData[field] = value || null;
+ break;
+ case "plannedStartTime":
+ case "plannedEndTime":
+ updateData[field] = value ? new Date(value).toISOString() : null;
+ break;
+ case "isFailure":
+ updateData[field] = value === "true";
+ break;
+ default:
+ return {
+ error: { message: `Invalid field: ${field}` },
+ data: null
+ };
+ }
+
+ // Handle special status updates with timestamps
+ if (field === "status") {
+ if (value === "In Progress") {
+ updateData.actualStartTime = new Date().toISOString();
+ } else if (value === "Completed") {
+ updateData.actualEndTime = new Date().toISOString();
+ }
+ }
+
+ // Update each maintenance dispatch individually since upsertMaintenanceDispatch expects single records
+ const results = await Promise.all(
+ ids.map(async (id) => {
+ return await upsertMaintenanceDispatch(client, {
+ id: id as string,
+ ...updateData
+ } as Parameters<typeof upsertMaintenanceDispatch>[1]);
+ })
+ );
+
+ // Check if any updates failed
+ const errors = results.filter((result) => result.error);
+ if (errors.length > 0) {
+ return {
+ error: { message: "Failed to update maintenance dispatch(es)" },
+ data: null
+ };
+ }
+
+ return { data: results.map((result) => result.data) };
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b9f9396b94..6ca69b618f 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -863,10 +863,19 @@ export const path = {
generatePath(`${x}/maintenance/${id}/events`),
maintenanceDispatchItems: (id: string) =>
generatePath(`${x}/maintenance/${id}/items`),
- maintenanceDispatchProperties: (id: string) =>
- generatePath(`${x}/maintenance/${id}/properties`),
+ maintenanceDispatchStatus: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/status`),
+ maintenanceDispatchUpdate: `${x}/maintenance/update`,
maintenanceDispatchWorkCenters: (id: string) =>
generatePath(`${x}/maintenance/${id}/work-centers`),
+ newMaintenanceDispatchItem: (dispatchId: string) =>
+ generatePath(`${x}/maintenance/${dispatchId}/item/new`),
+ deleteMaintenanceDispatchItem: (dispatchId: string, itemId: string) =>
+ generatePath(`${x}/maintenance/${dispatchId}/item/${itemId}/delete`),
+ newMaintenanceDispatchEvent: (dispatchId: string) =>
+ generatePath(`${x}/maintenance/${dispatchId}/event/new`),
+ deleteMaintenanceDispatchEvent: (dispatchId: string, eventId: string) =>
+ generatePath(`${x}/maintenance/${dispatchId}/event/${eventId}/delete`),
maintenanceDispatches: `${x}/production/maintenance`,
maintenanceSchedule: (id: string) =>
generatePath(`${x}/production/maintenance-schedules/${id}`),
diff --git a/package-lock.json b/package-lock.json
index 5ee2480df2..17f56bd6b5 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2994,7 +2994,8 @@
"node_modules/@jest/reporters": {
"version": "26.6.2",
"resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-26.6.2.tgz",
- "integrity": "sha512-h2bW53APG4HvkOnVMo8q3QXa6pcaNt1HkwVsOPMBV6LD/q9oSpxNSYZQYkAnjdMjrJ86UuYeLo+aEZClV6opnw==",
+ "integrity": "sha512-h2bW53APG4HvkOnVMo8q3QXa6pcaNt1HkwVsOperator PerfomedBV6LD/q9oSpxNSYZQYkAnjdMjrJ86UuYeLo+aEZClV6opnw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^0.2.3",
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 467f89742c..6ac00af0e4 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -74733,7 +74733,7 @@ export default {
type: "string",
},
severity: {
- enum: ["Preventive", "OPM", "Maintenance Required", "OEM Required"],
+ enum: ["Preventive", "Operator Perfomed", "Maintenance Required", "OEM Required"],
format: 'public."maintenanceSeverity"',
type: "string",
},
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index ed02e964aa..cea388fda6 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -53087,7 +53087,7 @@ export type Database = {
| "Annual"
maintenanceSeverity:
| "Preventive"
- | "OPM"
+ | "Operator Perfomed"
| "Maintenance Required"
| "OEM Required"
maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
@@ -54229,7 +54229,7 @@ export const Constants = {
],
maintenanceSeverity: [
"Preventive",
- "OPM",
+ "Operator Perfomed",
"Maintenance Required",
"OEM Required",
],
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index ed02e964aa..cea388fda6 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -53087,7 +53087,7 @@ export type Database = {
| "Annual"
maintenanceSeverity:
| "Preventive"
- | "OPM"
+ | "Operator Perfomed"
| "Maintenance Required"
| "OEM Required"
maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
@@ -54229,7 +54229,7 @@ export const Constants = {
],
maintenanceSeverity: [
"Preventive",
- "OPM",
+ "Operator Perfomed",
"Maintenance Required",
"OEM Required",
],
diff --git a/packages/database/supabase/migrations/20251216021152_maintenance.sql b/packages/database/supabase/migrations/20251216021152_maintenance.sql
index d70edfdd98..5fa75da089 100644
--- a/packages/database/supabase/migrations/20251216021152_maintenance.sql
+++ b/packages/database/supabase/migrations/20251216021152_maintenance.sql
@@ -27,7 +27,7 @@ END $$;
DO $$ BEGIN
CREATE TYPE "maintenanceSeverity" AS ENUM (
'Preventive',
- 'OPM',
+ 'Operator Perfomed',
'Maintenance Required',
'OEM Required'
);