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: add locationId and procedureId to maintenance dispatches and schedules

Brad Barbin7f8f47a18667
diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.ts
index 8abf7eff21..f0ea1d6003 100644
--- a/apps/erp/app/components/Form/index.ts
+++ b/apps/erp/app/components/Form/index.ts
@@ -55,6 +55,7 @@ import Location from "./Location";
import MaterialType from "./MaterialType";
import Part from "./Part";
import PaymentTerm from "./PaymentTerm";
+import Procedure from "./Procedure";
import Process from "./Process";
import Processes from "./Processes";
import Sequence from "./Sequence";
@@ -126,6 +127,7 @@ export {
Password,
PaymentTerm,
PhoneInput,
+ Procedure,
Process,
Processes,
Radios,
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index 38e34fd317..1bbcd7dfa5 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -176,7 +176,7 @@ export const maintenanceDispatchValidator = z.object({
.enum(["Down", "Planned", "Impact", "No Impact"] as const)
.optional(),
workCenterId: zfd.text(z.string().optional()),
- locationId: zfd.text(z.string().optional()),
+ locationId: z.string().min(1, { message: "Location is required" }),
suspectedFailureModeId: zfd.text(z.string().optional()),
plannedStartTime: zfd.text(z.string().optional()),
plannedEndTime: zfd.text(z.string().optional()),
@@ -231,6 +231,7 @@ export const maintenanceScheduleValidator = z.object({
name: z.string().min(1, { message: "Name is required" }),
description: zfd.text(z.string().optional()),
workCenterId: z.string().min(1, { message: "Work center is required" }),
+ locationId: z.string().min(1, { message: "Location is required" }),
frequency: z.enum(maintenanceFrequency),
priority: z.enum(maintenanceDispatchPriority),
estimatedDuration: zfd.numeric(z.number().optional()),
@@ -244,7 +245,9 @@ export const maintenanceScheduleValidator = z.object({
saturday: zfd.checkbox(),
sunday: zfd.checkbox(),
// Skip holidays option
- skipHolidays: zfd.checkbox()
+ skipHolidays: zfd.checkbox(),
+ // Procedure
+ procedureId: zfd.text(z.string().optional())
});
export const maintenanceSeverity = [
diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.ts
index 810dd8f04e..da7c9b6c1b 100644
--- a/apps/erp/app/modules/resources/resources.service.ts
+++ b/apps/erp/app/modules/resources/resources.service.ts
@@ -395,7 +395,8 @@ export async function getMaintenanceDispatch(
assignee:user!maintenanceDispatch_assignee_fkey(id, fullName, avatarUrl),
suspectedFailureMode:maintenanceFailureMode!maintenanceDispatch_suspectedFailureModeId_fkey(id, name),
actualFailureMode:maintenanceFailureMode!maintenanceDispatch_actualFailureModeId_fkey(id, name),
- schedule:maintenanceSchedule(id, name)`
+ schedule:maintenanceSchedule(id, name),
+ procedure:procedureId(id, name)`
)
.eq("id", dispatchId)
.single();
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchForm.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchForm.tsx
index c694e014a5..840efcb2b3 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchForm.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchForm.tsx
@@ -79,10 +79,6 @@ const MaintenanceDispatchForm = ({
initialValues?.oeeImpact ?? "No Impact"
);
- const [hasWorkCenter, setHasWorkCenter] = useState<boolean>(
- !!initialValues?.workCenterId
- );
-
const showFailureModes =
oeeImpactValue === "Down" || oeeImpactValue === "Impact";
@@ -169,20 +165,8 @@ const MaintenanceDispatchForm = ({
label: <MaintenanceSeverity severity={severity} />
}))}
/>
- <WorkCenter
- name="workCenterId"
- label="Work Center"
- onChange={(option) => {
- setHasWorkCenter(!!option?.value);
- }}
- />
- <Location
- name="locationId"
- label="Location"
- // @ts-ignore
- value={hasWorkCenter ? null : undefined}
- isReadOnly={hasWorkCenter}
- />
+ <WorkCenter name="workCenterId" label="Work Center" />
+ <Location name="locationId" label="Location" />
<Select
name="oeeImpact"
label="OEE Impact"
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx
index 6737649f45..b6f3df091b 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx
@@ -24,7 +24,7 @@ import {
EmployeeAvatar,
useOptimisticAssignment
} from "~/components";
-import { Location, WorkCenter } from "~/components/Form";
+import { Location, Procedure, WorkCenter } from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
@@ -350,6 +350,30 @@ const MaintenanceDispatchProperties = () => {
/>
</ValidatedForm>
+ <ValidatedForm
+ defaultValues={{
+ procedureId: (routeData?.dispatch as any)?.procedureId ?? ""
+ }}
+ validator={z.object({
+ procedureId: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Procedure
+ isReadOnly={!permissions.can("update", "resources")}
+ label="Procedure"
+ name="procedureId"
+ inline={(value, options) => {
+ const procedure = options.find((o) => o.value === value);
+ return procedure?.label ?? null;
+ }}
+ isClearable
+ onChange={(value) => {
+ onUpdate("procedureId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
<ValidatedForm
defaultValues={{
oeeImpact: routeData?.dispatch?.oeeImpact ?? "No Impact"
diff --git a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
index 82d1e03873..69378f0dd5 100644
--- a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
+++ b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
@@ -29,7 +29,14 @@ import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import { Enumerable } from "~/components/Enumerable";
-import { Hidden, Input, Submit, WorkCenter } from "~/components/Form";
+import {
+ Hidden,
+ Input,
+ Location,
+ Procedure,
+ Submit,
+ WorkCenter
+} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import {
@@ -149,6 +156,7 @@ const MaintenanceScheduleForm = ({
<VStack spacing={4}>
<Input name="name" label="Schedule Name" />
<WorkCenter name="workCenterId" label="Work Center" />
+ <Location name="locationId" label="Location" />
<Select
name="frequency"
label="Frequency"
@@ -175,6 +183,7 @@ const MaintenanceScheduleForm = ({
label="Estimated Duration (minutes)"
minValue={0}
/>
+ <Procedure name="procedureId" />
<Boolean name="active" label="Active" />
<DailyScheduleOptions />
</VStack>
diff --git a/apps/erp/app/routes/x+/maintenance+/new.tsx b/apps/erp/app/routes/x+/maintenance+/new.tsx
index bd4dbdcab6..312147f12c 100644
--- a/apps/erp/app/routes/x+/maintenance+/new.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/new.tsx
@@ -11,6 +11,7 @@ import {
} from "~/modules/resources";
import MaintenanceDispatchForm from "~/modules/resources/ui/Maintenance/MaintenanceDispatchForm";
import { getNextSequence } from "~/modules/settings";
+import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -21,14 +22,18 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "resources"
});
- const failureModes = await getFailureModesList(client, companyId);
+ const [failureModes, defaults] = await Promise.all([
+ getFailureModesList(client, companyId),
+ getUserDefaults(client, userId, companyId)
+ ]);
return {
- failureModes: failureModes.data ?? []
+ failureModes: failureModes.data ?? [],
+ defaultLocationId: defaults.data?.locationId ?? undefined
};
}
@@ -66,19 +71,6 @@ export async function action({ request }: ActionFunctionArgs) {
? JSON.parse(validation.data.content)
: {};
- // Determine locationId - use provided value or get from work center
- let locationId = validation.data.locationId || undefined;
- if (!locationId && validation.data.workCenterId) {
- const workCenter = await client
- .from("workCenter")
- .select("locationId")
- .eq("id", validation.data.workCenterId)
- .single();
- if (!workCenter.error && workCenter.data?.locationId) {
- locationId = workCenter.data.locationId;
- }
- }
-
const insertDispatch = await upsertMaintenanceDispatch(client, {
maintenanceDispatchId: nextSequence.data,
status: validation.data.status,
@@ -87,7 +79,7 @@ export async function action({ request }: ActionFunctionArgs) {
source: validation.data.source || "Reactive",
oeeImpact: validation.data.oeeImpact || "No Impact",
workCenterId: validation.data.workCenterId || undefined,
- locationId,
+ locationId: validation.data.locationId,
assignee: validation.data.assignee || undefined,
suspectedFailureModeId: validation.data.suspectedFailureModeId || undefined,
plannedStartTime: validation.data.plannedStartTime || undefined,
@@ -122,14 +114,15 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function NewMaintenanceDispatchRoute() {
- const { failureModes } = useLoaderData<typeof loader>();
+ const { failureModes, defaultLocationId } = useLoaderData<typeof loader>();
const initialValues = {
status: "Open" as const,
priority: "Medium" as const,
source: "Reactive" as const,
severity: "Support Required" as const,
- oeeImpact: "No Impact" as const
+ oeeImpact: "No Impact" as const,
+ locationId: defaultLocationId ?? ""
};
return (
diff --git a/apps/erp/app/routes/x+/maintenance+/update.tsx b/apps/erp/app/routes/x+/maintenance+/update.tsx
index 2704168e0a..f8e6547651 100644
--- a/apps/erp/app/routes/x+/maintenance+/update.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/update.tsx
@@ -32,6 +32,7 @@ export async function action({ request }: ActionFunctionArgs) {
case "oeeImpact":
case "suspectedFailureModeId":
case "actualFailureModeId":
+ case "procedureId":
case "workCenterId":
updateData[field] = value || null;
break;
diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx
index 34607a4d3a..e2833dd9dd 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx
@@ -86,6 +86,7 @@ export default function EditMaintenanceScheduleRoute() {
id: schedule.id ?? undefined,
name: schedule.name ?? "",
workCenterId: schedule.workCenterId ?? "",
+ locationId: (schedule as any).locationId ?? "",
frequency: schedule.frequency ?? ("Weekly" as const),
priority: schedule.priority ?? ("Medium" as const),
estimatedDuration: schedule.estimatedDuration ?? undefined,
@@ -98,7 +99,8 @@ export default function EditMaintenanceScheduleRoute() {
friday: schedule.friday ?? true,
saturday: schedule.saturday ?? true,
sunday: schedule.sunday ?? true,
- skipHolidays: schedule.skipHolidays ?? true
+ skipHolidays: schedule.skipHolidays ?? true,
+ procedureId: (schedule as any).procedureId ?? undefined
};
return (
diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx
index 077cccef38..a2af3bd249 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx
@@ -3,20 +3,25 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { redirect, useNavigate } from "react-router";
+import { redirect, useLoaderData, useNavigate } from "react-router";
import {
maintenanceScheduleValidator,
upsertMaintenanceSchedule
} from "~/modules/resources";
import MaintenanceScheduleForm from "~/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm";
+import { getUserDefaults } from "~/modules/users/users.server";
import { getParams, path, requestReferrer } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "resources"
});
- return null;
+ const defaults = await getUserDefaults(client, userId, companyId);
+
+ return {
+ defaultLocationId: defaults.data?.locationId ?? undefined
+ };
}
export async function action({ request }: ActionFunctionArgs) {
@@ -67,10 +72,12 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function NewMaintenanceScheduleRoute() {
+ const { defaultLocationId } = useLoaderData<typeof loader>();
const navigate = useNavigate();
const initialValues = {
name: "",
workCenterId: "",
+ locationId: defaultLocationId ?? "",
frequency: "Weekly" as const,
priority: "Medium" as const,
estimatedDuration: undefined,
@@ -83,7 +90,8 @@ export default function NewMaintenanceScheduleRoute() {
friday: true,
saturday: true,
sunday: true,
- skipHolidays: true
+ skipHolidays: true,
+ procedureId: undefined
};
return (
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index 886cc82d9c..e6175b9b0d 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -82,8 +82,10 @@ export function AppSidebar({
<TeamSwitcher company={company} />
</SidebarHeader>
<SidebarContent>
- <OperationsNav activeEvents={activeEvents} />
- <MaintenanceNav activeMaintenanceCount={activeMaintenanceCount} />
+ <OperationsNav
+ activeEvents={activeEvents}
+ activeMaintenanceCount={activeMaintenanceCount}
+ />
<ToolsNav />
</SidebarContent>
<SidebarFooter>
@@ -134,7 +136,13 @@ export function TeamSwitcher({ company }: { company: Company }) {
);
}
-export function OperationsNav({ activeEvents }: { activeEvents: number }) {
+export function OperationsNav({
+ activeEvents,
+ activeMaintenanceCount
+}: {
+ activeEvents: number;
+ activeMaintenanceCount: number;
+}) {
const links = [
{
title: "Schedule",
@@ -156,6 +164,12 @@ export function OperationsNav({ activeEvents }: { activeEvents: number }) {
title: "Recent",
icon: LuClock,
to: path.to.recent
+ },
+ {
+ title: "Maintenance",
+ icon: LuWrench,
+ label: (activeMaintenanceCount ?? 0).toString(),
+ to: path.to.maintenance
}
];
@@ -204,40 +218,6 @@ export function OperationsNav({ activeEvents }: { activeEvents: number }) {
);
}
-export function MaintenanceNav({
- activeMaintenanceCount
-}: {
- activeMaintenanceCount: number;
-}) {
- const { pathname } = useLocation();
- const { isMobile, setOpenMobile } = useSidebar();
- const isActive = pathname.includes(path.to.maintenance);
-
- return (
- <SidebarGroup>
- <SidebarGroupLabel>Maintenance</SidebarGroupLabel>
- <SidebarMenu>
- <SidebarMenuItem>
- <SidebarMenuButton tooltip="Maintenance" isActive={isActive} asChild>
- <Link
- to={path.to.maintenance}
- onClick={() => isMobile && setOpenMobile(false)}
- >
- <LuWrench />
- <span>Dispatches</span>
- {activeMaintenanceCount > 0 && (
- <span className="ml-auto text-muted-foreground text-sm">
- {activeMaintenanceCount}
- </span>
- )}
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarGroup>
- );
-}
-
export function ToolsNav() {
return (
<>
diff --git a/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx b/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
index 4e0343e27b..70c1633f0e 100644
--- a/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
+++ b/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
@@ -11,6 +11,7 @@ import {
ModalContent,
ModalDescription,
ModalFooter,
+ ModalHeader,
ModalTitle,
NumberDecrementStepper,
NumberField,
@@ -294,10 +295,12 @@ export function MaintenanceAddPartModal({
return (
<Modal open onOpenChange={onClose}>
<ModalContent>
- <ModalTitle>Add Spare Part</ModalTitle>
- <ModalDescription>
- Select an item and specify the quantity to issue
- </ModalDescription>
+ <ModalHeader>
+ <ModalTitle>Add Spare Part</ModalTitle>
+ <ModalDescription>
+ Select an item and specify the quantity to issue
+ </ModalDescription>
+ </ModalHeader>
<ModalBody>
<div className="flex flex-col gap-4">
{/* Item Selection */}
diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
index cf564d6b42..5040f84d98 100644
--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
@@ -3,9 +3,15 @@ import type { Database } from "@carbon/database";
import { Hidden, ValidatedForm } from "@carbon/form";
import {
Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ generateHTML,
Heading,
HStack,
IconButton,
+ type JSONContent,
SidebarTrigger,
Status,
useDisclosure,
@@ -242,99 +248,138 @@ export default function MaintenanceDetailRoute() {
<main className="h-[calc(100dvh-var(--header-height))] w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent p-4">
<VStack spacing={4} className="max-w-2xl mx-auto">
{/* Work Center & OEE Impact */}
- <div className="w-full p-4 bg-card rounded-lg border">
- <VStack spacing={2} className="items-start">
- <span className="text-sm text-muted-foreground">Work Center</span>
- <span className="text-lg font-semibold">
- {dispatch.workCenter?.name ?? "Unknown"}
- </span>
- <HStack className="mt-2">
- <MaintenanceOeeImpact oeeImpact={dispatch.oeeImpact} />
- <MaintenanceSeverity
- severity={
- dispatch.severity as (typeof maintenanceSeverity)[number]
- }
- />
- </HStack>
- </VStack>
- </div>
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle className="text-sm text-muted-foreground font-normal">
+ Work Center
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={2} className="items-start">
+ <span className="text-lg font-semibold">
+ {dispatch.workCenter?.name ?? "Unknown"}
+ </span>
+ <HStack>
+ <MaintenanceOeeImpact oeeImpact={dispatch.oeeImpact} />
+ <MaintenanceSeverity
+ severity={
+ dispatch.severity as (typeof maintenanceSeverity)[number]
+ }
+ />
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+
+ {/* Description */}
+ {dispatch.content &&
+ Object.keys(dispatch.content as object).length > 0 && (
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle className="text-sm text-muted-foreground font-normal">
+ Description
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div
+ className="prose dark:prose-invert prose-sm max-w-none"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ (dispatch.content ?? {}) as JSONContent
+ )
+ }}
+ />
+ </CardContent>
+ </Card>
+ )}
{/* Time Tracking Controls */}
{!isCompleted && (
- <div className="w-full p-6 bg-card rounded-lg border">
- <VStack spacing={4}>
- <span className="text-sm text-muted-foreground">
- Time Worked: {formatDuration(totalDuration)}
- </span>
- <HStack spacing={4} className="justify-center w-full">
- <ValidatedForm
- method="post"
- action={path.to.maintenanceEvent}
- validator={eventValidator}
- fetcher={fetcher}
- defaultValues={{
- action: isWorking ? "End" : "Start",
- dispatchId: dispatch.id,
- workCenterId: dispatch.workCenterId ?? undefined,
- eventId: myActiveEvent?.id
- }}
- >
- <Hidden name="dispatchId" value={dispatch.id} />
- <Hidden
- name="workCenterId"
- value={dispatch.workCenterId ?? ""}
- />
- <Hidden name="eventId" value={myActiveEvent?.id ?? ""} />
- <Hidden name="action" value={isWorking ? "End" : "Start"} />
- <button
- type="submit"
- disabled={fetcher.state !== "idle"}
- className={`group size-24 flex flex-row items-center gap-2 justify-center rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:scale-105 transition-all text-white text-3xl border-b-4 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 ${
- isWorking
- ? "bg-red-500 hover:bg-red-600 border-red-700"
- : "bg-emerald-500 hover:bg-emerald-600 border-emerald-700"
- }`}
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle>
+ <span className="text-sm text-muted-foreground">
+ Time Worked: {formatDuration(totalDuration)}
+ </span>
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-6">
+ <VStack spacing={4}>
+ <HStack spacing={4} className="justify-center w-full">
+ <ValidatedForm
+ method="post"
+ action={path.to.maintenanceEvent}
+ validator={eventValidator}
+ fetcher={fetcher}
+ defaultValues={{
+ action: isWorking ? "End" : "Start",
+ dispatchId: dispatch.id,
+ workCenterId: dispatch.workCenterId ?? undefined,
+ eventId: myActiveEvent?.id
+ }}
>
- {isWorking ? (
- <FaPause className="group-hover:scale-110" />
- ) : (
- <FaPlay className="group-hover:scale-110" />
- )}
- </button>
- </ValidatedForm>
+ <Hidden name="dispatchId" value={dispatch.id} />
+ <Hidden
+ name="workCenterId"
+ value={dispatch.workCenterId ?? ""}
+ />
+ <Hidden name="eventId" value={myActiveEvent?.id ?? ""} />
+ <Hidden
+ name="action"
+ value={isWorking ? "End" : "Start"}
+ />
+ <button
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ className={`group size-24 flex flex-row items-center gap-2 justify-center rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:scale-105 transition-all text-white text-3xl border-b-4 active:border-b-0 active:translate-y-1 disabled:bg-gray-500 disabled:hover:bg-gray-600 disabled:border-gray-700 ${
+ isWorking
+ ? "bg-red-500 hover:bg-red-600 border-red-700"
+ : "bg-emerald-500 hover:bg-emerald-600 border-emerald-700"
+ }`}
+ >
+ {isWorking ? (
+ <FaPause className="group-hover:scale-110" />
+ ) : (
+ <FaPlay className="group-hover:scale-110" />
+ )}
+ </button>
+ </ValidatedForm>
- <ValidatedForm
- method="post"
- action={path.to.maintenanceEvent}
- validator={eventValidator}
- fetcher={fetcher}
- defaultValues={{
- action: "Complete",
- dispatchId: dispatch.id,
- eventId: myActiveEvent?.id
- }}
- >
- <Hidden name="dispatchId" value={dispatch.id} />
- <Hidden name="eventId" value={myActiveEvent?.id ?? ""} />
- <Hidden name="action" value="Complete" />
- <button
- type="submit"
- disabled={fetcher.state !== "idle"}
- className="group size-24 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:scale-105 transition-all text-accent-foreground text-3xl disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30"
+ <ValidatedForm
+ method="post"
+ action={path.to.maintenanceEvent}
+ validator={eventValidator}
+ fetcher={fetcher}
+ defaultValues={{
+ action: "Complete",
+ dispatchId: dispatch.id,
+ eventId: myActiveEvent?.id
+ }}
>
- <FaCheck className="group-hover:scale-110" />
- </button>
- </ValidatedForm>
- </HStack>
- </VStack>
- </div>
+ <Hidden name="dispatchId" value={dispatch.id} />
+ <Hidden name="eventId" value={myActiveEvent?.id ?? ""} />
+ <Hidden name="action" value="Complete" />
+ <button
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ className="group size-24 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:scale-105 transition-all text-accent-foreground text-3xl disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30"
+ >
+ <FaCheck className="group-hover:scale-110" />
+ </button>
+ </ValidatedForm>
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
)}
{/* Time Entries */}
{events.length > 0 && (
- <div className="w-full p-4 bg-card rounded-lg border">
- <VStack spacing={2} className="items-start">
- <span className="text-sm font-medium">Time Entries</span>
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle>Time Entries</CardTitle>
+ </CardHeader>
+ <CardContent>
<div className="w-full divide-y">
{events.map((event) => (
<div
@@ -346,7 +391,6 @@ export default function MaintenanceDetailRoute() {
employeeId={event.employeeId}
size="xs"
/>
-
<span className="text-xs text-muted-foreground">
{new Date(event.startTime).toLocaleString()}
{event.endTime &&
@@ -361,16 +405,18 @@ export default function MaintenanceDetailRoute() {
</div>
))}
</div>
- </VStack>
- </div>
+ </CardContent>
+ </Card>
)}
{/* Spare Parts */}
{!isCompleted && (
- <div className="w-full p-4 bg-card rounded-lg border">
- <VStack spacing={2} className="items-start w-full">
+ <Card className="w-full">
+ <CardHeader>
<HStack className="justify-between w-full">
- <span className="text-sm font-medium">Spare Parts</span>
+ <CardTitle className="text-sm font-medium">
+ Spare Parts
+ </CardTitle>
<Button
variant="secondary"
leftIcon={<LuCirclePlus />}
@@ -379,8 +425,8 @@ export default function MaintenanceDetailRoute() {
Add
</Button>
</HStack>
-
- {/* Existing Parts */}
+ </CardHeader>
+ <CardContent>
{items.length > 0 && (
<div className="w-full divide-y">
{items.map((item) => {
@@ -418,21 +464,24 @@ export default function MaintenanceDetailRoute() {
})}
</div>
)}
-
{items.length === 0 && (
<span className="text-xs text-muted-foreground">
No spare parts added yet
</span>
)}
- </VStack>
- </div>
+ </CardContent>
+ </Card>
)}
{/* Materials (when completed) */}
{isCompleted && items.length > 0 && (
- <div className="w-full p-4 bg-card rounded-lg border">
- <VStack spacing={2} className="items-start">
- <span className="text-sm font-medium">Spare Parts Used</span>
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle className="text-sm font-medium">
+ Spare Parts Used
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
<div className="w-full divide-y">
{items.map((item) => (
<div
@@ -446,23 +495,53 @@ export default function MaintenanceDetailRoute() {
</div>
))}
</div>
- </VStack>
- </div>
+ </CardContent>
+ </Card>
)}
+ {/* Procedure */}
+ {dispatch.procedure &&
+ (dispatch.procedure as any).content &&
+ Object.keys((dispatch.procedure as any).content as object).length >
+ 0 && (
+ <Card className="w-full">
+ <CardHeader>
+ <CardTitle className="text-sm text-muted-foreground font-normal">
+ Procedure
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <span className="text-sm font-medium mb-2 block">
+ {(dispatch.procedure as any)?.name}
+ </span>
+ <div
+ className="prose dark:prose-invert prose-sm max-w-none"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ ((dispatch.procedure as any).content ??
+ {}) as JSONContent
+ )
+ }}
+ />
+ </CardContent>
+ </Card>
+ )}
+
{/* Completed State */}
{isCompleted && (
- <div className="w-full p-4 bg-emerald-50 dark:bg-emerald-950 rounded-lg border border-emerald-200 dark:border-emerald-800">
- <VStack spacing={2}>
- <LuCheck className="h-8 w-8 text-emerald-600" />
- <span className="text-sm font-medium text-emerald-700 dark:text-emerald-400">
- Maintenance Completed
- </span>
- <span className="text-xs text-muted-foreground">
- Total time: {formatDuration(totalDuration)}
- </span>
- </VStack>
- </div>
+ <Card className="w-full bg-emerald-50 dark:bg-emerald-950 border-emerald-200 dark:border-emerald-800">
+ <CardContent className="pt-6">
+ <VStack spacing={2}>
+ <LuCheck className="h-8 w-8 text-emerald-600" />
+ <span className="text-sm font-medium text-emerald-700 dark:text-emerald-400">
+ Maintenance Completed
+ </span>
+ <span className="text-xs text-muted-foreground">
+ Total time: {formatDuration(totalDuration)}
+ </span>
+ </VStack>
+ </CardContent>
+ </Card>
)}
</VStack>
</main>
diff --git a/apps/mes/app/services/maintenance.service.ts b/apps/mes/app/services/maintenance.service.ts
index 6126725e1d..206e1329ce 100644
--- a/apps/mes/app/services/maintenance.service.ts
+++ b/apps/mes/app/services/maintenance.service.ts
@@ -62,7 +62,8 @@ export async function getMaintenanceDispatch(
assigneeUser:assignee (id, fullName, avatarUrl),
suspectedFailureMode:suspectedFailureModeId (id, name),
actualFailureMode:actualFailureModeId (id, name),
- maintenanceSchedule:maintenanceScheduleId (id, name)
+ maintenanceSchedule:maintenanceScheduleId (id, name),
+ procedure:procedureId (id, name, content)
`
)
.eq("id", dispatchId)
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 846df8ff0d..a3359db890 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13283,6 +13283,7 @@ export type Database = {
plannedEndTime: string | null
plannedStartTime: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId: string | null
severity: Database["public"]["Enums"]["maintenanceSeverity"]
source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13311,6 +13312,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
severity: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13339,6 +13341,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
severity?: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13488,6 +13491,20 @@ export type Database = {
referencedRelation: "nonConformance"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceDispatch_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_suspectedFailureModeId_fkey"
columns: ["suspectedFailureModeId"]
@@ -14601,6 +14618,7 @@ export type Database = {
name: string
nextDueAt: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId: string | null
saturday: boolean
skipHolidays: boolean
sunday: boolean
@@ -14626,6 +14644,7 @@ export type Database = {
name: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
saturday?: boolean
skipHolidays?: boolean
sunday?: boolean
@@ -14651,6 +14670,7 @@ export type Database = {
name?: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
saturday?: boolean
skipHolidays?: boolean
sunday?: boolean
@@ -14725,6 +14745,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceSchedule_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
columns: ["updatedBy"]
@@ -33046,6 +33080,48 @@ export type Database = {
},
]
}
+ searchIndex_N4Mk6kWM4ycK5Qj941axi4: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -36106,6 +36182,9 @@ export type Database = {
customFields: Json | null
id: string
itemId: string
+ lastPOId: string | null
+ lastPOQuantity: number | null
+ lastPurchaseDate: string | null
minimumOrderQuantity: number | null
supplierId: string
supplierPartId: string | null
@@ -36124,6 +36203,9 @@ export type Database = {
customFields?: Json | null
id?: string
itemId: string
+ lastPOId?: string | null
+ lastPOQuantity?: number | null
+ lastPurchaseDate?: string | null
minimumOrderQuantity?: number | null
supplierId: string
supplierPartId?: string | null
@@ -36142,6 +36224,9 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string
+ lastPOId?: string | null
+ lastPOQuantity?: number | null
+ lastPurchaseDate?: string | null
minimumOrderQuantity?: number | null
supplierId?: string
supplierPartId?: string | null
@@ -36327,6 +36412,175 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderLocations"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ supplierPartPrice: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ leadTime: number | null
+ quantity: number
+ sourceDocumentId: string | null
+ sourceType: string
+ supplierPartId: string
+ unitPrice: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ leadTime?: number | null
+ quantity?: number
+ sourceDocumentId?: string | null
+ sourceType?: string
+ supplierPartId: string
+ unitPrice: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ leadTime?: number | null
+ quantity?: number
+ sourceDocumentId?: string | null
+ sourceType?: string
+ supplierPartId?: string
+ unitPrice?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_supplierPartId_companyId_fkey"
+ columns: ["supplierPartId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "supplierPart"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
supplierPayment: {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 846df8ff0d..a3359db890 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -13283,6 +13283,7 @@ export type Database = {
plannedEndTime: string | null
plannedStartTime: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId: string | null
severity: Database["public"]["Enums"]["maintenanceSeverity"]
source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13311,6 +13312,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
severity: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13339,6 +13341,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
severity?: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
@@ -13488,6 +13491,20 @@ export type Database = {
referencedRelation: "nonConformance"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceDispatch_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_suspectedFailureModeId_fkey"
columns: ["suspectedFailureModeId"]
@@ -14601,6 +14618,7 @@ export type Database = {
name: string
nextDueAt: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId: string | null
saturday: boolean
skipHolidays: boolean
sunday: boolean
@@ -14626,6 +14644,7 @@ export type Database = {
name: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
saturday?: boolean
skipHolidays?: boolean
sunday?: boolean
@@ -14651,6 +14670,7 @@ export type Database = {
name?: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ procedureId?: string | null
saturday?: boolean
skipHolidays?: boolean
sunday?: boolean
@@ -14725,6 +14745,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceSchedule_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
columns: ["updatedBy"]
@@ -33046,6 +33080,48 @@ export type Database = {
},
]
}
+ searchIndex_N4Mk6kWM4ycK5Qj941axi4: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -36106,6 +36182,9 @@ export type Database = {
customFields: Json | null
id: string
itemId: string
+ lastPOId: string | null
+ lastPOQuantity: number | null
+ lastPurchaseDate: string | null
minimumOrderQuantity: number | null
supplierId: string
supplierPartId: string | null
@@ -36124,6 +36203,9 @@ export type Database = {
customFields?: Json | null
id?: string
itemId: string
+ lastPOId?: string | null
+ lastPOQuantity?: number | null
+ lastPurchaseDate?: string | null
minimumOrderQuantity?: number | null
supplierId: string
supplierPartId?: string | null
@@ -36142,6 +36224,9 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string
+ lastPOId?: string | null
+ lastPOQuantity?: number | null
+ lastPurchaseDate?: string | null
minimumOrderQuantity?: number | null
supplierId?: string
supplierPartId?: string | null
@@ -36327,6 +36412,175 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrder"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderLocations"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPart_lastPOId_fkey"
+ columns: ["lastPOId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ supplierPartPrice: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ leadTime: number | null
+ quantity: number
+ sourceDocumentId: string | null
+ sourceType: string
+ supplierPartId: string
+ unitPrice: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ leadTime?: number | null
+ quantity?: number
+ sourceDocumentId?: string | null
+ sourceType?: string
+ supplierPartId: string
+ unitPrice: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ leadTime?: number | null
+ quantity?: number
+ sourceDocumentId?: string | null
+ sourceType?: string
+ supplierPartId?: string
+ unitPrice?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_supplierPartId_companyId_fkey"
+ columns: ["supplierPartId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "supplierPart"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierPartPrice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
supplierPayment: {
diff --git a/packages/database/supabase/migrations/20260220225128_maintenance-dispatch-procedure.sql b/packages/database/supabase/migrations/20260220225128_maintenance-dispatch-procedure.sql
new file mode 100644
index 0000000000..8dc409293b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260220225128_maintenance-dispatch-procedure.sql
@@ -0,0 +1,51 @@
+ALTER TABLE "maintenanceSchedule"
+ADD COLUMN IF NOT EXISTS "locationId" TEXT NOT NULL;
+
+UPDATE "maintenanceSchedule"
+SET "locationId" = (
+ SELECT "locationId" FROM "workCenter" WHERE "id" = "maintenanceSchedule"."workCenterId"
+) WHERE "locationId" IS NULL AND "workCenterId" IS NOT NULL;
+
+UPDATE "maintenanceDispatch"
+SET "locationId" = (
+ SELECT "locationId" FROM "workCenter" WHERE "id" = "maintenanceDispatch"."workCenterId"
+) WHERE "locationId" IS NULL AND "workCenterId" IS NOT NULL;
+
+DELETE FROM "maintenanceSchedule" WHERE "locationId" IS NULL;
+DELETE FROM "maintenanceDispatch" WHERE "locationId" IS NULL;
+
+ALTER TABLE "maintenanceSchedule"
+ADD CONSTRAINT "maintenanceSchedule_locationId_fkey"
+FOREIGN KEY ("locationId") REFERENCES "location"("id")
+ON DELETE CASCADE ON UPDATE CASCADE;
+
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_locationId_idx" ON "maintenanceSchedule" ("locationId");
+
+ALTER TABLE "maintenanceSchedule"
+ADD COLUMN IF NOT EXISTS "procedureId" TEXT;
+
+ALTER TABLE "maintenanceSchedule"
+ADD CONSTRAINT "maintenanceSchedule_procedureId_fkey"
+FOREIGN KEY ("procedureId") REFERENCES "procedure"("id")
+ON DELETE SET NULL ON UPDATE CASCADE;
+
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_procedureId_idx" ON "maintenanceSchedule" ("procedureId");
+
+ALTER TABLE "maintenanceDispatch"
+ADD COLUMN IF NOT EXISTS "procedureId" TEXT;
+
+ALTER TABLE "maintenanceDispatch"
+ADD CONSTRAINT "maintenanceDispatch_procedureId_fkey"
+FOREIGN KEY ("procedureId") REFERENCES "procedure"("id")
+ON DELETE SET NULL ON UPDATE CASCADE;
+
+ALTER TABLE "maintenanceSchedule"
+ADD COLUMN IF NOT EXISTS "locationId" TEXT;
+
+ALTER TABLE "maintenanceSchedule"
+ADD CONSTRAINT "maintenanceSchedule_locationId_fkey"
+FOREIGN KEY ("locationId") REFERENCES "location"("id")
+ON DELETE SET NULL ON UPDATE CASCADE;
+
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_locationId_idx" ON "maintenanceSchedule" ("locationId");
+
diff --git a/packages/jobs/trigger/dispatch.ts b/packages/jobs/trigger/dispatch.ts
index 284f5f29ed..161e6c4533 100644
--- a/packages/jobs/trigger/dispatch.ts
+++ b/packages/jobs/trigger/dispatch.ts
@@ -32,6 +32,7 @@ interface MaintenanceSchedule {
friday: boolean;
saturday: boolean;
sunday: boolean;
+ procedureId: string | null;
}
// Check if a date is enabled for the schedule based on day-of-week settings
@@ -205,6 +206,7 @@ export const generateMaintenanceDispatches = schedules.task({
oeeImpact: "Planned",
workCenterId: schedule.workCenterId,
maintenanceScheduleId: schedule.id,
+ procedureId: schedule.procedureId,
plannedStartTime: targetDate.toISOString(),
companyId: settings.id,
createdBy: "system"