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 rls to maintenance tables

Brad Barbinc3ff0dc0b695
diff --git a/apps/erp/app/components/Form/ItemPostingGroup.tsx b/apps/erp/app/components/Form/ItemPostingGroup.tsx
index 3f095acc1c..3c06585454 100644
--- a/apps/erp/app/components/Form/ItemPostingGroup.tsx
+++ b/apps/erp/app/components/Form/ItemPostingGroup.tsx
@@ -3,6 +3,7 @@ import { CreatableCombobox } from "@carbon/form";
import { useDisclosure, useMount } from "@carbon/react";
import { useMemo, useRef, useState } from "react";
import { useFetcher } from "react-router";
+import { Enumerable } from "~/components/Enumerable";
import type { getItemPostingGroupsList } from "~/modules/items";
import ItemPostingGroupForm from "~/modules/items/ui/ItemPostingGroups/ItemPostingGroupForm";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index 5408bd58a7..d54431c7b8 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -199,7 +199,17 @@ export const maintenanceScheduleValidator = z.object({
frequency: z.enum(maintenanceFrequency),
priority: z.enum(maintenanceDispatchPriority),
estimatedDuration: zfd.numeric(z.number().optional()),
- active: zfd.checkbox()
+ active: zfd.checkbox(),
+ // Day-of-week fields for daily frequency
+ monday: zfd.checkbox(),
+ tuesday: zfd.checkbox(),
+ wednesday: zfd.checkbox(),
+ thursday: zfd.checkbox(),
+ friday: zfd.checkbox(),
+ saturday: zfd.checkbox(),
+ sunday: zfd.checkbox(),
+ // Skip holidays option
+ skipHolidays: zfd.checkbox()
});
export const maintenanceSeverity = [
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
index 6f2a55b145..312bb00405 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
@@ -169,6 +169,35 @@ const MaintenanceDispatchesTable = memo(
}
}
},
+ {
+ accessorKey: "plannedStartTime",
+ header: "Planned Start",
+ cell: ({ row }) => {
+ const date = row.original.plannedStartTime;
+ return date ? formatDate(date) : "-";
+ },
+ meta: {
+ icon: <LuCalendar />
+ }
+ },
+ {
+ accessorKey: "assignee",
+ header: "Assignee",
+ cell: ({ row }) => {
+ const assignee = row.original.assignee;
+ if (!assignee) {
+ return <span className="text-muted-foreground">Unassigned</span>;
+ }
+ return (
+ <HStack>
+ <EmployeeAvatar employeeId={assignee} size="xs" />
+ </HStack>
+ );
+ },
+ meta: {
+ icon: <LuUser />
+ }
+ },
{
accessorKey: "actualFailureModeId",
header: "Actual Failure Mode",
@@ -217,36 +246,6 @@ const MaintenanceDispatchesTable = memo(
}
}
},
- {
- accessorKey: "assignee",
- header: "Assignee",
- cell: ({ row }) => {
- const assignee = row.original.assignee;
- if (!assignee) {
- return <span className="text-muted-foreground">Unassigned</span>;
- }
- return (
- <HStack>
- <EmployeeAvatar employeeId={assignee} size="xs" />
- </HStack>
- );
- },
- meta: {
- icon: <LuUser />
- }
- },
-
- {
- accessorKey: "plannedStartTime",
- header: "Planned Start",
- cell: ({ row }) => {
- const date = row.original.plannedStartTime;
- return date ? formatDate(date) : "-";
- },
- meta: {
- icon: <LuCalendar />
- }
- },
{
accessorKey: "createdBy",
header: "Created By",
@@ -343,7 +342,6 @@ const MaintenanceDispatchesTable = memo(
data={data}
columns={columns}
defaultColumnVisibility={{
- plannedStartTime: false,
suspectedFailureModeId: false,
createdBy: false,
createdAt: false,
diff --git a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
index 2391dccf0a..2e4d5c6d36 100644
--- a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
+++ b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
@@ -1,6 +1,14 @@
-import { Boolean, Number, Select, ValidatedForm } from "@carbon/form";
+import {
+ Boolean,
+ Number,
+ Select,
+ useControlField,
+ ValidatedForm
+} from "@carbon/form";
import {
Button,
+ FormControl,
+ FormLabel,
HStack,
ModalDrawer,
ModalDrawerBody,
@@ -45,6 +53,36 @@ function getPriorityIcon(
}
}
+// Component to show day selector and skip holidays when Daily frequency is selected
+function DailyScheduleOptions() {
+ const [frequency] = useControlField<string>("frequency");
+ const isDaily = frequency === "Daily";
+
+ if (!isDaily) return null;
+
+ return (
+ <>
+ <FormControl>
+ <FormLabel>Days</FormLabel>
+ <VStack>
+ <Boolean name="monday" description="Monday" />
+ <Boolean name="tuesday" description="Tuesday" />
+ <Boolean name="wednesday" description="Wednesday" />
+ <Boolean name="thursday" description="Thursday" />
+ <Boolean name="friday" description="Friday" />
+ <Boolean name="saturday" description="Saturday" />
+ <Boolean name="sunday" description="Sunday" />
+ </VStack>
+ </FormControl>
+ <Boolean
+ name="skipHolidays"
+ label="Skip Holidays"
+ description="Skip scheduled maintenance on company holidays"
+ />
+ </>
+ );
+}
+
type MaintenanceScheduleFormProps = {
initialValues: z.infer<typeof maintenanceScheduleValidator>;
type?: "modal" | "drawer";
@@ -138,6 +176,7 @@ const MaintenanceScheduleForm = ({
minValue={0}
/>
<Boolean name="active" label="Active" />
+ <DailyScheduleOptions />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx b/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx
index ec9b6e7b21..1cbd6d1212 100644
--- a/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx
+++ b/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx
@@ -79,7 +79,7 @@ export default function DeleteMaintenanceDispatchRoute() {
return (
<ConfirmDelete
action={path.to.deleteMaintenanceDispatch(dispatchId)}
- name={dispatch.id}
+ name={dispatch.maintenanceDispatchId}
text={`Are you sure you want to delete this maintenance dispatch? This cannot be undone.`}
onCancel={onCancel}
/>
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 634dd62b3e..34607a4d3a 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.$scheduleId.tsx
@@ -89,7 +89,16 @@ export default function EditMaintenanceScheduleRoute() {
frequency: schedule.frequency ?? ("Weekly" as const),
priority: schedule.priority ?? ("Medium" as const),
estimatedDuration: schedule.estimatedDuration ?? undefined,
- active: schedule.active ?? true
+ active: schedule.active ?? true,
+ // Day-of-week settings
+ monday: schedule.monday ?? true,
+ tuesday: schedule.tuesday ?? true,
+ wednesday: schedule.wednesday ?? true,
+ thursday: schedule.thursday ?? true,
+ friday: schedule.friday ?? true,
+ saturday: schedule.saturday ?? true,
+ sunday: schedule.sunday ?? true,
+ skipHolidays: schedule.skipHolidays ?? true
};
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 10aff0b593..077cccef38 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.new.tsx
@@ -74,7 +74,16 @@ export default function NewMaintenanceScheduleRoute() {
frequency: "Weekly" as const,
priority: "Medium" as const,
estimatedDuration: undefined,
- active: true
+ active: true,
+ // Day-of-week defaults (all days enabled by default)
+ monday: true,
+ tuesday: true,
+ wednesday: true,
+ thursday: true,
+ friday: true,
+ saturday: true,
+ sunday: true,
+ skipHolidays: true
};
return (
diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsx
index ea4416e29c..5545134212 100644
--- a/apps/erp/app/routes/x+/settings+/production.tsx
+++ b/apps/erp/app/routes/x+/settings+/production.tsx
@@ -1,13 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import {
- Boolean,
- Number,
- Submit,
- ValidatedForm,
- validator
-} from "@carbon/form";
+import { Submit, ValidatedForm, validator } from "@carbon/form";
import {
Card,
CardContent,
@@ -21,17 +15,11 @@ import {
toast,
VStack
} from "@carbon/react";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
-import { z } from "zod/v3";
-import { zfd } from "zod-form-data";
import { Users } from "~/components/Form";
-import {
- getCompanySettings,
- jobCompletedValidator,
- maintenanceSettingsValidator
-} from "~/modules/settings";
+import { getCompanySettings, jobCompletedValidator } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -64,63 +52,30 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const intent = formData.get("intent");
-
- if (intent === "maintenance") {
- const validation = await validator(maintenanceSettingsValidator).validate(
- formData
- );
-
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
- }
+ const validation = await validator(jobCompletedValidator).validate(formData);
- const update = await client
- .from("companySettings")
- .update({
- maintenanceGenerateInAdvance:
- validation.data.maintenanceGenerateInAdvance,
- maintenanceAdvanceDays: validation.data.maintenanceAdvanceDays
- })
- .eq("id", companyId);
-
- if (update.error) return { success: false, message: update.error.message };
-
- return { success: true, message: "Maintenance settings updated" };
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
}
- if (intent === "jobCompleted") {
- const validation = await validator(jobCompletedValidator).validate(
- formData
- );
-
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
- const update = await client
- .from("companySettings")
- .update({
- inventoryJobCompletedNotificationGroup:
- validation.data.inventoryJobCompletedNotificationGroup ?? [],
- salesJobCompletedNotificationGroup:
- validation.data.salesJobCompletedNotificationGroup ?? []
- })
- .eq("id", companyId);
-
- if (update.error) return { success: false, message: update.error.message };
+ const update = await client
+ .from("companySettings")
+ .update({
+ inventoryJobCompletedNotificationGroup:
+ validation.data.inventoryJobCompletedNotificationGroup ?? [],
+ salesJobCompletedNotificationGroup:
+ validation.data.salesJobCompletedNotificationGroup ?? []
+ })
+ .eq("id", companyId);
- return { success: true, message: "Job notification settings updated" };
- }
+ if (update.error) return { success: false, message: update.error.message };
- return null;
+ return { success: true, message: "Job notification settings updated" };
}
export default function ProductionSettingsRoute() {
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
- const [maintenanceGenerateInAdvance, setMaintenanceGenerateInAdvance] =
- useState(companySettings.maintenanceGenerateInAdvance ?? false);
useEffect(() => {
if (fetcher.data?.success === true && fetcher?.data?.message) {
@@ -152,7 +107,6 @@ export default function ProductionSettingsRoute() {
}}
fetcher={fetcher}
>
- <input type="hidden" name="intent" value="jobCompleted" />
<CardHeader>
<CardTitle className="flex items-center gap-2">
Completed Job Notifications
@@ -182,68 +136,7 @@ export default function ProductionSettingsRoute() {
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "jobCompleted"
- }
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
- </Card>
-
- <Card>
- <ValidatedForm
- method="post"
- validator={maintenanceSettingsValidator}
- defaultValues={{
- maintenanceGenerateInAdvance:
- companySettings.maintenanceGenerateInAdvance ?? false,
- maintenanceAdvanceDays:
- companySettings.maintenanceAdvanceDays ?? 7
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="maintenance" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- Maintenance Scheduling
- </CardTitle>
- <CardDescription>
- Configure how preventative maintenance dispatches are
- automatically generated from maintenance schedules.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-6 max-w-[400px]">
- <div className="flex flex-col gap-2">
- <Boolean
- name="maintenanceGenerateInAdvance"
- description="Create maintenance dispatches in advance."
- value={maintenanceGenerateInAdvance}
- onChange={setMaintenanceGenerateInAdvance}
- />
- </div>
- {maintenanceGenerateInAdvance && (
- <div className="flex flex-col gap-2">
- <Number
- name="maintenanceAdvanceDays"
- label="Days in advance to generate dispatches"
- minValue={1}
- maxValue={365}
- />
- </div>
- )}
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "maintenance"
- }
+ isLoading={fetcher.state !== "idle"}
>
Save
</Submit>
diff --git a/apps/erp/app/routes/x+/settings+/resources.tsx b/apps/erp/app/routes/x+/settings+/resources.tsx
index c333eaaae3..63f719bc23 100644
--- a/apps/erp/app/routes/x+/settings+/resources.tsx
+++ b/apps/erp/app/routes/x+/settings+/resources.tsx
@@ -1,7 +1,13 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { Submit, ValidatedForm, validator } from "@carbon/form";
+import {
+ Boolean,
+ Number,
+ Submit,
+ ValidatedForm,
+ validator
+} from "@carbon/form";
import {
Card,
CardContent,
@@ -15,12 +21,14 @@ import {
toast,
VStack
} from "@carbon/react";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
import { Users } from "~/components/Form";
import {
getCompany,
+ getCompanySettings,
+ maintenanceSettingsValidator,
suggestionNotificationValidator,
updateSuggestionNotificationSetting
} from "~/modules/settings";
@@ -37,14 +45,27 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "settings"
});
- const company = await getCompany(client, companyId);
+ const [company, companySettings] = await Promise.all([
+ getCompany(client, companyId),
+ getCompanySettings(client, companyId)
+ ]);
if (!company.data)
throw redirect(
path.to.settings,
await flash(request, error(company.error, "Failed to get company"))
);
- return { company: company.data };
+
+ if (!companySettings.data)
+ throw redirect(
+ path.to.settings,
+ await flash(
+ request,
+ error(companySettings.error, "Failed to get company settings")
+ )
+ );
+
+ return { company: company.data, companySettings: companySettings.data };
}
export async function action({ request }: ActionFunctionArgs) {
@@ -53,31 +74,62 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(suggestionNotificationValidator).validate(
- formData
- );
+ const intent = formData.get("intent");
+
+ if (intent === "maintenance") {
+ const validation = await validator(maintenanceSettingsValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const update = await client
+ .from("companySettings")
+ .update({
+ maintenanceGenerateInAdvance:
+ validation.data.maintenanceGenerateInAdvance,
+ maintenanceAdvanceDays: validation.data.maintenanceAdvanceDays
+ })
+ .eq("id", companyId);
+
+ if (update.error) return { success: false, message: update.error.message };
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
+ return { success: true, message: "Maintenance settings updated" };
}
- const update = await updateSuggestionNotificationSetting(
- client,
- companyId,
- validation.data.suggestionNotificationGroup ?? []
- );
+ if (intent === "suggestions") {
+ const validation = await validator(
+ suggestionNotificationValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const update = await updateSuggestionNotificationSetting(
+ client,
+ companyId,
+ validation.data.suggestionNotificationGroup ?? []
+ );
+
+ if (update.error) return { success: false, message: update.error.message };
- if (update.error) return { success: false, message: update.error.message };
+ return {
+ success: true,
+ message: "Suggestion notification settings updated"
+ };
+ }
- return {
- success: true,
- message: "Suggestion notification settings updated"
- };
+ return null;
}
export default function ResourcesSettingsRoute() {
- const { company } = useLoaderData<typeof loader>();
+ const { company, companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ const [maintenanceGenerateInAdvance, setMaintenanceGenerateInAdvance] =
+ useState(companySettings.maintenanceGenerateInAdvance ?? false);
useEffect(() => {
if (fetcher.data?.success === true && fetcher?.data?.message) {
@@ -107,6 +159,7 @@ export default function ResourcesSettingsRoute() {
}}
fetcher={fetcher}
>
+ <input type="hidden" name="intent" value="suggestions" />
<CardHeader>
<CardTitle className="flex items-center gap-2">
Suggestion Notifications
@@ -129,7 +182,68 @@ export default function ResourcesSettingsRoute() {
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
- isLoading={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "suggestions"
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={maintenanceSettingsValidator}
+ defaultValues={{
+ maintenanceGenerateInAdvance:
+ companySettings.maintenanceGenerateInAdvance ?? false,
+ maintenanceAdvanceDays:
+ companySettings.maintenanceAdvanceDays ?? 7
+ }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="maintenance" />
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Maintenance Scheduling
+ </CardTitle>
+ <CardDescription>
+ Configure how preventative maintenance dispatches are
+ automatically generated from maintenance schedules.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col gap-6 max-w-[400px]">
+ <div className="flex flex-col gap-2">
+ <Boolean
+ name="maintenanceGenerateInAdvance"
+ description="Create maintenance dispatches in advance"
+ value={maintenanceGenerateInAdvance}
+ onChange={setMaintenanceGenerateInAdvance}
+ />
+ </div>
+ {maintenanceGenerateInAdvance && (
+ <div className="flex flex-col gap-2">
+ <Number
+ name="maintenanceAdvanceDays"
+ label="Days in advance to generate dispatches"
+ minValue={1}
+ maxValue={365}
+ />
+ </div>
+ )}
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "maintenance"
+ }
>
Save
</Submit>
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index 80d8d7bbd6..009b683fd8 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -209,19 +209,14 @@ export function MaintenanceNav({
}) {
const { pathname } = useLocation();
const { isMobile, setOpenMobile } = useSidebar();
- const isActive = pathname.includes("/maintenance");
+ const isActive = pathname.includes(path.to.maintenance);
return (
<SidebarGroup>
<SidebarGroupLabel>Maintenance</SidebarGroupLabel>
<SidebarMenu>
<SidebarMenuItem>
- <SidebarMenuButton
- tooltip="Maintenance"
- className={cn(activeMaintenanceCount > 0 && "text-emerald-500")}
- isActive={isActive}
- asChild
- >
+ <SidebarMenuButton tooltip="Maintenance" isActive={isActive} asChild>
<Link
to={path.to.maintenance}
onClick={() => isMobile && setOpenMobile(false)}
diff --git a/apps/mes/app/routes/x+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsx
index 75ac23f75c..7acdad582b 100644
--- a/apps/mes/app/routes/x+/dispatch.new.tsx
+++ b/apps/mes/app/routes/x+/dispatch.new.tsx
@@ -56,6 +56,8 @@ export async function action({ request }: ActionFunctionArgs) {
: "In Progress"
: "Open";
+ const currentTime = now(getLocalTimeZone()).toAbsoluteString();
+
const insertDispatch = await serviceRole
.from("maintenanceDispatch")
.insert([
@@ -71,6 +73,7 @@ export async function action({ request }: ActionFunctionArgs) {
suspectedFailureModeId:
validation.data.suspectedFailureModeId || undefined,
actualFailureModeId: validation.data.actualFailureModeId || undefined,
+ plannedStartTime: currentTime, // Set plannedStartTime to today for reactive maintenance
actualStartTime: validation.data.actualStartTime || undefined,
actualEndTime: validation.data.actualEndTime || undefined,
content,
diff --git a/apps/mes/app/routes/x+/maintenance.tsx b/apps/mes/app/routes/x+/maintenance.tsx
index 6e1ca30a68..7026960f02 100644
--- a/apps/mes/app/routes/x+/maintenance.tsx
+++ b/apps/mes/app/routes/x+/maintenance.tsx
@@ -10,7 +10,6 @@ import {
CardTitle,
Heading,
HStack,
- Input,
SidebarTrigger,
Tabs,
TabsContent,
@@ -20,19 +19,24 @@ import {
} from "@carbon/react";
import { useMemo, useState } from "react";
import { BsExclamationSquareFill } from "react-icons/bs";
-import { LuSearch, LuTriangleAlert } from "react-icons/lu";
+import { LuTriangleAlert } from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
import { Link, useLoaderData } from "react-router";
import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import EmployeeAvatar from "~/components/EmployeeAvatar";
+import type { ColumnFilter } from "~/components/Filter";
+import { ActiveFilters, Filter, useFilters } from "~/components/Filter";
+import SearchFilter from "~/components/SearchFilter";
+import { useUrlParams } from "~/hooks";
import { getLocation } from "~/services/location.server";
import {
getActiveMaintenanceDispatchesByLocation,
getMaintenanceDispatchesAssignedTo
} from "~/services/maintenance.service";
-import type { maintenanceDispatchPriority } from "~/services/models";
+import { maintenanceDispatchPriority } from "~/services/models";
+import { getWorkCentersByLocation } from "~/services/operations.service";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -43,15 +47,138 @@ export async function loader({ request }: LoaderFunctionArgs) {
userId
});
- const [allDispatches, assignedDispatches] = await Promise.all([
- getActiveMaintenanceDispatchesByLocation(client, location),
- getMaintenanceDispatchesAssignedTo(client, userId)
- ]);
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const filterParam = searchParams.getAll("filter").filter(Boolean);
+
+ let selectedWorkCenterIds: string[] = [];
+ let selectedPriorities: string[] = [];
+ let selectedStatuses: string[] = [];
+ let selectedOeeImpacts: string[] = [];
+
+ if (filterParam) {
+ for (const filter of filterParam) {
+ const [key, operator, value] = filter.split(":");
+ if (key === "workCenterId") {
+ if (operator === "in") {
+ selectedWorkCenterIds = value.split(",");
+ } else if (operator === "eq") {
+ selectedWorkCenterIds = [value];
+ }
+ } else if (key === "priority") {
+ if (operator === "in") {
+ selectedPriorities = value.split(",");
+ } else if (operator === "eq") {
+ selectedPriorities = [value];
+ }
+ } else if (key === "status") {
+ if (operator === "in") {
+ selectedStatuses = value.split(",");
+ } else if (operator === "eq") {
+ selectedStatuses = [value];
+ }
+ } else if (key === "oeeImpact") {
+ if (operator === "in") {
+ selectedOeeImpacts = value.split(",");
+ } else if (operator === "eq") {
+ selectedOeeImpacts = [value];
+ }
+ }
+ }
+ }
+
+ const [allDispatches, assignedDispatches, workCentersResult] =
+ await Promise.all([
+ getActiveMaintenanceDispatchesByLocation(client, location),
+ getMaintenanceDispatchesAssignedTo(client, userId),
+ getWorkCentersByLocation(client, location)
+ ]);
+
+ let filteredDispatches = allDispatches?.data ?? [];
+
+ // Apply filters
+ if (selectedWorkCenterIds.length) {
+ filteredDispatches = filteredDispatches.filter((d) =>
+ selectedWorkCenterIds.includes(d.workCenterId ?? "")
+ );
+ }
+
+ if (selectedPriorities.length) {
+ filteredDispatches = filteredDispatches.filter((d) =>
+ selectedPriorities.includes(d.priority ?? "")
+ );
+ }
+
+ if (selectedStatuses.length) {
+ filteredDispatches = filteredDispatches.filter((d) =>
+ selectedStatuses.includes(d.status ?? "")
+ );
+ }
+
+ if (selectedOeeImpacts.length) {
+ filteredDispatches = filteredDispatches.filter((d) =>
+ selectedOeeImpacts.includes(d.oeeImpact ?? "")
+ );
+ }
+
+ if (search) {
+ const lowercasedSearch = search.toLowerCase();
+ filteredDispatches = filteredDispatches.filter(
+ (d) =>
+ d.maintenanceDispatchId?.toLowerCase().includes(lowercasedSearch) ||
+ d.workCenterName?.toLowerCase().includes(lowercasedSearch) ||
+ d.severity?.toLowerCase().includes(lowercasedSearch) ||
+ d.assigneeName?.toLowerCase().includes(lowercasedSearch)
+ );
+ }
+
+ // Also filter assigned dispatches with the same criteria
+ let filteredAssignedDispatches = assignedDispatches?.data ?? [];
+
+ if (selectedWorkCenterIds.length) {
+ filteredAssignedDispatches = filteredAssignedDispatches.filter((d) =>
+ selectedWorkCenterIds.includes(d.workCenterId ?? "")
+ );
+ }
+
+ if (selectedPriorities.length) {
+ filteredAssignedDispatches = filteredAssignedDispatches.filter((d) =>
+ selectedPriorities.includes(d.priority ?? "")
+ );
+ }
+
+ if (selectedStatuses.length) {
+ filteredAssignedDispatches = filteredAssignedDispatches.filter((d) =>
+ selectedStatuses.includes(d.status ?? "")
+ );
+ }
+
+ if (selectedOeeImpacts.length) {
+ filteredAssignedDispatches = filteredAssignedDispatches.filter((d) =>
+ selectedOeeImpacts.includes(d.oeeImpact ?? "")
+ );
+ }
+
+ if (search) {
+ const lowercasedSearch = search.toLowerCase();
+ filteredAssignedDispatches = filteredAssignedDispatches.filter(
+ (d) =>
+ d.maintenanceDispatchId?.toLowerCase().includes(lowercasedSearch) ||
+ d.workCenterName?.toLowerCase().includes(lowercasedSearch) ||
+ d.severity?.toLowerCase().includes(lowercasedSearch) ||
+ d.assigneeName?.toLowerCase().includes(lowercasedSearch)
+ );
+ }
return {
- dispatches: allDispatches?.data ?? [],
- assignedDispatches: assignedDispatches?.data ?? [],
- locationId: location
+ dispatches: filteredDispatches,
+ assignedDispatches: filteredAssignedDispatches,
+ locationId: location,
+ workCenters: (workCentersResult?.data ?? []).map((wc) => ({
+ value: wc.id,
+ label: wc.name
+ }))
};
}
@@ -163,39 +290,102 @@ function EmptyState({
);
}
+function isToday(dateString: string | null): boolean {
+ if (!dateString) return false;
+ const date = new Date(dateString);
+ const today = new Date();
+ return (
+ date.getFullYear() === today.getFullYear() &&
+ date.getMonth() === today.getMonth() &&
+ date.getDate() === today.getDate()
+ );
+}
+
export default function MaintenanceRoute() {
- const { dispatches, assignedDispatches } = useLoaderData<typeof loader>();
- const [searchTerm, setSearchTerm] = useState("");
+ const { dispatches, assignedDispatches, workCenters } =
+ useLoaderData<typeof loader>();
const [activeTab, setActiveTab] = useState("all");
+ const [params] = useUrlParams();
+ const { hasFilters, clearFilters } = useFilters();
+ const currentFilters = params.getAll("filter").filter(Boolean);
const blockingDispatches = useMemo(() => {
- return dispatches.filter(
- (d) => d.oeeImpact === "Down" || d.oeeImpact === "Planned"
- );
+ return dispatches.filter((d) => {
+ // Down is always blocking
+ if (d.oeeImpact === "Down") return true;
+ // Planned is only blocking if status is In Progress (active)
+ if (d.oeeImpact === "Planned" && d.status === "In Progress") return true;
+ return false;
+ });
}, [dispatches]);
- const filterDispatches = (dispatchList: typeof dispatches) => {
- if (!searchTerm) return dispatchList;
- const lowercasedTerm = searchTerm.toLowerCase();
- return dispatchList.filter(
- (dispatch) =>
- dispatch.maintenanceDispatchId
- ?.toLowerCase()
- .includes(lowercasedTerm) ||
- dispatch.workCenterName?.toLowerCase().includes(lowercasedTerm) ||
- dispatch.severity?.toLowerCase().includes(lowercasedTerm) ||
- dispatch.assigneeName?.toLowerCase().includes(lowercasedTerm)
- );
- };
+ const todayDispatches = useMemo(() => {
+ return dispatches.filter((d) => isToday(d.plannedStartTime));
+ }, [dispatches]);
+
+ const filters = useMemo<ColumnFilter[]>(() => {
+ return [
+ {
+ accessorKey: "workCenterId",
+ header: "Work Center",
+ filter: {
+ type: "static",
+ options: workCenters.map((wc) => ({
+ label: wc.label,
+ value: wc.value
+ }))
+ }
+ },
+ {
+ accessorKey: "priority",
+ header: "Priority",
+ filter: {
+ type: "static",
+ options: maintenanceDispatchPriority.map((p) => ({
+ label: p,
+ value: p
+ }))
+ }
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ pluralHeader: "Statuses",
+ filter: {
+ type: "static",
+ options: [
+ { label: "Open", value: "Open" },
+ { label: "Assigned", value: "Assigned" },
+ { label: "In Progress", value: "In Progress" }
+ ]
+ }
+ },
+ {
+ accessorKey: "oeeImpact",
+ header: "OEE Impact",
+ filter: {
+ type: "static",
+ options: [
+ { label: "Down", value: "Down" },
+ { label: "Planned", value: "Planned" },
+ { label: "Impact", value: "Impact" },
+ { label: "No Impact", value: "No Impact" }
+ ]
+ }
+ }
+ ];
+ }, [workCenters]);
const getActiveDispatches = () => {
switch (activeTab) {
case "assigned":
- return filterDispatches(assignedDispatches);
+ return assignedDispatches;
case "blocking":
- return filterDispatches(blockingDispatches);
+ return blockingDispatches;
+ case "today":
+ return todayDispatches;
default:
- return filterDispatches(dispatches);
+ return dispatches;
}
};
@@ -225,6 +415,14 @@ export default function MaintenanceRoute() {
</Badge>
)}
</TabsTrigger>
+ <TabsTrigger value="today">
+ Today
+ {todayDispatches.length > 0 && (
+ <Badge variant="secondary" className="ml-2">
+ {todayDispatches.length}
+ </Badge>
+ )}
+ </TabsTrigger>
<TabsTrigger value="assigned">
Assigned to Me
{assignedDispatches.length > 0 && (
@@ -242,16 +440,20 @@ export default function MaintenanceRoute() {
)}
</TabsTrigger>
</TabsList>
- <div className="relative w-64">
- <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
+ <HStack spacing={2}>
+ <SearchFilter
+ param="search"
+ size="sm"
placeholder="Search"
- className="pl-8"
/>
- </div>
+ <Filter filters={filters} />
+ </HStack>
</HStack>
+ {currentFilters.length > 0 && (
+ <HStack className="py-1.5 justify-between w-full">
+ <ActiveFilters filters={filters} />
+ </HStack>
+ )}
<TabsContent value="all" className="mt-4">
{activeDispatches.length > 0 ? (
<div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] gap-4">
@@ -262,15 +464,34 @@ export default function MaintenanceRoute() {
/>
))}
</div>
- ) : searchTerm ? (
+ ) : hasFilters ? (
<EmptyState
message="No results found"
- onClear={() => setSearchTerm("")}
+ onClear={clearFilters}
/>
) : (
<EmptyState message="No active maintenance dispatches" />
)}
</TabsContent>
+ <TabsContent value="today" className="mt-4">
+ {activeDispatches.length > 0 ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] gap-4">
+ {activeDispatches.map((dispatch) => (
+ <MaintenanceCard
+ key={dispatch.id}
+ dispatch={dispatch}
+ />
+ ))}
+ </div>
+ ) : hasFilters ? (
+ <EmptyState
+ message="No results found"
+ onClear={clearFilters}
+ />
+ ) : (
+ <EmptyState message="No maintenance scheduled for today" />
+ )}
+ </TabsContent>
<TabsContent value="assigned" className="mt-4">
{activeDispatches.length > 0 ? (
<div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] gap-4">
@@ -281,10 +502,10 @@ export default function MaintenanceRoute() {
/>
))}
</div>
- ) : searchTerm ? (
+ ) : hasFilters ? (
<EmptyState
message="No results found"
- onClear={() => setSearchTerm("")}
+ onClear={clearFilters}
/>
) : (
<EmptyState message="No dispatches assigned to you" />
@@ -300,10 +521,10 @@ export default function MaintenanceRoute() {
/>
))}
</div>
- ) : searchTerm ? (
+ ) : hasFilters ? (
<EmptyState
message="No results found"
- onClear={() => setSearchTerm("")}
+ onClear={clearFilters}
/>
) : (
<EmptyState message="No work centers are blocked" />
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 5f8ee5b8d8..8dc87c35d5 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -41802,6 +41802,30 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.monday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.tuesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.wednesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.thursday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.friday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.saturday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.sunday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.skipHolidays",
+ },
{
$ref: "#/parameters/select",
},
@@ -41906,6 +41930,30 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.monday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.tuesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.wednesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.thursday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.friday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.saturday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.sunday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.skipHolidays",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -41964,6 +42012,30 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.monday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.tuesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.wednesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.thursday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.friday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.saturday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.sunday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.skipHolidays",
+ },
{
$ref: "#/parameters/body.maintenanceSchedule",
},
@@ -54255,6 +54327,30 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceSchedules.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.monday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.tuesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.wednesday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.thursday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.friday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.saturday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.sunday",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceSchedules.skipHolidays",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceSchedules.locationId",
},
@@ -67883,7 +67979,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -67932,7 +68028,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -83769,6 +83865,14 @@ export default {
"companyId",
"createdBy",
"createdAt",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+ "skipHolidays",
],
properties: {
id: {
@@ -83846,6 +83950,46 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ monday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ tuesday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ wednesday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ thursday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ friday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ saturday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ sunday: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ skipHolidays: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
},
type: "object",
},
@@ -90210,6 +90354,38 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ monday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ tuesday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ wednesday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ thursday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ friday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ saturday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ sunday: {
+ format: "boolean",
+ type: "boolean",
+ },
+ skipHolidays: {
+ format: "boolean",
+ type: "boolean",
+ },
locationId: {
description:
"Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
@@ -92484,12 +92660,12 @@ export default {
type: "array",
},
maintenanceGenerateInAdvance: {
- default: false,
+ default: true,
format: "boolean",
type: "boolean",
},
maintenanceAdvanceDays: {
- default: 7,
+ default: 3,
format: "integer",
type: "integer",
},
@@ -115030,6 +115206,54 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceSchedule.monday": {
+ name: "monday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.tuesday": {
+ name: "tuesday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.wednesday": {
+ name: "wednesday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.thursday": {
+ name: "thursday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.friday": {
+ name: "friday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.saturday": {
+ name: "saturday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.sunday": {
+ name: "sunday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.skipHolidays": {
+ name: "skipHolidays",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.quoteLines": {
name: "quoteLines",
description: "quoteLines",
@@ -122173,6 +122397,54 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceSchedules.monday": {
+ name: "monday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.tuesday": {
+ name: "tuesday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.wednesday": {
+ name: "wednesday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.thursday": {
+ name: "thursday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.friday": {
+ name: "friday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.saturday": {
+ name: "saturday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.sunday": {
+ name: "sunday",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedules.skipHolidays": {
+ name: "skipHolidays",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceSchedules.locationId": {
name: "locationId",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 6652e054f1..30d86c35e6 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13586,13 +13586,21 @@ export type Database = {
description: string | null
estimatedDuration: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday: boolean
id: string
lastGeneratedAt: string | null
+ monday: boolean
name: string
nextDueAt: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday: boolean
+ skipHolidays: boolean
+ sunday: boolean
+ thursday: boolean
+ tuesday: boolean
updatedAt: string | null
updatedBy: string | null
+ wednesday: boolean
workCenterId: string
}
Insert: {
@@ -13603,13 +13611,21 @@ export type Database = {
description?: string | null
estimatedDuration?: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday?: boolean
id?: string
lastGeneratedAt?: string | null
+ monday?: boolean
name: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday?: boolean
+ skipHolidays?: boolean
+ sunday?: boolean
+ thursday?: boolean
+ tuesday?: boolean
updatedAt?: string | null
updatedBy?: string | null
+ wednesday?: boolean
workCenterId: string
}
Update: {
@@ -13620,13 +13636,21 @@ export type Database = {
description?: string | null
estimatedDuration?: number | null
frequency?: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday?: boolean
id?: string
lastGeneratedAt?: string | null
+ monday?: boolean
name?: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday?: boolean
+ skipHolidays?: boolean
+ sunday?: boolean
+ thursday?: boolean
+ tuesday?: boolean
updatedAt?: string | null
updatedBy?: string | null
+ wednesday?: boolean
workCenterId?: string
}
Relationships: [
@@ -43928,17 +43952,25 @@ export type Database = {
description: string | null
estimatedDuration: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"] | null
+ friday: boolean | null
id: string | null
lastGeneratedAt: string | null
locationId: string | null
locationName: string | null
+ monday: boolean | null
name: string | null
nextDueAt: string | null
priority:
| Database["public"]["Enums"]["maintenanceDispatchPriority"]
| null
+ saturday: boolean | null
+ skipHolidays: boolean | null
+ sunday: boolean | null
+ thursday: boolean | null
+ tuesday: boolean | null
updatedAt: string | null
updatedBy: string | null
+ wednesday: boolean | null
workCenterId: string | null
workCenterName: string | null
}
@@ -49513,14 +49545,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"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 6652e054f1..30d86c35e6 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -13586,13 +13586,21 @@ export type Database = {
description: string | null
estimatedDuration: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday: boolean
id: string
lastGeneratedAt: string | null
+ monday: boolean
name: string
nextDueAt: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday: boolean
+ skipHolidays: boolean
+ sunday: boolean
+ thursday: boolean
+ tuesday: boolean
updatedAt: string | null
updatedBy: string | null
+ wednesday: boolean
workCenterId: string
}
Insert: {
@@ -13603,13 +13611,21 @@ export type Database = {
description?: string | null
estimatedDuration?: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday?: boolean
id?: string
lastGeneratedAt?: string | null
+ monday?: boolean
name: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday?: boolean
+ skipHolidays?: boolean
+ sunday?: boolean
+ thursday?: boolean
+ tuesday?: boolean
updatedAt?: string | null
updatedBy?: string | null
+ wednesday?: boolean
workCenterId: string
}
Update: {
@@ -13620,13 +13636,21 @@ export type Database = {
description?: string | null
estimatedDuration?: number | null
frequency?: Database["public"]["Enums"]["maintenanceFrequency"]
+ friday?: boolean
id?: string
lastGeneratedAt?: string | null
+ monday?: boolean
name?: string
nextDueAt?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ saturday?: boolean
+ skipHolidays?: boolean
+ sunday?: boolean
+ thursday?: boolean
+ tuesday?: boolean
updatedAt?: string | null
updatedBy?: string | null
+ wednesday?: boolean
workCenterId?: string
}
Relationships: [
@@ -43928,17 +43952,25 @@ export type Database = {
description: string | null
estimatedDuration: number | null
frequency: Database["public"]["Enums"]["maintenanceFrequency"] | null
+ friday: boolean | null
id: string | null
lastGeneratedAt: string | null
locationId: string | null
locationName: string | null
+ monday: boolean | null
name: string | null
nextDueAt: string | null
priority:
| Database["public"]["Enums"]["maintenanceDispatchPriority"]
| null
+ saturday: boolean | null
+ skipHolidays: boolean | null
+ sunday: boolean | null
+ thursday: boolean | null
+ tuesday: boolean | null
updatedAt: string | null
updatedBy: string | null
+ wednesday: boolean | null
workCenterId: string | null
workCenterName: string | null
}
@@ -49513,14 +49545,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"]
diff --git a/packages/database/supabase/migrations/20251216021152_maintenance.sql b/packages/database/supabase/migrations/20251216021152_maintenance.sql
index b04cda2f26..21862c36d4 100644
--- a/packages/database/supabase/migrations/20251216021152_maintenance.sql
+++ b/packages/database/supabase/migrations/20251216021152_maintenance.sql
@@ -75,6 +75,10 @@ CREATE TABLE "maintenanceFailureMode" (
CONSTRAINT "maintenanceFailureMode_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
+CREATE INDEX IF NOT EXISTS "maintenanceFailureMode_companyId_idx" ON "maintenanceFailureMode" ("companyId");
+
+ALTER TABLE "maintenanceFailureMode" ENABLE ROW LEVEL SECURITY;
+
CREATE POLICY "SELECT" ON "public"."maintenanceFailureMode"
FOR SELECT USING (
"companyId" = ANY (
@@ -91,7 +95,7 @@ CREATE POLICY "INSERT" ON "maintenanceFailureMode"
"companyId" = ANY (
(
SELECT
- get_companies_with_employee_permission('production_create')
+ get_companies_with_employee_permission('resources_create')
)::text[]
)
);
@@ -101,7 +105,7 @@ CREATE POLICY "UPDATE" ON "maintenanceFailureMode"
"companyId" = ANY (
(
SELECT
- get_companies_with_employee_permission('production_update')
+ get_companies_with_employee_permission('resources_update')
)::text[]
)
);
@@ -111,7 +115,7 @@ CREATE POLICY "DELETE" ON "maintenanceFailureMode"
"companyId" = ANY (
(
SELECT
- get_companies_with_employee_permission('production_delete')
+ get_companies_with_employee_permission('resources_delete')
)::text[]
)
);
@@ -145,6 +149,49 @@ CREATE INDEX IF NOT EXISTS "maintenanceSchedule_workCenterId_idx" ON "maintenanc
CREATE INDEX IF NOT EXISTS "maintenanceSchedule_companyId_idx" ON "maintenanceSchedule" ("companyId");
CREATE INDEX IF NOT EXISTS "maintenanceSchedule_active_idx" ON "maintenanceSchedule" ("active");
+ALTER TABLE "maintenanceSchedule" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceSchedule"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_view')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceSchedule"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_create')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceSchedule"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceSchedule"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Maintenance schedule items (parts required for scheduled maintenance)
CREATE TABLE IF NOT EXISTS "maintenanceScheduleItem" (
"id" TEXT NOT NULL DEFAULT id(),
@@ -170,8 +217,51 @@ CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_maintenanceScheduleId_idx" O
CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_itemId_idx" ON "maintenanceScheduleItem" ("itemId");
CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_companyId_idx" ON "maintenanceScheduleItem" ("companyId");
+ALTER TABLE "maintenanceScheduleItem" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceScheduleItem"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceScheduleItem"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceScheduleItem"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceScheduleItem"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Main dispatch table
-CREATE TABLE "maintenanceDispatch" (
+CREATE TABLE IF NOT EXISTS "maintenanceDispatch" (
"id" TEXT NOT NULL DEFAULT id('main'),
"maintenanceDispatchId" TEXT NOT NULL,
"content" JSON NOT NULL DEFAULT '{}',
@@ -217,6 +307,49 @@ CREATE TABLE "maintenanceDispatch" (
CREATE INDEX "maintenanceDispatch_status_idx" ON "maintenanceDispatch" ("status");
CREATE INDEX "maintenanceDispatch_companyId_idx" ON "maintenanceDispatch" ("companyId");
+ALTER TABLE "maintenanceDispatch" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceDispatch"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceDispatch"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceDispatch"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceDispatch"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Time tracking events
CREATE TABLE "maintenanceDispatchEvent" (
"id" TEXT NOT NULL DEFAULT id(),
@@ -251,8 +384,51 @@ CREATE INDEX "maintenanceDispatchEvent_maintenanceDispatchId_idx" ON "maintenanc
CREATE INDEX "maintenanceDispatchEvent_employeeId_idx" ON "maintenanceDispatchEvent" ("employeeId");
CREATE INDEX "maintenanceDispatchEvent_companyId_idx" ON "maintenanceDispatchEvent" ("companyId");
+ALTER TABLE "maintenanceDispatchEvent" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchEvent"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceDispatchEvent"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceDispatchEvent"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceDispatchEvent"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Comments on dispatches
-CREATE TABLE "maintenanceDispatchComment" (
+CREATE TABLE IF NOT EXISTS "maintenanceDispatchComment" (
"id" TEXT NOT NULL DEFAULT id(),
"maintenanceDispatchId" TEXT NOT NULL,
"comment" TEXT NOT NULL,
@@ -271,6 +447,39 @@ CREATE TABLE "maintenanceDispatchComment" (
CREATE INDEX "maintenanceDispatchComment_maintenanceDispatchId_idx" ON "maintenanceDispatchComment" ("maintenanceDispatchId");
+ALTER TABLE "maintenanceDispatchComment" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchComment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceDispatchComment"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceDispatchComment"
+ FOR UPDATE USING (
+ "createdBy" = auth.uid()::text
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceDispatchComment"
+ FOR DELETE USING (
+ "createdBy" = auth.uid()::text
+ );
+
-- Work centers involved in dispatch
CREATE TABLE "maintenanceDispatchWorkCenter" (
"id" TEXT NOT NULL DEFAULT id(),
@@ -294,6 +503,50 @@ CREATE INDEX "maintenanceDispatchWorkCenter_maintenanceDispatchId_idx" ON "maint
CREATE INDEX "maintenanceDispatchWorkCenter_workCenterId_idx" ON "maintenanceDispatchWorkCenter" ("workCenterId");
CREATE INDEX "maintenanceDispatchWorkCenter_companyId_idx" ON "maintenanceDispatchWorkCenter" ("companyId");
+ALTER TABLE "maintenanceDispatchWorkCenter" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchWorkCenter"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceDispatchWorkCenter"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceDispatchWorkCenter"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceDispatchWorkCenter"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
+
-- Parts/materials consumed
CREATE TABLE "maintenanceDispatchItem" (
"id" TEXT NOT NULL DEFAULT id(),
@@ -321,6 +574,49 @@ CREATE INDEX "maintenanceDispatchItem_maintenanceDispatchId_idx" ON "maintenance
CREATE INDEX "maintenanceDispatchItem_itemId_idx" ON "maintenanceDispatchItem" ("itemId");
CREATE INDEX "maintenanceDispatchItem_companyId_idx" ON "maintenanceDispatchItem" ("companyId");
+ALTER TABLE "maintenanceDispatchItem" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."maintenanceDispatchItem"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "maintenanceDispatchItem"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_role()
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceDispatchItem"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceDispatchItem"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Standard replacement parts for work centers
CREATE TABLE "workCenterReplacementPart" (
"id" TEXT NOT NULL DEFAULT id(),
@@ -346,12 +642,55 @@ CREATE INDEX "workCenterReplacementPart_workCenterId_idx" ON "workCenterReplacem
CREATE INDEX "workCenterReplacementPart_itemId_idx" ON "workCenterReplacementPart" ("itemId");
CREATE INDEX "workCenterReplacementPart_companyId_idx" ON "workCenterReplacementPart" ("companyId");
+ALTER TABLE "workCenterReplacementPart" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."workCenterReplacementPart"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_view')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "workCenterReplacementPart"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_create')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "workCenterReplacementPart"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "workCenterReplacementPart"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('resources_delete')
+ )::text[]
+ )
+ );
+
-- Company settings for maintenance scheduling
ALTER TABLE "companySettings"
- ADD COLUMN IF NOT EXISTS "maintenanceGenerateInAdvance" BOOLEAN NOT NULL DEFAULT false;
+ ADD COLUMN IF NOT EXISTS "maintenanceGenerateInAdvance" BOOLEAN NOT NULL DEFAULT true;
ALTER TABLE "companySettings"
- ADD COLUMN IF NOT EXISTS "maintenanceAdvanceDays" INTEGER NOT NULL DEFAULT 7;
+ ADD COLUMN IF NOT EXISTS "maintenanceAdvanceDays" INTEGER NOT NULL DEFAULT 3;
-- salesRfq sequence for existing companies
INSERT INTO "sequence" (
diff --git a/packages/database/supabase/migrations/20251226000001_maintenance_schedule_days.sql b/packages/database/supabase/migrations/20251226000001_maintenance_schedule_days.sql
new file mode 100644
index 0000000000..c652329a98
--- /dev/null
+++ b/packages/database/supabase/migrations/20251226000001_maintenance_schedule_days.sql
@@ -0,0 +1,27 @@
+-- Add day-of-week columns to maintenanceSchedule for daily frequency
+-- These columns control which days of the week maintenance should run
+ALTER TABLE "maintenanceSchedule"
+ ADD COLUMN IF NOT EXISTS "monday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "tuesday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "wednesday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "thursday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "friday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "saturday" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN IF NOT EXISTS "sunday" BOOLEAN NOT NULL DEFAULT true;
+
+-- Add skipHolidays column to skip maintenance on company holidays
+ALTER TABLE "maintenanceSchedule"
+ ADD COLUMN IF NOT EXISTS "skipHolidays" BOOLEAN NOT NULL DEFAULT true;
+
+-- Update the maintenanceSchedules view to include new columns
+DROP VIEW IF EXISTS "maintenanceSchedules";
+
+CREATE OR REPLACE VIEW "maintenanceSchedules" AS
+SELECT
+ ms.*,
+ wc."locationId",
+ wc."name" AS "workCenterName",
+ l."name" AS "locationName"
+FROM "maintenanceSchedule" ms
+LEFT JOIN "workCenter" wc ON ms."workCenterId" = wc."id"
+LEFT JOIN "location" l ON wc."locationId" = l."id";
diff --git a/packages/jobs/trigger/dispatch.ts b/packages/jobs/trigger/dispatch.ts
new file mode 100644
index 0000000000..284f5f29ed
--- /dev/null
+++ b/packages/jobs/trigger/dispatch.ts
@@ -0,0 +1,330 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { NotificationEvent } from "@carbon/notifications";
+import { schedules } from "@trigger.dev/sdk";
+import { now, getLocalTimeZone } from "@internationalized/date";
+import { notifyTask } from "./notify.ts";
+
+const serviceRole = getCarbonServiceRole();
+
+// Day of week mapping (0 = Sunday, 1 = Monday, etc.)
+const dayOfWeekFields = [
+ "sunday",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday"
+] as const;
+
+interface MaintenanceSchedule {
+ id: string;
+ name: string;
+ frequency: string;
+ priority: string;
+ workCenterId: string;
+ nextDueAt: string | null;
+ skipHolidays: boolean;
+ monday: boolean;
+ tuesday: boolean;
+ wednesday: boolean;
+ thursday: boolean;
+ friday: boolean;
+ saturday: boolean;
+ sunday: boolean;
+}
+
+// Check if a date is enabled for the schedule based on day-of-week settings
+function isDayEnabledForSchedule(
+ schedule: MaintenanceSchedule,
+ targetDate: Date
+): boolean {
+ // Only check day-of-week for Daily frequency
+ if (schedule.frequency !== "Daily") {
+ return true;
+ }
+
+ const dayOfWeek = targetDate.getDay(); // 0 = Sunday, 1 = Monday, etc.
+ const dayField = dayOfWeekFields[dayOfWeek];
+ return schedule[dayField] === true;
+}
+
+// Check if a date is a holiday for the company
+async function isHoliday(companyId: string, date: Date): Promise<boolean> {
+ const dateString = date.toISOString().split("T")[0]; // YYYY-MM-DD format
+
+ const { data: holiday, error } = await serviceRole
+ .from("holiday")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("date", dateString)
+ .maybeSingle();
+
+ if (error) {
+ console.error(`Error checking holiday for ${dateString}: ${error.message}`);
+ return false;
+ }
+
+ return holiday !== null;
+}
+
+export const generateMaintenanceDispatches = schedules.task({
+ id: "dispatch",
+ // Run daily at 6 AM UTC
+ cron: "0 6 * * *",
+ run: async () => {
+ const currentDateTime = now(getLocalTimeZone());
+ console.log(
+ `🔧 Starting maintenance dispatch generation: ${currentDateTime.toString()}`
+ );
+
+ try {
+ // Get all companies with maintenanceGenerateInAdvance enabled
+ const { data: companiesWithSettings, error: settingsError } =
+ await serviceRole
+ .from("companySettings")
+ .select("id, maintenanceGenerateInAdvance, maintenanceAdvanceDays")
+ .eq("maintenanceGenerateInAdvance", true);
+
+ if (settingsError) {
+ console.error(
+ `Failed to fetch company settings: ${settingsError.message}`
+ );
+ return;
+ }
+
+ console.log(
+ `Found ${companiesWithSettings?.length || 0} companies with auto-generation enabled`
+ );
+
+ let totalDispatchesCreated = 0;
+
+ for (const settings of companiesWithSettings ?? []) {
+ const advanceDays = settings.maintenanceAdvanceDays ?? 7;
+ const futureDate = currentDateTime.add({ days: advanceDays });
+
+ // Get active schedules that are due
+ const { data: dueSchedules, error: schedulesError } = await serviceRole
+ .from("maintenanceSchedule")
+ .select("*")
+ .eq("companyId", settings.id)
+ .eq("active", true)
+ .or(`nextDueAt.is.null,nextDueAt.lte.${futureDate.toAbsoluteString()}`);
+
+ if (schedulesError) {
+ console.error(
+ `Failed to fetch schedules for company ${settings.id}: ${schedulesError.message}`
+ );
+ continue;
+ }
+
+ console.log(
+ `Company ${settings.id}: ${dueSchedules?.length || 0} schedules due`
+ );
+
+ for (const schedule of dueSchedules ?? []) {
+ try {
+ const typedSchedule = schedule as MaintenanceSchedule;
+
+ // Track current nextDueAt for this schedule (will be updated as we create dispatches)
+ let currentNextDueAt = typedSchedule.nextDueAt
+ ? new Date(typedSchedule.nextDueAt)
+ : new Date();
+
+ // Loop to create dispatches for all dates within the advance window
+ while (currentNextDueAt <= new Date(futureDate.toAbsoluteString())) {
+ const targetDate = currentNextDueAt;
+
+ // For Daily schedules, check if this day of week is enabled
+ if (!isDayEnabledForSchedule(typedSchedule, targetDate)) {
+ console.log(
+ `Skipping schedule "${typedSchedule.name}" for ${targetDate.toISOString().split("T")[0]} - day of week not enabled`
+ );
+ // Advance to next day for daily schedules
+ if (typedSchedule.frequency === "Daily") {
+ currentNextDueAt = new Date(currentNextDueAt);
+ currentNextDueAt.setDate(currentNextDueAt.getDate() + 1);
+ continue;
+ }
+ break;
+ }
+
+ // Check if this date is a holiday and skipHolidays is enabled
+ if (typedSchedule.skipHolidays) {
+ const isHolidayDate = await isHoliday(settings.id, targetDate);
+ if (isHolidayDate) {
+ console.log(
+ `Skipping schedule "${typedSchedule.name}" - ${targetDate.toISOString().split("T")[0]} is a holiday`
+ );
+ // Advance to next occurrence based on frequency
+ currentNextDueAt = new Date(currentNextDueAt);
+ switch (typedSchedule.frequency) {
+ case "Daily":
+ currentNextDueAt.setDate(currentNextDueAt.getDate() + 1);
+ break;
+ case "Weekly":
+ currentNextDueAt.setDate(currentNextDueAt.getDate() + 7);
+ break;
+ case "Monthly":
+ currentNextDueAt.setMonth(currentNextDueAt.getMonth() + 1);
+ break;
+ case "Quarterly":
+ currentNextDueAt.setMonth(currentNextDueAt.getMonth() + 3);
+ break;
+ case "Annual":
+ currentNextDueAt.setFullYear(currentNextDueAt.getFullYear() + 1);
+ break;
+ }
+ continue;
+ }
+ }
+
+ // Get next sequence number
+ const { data: sequenceData, error: sequenceError } =
+ await serviceRole.rpc("get_next_sequence", {
+ sequence_name: "maintenanceDispatch",
+ company_id: settings.id
+ });
+
+ if (sequenceError) {
+ console.error(
+ `Failed to get sequence for schedule ${schedule.id}: ${sequenceError.message}`
+ );
+ break;
+ }
+
+ // Create the dispatch
+ const { data: newDispatch, error: dispatchError } = await serviceRole
+ .from("maintenanceDispatch")
+ .insert({
+ maintenanceDispatchId: sequenceData,
+ status: "Open",
+ priority: schedule.priority,
+ source: "Scheduled",
+ severity: "Preventive",
+ oeeImpact: "Planned",
+ workCenterId: schedule.workCenterId,
+ maintenanceScheduleId: schedule.id,
+ plannedStartTime: targetDate.toISOString(),
+ companyId: settings.id,
+ createdBy: "system"
+ })
+ .select("id")
+ .single();
+
+ if (dispatchError) {
+ console.error(
+ `Failed to create dispatch for schedule ${schedule.id}: ${dispatchError.message}`
+ );
+ break;
+ }
+
+ // Copy items from schedule to dispatch
+ const { data: scheduleItems } = await serviceRole
+ .from("maintenanceScheduleItem")
+ .select("itemId, quantity, unitOfMeasureCode")
+ .eq("maintenanceScheduleId", schedule.id);
+
+ if (scheduleItems && scheduleItems.length > 0) {
+ await serviceRole.from("maintenanceDispatchItem").insert(
+ scheduleItems.map((item) => ({
+ maintenanceDispatchId: newDispatch.id,
+ itemId: item.itemId,
+ quantity: item.quantity,
+ unitOfMeasureCode: item.unitOfMeasureCode,
+ companyId: settings.id,
+ createdBy: "system"
+ }))
+ );
+ }
+
+ // Link work center
+ await serviceRole.from("maintenanceDispatchWorkCenter").insert({
+ maintenanceDispatchId: newDispatch.id,
+ workCenterId: schedule.workCenterId,
+ companyId: settings.id,
+ createdBy: "system"
+ });
+
+ totalDispatchesCreated++;
+ console.log(
+ `Created dispatch ${sequenceData} for schedule "${schedule.name}" on ${targetDate.toISOString().split("T")[0]}`
+ );
+
+ // Get employees assigned to this work center to notify them
+ const { data: workCenterEmployees } = await serviceRole
+ .from("workCenterEmployee")
+ .select("userId")
+ .eq("workCenterId", schedule.workCenterId);
+
+ if (workCenterEmployees && workCenterEmployees.length > 0) {
+ const userIds = workCenterEmployees.map((e) => e.userId);
+ await notifyTask.trigger({
+ event: NotificationEvent.MaintenanceDispatchCreated,
+ companyId: settings.id,
+ documentId: newDispatch.id,
+ recipient: {
+ type: "users",
+ userIds
+ }
+ });
+ console.log(
+ `Notified ${userIds.length} work center employees about dispatch ${sequenceData}`
+ );
+ }
+
+ // Calculate next due date based on frequency
+ currentNextDueAt = new Date(currentNextDueAt);
+ switch (schedule.frequency) {
+ case "Daily":
+ currentNextDueAt.setDate(currentNextDueAt.getDate() + 1);
+ break;
+ case "Weekly":
+ currentNextDueAt.setDate(currentNextDueAt.getDate() + 7);
+ break;
+ case "Monthly":
+ currentNextDueAt.setMonth(currentNextDueAt.getMonth() + 1);
+ break;
+ case "Quarterly":
+ currentNextDueAt.setMonth(currentNextDueAt.getMonth() + 3);
+ break;
+ case "Annual":
+ currentNextDueAt.setFullYear(currentNextDueAt.getFullYear() + 1);
+ break;
+ }
+ }
+
+ // Update schedule's lastGeneratedAt and nextDueAt after processing all dates
+ await serviceRole
+ .from("maintenanceSchedule")
+ .update({
+ lastGeneratedAt: currentDateTime.toAbsoluteString(),
+ nextDueAt: currentNextDueAt.toISOString()
+ })
+ .eq("id", schedule.id);
+
+ } catch (err) {
+ console.error(
+ `Error processing schedule ${schedule.id}: ${
+ err instanceof Error ? err.message : String(err)
+ }`
+ );
+ }
+ }
+ }
+
+ console.log(
+ `🔧 Maintenance dispatch generation completed: ${totalDispatchesCreated} dispatches created`
+ );
+
+ return { dispatchesCreated: totalDispatchesCreated };
+ } catch (error) {
+ console.error(
+ `Unexpected error in maintenance generation: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ throw error;
+ }
+ }
+});
diff --git a/packages/jobs/trigger/maintenance.ts b/packages/jobs/trigger/maintenance.ts
deleted file mode 100644
index 4799a2221b..0000000000
--- a/packages/jobs/trigger/maintenance.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { getCarbonServiceRole } from "@carbon/auth";
-import { NotificationEvent } from "@carbon/notifications";
-import { schedules } from "@trigger.dev/sdk";
-import { notifyTask } from "./notify.ts";
-
-const serviceRole = getCarbonServiceRole();
-
-export const generateMaintenanceDispatches = schedules.task({
- id: "generate-maintenance-dispatches",
- // Run daily at 6 AM UTC
- cron: "0 6 * * *",
- run: async () => {
- console.log(
- `🔧 Starting maintenance dispatch generation: ${new Date().toISOString()}`
- );
-
- try {
- // Get all companies with maintenanceGenerateInAdvance enabled
- const { data: companiesWithSettings, error: settingsError } =
- await serviceRole
- .from("companySettings")
- .select("companyId, maintenanceGenerateInAdvance, maintenanceAdvanceDays")
- .eq("maintenanceGenerateInAdvance", true);
-
- if (settingsError) {
- console.error(
- `Failed to fetch company settings: ${settingsError.message}`
- );
- return;
- }
-
- console.log(
- `Found ${companiesWithSettings?.length || 0} companies with auto-generation enabled`
- );
-
- let totalDispatchesCreated = 0;
-
- for (const settings of companiesWithSettings ?? []) {
- const advanceDays = settings.maintenanceAdvanceDays ?? 7;
- const futureDate = new Date();
- futureDate.setDate(futureDate.getDate() + advanceDays);
-
- // Get active schedules that are due
- const { data: dueSchedules, error: schedulesError } = await serviceRole
- .from("maintenanceSchedule")
- .select("*")
- .eq("companyId", settings.companyId)
- .eq("active", true)
- .or(`nextDueAt.is.null,nextDueAt.lte.${futureDate.toISOString()}`);
-
- if (schedulesError) {
- console.error(
- `Failed to fetch schedules for company ${settings.companyId}: ${schedulesError.message}`
- );
- continue;
- }
-
- console.log(
- `Company ${settings.companyId}: ${dueSchedules?.length || 0} schedules due`
- );
-
- for (const schedule of dueSchedules ?? []) {
- try {
- // Get next sequence number
- const { data: sequenceData, error: sequenceError } =
- await serviceRole.rpc("get_next_sequence", {
- sequence_name: "maintenanceDispatch",
- company_id: settings.companyId
- });
-
- if (sequenceError) {
- console.error(
- `Failed to get sequence for schedule ${schedule.id}: ${sequenceError.message}`
- );
- continue;
- }
-
- // Create the dispatch
- const { data: newDispatch, error: dispatchError } = await serviceRole
- .from("maintenanceDispatch")
- .insert({
- maintenanceDispatchId: sequenceData,
- status: "Open",
- priority: schedule.priority,
- source: "Scheduled",
- severity: "Preventive",
- oeeImpact: "Planned",
- workCenterId: schedule.workCenterId,
- maintenanceScheduleId: schedule.id,
- plannedStartTime: schedule.nextDueAt || new Date().toISOString(),
- companyId: settings.companyId,
- createdBy: "system"
- })
- .select("id")
- .single();
-
- if (dispatchError) {
- console.error(
- `Failed to create dispatch for schedule ${schedule.id}: ${dispatchError.message}`
- );
- continue;
- }
-
- // Copy items from schedule to dispatch
- const { data: scheduleItems } = await serviceRole
- .from("maintenanceScheduleItem")
- .select("itemId, quantity, unitOfMeasureCode")
- .eq("maintenanceScheduleId", schedule.id);
-
- if (scheduleItems && scheduleItems.length > 0) {
- await serviceRole.from("maintenanceDispatchItem").insert(
- scheduleItems.map((item) => ({
- maintenanceDispatchId: newDispatch.id,
- itemId: item.itemId,
- quantity: item.quantity,
- unitOfMeasureCode: item.unitOfMeasureCode,
- companyId: settings.companyId,
- createdBy: "system"
- }))
- );
- }
-
- // Link work center
- await serviceRole.from("maintenanceDispatchWorkCenter").insert({
- maintenanceDispatchId: newDispatch.id,
- workCenterId: schedule.workCenterId,
- companyId: settings.companyId,
- createdBy: "system"
- });
-
- // Calculate next due date based on frequency
- let nextDueAt = new Date(schedule.nextDueAt || new Date());
- switch (schedule.frequency) {
- case "Daily":
- nextDueAt.setDate(nextDueAt.getDate() + 1);
- break;
- case "Weekly":
- nextDueAt.setDate(nextDueAt.getDate() + 7);
- break;
- case "Monthly":
- nextDueAt.setMonth(nextDueAt.getMonth() + 1);
- break;
- case "Quarterly":
- nextDueAt.setMonth(nextDueAt.getMonth() + 3);
- break;
- case "Annual":
- nextDueAt.setFullYear(nextDueAt.getFullYear() + 1);
- break;
- }
-
- // Update schedule's lastGeneratedAt and nextDueAt
- await serviceRole
- .from("maintenanceSchedule")
- .update({
- lastGeneratedAt: new Date().toISOString(),
- nextDueAt: nextDueAt.toISOString()
- })
- .eq("id", schedule.id);
-
- totalDispatchesCreated++;
- console.log(
- `Created dispatch ${sequenceData} for schedule "${schedule.name}"`
- );
-
- // Get employees assigned to this work center to notify them
- const { data: workCenterEmployees } = await serviceRole
- .from("workCenterEmployee")
- .select("userId")
- .eq("workCenterId", schedule.workCenterId);
-
- if (workCenterEmployees && workCenterEmployees.length > 0) {
- const userIds = workCenterEmployees.map((e) => e.userId);
- await notifyTask.trigger({
- event: NotificationEvent.MaintenanceDispatchCreated,
- companyId: settings.companyId,
- documentId: newDispatch.id,
- recipient: {
- type: "users",
- userIds
- }
- });
- console.log(
- `Notified ${userIds.length} work center employees about dispatch ${sequenceData}`
- );
- }
- } catch (err) {
- console.error(
- `Error processing schedule ${schedule.id}: ${
- err instanceof Error ? err.message : String(err)
- }`
- );
- }
- }
- }
-
- console.log(
- `🔧 Maintenance dispatch generation completed: ${totalDispatchesCreated} dispatches created`
- );
-
- return { dispatchesCreated: totalDispatchesCreated };
- } catch (error) {
- console.error(
- `Unexpected error in maintenance generation: ${
- error instanceof Error ? error.message : String(error)
- }`
- );
- throw error;
- }
- }
-});