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 different notification groups for different types of dispatches

Brad Barbin386a57bad069
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index a44da2402b..c4da22dbe0 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -32,7 +32,8 @@ import {
LuMessageSquare,
LuShieldAlert,
LuShieldX,
- LuShoppingCart
+ LuShoppingCart,
+ LuWrench
} from "react-icons/lu";
import {
RiProgress2Line,
@@ -229,6 +230,15 @@ function GenericNotification({
{...props}
/>
);
+ case NotificationEvent.MaintenanceDispatchCreated:
+ case NotificationEvent.MaintenanceDispatchAssignment:
+ return (
+ <Notification
+ icon={<LuWrench />}
+ to={path.to.maintenanceDispatch(id)}
+ {...props}
+ />
+ );
case NotificationEvent.NonConformanceAssignment:
return (
<Notification icon={<LuShieldX />} to={path.to.issue(id)} {...props} />
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 41644b3dee..2f1d94c579 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -82,7 +82,7 @@ export const maintenanceFrequency = [
export const maintenanceSeverity = [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required"
] as const;
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index 9e40f6d078..cd600a41a9 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -54,9 +54,17 @@ export const employeeAbilityValidator = z.object({
trainingDays: zfd.numeric(z.number().optional())
});
+export const maintenanceFailureModeType = [
+ "Maintenance",
+ "Quality",
+ "Operations",
+ "Other"
+] as const;
+
export const failureModeValidator = z.object({
id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" })
+ name: z.string().min(1, { message: "Name is required" }),
+ type: z.enum(maintenanceFailureModeType)
});
export const locationValidator = z
@@ -157,7 +165,7 @@ export const maintenanceDispatchValidator = z.object({
.enum([
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required"
] as const)
.optional(),
@@ -223,7 +231,7 @@ export const maintenanceScheduleValidator = z.object({
export const maintenanceSeverity = [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required"
] as const;
diff --git a/apps/erp/app/modules/resources/ui/FailureModes/FailureModeForm.tsx b/apps/erp/app/modules/resources/ui/FailureModes/FailureModeForm.tsx
index 47d57b608e..fd9f238a59 100644
--- a/apps/erp/app/modules/resources/ui/FailureModes/FailureModeForm.tsx
+++ b/apps/erp/app/modules/resources/ui/FailureModes/FailureModeForm.tsx
@@ -16,10 +16,20 @@ import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect } from "react";
import { useFetcher } from "react-router";
import type { z } from "zod/v3";
-import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
+import { Enumerable } from "~/components/Enumerable";
+import {
+ CustomFormFields,
+ Hidden,
+ Input,
+ Select,
+ Submit
+} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import { failureModeValidator } from "../../resources.models";
+import {
+ failureModeValidator,
+ maintenanceFailureModeType
+} from "../../resources.models";
type FailureModeFormProps = {
initialValues: z.infer<typeof failureModeValidator>;
@@ -83,9 +93,17 @@ const FailureModeForm = ({
</ModalDrawerHeader>
<ModalDrawerBody>
<Hidden name="id" />
- <Hidden name="type" value={type} />
+ <Hidden name="formType" value={type} />
<VStack spacing={4}>
<Input name="name" label="Failure Mode" />
+ <Select
+ name="type"
+ label="Type"
+ options={maintenanceFailureModeType.map((t) => ({
+ value: t,
+ label: <Enumerable value={t} />
+ }))}
+ />
<CustomFormFields table="maintenanceFailureMode" />
</VStack>
</ModalDrawerBody>
diff --git a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
index d7918141a5..15a0efdd09 100644
--- a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
@@ -1,13 +1,13 @@
import { MenuIcon, MenuItem } from "@carbon/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
-import { LuPencil, LuTrash } from "react-icons/lu";
+import { LuCircleAlert, LuPencil, LuShapes, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
-import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
+import { maintenanceFailureModeType } from "../../resources.models";
import type { FailureMode } from "../../types";
type FailureModesTableProps = {
@@ -29,7 +29,25 @@ const FailureModesTable = memo(({ data, count }: FailureModesTableProps) => {
<Hyperlink to={row.original.id}>
<Enumerable value={row.original.name} />
</Hyperlink>
- )
+ ),
+ meta: {
+ icon: <LuCircleAlert />
+ }
+ },
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) => <Enumerable value={row.original.type} />,
+ meta: {
+ icon: <LuShapes />,
+ filter: {
+ type: "static",
+ options: maintenanceFailureModeType.map((type) => ({
+ label: <Enumerable value={type} />,
+ value: type
+ }))
+ }
+ }
}
];
return [...defaultColumns];
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceSeverity.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceSeverity.tsx
index 7fb9e4aeaf..949e178cfa 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceSeverity.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceSeverity.tsx
@@ -37,7 +37,7 @@ function MaintenanceSeverity({
{severity}
</Badge>
);
- case "Maintenance Required":
+ case "Support Required":
return (
<Badge
variant="yellow"
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index b6e23b61c7..5b446b0d02 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -130,6 +130,21 @@ export const suggestionNotificationValidator = z.object({
.optional()
});
+export const maintenanceDispatchNotificationValidator = z.object({
+ maintenanceDispatchNotificationGroup: z
+ .array(z.string().min(1, { message: "Invalid selection" }))
+ .optional(),
+ qualityDispatchNotificationGroup: z
+ .array(z.string().min(1, { message: "Invalid selection" }))
+ .optional(),
+ operationsDispatchNotificationGroup: z
+ .array(z.string().min(1, { message: "Invalid selection" }))
+ .optional(),
+ otherDispatchNotificationGroup: z
+ .array(z.string().min(1, { message: "Invalid selection" }))
+ .optional()
+});
+
export const supplierQuoteNotificationValidator = z.object({
supplierQuoteNotificationGroup: z
.array(z.string().min(1, { message: "Invalid selection" }))
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index fc89b70d11..03fb67c9b1 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -588,6 +588,22 @@ export async function updateSuggestionNotificationSetting(
.eq("id", companyId);
}
+export async function updateMaintenanceDispatchNotificationSettings(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ settings: {
+ maintenanceDispatchNotificationGroup?: string[];
+ qualityDispatchNotificationGroup?: string[];
+ operationsDispatchNotificationGroup?: string[];
+ otherDispatchNotificationGroup?: string[];
+ }
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize(settings))
+ .eq("id", companyId);
+}
+
export async function updateSupplierQuoteNotificationSetting(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/novu/workflows.ts b/apps/erp/app/novu/workflows.ts
index d184085358..6cac2bcae1 100644
--- a/apps/erp/app/novu/workflows.ts
+++ b/apps/erp/app/novu/workflows.ts
@@ -16,6 +16,8 @@ const payloadSchema = z.object({
NotificationEvent.JobCompleted,
NotificationEvent.JobOperationAssignment,
NotificationEvent.JobOperationMessage,
+ NotificationEvent.MaintenanceDispatchCreated,
+ NotificationEvent.MaintenanceDispatchAssignment,
NotificationEvent.NonConformanceAssignment,
NotificationEvent.ProcedureAssignment,
NotificationEvent.PurchaseInvoiceAssignment,
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index 24667d12a8..1ad04e591c 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -13,8 +13,9 @@ import { useFlags } from "~/hooks/useFlags";
import type { Authenticated, NavItem } from "~/types";
export default function AppIndexRoute() {
- const { isCommunity, isInternal } = useFlags();
- const hasChatPrototype = isInternal || isCommunity;
+ const { isCommunity, isControlledEnvironment, isInternal } = useFlags();
+ const hasChatPrototype =
+ (isInternal && !isControlledEnvironment) || isCommunity;
return hasChatPrototype ? <ChatPage /> : <AppsPage />;
}
diff --git a/apps/erp/app/routes/x+/maintenance+/new.tsx b/apps/erp/app/routes/x+/maintenance+/new.tsx
index 9c2221e6e6..4915e6183a 100644
--- a/apps/erp/app/routes/x+/maintenance+/new.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/new.tsx
@@ -4,7 +4,6 @@ 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,
@@ -71,7 +70,7 @@ export async function action({ request }: ActionFunctionArgs) {
maintenanceDispatchId: nextSequence.data,
status: validation.data.status,
priority: validation.data.priority,
- severity: validation.data.severity || "Maintenance Required",
+ severity: validation.data.severity || "Support Required",
source: validation.data.source || "Reactive",
oeeImpact: validation.data.oeeImpact || "No Impact",
workCenterId: validation.data.workCenterId || undefined,
@@ -115,7 +114,7 @@ export default function NewMaintenanceDispatchRoute() {
status: "Open" as const,
priority: "Medium" as const,
source: "Reactive" as const,
- severity: "Maintenance Required" as const,
+ severity: "Support Required" as const,
oeeImpact: "No Impact" as const
};
diff --git a/apps/erp/app/routes/x+/resources+/failure-modes.$failureModeId.tsx b/apps/erp/app/routes/x+/resources+/failure-modes.$failureModeId.tsx
index f2f63b0c5f..c406a34445 100644
--- a/apps/erp/app/routes/x+/resources+/failure-modes.$failureModeId.tsx
+++ b/apps/erp/app/routes/x+/resources+/failure-modes.$failureModeId.tsx
@@ -10,7 +10,6 @@ import {
upsertFailureMode
} from "~/modules/resources";
import FailureModeForm from "~/modules/resources/ui/FailureModes/FailureModeForm";
-import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -83,7 +82,8 @@ export default function EditFailureModeRoute() {
const initialValues = {
id: failureMode.id ?? undefined,
- name: failureMode.name ?? ""
+ name: failureMode.name ?? "",
+ type: failureMode.type ?? "Maintenance"
};
return (
diff --git a/apps/erp/app/routes/x+/resources+/failure-modes.new.tsx b/apps/erp/app/routes/x+/resources+/failure-modes.new.tsx
index ce3e64fe3d..9d590fd1b1 100644
--- a/apps/erp/app/routes/x+/resources+/failure-modes.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/failure-modes.new.tsx
@@ -23,7 +23,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const modal = formData.get("type") === "modal";
+ const modal = formData.get("formType") === "modal";
const validation = await validator(failureModeValidator).validate(formData);
@@ -63,7 +63,8 @@ export async function action({ request }: ActionFunctionArgs) {
export default function NewFailureModeRoute() {
const navigate = useNavigate();
const initialValues = {
- name: ""
+ name: "",
+ type: "Maintenance" as const
};
return (
diff --git a/apps/erp/app/routes/x+/settings+/resources.tsx b/apps/erp/app/routes/x+/settings+/resources.tsx
index 63f719bc23..d9ab98939e 100644
--- a/apps/erp/app/routes/x+/settings+/resources.tsx
+++ b/apps/erp/app/routes/x+/settings+/resources.tsx
@@ -28,8 +28,10 @@ import { Users } from "~/components/Form";
import {
getCompany,
getCompanySettings,
+ maintenanceDispatchNotificationValidator,
maintenanceSettingsValidator,
suggestionNotificationValidator,
+ updateMaintenanceDispatchNotificationSettings,
updateSuggestionNotificationSetting
} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
@@ -122,6 +124,38 @@ export async function action({ request }: ActionFunctionArgs) {
};
}
+ if (intent === "maintenanceDispatchNotifications") {
+ const validation = await validator(
+ maintenanceDispatchNotificationValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const update = await updateMaintenanceDispatchNotificationSettings(
+ client,
+ companyId,
+ {
+ maintenanceDispatchNotificationGroup:
+ validation.data.maintenanceDispatchNotificationGroup ?? [],
+ qualityDispatchNotificationGroup:
+ validation.data.qualityDispatchNotificationGroup ?? [],
+ operationsDispatchNotificationGroup:
+ validation.data.operationsDispatchNotificationGroup ?? [],
+ otherDispatchNotificationGroup:
+ validation.data.otherDispatchNotificationGroup ?? []
+ }
+ );
+
+ if (update.error) return { success: false, message: update.error.message };
+
+ return {
+ success: true,
+ message: "Maintenance dispatch notification settings updated"
+ };
+ }
+
return null;
}
@@ -152,29 +186,64 @@ export default function ResourcesSettingsRoute() {
<Card>
<ValidatedForm
method="post"
- validator={suggestionNotificationValidator}
+ validator={maintenanceDispatchNotificationValidator}
defaultValues={{
- suggestionNotificationGroup:
- company.suggestionNotificationGroup ?? []
+ maintenanceDispatchNotificationGroup:
+ (companySettings as any).maintenanceDispatchNotificationGroup ??
+ [],
+ qualityDispatchNotificationGroup:
+ (companySettings as any).qualityDispatchNotificationGroup ?? [],
+ operationsDispatchNotificationGroup:
+ (companySettings as any).operationsDispatchNotificationGroup ??
+ [],
+ otherDispatchNotificationGroup:
+ (companySettings as any).otherDispatchNotificationGroup ?? []
}}
fetcher={fetcher}
>
- <input type="hidden" name="intent" value="suggestions" />
+ <input
+ type="hidden"
+ name="intent"
+ value="maintenanceDispatchNotifications"
+ />
<CardHeader>
<CardTitle className="flex items-center gap-2">
- Suggestion Notifications
+ Maintenance Dispatch Notifications
</CardTitle>
<CardDescription>
- Configure notifications for when new suggestions are submitted.
+ Configure notifications for when maintenance dispatches are
+ created from the shop floor. Notifications are routed based on
+ the failure mode type.
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-8 max-w-[400px]">
<div className="flex flex-col gap-2">
- <Label>Suggestion Notifications</Label>
+ <Label>Maintenance Type</Label>
<Users
- name="suggestionNotificationGroup"
- label="Who should receive notifications when a new suggestion is submitted?"
+ name="maintenanceDispatchNotificationGroup"
+ label="Who should receive notifications for maintenance-related dispatches?"
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>Quality Type</Label>
+ <Users
+ name="qualityDispatchNotificationGroup"
+ label="Who should receive notifications for quality-related dispatches?"
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>Operations Type</Label>
+ <Users
+ name="operationsDispatchNotificationGroup"
+ label="Who should receive notifications for operations-related dispatches?"
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>Other Type</Label>
+ <Users
+ name="otherDispatchNotificationGroup"
+ label="Who should receive notifications for other dispatches?"
/>
</div>
</div>
@@ -184,7 +253,8 @@ export default function ResourcesSettingsRoute() {
isDisabled={fetcher.state !== "idle"}
isLoading={
fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "suggestions"
+ fetcher.formData?.get("intent") ===
+ "maintenanceDispatchNotifications"
}
>
Save
@@ -250,6 +320,49 @@ export default function ResourcesSettingsRoute() {
</CardFooter>
</ValidatedForm>
</Card>
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={suggestionNotificationValidator}
+ defaultValues={{
+ suggestionNotificationGroup:
+ company.suggestionNotificationGroup ?? []
+ }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="suggestions" />
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Suggestion Notifications
+ </CardTitle>
+ <CardDescription>
+ Configure notifications for when new suggestions are submitted.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-8 max-w-[400px]">
+ <div className="flex flex-col gap-2">
+ <Label>Suggestion Notifications</Label>
+ <Users
+ name="suggestionNotificationGroup"
+ label="Who should receive notifications when a new suggestion is submitted?"
+ />
+ </div>
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "suggestions"
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
</VStack>
</ScrollArea>
);
diff --git a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
index 950a9ca49a..095b97d5c4 100644
--- a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
+++ b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
@@ -15,7 +15,6 @@ import {
Modal,
ModalBody,
ModalContent,
- ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -66,8 +65,8 @@ function getSeverityLabel(severity: (typeof maintenanceSeverity)[number]) {
return "Preventive";
case "Operator Performed":
return "Operator Performed";
- case "Maintenance Required":
- return "Maintenance Required";
+ case "Support Required":
+ return "Support Required";
case "OEM Required":
return "OEM Required";
}
@@ -97,10 +96,6 @@ export function MaintenanceDispatch({
useState<(typeof maintenanceSeverity)[number]>("Operator Performed");
const [oeeImpactValue, setOeeImpactValue] =
useState<(typeof oeeImpact)[number]>("No Impact");
- const [actualStartTime, setActualStartTime] = useState<string>(
- new Date().toISOString()
- );
- const [actualEndTime, setActualEndTime] = useState<string>("");
const failureModes = failureModeFetcher.data?.data ?? [];
@@ -113,8 +108,6 @@ export function MaintenanceDispatch({
setContent({});
setSeverity("Operator Performed");
setOeeImpactValue("No Impact");
- setActualStartTime(new Date().toISOString());
- setActualEndTime("");
disclosure.onClose();
};
@@ -177,7 +170,9 @@ export function MaintenanceDispatch({
priority: "Medium",
severity: "Operator Performed",
oeeImpact: "No Impact",
- suspectedFailureModeId: undefined
+ suspectedFailureModeId: undefined,
+ actualStartTime: new Date().toISOString(),
+ actualEndTime: undefined
}}
fetcher={fetcher}
>
@@ -233,17 +228,8 @@ export function MaintenanceDispatch({
<DateTimePicker
name="actualStartTime"
label="Start Time"
- onChange={(value) => {
- if (value) setActualStartTime(value.toString());
- }}
- />
- <DateTimePicker
- name="actualEndTime"
- label="End Time"
- onChange={(value) => {
- if (value) setActualEndTime(value.toString());
- }}
/>
+ <DateTimePicker name="actualEndTime" label="End Time" />
</>
)}
<Select
diff --git a/apps/mes/app/components/MaintenanceSeverity.tsx b/apps/mes/app/components/MaintenanceSeverity.tsx
index 453fd232e6..a4be1121c1 100644
--- a/apps/mes/app/components/MaintenanceSeverity.tsx
+++ b/apps/mes/app/components/MaintenanceSeverity.tsx
@@ -37,7 +37,7 @@ function MaintenanceSeverity({
{severity}
</Badge>
);
- case "Maintenance Required":
+ case "Support Required":
return (
<Badge
variant="yellow"
diff --git a/apps/mes/app/routes/x+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsx
index 7acdad582b..fe24ff6ed6 100644
--- a/apps/mes/app/routes/x+/dispatch.new.tsx
+++ b/apps/mes/app/routes/x+/dispatch.new.tsx
@@ -7,7 +7,10 @@ import {
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import type { notifyTask } from "@carbon/jobs/trigger/notify";
+import { NotificationEvent } from "@carbon/notifications";
import { getLocalTimeZone, now } from "@internationalized/date";
+import { tasks } from "@trigger.dev/sdk";
import { type ActionFunctionArgs, data, redirect } from "react-router";
import { maintenanceDispatchValidator } from "~/services/models";
import { endProductionEventsByWorkCenter } from "~/services/operations.service";
@@ -103,6 +106,79 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
+ // Send notification based on failure mode type
+ if (insertDispatch.data?.id) {
+ try {
+ // Get company settings
+ const companySettings = await serviceRole
+ .from("companySettings")
+ .select(
+ "maintenanceDispatchNotificationGroup, qualityDispatchNotificationGroup, operationsDispatchNotificationGroup, otherDispatchNotificationGroup"
+ )
+ .eq("id", companyId)
+ .single();
+
+ if (!companySettings.error && companySettings.data) {
+ let notificationGroup: string[] = [];
+
+ // If there's a suspected failure mode, look up its type
+ if (validation.data.suspectedFailureModeId) {
+ const failureMode = await serviceRole
+ .from("maintenanceFailureMode")
+ .select("type")
+ .eq("id", validation.data.suspectedFailureModeId)
+ .single();
+
+ if (!failureMode.error && failureMode.data?.type) {
+ // Route to the appropriate notification group based on type
+ switch (failureMode.data.type) {
+ case "Maintenance":
+ notificationGroup =
+ companySettings.data.maintenanceDispatchNotificationGroup ??
+ [];
+ break;
+ case "Quality":
+ notificationGroup =
+ companySettings.data.qualityDispatchNotificationGroup ?? [];
+ break;
+ case "Operations":
+ notificationGroup =
+ companySettings.data.operationsDispatchNotificationGroup ??
+ [];
+ break;
+ case "Other":
+ notificationGroup =
+ companySettings.data.otherDispatchNotificationGroup ?? [];
+ break;
+ }
+ }
+ }
+
+ // Default to maintenance group if no failure mode or no notification group found
+ if (notificationGroup.length === 0) {
+ notificationGroup =
+ companySettings.data.maintenanceDispatchNotificationGroup ?? [];
+ }
+
+ // Send notification if there's a notification group configured
+ if (notificationGroup.length > 0) {
+ await tasks.trigger<typeof notifyTask>("notify", {
+ companyId,
+ documentId: insertDispatch.data.id,
+ event: NotificationEvent.MaintenanceDispatchCreated,
+ recipient: {
+ type: "group",
+ groupIds: notificationGroup
+ },
+ from: userId
+ });
+ }
+ }
+ } catch (err) {
+ console.error("Failed to trigger maintenance dispatch notification", err);
+ }
+ }
+
if (insertDispatch.data?.id && isOperatorPerformed) {
throw redirect(path.to.maintenanceDetail(insertDispatch.data.id));
}
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index a03548c325..954608a994 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -51,7 +51,7 @@ export const maintenanceDispatchPriority = [
export const maintenanceSeverity = [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required"
] as const;
diff --git a/biome.jsonc b/biome.jsonc
index cc41a520f0..99f5afa03e 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -93,9 +93,6 @@
"noUnsafeNegation": "warn",
"useGetterReturn": "warn",
"useIterableCallbackReturn": "warn"
- },
- "nursery": {
- "noShadow": "warn"
}
}
},
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 84bdfd6d9c..d1f421a94f 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -75171,7 +75171,7 @@ export default {
enum: [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required",
],
format: 'public."maintenanceSeverity"',
@@ -81034,7 +81034,7 @@ export default {
enum: [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required",
],
format: 'public."maintenanceSeverity"',
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 21ae439e07..16cdf50a90 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2258,10 +2258,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup: string[]
kanbanOutput: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays: number
+ maintenanceDispatchNotificationGroup: string[] | null
maintenanceGenerateInAdvance: boolean
materialGeneratedIds: boolean
+ operationsDispatchNotificationGroup: string[] | null
+ otherDispatchNotificationGroup: string[] | null
productLabelSize: string | null
purchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup: string[] | null
rfqReadyNotificationGroup: string[]
salesJobCompletedNotificationGroup: string[]
shelfLabelSize: string | null
@@ -2277,10 +2281,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup?: string[]
kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays?: number
+ maintenanceDispatchNotificationGroup?: string[] | null
maintenanceGenerateInAdvance?: boolean
materialGeneratedIds?: boolean
+ operationsDispatchNotificationGroup?: string[] | null
+ otherDispatchNotificationGroup?: string[] | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup?: string[] | null
rfqReadyNotificationGroup?: string[]
salesJobCompletedNotificationGroup?: string[]
shelfLabelSize?: string | null
@@ -2296,10 +2304,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup?: string[]
kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays?: number
+ maintenanceDispatchNotificationGroup?: string[] | null
maintenanceGenerateInAdvance?: boolean
materialGeneratedIds?: boolean
+ operationsDispatchNotificationGroup?: string[] | null
+ otherDispatchNotificationGroup?: string[] | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup?: string[] | null
rfqReadyNotificationGroup?: string[]
salesJobCompletedNotificationGroup?: string[]
shelfLabelSize?: string | null
@@ -12470,7 +12482,7 @@ export type Database = {
plannedEndTime: string | null
plannedStartTime: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity: Database["public"]["Enums"]["maintenanceSeverity"]
source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
@@ -12497,7 +12509,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
@@ -12524,7 +12536,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity?: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
@@ -13461,6 +13473,7 @@ export type Database = {
createdBy: string
id: string
name: string
+ type: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt: string | null
updatedBy: string | null
}
@@ -13470,6 +13483,7 @@ export type Database = {
createdBy: string
id?: string
name: string
+ type?: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -13479,6 +13493,7 @@ export type Database = {
createdBy?: string
id?: string
name?: string
+ type?: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -45101,14 +45116,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -46481,14 +46496,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49008,14 +49023,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49551,14 +49566,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -54030,6 +54045,12 @@ export type Database = {
| "In Progress"
| "Completed"
| "Cancelled"
+ maintenanceFailureModeType:
+ | "Maintenance"
+ | "Quality"
+ | "Safety"
+ | "Operations"
+ | "Other"
maintenanceFrequency:
| "Daily"
| "Weekly"
@@ -54039,7 +54060,7 @@ export type Database = {
maintenanceSeverity:
| "Preventive"
| "Operator Performed"
- | "Maintenance Required"
+ | "Support Required"
| "OEM Required"
maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
makeMethodStatus: "Draft" | "Active" | "Archived"
@@ -55172,6 +55193,13 @@ export const Constants = {
"Completed",
"Cancelled",
],
+ maintenanceFailureModeType: [
+ "Maintenance",
+ "Quality",
+ "Safety",
+ "Operations",
+ "Other",
+ ],
maintenanceFrequency: [
"Daily",
"Weekly",
@@ -55182,7 +55210,7 @@ export const Constants = {
maintenanceSeverity: [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required",
],
maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 21ae439e07..16cdf50a90 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2258,10 +2258,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup: string[]
kanbanOutput: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays: number
+ maintenanceDispatchNotificationGroup: string[] | null
maintenanceGenerateInAdvance: boolean
materialGeneratedIds: boolean
+ operationsDispatchNotificationGroup: string[] | null
+ otherDispatchNotificationGroup: string[] | null
productLabelSize: string | null
purchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup: string[] | null
rfqReadyNotificationGroup: string[]
salesJobCompletedNotificationGroup: string[]
shelfLabelSize: string | null
@@ -2277,10 +2281,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup?: string[]
kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays?: number
+ maintenanceDispatchNotificationGroup?: string[] | null
maintenanceGenerateInAdvance?: boolean
materialGeneratedIds?: boolean
+ operationsDispatchNotificationGroup?: string[] | null
+ otherDispatchNotificationGroup?: string[] | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup?: string[] | null
rfqReadyNotificationGroup?: string[]
salesJobCompletedNotificationGroup?: string[]
shelfLabelSize?: string | null
@@ -2296,10 +2304,14 @@ export type Database = {
inventoryJobCompletedNotificationGroup?: string[]
kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]
maintenanceAdvanceDays?: number
+ maintenanceDispatchNotificationGroup?: string[] | null
maintenanceGenerateInAdvance?: boolean
materialGeneratedIds?: boolean
+ operationsDispatchNotificationGroup?: string[] | null
+ otherDispatchNotificationGroup?: string[] | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
+ qualityDispatchNotificationGroup?: string[] | null
rfqReadyNotificationGroup?: string[]
salesJobCompletedNotificationGroup?: string[]
shelfLabelSize?: string | null
@@ -12470,7 +12482,7 @@ export type Database = {
plannedEndTime: string | null
plannedStartTime: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity: Database["public"]["Enums"]["maintenanceSeverity"]
source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
@@ -12497,7 +12509,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
@@ -12524,7 +12536,7 @@ export type Database = {
plannedEndTime?: string | null
plannedStartTime?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
- severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ severity?: Database["public"]["Enums"]["maintenanceSeverity"]
source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
@@ -13461,6 +13473,7 @@ export type Database = {
createdBy: string
id: string
name: string
+ type: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt: string | null
updatedBy: string | null
}
@@ -13470,6 +13483,7 @@ export type Database = {
createdBy: string
id?: string
name: string
+ type?: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -13479,6 +13493,7 @@ export type Database = {
createdBy?: string
id?: string
name?: string
+ type?: Database["public"]["Enums"]["maintenanceFailureModeType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -45101,14 +45116,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -46481,14 +46496,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49008,14 +49023,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49551,14 +49566,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -54030,6 +54045,12 @@ export type Database = {
| "In Progress"
| "Completed"
| "Cancelled"
+ maintenanceFailureModeType:
+ | "Maintenance"
+ | "Quality"
+ | "Safety"
+ | "Operations"
+ | "Other"
maintenanceFrequency:
| "Daily"
| "Weekly"
@@ -54039,7 +54060,7 @@ export type Database = {
maintenanceSeverity:
| "Preventive"
| "Operator Performed"
- | "Maintenance Required"
+ | "Support Required"
| "OEM Required"
maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
makeMethodStatus: "Draft" | "Active" | "Archived"
@@ -55172,6 +55193,13 @@ export const Constants = {
"Completed",
"Cancelled",
],
+ maintenanceFailureModeType: [
+ "Maintenance",
+ "Quality",
+ "Safety",
+ "Operations",
+ "Other",
+ ],
maintenanceFrequency: [
"Daily",
"Weekly",
@@ -55182,7 +55210,7 @@ export const Constants = {
maintenanceSeverity: [
"Preventive",
"Operator Performed",
- "Maintenance Required",
+ "Support Required",
"OEM Required",
],
maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],
diff --git a/packages/database/supabase/migrations/20251230202851_failure-mode-type.sql b/packages/database/supabase/migrations/20251230202851_failure-mode-type.sql
new file mode 100644
index 0000000000..d943ca7c07
--- /dev/null
+++ b/packages/database/supabase/migrations/20251230202851_failure-mode-type.sql
@@ -0,0 +1,174 @@
+DROP VIEW IF EXISTS "activeMaintenanceDispatchesByLocation";
+DROP FUNCTION IF EXISTS get_maintenance_dispatches_by_location;
+
+-- Add temporary text column to store current values
+ALTER TABLE "maintenanceDispatch" ADD COLUMN "severity_temp" TEXT;
+
+-- Copy existing values to temporary column
+UPDATE "maintenanceDispatch" SET "severity_temp" = "severity"::TEXT;
+
+-- Drop the severity column (this will also drop the enum if no other columns use it)
+ALTER TABLE "maintenanceDispatch" DROP COLUMN "severity";
+
+DROP TYPE IF EXISTS "maintenanceSeverity";
+
+-- Recreate the enum with the new values
+CREATE TYPE "maintenanceSeverity" AS ENUM (
+ 'Preventive',
+ 'Operator Performed',
+ 'Support Required',
+ 'OEM Required'
+);
+
+-- Add the severity column back with the new enum type
+ALTER TABLE "maintenanceDispatch" ADD COLUMN "severity" "maintenanceSeverity";
+
+-- Update the new column, mapping old values to new ones
+UPDATE "maintenanceDispatch" SET "severity" =
+ CASE
+ WHEN "severity_temp" = 'Maintenance Required' THEN 'Support Required'
+ ELSE "severity_temp"::"maintenanceSeverity"
+ END;
+
+-- Make the column NOT NULL if it was before
+ALTER TABLE "maintenanceDispatch" ALTER COLUMN "severity" SET NOT NULL;
+
+-- Drop the temporary column
+ALTER TABLE "maintenanceDispatch" DROP COLUMN "severity_temp";
+
+
+CREATE TYPE "maintenanceFailureModeType" AS ENUM (
+ 'Maintenance',
+ 'Quality',
+ 'Operations',
+ 'Other'
+);
+
+ALTER TABLE "maintenanceFailureMode" ADD COLUMN "type" "maintenanceFailureModeType" NOT NULL DEFAULT 'Maintenance';
+
+-- Add notification group columns for maintenance dispatch failure mode types
+ALTER TABLE "companySettings"
+ADD COLUMN IF NOT EXISTS "maintenanceDispatchNotificationGroup" text[] DEFAULT '{}',
+ADD COLUMN IF NOT EXISTS "qualityDispatchNotificationGroup" text[] DEFAULT '{}',
+ADD COLUMN IF NOT EXISTS "operationsDispatchNotificationGroup" text[] DEFAULT '{}',
+ADD COLUMN IF NOT EXISTS "otherDispatchNotificationGroup" text[] DEFAULT '{}';
+
+-- View for active maintenance dispatches by location (for MES dashboard)
+DROP VIEW IF EXISTS "activeMaintenanceDispatchesByLocation";
+CREATE OR REPLACE VIEW "activeMaintenanceDispatchesByLocation" WITH (security_invoker = true) AS
+SELECT
+ md.id,
+ md."maintenanceDispatchId",
+ md.content,
+ md.status,
+ md.priority,
+ md.source,
+ md.severity,
+ md."oeeImpact",
+ md."workCenterId",
+ md."maintenanceScheduleId",
+ md."suspectedFailureModeId",
+ md."actualFailureModeId",
+ md."plannedStartTime",
+ md."plannedEndTime",
+ md."actualStartTime",
+ md."actualEndTime",
+ md.duration,
+ md."nonConformanceId",
+ md."completedAt",
+ md.assignee,
+ md."companyId",
+ md."createdBy",
+ md."createdAt",
+ md."updatedBy",
+ md."updatedAt",
+ wc."locationId",
+ wc.name AS "workCenterName",
+ l.name AS "locationName",
+ assignee."fullName" AS "assigneeName",
+ assignee."avatarUrl" AS "assigneeAvatarUrl",
+ sfm.name AS "suspectedFailureModeName",
+ afm.name AS "actualFailureModeName"
+FROM "maintenanceDispatch" md
+LEFT JOIN "workCenter" wc ON md."workCenterId" = wc.id
+LEFT JOIN "location" l ON wc."locationId" = l.id
+LEFT JOIN "user" assignee ON md.assignee = assignee.id
+LEFT JOIN "maintenanceFailureMode" sfm ON md."suspectedFailureModeId" = sfm.id
+LEFT JOIN "maintenanceFailureMode" afm ON md."actualFailureModeId" = afm.id
+WHERE md.status IN ('Open', 'Assigned', 'In Progress');
+
+
+-- RPC function to get maintenance dispatches by location
+-- This joins maintenanceDispatch with workCenter to filter by locationId
+CREATE OR REPLACE FUNCTION get_maintenance_dispatches_by_location(
+ p_company_id TEXT,
+ p_location_id TEXT
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "maintenanceDispatchId" TEXT,
+ "content" JSON,
+ "status" "maintenanceDispatchStatus",
+ "priority" "maintenanceDispatchPriority",
+ "source" "maintenanceSource",
+ "severity" "maintenanceSeverity",
+ "oeeImpact" "oeeImpact",
+ "workCenterId" TEXT,
+ "maintenanceScheduleId" TEXT,
+ "suspectedFailureModeId" TEXT,
+ "actualFailureModeId" TEXT,
+ "plannedStartTime" TIMESTAMP WITH TIME ZONE,
+ "plannedEndTime" TIMESTAMP WITH TIME ZONE,
+ "actualStartTime" TIMESTAMP WITH TIME ZONE,
+ "actualEndTime" TIMESTAMP WITH TIME ZONE,
+ "duration" INTEGER,
+ "nonConformanceId" TEXT,
+ "completedAt" TIMESTAMP WITH TIME ZONE,
+ "assignee" TEXT,
+ "companyId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "locationId" TEXT,
+ "workCenterName" TEXT,
+ "locationName" TEXT
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ md."id",
+ md."maintenanceDispatchId",
+ md."content",
+ md."status",
+ md."priority",
+ md."source",
+ md."severity",
+ md."oeeImpact",
+ md."workCenterId",
+ md."maintenanceScheduleId",
+ md."suspectedFailureModeId",
+ md."actualFailureModeId",
+ md."plannedStartTime",
+ md."plannedEndTime",
+ md."actualStartTime",
+ md."actualEndTime",
+ md."duration",
+ md."nonConformanceId",
+ md."completedAt",
+ md."assignee",
+ md."companyId",
+ md."createdBy",
+ md."createdAt",
+ md."updatedBy",
+ md."updatedAt",
+ wc."locationId",
+ wc."name" AS "workCenterName",
+ l."name" AS "locationName"
+ FROM "maintenanceDispatch" md
+ INNER JOIN "workCenter" wc ON md."workCenterId" = wc."id"
+ INNER JOIN "location" l ON wc."locationId" = l."id"
+ WHERE md."companyId" = p_company_id
+ AND wc."locationId" = p_location_id;
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;
diff --git a/packages/jobs/trigger/notify.ts b/packages/jobs/trigger/notify.ts
index d4f5e442eb..1e3f7806a9 100644
--- a/packages/jobs/trigger/notify.ts
+++ b/packages/jobs/trigger/notify.ts
@@ -136,6 +136,33 @@ export const notifyTask = task({
return `Sales Order ${salesOrder?.data?.salesOrderId} assigned to you`;
+ case NotificationEvent.MaintenanceDispatchCreated:
+ const maintenanceDispatchCreated = await client
+ .from("maintenanceDispatch")
+ .select("*")
+ .eq("id", documentId)
+ .single();
+
+ if (maintenanceDispatchCreated.error) {
+ console.error("Failed to get maintenanceDispatchCreated", maintenanceDispatchCreated.error);
+ throw maintenanceDispatchCreated.error;
+ }
+
+ return `New maintenance dispatch ${maintenanceDispatchCreated?.data?.maintenanceDispatchId} created`;
+ case NotificationEvent.MaintenanceDispatchAssignment:
+ const maintenanceDispatchAssignment = await client
+ .from("maintenanceDispatch")
+ .select("*")
+ .eq("id", documentId)
+ .single();
+
+ if (maintenanceDispatchAssignment.error) {
+ console.error("Failed to get maintenanceDispatchAssignment", maintenanceDispatchAssignment.error);
+ throw maintenanceDispatchAssignment.error;
+ }
+
+ return `Maintenance dispatch ${maintenanceDispatchAssignment?.data?.maintenanceDispatchId} assigned to you`;
+
case NotificationEvent.NonConformanceAssignment:
const nonConformance = await client
.from("nonConformance")