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 crud for failure modes

Brad Barbind1dcd8798ef0
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index a2a125d2bd..9ac4bfcf2c 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -56,6 +56,42 @@ export const jobOperationStatus = [
"Canceled"
] as const;
+export const maintenanceDispatchPriority = [
+ "Low",
+ "Medium",
+ "High",
+ "Critical"
+] as const;
+
+export const maintenanceDispatchStatus = [
+ "Open",
+ "Assigned",
+ "In Progress",
+ "Completed",
+ "Cancelled"
+] as const;
+
+export const maintenanceFrequency = [
+ "Daily",
+ "Weekly",
+ "Monthly",
+ "Quarterly",
+ "Annual"
+] as const;
+
+export const maintenanceSeverity = [
+ "Preventive",
+ "OPM",
+ "Maintenance Required",
+ "OEM Required"
+] as const;
+
+export const maintenanceSource = [
+ "scheduled",
+ "reactive",
+ "non-conformance"
+] as const;
+
export const procedureStatus = ["Draft", "Active", "Archived"] as const;
const baseJobValidator = z.object({
@@ -848,6 +884,95 @@ export const scrapReasonValidator = z.object({
name: z.string().min(1, { message: "Name is required" })
});
+export const failureModeValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" })
+});
+
+export const maintenanceDispatchValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ status: z.enum(maintenanceDispatchStatus),
+ priority: z.enum(maintenanceDispatchPriority),
+ severity: z.enum(maintenanceSeverity).optional(),
+ source: z.enum(maintenanceSource).optional(),
+ suspectedFailureModeId: zfd.text(z.string().optional()),
+ actualFailureModeId: zfd.text(z.string().optional()),
+ plannedStartTime: zfd.text(z.string().optional()),
+ plannedEndTime: zfd.text(z.string().optional()),
+ assignee: zfd.text(z.string().optional()),
+ nonConformanceId: zfd.text(z.string().optional()),
+ isFailure: z.boolean().optional()
+});
+
+export const maintenanceDispatchCommentValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ maintenanceDispatchId: z.string().min(1, { message: "Dispatch is required" }),
+ comment: z.string().min(1, { message: "Comment is required" })
+});
+
+export const maintenanceDispatchEventValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ maintenanceDispatchId: z
+ .string()
+ .min(1, { message: "Dispatch is required" }),
+ employeeId: z.string().min(1, { message: "Employee is required" }),
+ workCenterId: z.string().min(1, { message: "Work center is required" }),
+ startTime: z.string().min(1, { message: "Start time is required" }),
+ endTime: zfd.text(z.string().optional()),
+ notes: zfd.text(z.string().optional())
+ })
+ .refine(
+ (data) => {
+ if (data.endTime) {
+ return new Date(data.startTime) < new Date(data.endTime);
+ }
+ return true;
+ },
+ {
+ message: "Start time must be before end time",
+ path: ["endTime"]
+ }
+ );
+
+export const maintenanceDispatchItemValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ maintenanceDispatchId: z.string().min(1, { message: "Dispatch is required" }),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ quantity: zfd.numeric(z.number().min(1)),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of measure is required" }),
+ unitCost: zfd.numeric(z.number().min(0).optional())
+});
+
+export const maintenanceDispatchWorkCenterValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ maintenanceDispatchId: z.string().min(1, { message: "Dispatch is required" }),
+ workCenterId: z.string().min(1, { message: "Work center is required" })
+});
+
+export const maintenanceScheduleValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: zfd.text(z.string().optional()),
+ workCenterId: z.string().min(1, { message: "Work center is required" }),
+ frequency: z.enum(maintenanceFrequency),
+ priority: z.enum(maintenanceDispatchPriority),
+ estimatedDuration: zfd.numeric(z.number().optional()),
+ active: z.boolean().default(true)
+});
+
+export const maintenanceScheduleItemValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ maintenanceScheduleId: z.string().min(1, { message: "Schedule is required" }),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ quantity: zfd.numeric(z.number().min(1)),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of measure is required" })
+});
+
export const demandProjectionValidator = z.object({
itemId: z.string().min(1, { message: "Item is required" }),
locationId: z.string().min(1, { message: "Location is required" }),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6793edca0d..665dcb5eb5 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -21,11 +21,19 @@ import type {
} from "../shared";
import type {
deadlineTypes,
+ failureModeValidator,
jobMaterialValidator,
jobOperationStatus,
jobOperationValidator,
jobStatus,
jobValidator,
+ maintenanceDispatchCommentValidator,
+ maintenanceDispatchEventValidator,
+ maintenanceDispatchItemValidator,
+ maintenanceDispatchValidator,
+ maintenanceDispatchWorkCenterValidator,
+ maintenanceScheduleItemValidator,
+ maintenanceScheduleValidator,
procedureParameterValidator,
procedureStepValidator,
procedureValidator,
@@ -612,6 +620,65 @@ export async function deleteScrapReason(
return client.from("scrapReason").delete().eq("id", scrapReasonId);
}
+export async function deleteFailureMode(
+ client: SupabaseClient<Database>,
+ failureModeId: string
+) {
+ return client.from("maintenanceFailureMode").delete().eq("id", failureModeId);
+}
+
+export async function deleteMaintenanceDispatch(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client.from("maintenanceDispatch").delete().eq("id", dispatchId);
+}
+
+export async function deleteMaintenanceDispatchComment(
+ client: SupabaseClient<Database>,
+ commentId: string
+) {
+ return client.from("maintenanceDispatchComment").delete().eq("id", commentId);
+}
+
+export async function deleteMaintenanceDispatchEvent(
+ client: SupabaseClient<Database>,
+ eventId: string
+) {
+ return client.from("maintenanceDispatchEvent").delete().eq("id", eventId);
+}
+
+export async function deleteMaintenanceDispatchItem(
+ client: SupabaseClient<Database>,
+ itemId: string
+) {
+ return client.from("maintenanceDispatchItem").delete().eq("id", itemId);
+}
+
+export async function deleteMaintenanceDispatchWorkCenter(
+ client: SupabaseClient<Database>,
+ workCenterId: string
+) {
+ return client
+ .from("maintenanceDispatchWorkCenter")
+ .delete()
+ .eq("id", workCenterId);
+}
+
+export async function deleteMaintenanceSchedule(
+ client: SupabaseClient<Database>,
+ scheduleId: string
+) {
+ return client.from("maintenanceSchedule").delete().eq("id", scheduleId);
+}
+
+export async function deleteMaintenanceScheduleItem(
+ client: SupabaseClient<Database>,
+ itemId: string
+) {
+ return client.from("maintenanceScheduleItem").delete().eq("id", itemId);
+}
+
export async function getDemandForecasts(
client: SupabaseClient<Database>,
params: {
@@ -1448,6 +1515,210 @@ export async function getScrapReasons(
return query;
}
+export async function getFailureMode(
+ client: SupabaseClient<Database>,
+ failureModeId: string
+) {
+ return client
+ .from("maintenanceFailureMode")
+ .select("*")
+ .eq("id", failureModeId)
+ .single();
+}
+
+export async function getFailureModes(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+) {
+ let query = client
+ .from("maintenanceFailureMode")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true }
+ ]);
+ }
+
+ return query;
+}
+
+export async function getFailureModesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("maintenanceFailureMode")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name");
+}
+
+export async function getMaintenanceDispatch(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client
+ .from("maintenanceDispatch")
+ .select(
+ `*,
+ assignee:user!maintenanceDispatch_assignee_fkey(id, fullName, avatarUrl),
+ suspectedFailureMode:maintenanceFailureMode!maintenanceDispatch_suspectedFailureModeId_fkey(id, name),
+ actualFailureMode:maintenanceFailureMode!maintenanceDispatch_actualFailureModeId_fkey(id, name),
+ schedule:maintenanceSchedule(id, name)`
+ )
+ .eq("id", dispatchId)
+ .single();
+}
+
+export async function getMaintenanceDispatches(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null; status?: string }
+) {
+ let query = client
+ .from("maintenanceDispatch")
+ .select(
+ `id, status, priority, severity, source, isFailure,
+ plannedStartTime, plannedEndTime, actualStartTime, actualEndTime, duration,
+ assignee:user!maintenanceDispatch_assignee_fkey(id, fullName, avatarUrl),
+ createdAt`,
+ { count: "exact" }
+ )
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("id", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "createdAt", ascending: false }
+ ]);
+ }
+
+ return query;
+}
+
+export async function getMaintenanceDispatchComments(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client
+ .from("maintenanceDispatchComment")
+ .select(
+ `id, comment, createdAt,
+ createdBy:user!maintenanceDispatchComment_createdBy_fkey(id, fullName, avatarUrl)`
+ )
+ .eq("maintenanceDispatchId", dispatchId)
+ .order("createdAt", { ascending: false });
+}
+
+export async function getMaintenanceDispatchEvents(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client
+ .from("maintenanceDispatchEvent")
+ .select(
+ `id, startTime, endTime, duration, notes,
+ employee:user!maintenanceDispatchEvent_employeeId_fkey(id, fullName, avatarUrl),
+ workCenter:workCenter!maintenanceDispatchEvent_workCenterId_fkey(id, name)`
+ )
+ .eq("maintenanceDispatchId", dispatchId)
+ .order("startTime", { ascending: false });
+}
+
+export async function getMaintenanceDispatchItems(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client
+ .from("maintenanceDispatchItem")
+ .select(
+ `id, quantity, unitOfMeasureCode, unitCost, totalCost,
+ item:item!maintenanceDispatchItem_itemId_fkey(id, name)`
+ )
+ .eq("maintenanceDispatchId", dispatchId);
+}
+
+export async function getMaintenanceDispatchWorkCenters(
+ client: SupabaseClient<Database>,
+ dispatchId: string
+) {
+ return client
+ .from("maintenanceDispatchWorkCenter")
+ .select(
+ `id,
+ workCenter:workCenter!maintenanceDispatchWorkCenter_workCenterId_fkey(id, name)`
+ )
+ .eq("maintenanceDispatchId", dispatchId);
+}
+
+export async function getMaintenanceSchedule(
+ client: SupabaseClient<Database>,
+ scheduleId: string
+) {
+ return client
+ .from("maintenanceSchedule")
+ .select(
+ `*,
+ workCenter:workCenter!maintenanceSchedule_workCenterId_fkey(id, name)`
+ )
+ .eq("id", scheduleId)
+ .single();
+}
+
+export async function getMaintenanceSchedules(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null; active?: boolean }
+) {
+ let query = client
+ .from("maintenanceSchedule")
+ .select(
+ `id, name, frequency, priority, estimatedDuration, active, nextDueAt, lastGeneratedAt,
+ workCenter:workCenter!maintenanceSchedule_workCenterId_fkey(id, name)`,
+ { count: "exact" }
+ )
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args?.active !== undefined) {
+ query = query.eq("active", args.active);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true }
+ ]);
+ }
+
+ return query;
+}
+
+export async function getMaintenanceScheduleItems(
+ client: SupabaseClient<Database>,
+ scheduleId: string
+) {
+ return client
+ .from("maintenanceScheduleItem")
+ .select(
+ `id, quantity, unitOfMeasureCode,
+ item:item!maintenanceScheduleItem_itemId_fkey(id, name)`
+ )
+ .eq("maintenanceScheduleId", scheduleId);
+}
+
export async function getTrackedEntityByJobId(
client: SupabaseClient<Database>,
jobId: string
@@ -2342,6 +2613,217 @@ export async function upsertScrapReason(
}
}
+export async function upsertFailureMode(
+ client: SupabaseClient<Database>,
+ failureMode:
+ | (Omit<z.infer<typeof failureModeValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof failureModeValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in failureMode) {
+ return client
+ .from("maintenanceFailureMode")
+ .insert([failureMode])
+ .select("id");
+ } else {
+ return client
+ .from("maintenanceFailureMode")
+ .update(sanitize(failureMode))
+ .eq("id", failureMode.id);
+ }
+}
+
+export async function upsertMaintenanceDispatch(
+ client: SupabaseClient<Database>,
+ dispatch:
+ | (Omit<z.infer<typeof maintenanceDispatchValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ content?: Json;
+ })
+ | (Omit<z.infer<typeof maintenanceDispatchValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ content?: Json;
+ })
+) {
+ if ("createdBy" in dispatch) {
+ return client
+ .from("maintenanceDispatch")
+ .insert([dispatch])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceDispatch")
+ .update(sanitize(dispatch))
+ .eq("id", dispatch.id);
+ }
+}
+
+export async function upsertMaintenanceDispatchComment(
+ client: SupabaseClient<Database>,
+ comment:
+ | (Omit<z.infer<typeof maintenanceDispatchCommentValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceDispatchCommentValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in comment) {
+ return client
+ .from("maintenanceDispatchComment")
+ .insert([comment])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceDispatchComment")
+ .update(sanitize(comment))
+ .eq("id", comment.id);
+ }
+}
+
+export async function upsertMaintenanceDispatchEvent(
+ client: SupabaseClient<Database>,
+ event:
+ | (Omit<z.infer<typeof maintenanceDispatchEventValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceDispatchEventValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in event) {
+ return client
+ .from("maintenanceDispatchEvent")
+ .insert([event])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceDispatchEvent")
+ .update(sanitize(event))
+ .eq("id", event.id);
+ }
+}
+
+export async function upsertMaintenanceDispatchItem(
+ client: SupabaseClient<Database>,
+ item:
+ | (Omit<z.infer<typeof maintenanceDispatchItemValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceDispatchItemValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in item) {
+ return client
+ .from("maintenanceDispatchItem")
+ .insert([item])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceDispatchItem")
+ .update(sanitize(item))
+ .eq("id", item.id);
+ }
+}
+
+export async function upsertMaintenanceDispatchWorkCenter(
+ client: SupabaseClient<Database>,
+ workCenter:
+ | (Omit<z.infer<typeof maintenanceDispatchWorkCenterValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceDispatchWorkCenterValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in workCenter) {
+ return client
+ .from("maintenanceDispatchWorkCenter")
+ .insert([workCenter])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceDispatchWorkCenter")
+ .update(sanitize(workCenter))
+ .eq("id", workCenter.id);
+ }
+}
+
+export async function upsertMaintenanceSchedule(
+ client: SupabaseClient<Database>,
+ schedule:
+ | (Omit<z.infer<typeof maintenanceScheduleValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceScheduleValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in schedule) {
+ return client
+ .from("maintenanceSchedule")
+ .insert([schedule])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceSchedule")
+ .update(sanitize(schedule))
+ .eq("id", schedule.id);
+ }
+}
+
+export async function upsertMaintenanceScheduleItem(
+ client: SupabaseClient<Database>,
+ item:
+ | (Omit<z.infer<typeof maintenanceScheduleItemValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof maintenanceScheduleItemValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in item) {
+ return client
+ .from("maintenanceScheduleItem")
+ .insert([item])
+ .select("id")
+ .single();
+ } else {
+ return client
+ .from("maintenanceScheduleItem")
+ .update(sanitize(item))
+ .eq("id", item.id);
+ }
+}
+
export async function upsertDemandForecasts(
client: SupabaseClient<Database>,
forecasts: Array<{
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index 2f5945a2c9..f917502d18 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -1,11 +1,22 @@
import type {
getActiveProductionEvents,
+ getFailureMode,
+ getFailureModes,
getJob,
getJobMakeMethodById,
getJobMaterialsWithQuantityOnHand,
getJobMethodTree,
getJobOperations,
getJobPurchaseOrderLines,
+ getMaintenanceDispatch,
+ getMaintenanceDispatchComments,
+ getMaintenanceDispatchEvents,
+ getMaintenanceDispatches,
+ getMaintenanceDispatchItems,
+ getMaintenanceDispatchWorkCenters,
+ getMaintenanceSchedule,
+ getMaintenanceScheduleItems,
+ getMaintenanceSchedules,
getProcedure,
getProcedureParameters,
getProcedureSteps,
@@ -25,6 +36,50 @@ export type DemandProjection = NonNullable<
Awaited<ReturnType<typeof getProductionProjections>>["data"]
>[number];
+export type FailureMode = NonNullable<
+ Awaited<ReturnType<typeof getFailureModes>>["data"]
+>[number];
+
+export type FailureModeDetail = NonNullable<
+ Awaited<ReturnType<typeof getFailureMode>>["data"]
+>;
+
+export type MaintenanceDispatch = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatches>>["data"]
+>[number];
+
+export type MaintenanceDispatchDetail = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatch>>["data"]
+>;
+
+export type MaintenanceDispatchComment = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatchComments>>["data"]
+>[number];
+
+export type MaintenanceDispatchEvent = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatchEvents>>["data"]
+>[number];
+
+export type MaintenanceDispatchItem = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatchItems>>["data"]
+>[number];
+
+export type MaintenanceDispatchWorkCenter = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceDispatchWorkCenters>>["data"]
+>[number];
+
+export type MaintenanceSchedule = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceSchedules>>["data"]
+>[number];
+
+export type MaintenanceScheduleDetail = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceSchedule>>["data"]
+>;
+
+export type MaintenanceScheduleItem = NonNullable<
+ Awaited<ReturnType<typeof getMaintenanceScheduleItems>>["data"]
+>[number];
+
export type Job = NonNullable<Awaited<ReturnType<typeof getJob>>["data"]>;
export type JobMakeMethod = NonNullable<
diff --git a/apps/erp/app/modules/production/ui/FailureModes/FailureModeForm.tsx b/apps/erp/app/modules/production/ui/FailureModes/FailureModeForm.tsx
new file mode 100644
index 0000000000..f73545b126
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/FailureModes/FailureModeForm.tsx
@@ -0,0 +1,107 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ toast,
+ VStack
+} from "@carbon/react";
+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 { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { failureModeValidator } from "../../production.models";
+
+type FailureModeFormProps = {
+ initialValues: z.infer<typeof failureModeValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: () => void;
+};
+
+const FailureModeForm = ({
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose
+}: FailureModeFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created failure mode`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create failure mode: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "production")
+ : !permissions.can("create", "production");
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={failureModeValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.failureMode(initialValues.id!)
+ : path.to.newFailureMode
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Failure Mode
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <VStack spacing={4}>
+ <Input name="name" label="Failure Mode" />
+ <CustomFormFields table="maintenanceFailureMode" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default FailureModeForm;
diff --git a/apps/erp/app/modules/production/ui/FailureModes/FailureModesTable.tsx b/apps/erp/app/modules/production/ui/FailureModes/FailureModesTable.tsx
new file mode 100644
index 0000000000..88318e4bca
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/FailureModes/FailureModesTable.tsx
@@ -0,0 +1,89 @@
+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 { 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 type { FailureMode } from "../../types";
+
+type FailureModesTableProps = {
+ data: FailureMode[];
+ count: number;
+};
+
+const FailureModesTable = memo(({ data, count }: FailureModesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const customColumns = useCustomColumns<FailureMode>("maintenanceFailureMode");
+ const columns = useMemo<ColumnDef<FailureMode>[]>(() => {
+ const defaultColumns: ColumnDef<FailureMode>[] = [
+ {
+ accessorKey: "name",
+ header: "Failure Mode",
+ cell: ({ row }) => (
+ <Hyperlink to={row.original.id}>
+ <Enumerable value={row.original.name} />
+ </Hyperlink>
+ )
+ }
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [customColumns]);
+
+ const renderContextMenu = useCallback(
+ (row: FailureMode) => {
+ return (
+ <>
+ <MenuItem
+ onClick={() => {
+ navigate(`${path.to.failureMode(row.id)}?${params.toString()}`);
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Failure Mode
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "production")}
+ onClick={() => {
+ navigate(
+ `${path.to.deleteFailureMode(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Failure Mode
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<FailureMode>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "production") && (
+ <New
+ label="Failure Mode"
+ to={`${path.to.newFailureMode}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Failure Modes"
+ />
+ );
+});
+
+FailureModesTable.displayName = "FailureModesTable";
+export default FailureModesTable;
diff --git a/apps/erp/app/modules/production/ui/FailureModes/index.ts b/apps/erp/app/modules/production/ui/FailureModes/index.ts
new file mode 100644
index 0000000000..bad33e9fc7
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/FailureModes/index.ts
@@ -0,0 +1,2 @@
+export { default as FailureModeForm } from "./FailureModeForm";
+export { default as FailureModesTable } from "./FailureModesTable";
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx
new file mode 100644
index 0000000000..0b0f53095e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchHeader.tsx
@@ -0,0 +1,169 @@
+import {
+ Button,
+ Copy,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Heading,
+ HStack,
+ IconButton,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+import {
+ LuCircleCheck,
+ LuCirclePlay,
+ LuEllipsisVertical,
+ LuLoaderCircle,
+ LuTrash
+} from "react-icons/lu";
+import { Link, useFetcher, useParams } from "react-router";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { usePermissions, useRouteData } from "~/hooks";
+import { path } from "~/utils/path";
+import type { MaintenanceDispatchDetail } from "../../types";
+import MaintenanceStatus from "./MaintenanceStatus";
+
+const MaintenanceDispatchHeader = () => {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const routeData = useRouteData<{
+ dispatch: MaintenanceDispatchDetail;
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const status = routeData?.dispatch?.status;
+ const permissions = usePermissions();
+ const statusFetcher = useFetcher<{}>();
+ const deleteModal = useDisclosure();
+
+ return (
+ <>
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
+ <VStack spacing={0}>
+ <HStack>
+ <Link to={path.to.maintenanceDispatch(dispatchId)}>
+ <Heading size="h4" className="flex items-center gap-2">
+ <span>{routeData?.dispatch?.id}</span>
+ </Heading>
+ </Link>
+ <MaintenanceStatus status={status} />
+ <Copy text={routeData?.dispatch?.id ?? ""} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ destructive
+ disabled={
+ !permissions.can("delete", "production") ||
+ !permissions.is("employee")
+ }
+ onClick={deleteModal.onOpen}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Dispatch
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ </VStack>
+
+ <HStack>
+ <statusFetcher.Form
+ method="post"
+ action={path.to.maintenanceDispatchProperties(dispatchId)}
+ >
+ <input type="hidden" name="status" value="In Progress" />
+ <Button
+ type="submit"
+ leftIcon={<LuCirclePlay />}
+ variant={
+ status === "Open" || status === "Assigned"
+ ? "primary"
+ : "secondary"
+ }
+ isDisabled={
+ !["Open", "Assigned"].includes(status ?? "") ||
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "production")
+ }
+ isLoading={
+ statusFetcher.state !== "idle" &&
+ statusFetcher.formData?.get("status") === "In Progress"
+ }
+ >
+ Start
+ </Button>
+ </statusFetcher.Form>
+
+ <statusFetcher.Form
+ method="post"
+ action={path.to.maintenanceDispatchProperties(dispatchId)}
+ >
+ <input type="hidden" name="status" value="Completed" />
+ <Button
+ type="submit"
+ leftIcon={<LuCircleCheck />}
+ variant={status === "In Progress" ? "primary" : "secondary"}
+ isDisabled={
+ status !== "In Progress" ||
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "production")
+ }
+ isLoading={
+ statusFetcher.state !== "idle" &&
+ statusFetcher.formData?.get("status") === "Completed"
+ }
+ >
+ Complete
+ </Button>
+ </statusFetcher.Form>
+
+ <statusFetcher.Form
+ method="post"
+ action={path.to.maintenanceDispatchProperties(dispatchId)}
+ >
+ <input type="hidden" name="status" value="Open" />
+ <Button
+ type="submit"
+ leftIcon={<LuLoaderCircle />}
+ variant={status === "Completed" ? "primary" : "secondary"}
+ isDisabled={
+ !["In Progress", "Completed"].includes(status ?? "") ||
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "production")
+ }
+ >
+ Reopen
+ </Button>
+ </statusFetcher.Form>
+ </HStack>
+ </div>
+ {deleteModal.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteMaintenanceDispatch(dispatchId)}
+ isOpen={deleteModal.isOpen}
+ name={routeData?.dispatch?.id!}
+ text={`Are you sure you want to delete this maintenance dispatch? This cannot be undone.`}
+ onCancel={() => {
+ deleteModal.onClose();
+ }}
+ onSubmit={() => {
+ deleteModal.onClose();
+ }}
+ />
+ )}
+ </>
+ );
+};
+
+export default MaintenanceDispatchHeader;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx
new file mode 100644
index 0000000000..8b3371d1c5
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchProperties.tsx
@@ -0,0 +1,310 @@
+import { Select, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ toast,
+ VStack
+} from "@carbon/react";
+import { useCallback, useEffect } from "react";
+import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
+import { useFetcher, useParams } from "react-router";
+import { z } from "zod/v3";
+import {
+ Assignee,
+ EmployeeAvatar,
+ useOptimisticAssignment
+} from "~/components";
+import { usePermissions, useRouteData } from "~/hooks";
+import { path } from "~/utils/path";
+import { copyToClipboard } from "~/utils/string";
+import {
+ maintenanceDispatchPriority,
+ maintenanceSeverity,
+ maintenanceSource
+} from "../../production.models";
+import type { MaintenanceDispatchDetail } from "../../types";
+import MaintenancePriority from "./MaintenancePriority";
+
+const MaintenanceDispatchProperties = () => {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const permissions = usePermissions();
+
+ const routeData = useRouteData<{
+ dispatch: MaintenanceDispatchDetail;
+ failureModes: { id: string; name: string }[];
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const optimisticAssignment = useOptimisticAssignment({
+ id: dispatchId,
+ table: "maintenanceDispatch"
+ });
+ const assignee =
+ optimisticAssignment !== undefined
+ ? optimisticAssignment
+ : routeData?.dispatch?.assignee;
+
+ const fetcher = useFetcher<{ error?: { message: string } }>();
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error.message);
+ }
+ }, [fetcher.data]);
+
+ const onUpdate = useCallback(
+ (field: string, value: string | null) => {
+ const formData = new FormData();
+ formData.append("field", field);
+ formData.append("value", value?.toString() ?? "");
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.maintenanceDispatchProperties(dispatchId)
+ });
+ },
+ [dispatchId, fetcher]
+ );
+
+ return (
+ <VStack
+ spacing={4}
+ className="w-80 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"
+ >
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">Properties</h3>
+ <HStack spacing={1}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Link"
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(
+ window.location.origin +
+ path.to.maintenanceDispatch(dispatchId)
+ )
+ }
+ >
+ <LuLink className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy link to dispatch</span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Copy ID"
+ size="sm"
+ className="p-1"
+ onClick={() => copyToClipboard(routeData?.dispatch?.id ?? "")}
+ >
+ <LuKeySquare className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy dispatch ID</span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Copy"
+ size="sm"
+ className="p-1"
+ onClick={() => copyToClipboard(routeData?.dispatch?.id ?? "")}
+ >
+ <LuCopy className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy dispatch number</span>
+ </TooltipContent>
+ </Tooltip>
+ </HStack>
+ </HStack>
+ <span className="text-sm tracking-tight">
+ {routeData?.dispatch?.id}
+ </span>
+ </VStack>
+
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">Assignee</h3>
+ <Assignee
+ id={dispatchId}
+ table="maintenanceDispatch"
+ size="sm"
+ value={assignee ?? ""}
+ isReadOnly={!permissions.can("update", "production")}
+ />
+ </VStack>
+
+ <ValidatedForm
+ defaultValues={{
+ priority: routeData?.dispatch?.priority ?? ""
+ }}
+ validator={z.object({
+ priority: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Select
+ options={maintenanceDispatchPriority.map((priority) => ({
+ value: priority,
+ label: (
+ <div className="flex gap-2 items-center">
+ <MaintenancePriority priority={priority} />
+ </div>
+ )
+ }))}
+ isReadOnly={!permissions.can("update", "production")}
+ label="Priority"
+ name="priority"
+ inline={(value) => {
+ return (
+ <MaintenancePriority
+ priority={value as (typeof maintenanceDispatchPriority)[number]}
+ />
+ );
+ }}
+ onChange={(value) => {
+ if (value) {
+ onUpdate("priority", value.value);
+ }
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ severity: routeData?.dispatch?.severity ?? ""
+ }}
+ validator={z.object({
+ severity: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Select
+ options={maintenanceSeverity.map((severity) => ({
+ value: severity,
+ label: severity
+ }))}
+ isReadOnly={!permissions.can("update", "production")}
+ label="Severity"
+ name="severity"
+ inline
+ onChange={(value) => {
+ if (value) {
+ onUpdate("severity", value.value);
+ }
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ source: routeData?.dispatch?.source ?? ""
+ }}
+ validator={z.object({
+ source: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Select
+ options={maintenanceSource.map((source) => ({
+ value: source,
+ label: source
+ }))}
+ isReadOnly={!permissions.can("update", "production")}
+ label="Source"
+ name="source"
+ inline
+ onChange={(value) => {
+ if (value) {
+ onUpdate("source", value.value);
+ }
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ suspectedFailureModeId:
+ routeData?.dispatch?.suspectedFailureModeId ?? ""
+ }}
+ validator={z.object({
+ suspectedFailureModeId: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Select
+ options={(routeData?.failureModes ?? []).map((mode) => ({
+ value: mode.id,
+ label: mode.name
+ }))}
+ isReadOnly={!permissions.can("update", "production")}
+ label="Suspected Failure Mode"
+ name="suspectedFailureModeId"
+ inline
+ isClearable
+ onChange={(value) => {
+ onUpdate("suspectedFailureModeId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ actualFailureModeId: routeData?.dispatch?.actualFailureModeId ?? ""
+ }}
+ validator={z.object({
+ actualFailureModeId: z.string().optional()
+ })}
+ className="w-full"
+ >
+ <Select
+ options={(routeData?.failureModes ?? []).map((mode) => ({
+ value: mode.id,
+ label: mode.name
+ }))}
+ isReadOnly={!permissions.can("update", "production")}
+ label="Actual Failure Mode"
+ name="actualFailureModeId"
+ inline
+ isClearable
+ onChange={(value) => {
+ onUpdate("actualFailureModeId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">Created By</h3>
+ <EmployeeAvatar
+ employeeId={routeData?.dispatch?.createdBy!}
+ size="xxs"
+ />
+ </VStack>
+
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">Created At</h3>
+ <span className="text-sm">
+ {routeData?.dispatch?.createdAt
+ ? new Date(routeData.dispatch.createdAt).toLocaleString()
+ : "-"}
+ </span>
+ </VStack>
+ </VStack>
+ );
+};
+
+export default MaintenanceDispatchProperties;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx
new file mode 100644
index 0000000000..3bafb4d292
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx
@@ -0,0 +1,162 @@
+import { HStack, 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 { useNavigate } from "react-router";
+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { path } from "~/utils/path";
+import {
+ maintenanceDispatchPriority,
+ maintenanceDispatchStatus
+} from "../../production.models";
+import type { MaintenanceDispatch } from "../../types";
+import MaintenancePriority from "./MaintenancePriority";
+import MaintenanceStatus from "./MaintenanceStatus";
+
+type MaintenanceDispatchesTableProps = {
+ data: MaintenanceDispatch[];
+ count: number;
+};
+
+const MaintenanceDispatchesTable = memo(
+ ({ data, count }: MaintenanceDispatchesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<MaintenanceDispatch>[]>(() => {
+ return [
+ {
+ accessorKey: "id",
+ header: "Dispatch ID",
+ cell: ({ row }) => (
+ <Hyperlink to={path.to.maintenanceDispatch(row.original.id)}>
+ {row.original.id}
+ </Hyperlink>
+ )
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: (item) => {
+ const status =
+ item.getValue<(typeof maintenanceDispatchStatus)[number]>();
+ return <MaintenanceStatus status={status} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: maintenanceDispatchStatus.map((status) => ({
+ value: status,
+ label: <MaintenanceStatus status={status} />
+ }))
+ },
+ pluralHeader: "Statuses"
+ }
+ },
+ {
+ accessorKey: "priority",
+ header: "Priority",
+ cell: (item) => {
+ const priority =
+ item.getValue<(typeof maintenanceDispatchPriority)[number]>();
+ return <MaintenancePriority priority={priority} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: maintenanceDispatchPriority.map((priority) => ({
+ value: priority,
+ label: <MaintenancePriority priority={priority} />
+ }))
+ },
+ pluralHeader: "Priorities"
+ }
+ },
+ {
+ accessorKey: "assignee",
+ header: "Assignee",
+ cell: ({ row }) => {
+ const assignee = row.original.assignee;
+ if (!assignee?.id) {
+ return <span className="text-muted-foreground">Unassigned</span>;
+ }
+ return (
+ <HStack>
+ <EmployeeAvatar employeeId={assignee.id} size="xs" />
+ </HStack>
+ );
+ }
+ },
+ {
+ accessorKey: "plannedStartTime",
+ header: "Planned Start",
+ cell: ({ row }) => {
+ const date = row.original.plannedStartTime;
+ return date ? new Date(date).toLocaleDateString() : "-";
+ }
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created",
+ cell: ({ row }) => {
+ const date = row.original.createdAt;
+ return date ? new Date(date).toLocaleDateString() : "-";
+ }
+ }
+ ];
+ }, []);
+
+ const renderContextMenu = useCallback(
+ (row: MaintenanceDispatch) => {
+ return (
+ <>
+ <MenuItem
+ onClick={() => {
+ navigate(path.to.maintenanceDispatch(row.id));
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Dispatch
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "production")}
+ onClick={() => {
+ navigate(
+ `${path.to.deleteMaintenanceDispatch(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Dispatch
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<MaintenanceDispatch>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "production") && (
+ <New
+ label="Maintenance Dispatch"
+ to={`${path.to.newMaintenanceDispatch}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Maintenance Dispatches"
+ />
+ );
+ }
+);
+
+MaintenanceDispatchesTable.displayName = "MaintenanceDispatchesTable";
+export default MaintenanceDispatchesTable;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx
new file mode 100644
index 0000000000..37876edaa3
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenancePriority.tsx
@@ -0,0 +1,43 @@
+import { Status } from "@carbon/react";
+import type { maintenanceDispatchPriority } from "../../production.models";
+
+type MaintenancePriorityProps = {
+ priority?: (typeof maintenanceDispatchPriority)[number] | null;
+ className?: string;
+};
+
+function MaintenancePriority({
+ priority,
+ className
+}: MaintenancePriorityProps) {
+ switch (priority) {
+ case "Low":
+ return (
+ <Status color="gray" className={className}>
+ {priority}
+ </Status>
+ );
+ case "Medium":
+ return (
+ <Status color="yellow" className={className}>
+ {priority}
+ </Status>
+ );
+ case "High":
+ return (
+ <Status color="orange" className={className}>
+ {priority}
+ </Status>
+ );
+ case "Critical":
+ return (
+ <Status color="red" className={className}>
+ {priority}
+ </Status>
+ );
+ default:
+ return null;
+ }
+}
+
+export default MaintenancePriority;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceStatus.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceStatus.tsx
new file mode 100644
index 0000000000..10b979c5ce
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceStatus.tsx
@@ -0,0 +1,46 @@
+import { Status } from "@carbon/react";
+import type { maintenanceDispatchStatus } from "../../production.models";
+
+type MaintenanceStatusProps = {
+ status?: (typeof maintenanceDispatchStatus)[number] | null;
+ className?: string;
+};
+
+function MaintenanceStatus({ status, className }: MaintenanceStatusProps) {
+ switch (status) {
+ case "Open":
+ return (
+ <Status color="gray" className={className}>
+ {status}
+ </Status>
+ );
+ case "Assigned":
+ return (
+ <Status color="yellow" className={className}>
+ {status}
+ </Status>
+ );
+ case "In Progress":
+ return (
+ <Status color="blue" className={className}>
+ {status}
+ </Status>
+ );
+ case "Completed":
+ return (
+ <Status color="green" className={className}>
+ {status}
+ </Status>
+ );
+ case "Cancelled":
+ return (
+ <Status color="red" className={className}>
+ {status}
+ </Status>
+ );
+ default:
+ return null;
+ }
+}
+
+export default MaintenanceStatus;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/index.ts b/apps/erp/app/modules/production/ui/Maintenance/index.ts
new file mode 100644
index 0000000000..d7e5ec0543
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/index.ts
@@ -0,0 +1,5 @@
+export { default as MaintenanceDispatchesTable } from "./MaintenanceDispatchesTable";
+export { default as MaintenanceDispatchHeader } from "./MaintenanceDispatchHeader";
+export { default as MaintenanceDispatchProperties } from "./MaintenanceDispatchProperties";
+export { default as MaintenancePriority } from "./MaintenancePriority";
+export { default as MaintenanceStatus } from "./MaintenanceStatus";
diff --git a/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx b/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
new file mode 100644
index 0000000000..f050fcbae5
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceScheduleForm.tsx
@@ -0,0 +1,134 @@
+import { Number, Select, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Checkbox,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ toast,
+ VStack
+} from "@carbon/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect } from "react";
+import { useFetcher } from "react-router";
+import type { z } from "zod/v3";
+import { Hidden, Input, Submit, WorkCenter } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import {
+ maintenanceDispatchPriority,
+ maintenanceFrequency,
+ maintenanceScheduleValidator
+} from "../../production.models";
+
+type MaintenanceScheduleFormProps = {
+ initialValues: z.infer<typeof maintenanceScheduleValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: () => void;
+};
+
+const MaintenanceScheduleForm = ({
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose
+}: MaintenanceScheduleFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created maintenance schedule`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create maintenance schedule: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "production")
+ : !permissions.can("create", "production");
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={maintenanceScheduleValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.maintenanceSchedule(initialValues.id!)
+ : path.to.newMaintenanceSchedule
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Maintenance Schedule
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <VStack spacing={4}>
+ <Input name="name" label="Schedule Name" />
+ <WorkCenter name="workCenterId" label="Work Center" />
+ <Select
+ name="frequency"
+ label="Frequency"
+ options={maintenanceFrequency.map((freq) => ({
+ value: freq,
+ label: freq
+ }))}
+ />
+ <Select
+ name="priority"
+ label="Priority"
+ options={maintenanceDispatchPriority.map((priority) => ({
+ value: priority,
+ label: priority
+ }))}
+ />
+ <Number
+ name="estimatedDuration"
+ label="Estimated Duration (minutes)"
+ min={0}
+ />
+ <Checkbox name="active" label="Active" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default MaintenanceScheduleForm;
diff --git a/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx b/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx
new file mode 100644
index 0000000000..8efbf51714
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx
@@ -0,0 +1,164 @@
+import { HStack, MenuIcon, MenuItem, Status } from "@carbon/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { LuPencil, 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 { path } from "~/utils/path";
+import {
+ maintenanceDispatchPriority,
+ maintenanceFrequency
+} from "../../production.models";
+import type { MaintenanceSchedule } from "../../types";
+import { MaintenancePriority } from "../Maintenance";
+
+type MaintenanceSchedulesTableProps = {
+ data: MaintenanceSchedule[];
+ count: number;
+};
+
+const MaintenanceSchedulesTable = memo(
+ ({ data, count }: MaintenanceSchedulesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<MaintenanceSchedule>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Schedule Name",
+ cell: ({ row }) => (
+ <Hyperlink to={row.original.id}>
+ <Enumerable value={row.original.name} />
+ </Hyperlink>
+ )
+ },
+ {
+ accessorKey: "workCenter",
+ header: "Work Center",
+ cell: ({ row }) => row.original.workCenter?.name ?? "-"
+ },
+ {
+ accessorKey: "frequency",
+ header: "Frequency",
+ cell: (item) => {
+ const frequency =
+ item.getValue<(typeof maintenanceFrequency)[number]>();
+ return <Enumerable value={frequency} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: maintenanceFrequency.map((freq) => ({
+ value: freq,
+ label: freq
+ }))
+ },
+ pluralHeader: "Frequencies"
+ }
+ },
+ {
+ accessorKey: "priority",
+ header: "Priority",
+ cell: (item) => {
+ const priority =
+ item.getValue<(typeof maintenanceDispatchPriority)[number]>();
+ return <MaintenancePriority priority={priority} />;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: maintenanceDispatchPriority.map((priority) => ({
+ value: priority,
+ label: <MaintenancePriority priority={priority} />
+ }))
+ },
+ pluralHeader: "Priorities"
+ }
+ },
+ {
+ accessorKey: "estimatedDuration",
+ header: "Est. Duration",
+ cell: ({ row }) =>
+ row.original.estimatedDuration
+ ? `${row.original.estimatedDuration} min`
+ : "-"
+ },
+ {
+ accessorKey: "active",
+ header: "Status",
+ cell: ({ row }) =>
+ row.original.active ? (
+ <Status color="green">Active</Status>
+ ) : (
+ <Status color="gray">Inactive</Status>
+ )
+ },
+ {
+ accessorKey: "nextDueAt",
+ header: "Next Due",
+ cell: ({ row }) =>
+ row.original.nextDueAt
+ ? new Date(row.original.nextDueAt).toLocaleDateString()
+ : "-"
+ }
+ ];
+ }, []);
+
+ const renderContextMenu = useCallback(
+ (row: MaintenanceSchedule) => {
+ return (
+ <>
+ <MenuItem
+ onClick={() => {
+ navigate(
+ `${path.to.maintenanceSchedule(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Schedule
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "production")}
+ onClick={() => {
+ navigate(
+ `${path.to.deleteMaintenanceSchedule(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Schedule
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<MaintenanceSchedule>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "production") && (
+ <New
+ label="Maintenance Schedule"
+ to={`${path.to.newMaintenanceSchedule}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Maintenance Schedules"
+ />
+ );
+ }
+);
+
+MaintenanceSchedulesTable.displayName = "MaintenanceSchedulesTable";
+export default MaintenanceSchedulesTable;
diff --git a/apps/erp/app/modules/production/ui/MaintenanceSchedule/index.ts b/apps/erp/app/modules/production/ui/MaintenanceSchedule/index.ts
new file mode 100644
index 0000000000..db03b975ff
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MaintenanceSchedule/index.ts
@@ -0,0 +1,2 @@
+export { default as MaintenanceScheduleForm } from "./MaintenanceScheduleForm";
+export { default as MaintenanceSchedulesTable } from "./MaintenanceSchedulesTable";
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index 7574662c28..b1f3394216 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -1,10 +1,13 @@
import {
+ LuCalendarClock,
LuChartLine,
+ LuCircleAlert,
LuHardHat,
LuListChecks,
LuSquareChartGantt,
LuSquareKanban,
- LuTrash
+ LuTrash,
+ LuWrench
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
import { useSavedViews } from "~/hooks/useSavedViews";
@@ -13,13 +16,20 @@ import { path } from "~/utils/path";
const productionRoutes: AuthenticatedRouteGroup[] = [
{
- name: "Manage",
+ name: "Production",
routes: [
{
name: "Jobs",
to: path.to.jobs,
icon: <LuHardHat />,
table: "job"
+ },
+ {
+ name: "Procedures",
+ to: path.to.procedures,
+ icon: <LuListChecks />,
+ table: "procedure",
+ role: "employee"
}
]
},
@@ -46,20 +56,37 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
]
},
{
- name: "Configure",
+ name: "Maintenance",
routes: [
{
- name: "Procedures",
- to: path.to.procedures,
- icon: <LuListChecks />,
- table: "procedure",
- role: "employee"
+ name: "Dispatches",
+ to: path.to.maintenanceDispatches,
+ icon: <LuWrench />,
+ table: "maintenanceDispatch"
},
+ {
+ name: "Schedules",
+ to: path.to.maintenanceSchedules,
+ icon: <LuCalendarClock />,
+ table: "maintenanceSchedule",
+ role: "employee"
+ }
+ ]
+ },
+ {
+ name: "Configure",
+ routes: [
{
name: "Scrap Reasons",
to: path.to.scrapReasons,
role: "employee",
icon: <LuTrash />
+ },
+ {
+ name: "Failure Modes",
+ to: path.to.failureModes,
+ role: "employee",
+ icon: <LuCircleAlert />
}
]
}
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index cc1d687a6d..b6e23b61c7 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -83,6 +83,11 @@ export const digitalQuoteValidator = z.object({
digitalQuoteIncludesPurchaseOrders: zfd.checkbox()
});
+export const jobCompletedValidator = z.object({
+ inventoryJobCompletedNotificationGroup: z.array(z.string()).optional(),
+ salesJobCompletedNotificationGroup: z.array(z.string()).optional()
+});
+
export const kanbanOutputValidator = z.object({
kanbanOutput: z.enum(kanbanOutputTypes)
});
@@ -91,6 +96,11 @@ export const purchasePriceUpdateTimingValidator = z.object({
purchasePriceUpdateTiming: z.enum(purchasePriceUpdateTimingTypes)
});
+export const maintenanceSettingsValidator = z.object({
+ maintenanceGenerateInAdvance: zfd.checkbox(),
+ maintenanceAdvanceDays: zfd.numeric(z.number().min(1).max(90).default(7))
+});
+
export const materialIdsValidator = z.object({
materialGeneratedIds: zfd.checkbox()
});
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx
new file mode 100644
index 0000000000..090fed14c4
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId._index.tsx
@@ -0,0 +1,156 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack,
+ VStack
+} from "@carbon/react";
+import { useParams } from "react-router";
+import { EmployeeAvatar } from "~/components";
+import { useRouteData } from "~/hooks";
+import type { MaintenanceDispatchDetail } from "~/modules/production/types";
+import {
+ MaintenancePriority,
+ MaintenanceStatus
+} from "~/modules/production/ui/Maintenance";
+import { path } from "~/utils/path";
+
+export default function MaintenanceDispatchOverview() {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const routeData = useRouteData<{
+ dispatch: MaintenanceDispatchDetail;
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const dispatch = routeData?.dispatch;
+
+ return (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Card>
+ <CardHeader>
+ <CardTitle>Status</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Status</span>
+ <MaintenanceStatus status={dispatch?.status} />
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Priority</span>
+ <MaintenancePriority priority={dispatch?.priority} />
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Severity</span>
+ <span>{dispatch?.severity ?? "-"}</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Source</span>
+ <span>{dispatch?.source ?? "-"}</span>
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Timing</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Planned Start</span>
+ <span>
+ {dispatch?.plannedStartTime
+ ? new Date(dispatch.plannedStartTime).toLocaleString()
+ : "-"}
+ </span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Planned End</span>
+ <span>
+ {dispatch?.plannedEndTime
+ ? new Date(dispatch.plannedEndTime).toLocaleString()
+ : "-"}
+ </span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Actual Start</span>
+ <span>
+ {dispatch?.actualStartTime
+ ? new Date(dispatch.actualStartTime).toLocaleString()
+ : "-"}
+ </span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Actual End</span>
+ <span>
+ {dispatch?.actualEndTime
+ ? new Date(dispatch.actualEndTime).toLocaleString()
+ : "-"}
+ </span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Duration</span>
+ <span>
+ {dispatch?.duration ? `${dispatch.duration} min` : "-"}
+ </span>
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Assignment</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Assignee</span>
+ {dispatch?.assignee ? (
+ <EmployeeAvatar employeeId={dispatch.assignee} size="xs" />
+ ) : (
+ <span>Unassigned</span>
+ )}
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Created By</span>
+ {dispatch?.createdBy ? (
+ <EmployeeAvatar employeeId={dispatch.createdBy} size="xs" />
+ ) : (
+ <span>-</span>
+ )}
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Failure Analysis</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Is Failure</span>
+ <span>{dispatch?.isFailure ? "Yes" : "No"}</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Suspected Failure Mode
+ </span>
+ <span>{dispatch?.suspectedFailureMode?.name ?? "-"}</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Actual Failure Mode</span>
+ <span>{dispatch?.actualFailureMode?.name ?? "-"}</span>
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.comments.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.comments.tsx
new file mode 100644
index 0000000000..5bce4188b6
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.comments.tsx
@@ -0,0 +1,148 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import {
+ Button,
+ Card,
+ CardContent,
+ HStack,
+ Textarea,
+ VStack
+} from "@carbon/react";
+import { useState } from "react";
+import { LuSend } from "react-icons/lu";
+import type { ActionFunctionArgs } from "react-router";
+import { data, useFetcher, useParams } from "react-router";
+import { EmployeeAvatar } from "~/components";
+import { usePermissions, useRouteData } from "~/hooks";
+import {
+ maintenanceDispatchCommentValidator,
+ upsertMaintenanceDispatchComment
+} from "~/modules/production";
+import type { MaintenanceDispatchComment } from "~/modules/production/types";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const formData = await request.formData();
+ const validation = await validator(
+ maintenanceDispatchCommentValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const upsertComment = await upsertMaintenanceDispatchComment(client, {
+ ...validation.data,
+ maintenanceDispatchId: dispatchId,
+ createdBy: userId,
+ updatedBy: validation.data.id ? userId : undefined
+ });
+
+ if (upsertComment.error) {
+ return data(
+ {},
+ await flash(request, error(upsertComment.error, "Failed to save comment"))
+ );
+ }
+
+ return data({}, await flash(request, success("Comment saved")));
+}
+
+export default function MaintenanceDispatchCommentsRoute() {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+ const [comment, setComment] = useState("");
+
+ const routeData = useRouteData<{
+ comments: MaintenanceDispatchComment[];
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const comments = routeData?.comments ?? [];
+
+ const handleSubmit = () => {
+ if (!comment.trim()) return;
+
+ const formData = new FormData();
+ formData.append("comment", comment);
+ fetcher.submit(formData, { method: "post" });
+ setComment("");
+ };
+
+ return (
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <h2 className="text-lg font-semibold">Comments</h2>
+ </HStack>
+
+ {permissions.can("update", "production") && (
+ <Card>
+ <CardContent className="py-4">
+ <VStack spacing={2}>
+ <Textarea
+ placeholder="Add a comment..."
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ rows={3}
+ />
+ <HStack className="justify-end w-full">
+ <Button
+ variant="primary"
+ leftIcon={<LuSend />}
+ onClick={handleSubmit}
+ isDisabled={!comment.trim()}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Post Comment
+ </Button>
+ </HStack>
+ </VStack>
+ </CardContent>
+ </Card>
+ )}
+
+ {comments.length === 0 ? (
+ <Card>
+ <CardContent className="py-8 text-center text-muted-foreground">
+ No comments yet. Be the first to add a comment.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-2">
+ {comments.map((c) => (
+ <Card key={c.id}>
+ <CardContent className="py-4">
+ <VStack spacing={2}>
+ <HStack className="justify-between w-full">
+ <HStack>
+ <EmployeeAvatar employeeId={c.createdBy} size="xs" />
+ <span className="text-sm font-medium">
+ {c.user?.fullName ?? "Unknown"}
+ </span>
+ </HStack>
+ <span className="text-xs text-muted-foreground">
+ {new Date(c.createdAt).toLocaleString()}
+ </span>
+ </HStack>
+ <p className="text-sm">{c.comment}</p>
+ </VStack>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx
new file mode 100644
index 0000000000..40401b9ae2
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx
@@ -0,0 +1,208 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack,
+ VStack
+} from "@carbon/react";
+import { LuPlay, LuSquare } from "react-icons/lu";
+import type { ActionFunctionArgs } from "react-router";
+import { data, useFetcher, useParams } from "react-router";
+import { EmployeeAvatar } from "~/components";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import {
+ maintenanceDispatchEventValidator,
+ upsertMaintenanceDispatchEvent
+} from "~/modules/production";
+import type { MaintenanceDispatchEvent } from "~/modules/production/types";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "start") {
+ const insertEvent = await upsertMaintenanceDispatchEvent(client, {
+ maintenanceDispatchId: dispatchId,
+ employeeId: userId,
+ startTime: new Date().toISOString(),
+ createdBy: userId
+ });
+
+ if (insertEvent.error) {
+ return data(
+ {},
+ await flash(request, error(insertEvent.error, "Failed to start event"))
+ );
+ }
+
+ return data({}, await flash(request, success("Event started")));
+ }
+
+ if (intent === "stop") {
+ const eventId = formData.get("eventId") as string;
+ if (!eventId) throw new Error("eventId not found");
+
+ const updateEvent = await upsertMaintenanceDispatchEvent(client, {
+ id: eventId,
+ endTime: new Date().toISOString(),
+ updatedBy: userId
+ });
+
+ if (updateEvent.error) {
+ return data(
+ {},
+ await flash(request, error(updateEvent.error, "Failed to stop event"))
+ );
+ }
+
+ return data({}, await flash(request, success("Event stopped")));
+ }
+
+ const validation = await validator(
+ maintenanceDispatchEventValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const upsertEvent = await upsertMaintenanceDispatchEvent(client, {
+ ...validation.data,
+ maintenanceDispatchId: dispatchId,
+ createdBy: userId,
+ updatedBy: validation.data.id ? userId : undefined
+ });
+
+ if (upsertEvent.error) {
+ return data(
+ {},
+ await flash(request, error(upsertEvent.error, "Failed to save event"))
+ );
+ }
+
+ return data({}, await flash(request, success("Event saved")));
+}
+
+export default function MaintenanceDispatchEventsRoute() {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const user = useUser();
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+
+ const routeData = useRouteData<{
+ events: MaintenanceDispatchEvent[];
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const events = routeData?.events ?? [];
+ const activeEvent = events.find(
+ (e) => e.employeeId === user.id && !e.endTime
+ );
+
+ return (
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <h2 className="text-lg font-semibold">Time Events</h2>
+ {permissions.can("update", "production") && (
+ <fetcher.Form method="post">
+ {activeEvent ? (
+ <>
+ <input type="hidden" name="intent" value="stop" />
+ <input type="hidden" name="eventId" value={activeEvent.id} />
+ <Button
+ type="submit"
+ variant="secondary"
+ leftIcon={<LuSquare />}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Stop Timer
+ </Button>
+ </>
+ ) : (
+ <>
+ <input type="hidden" name="intent" value="start" />
+ <Button
+ type="submit"
+ variant="primary"
+ leftIcon={<LuPlay />}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Start Timer
+ </Button>
+ </>
+ )}
+ </fetcher.Form>
+ )}
+ </HStack>
+
+ {events.length === 0 ? (
+ <Card>
+ <CardContent className="py-8 text-center text-muted-foreground">
+ No time events recorded yet. Click "Start Timer" to begin tracking
+ time.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-2">
+ {events.map((event) => (
+ <Card key={event.id}>
+ <CardHeader className="pb-2">
+ <HStack className="justify-between">
+ <HStack>
+ <EmployeeAvatar employeeId={event.employeeId} size="xs" />
+ <span className="text-sm font-medium">
+ {event.employee?.fullName ?? "Unknown"}
+ </span>
+ </HStack>
+ {!event.endTime && (
+ <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded">
+ In Progress
+ </span>
+ )}
+ </HStack>
+ </CardHeader>
+ <CardContent>
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span className="text-muted-foreground">Start:</span>{" "}
+ {new Date(event.startTime).toLocaleString()}
+ </div>
+ <div>
+ <span className="text-muted-foreground">End:</span>{" "}
+ {event.endTime
+ ? new Date(event.endTime).toLocaleString()
+ : "-"}
+ </div>
+ <div>
+ <span className="text-muted-foreground">Duration:</span>{" "}
+ {event.duration ? `${event.duration} min` : "-"}
+ </div>
+ <div>
+ <span className="text-muted-foreground">Work Center:</span>{" "}
+ {event.workCenter?.name ?? "-"}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx
new file mode 100644
index 0000000000..901f1da091
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx
@@ -0,0 +1,107 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { Card, CardContent, HStack, VStack } from "@carbon/react";
+import type { ActionFunctionArgs } from "react-router";
+import { data, useParams } from "react-router";
+import { useRouteData } from "~/hooks";
+import {
+ maintenanceDispatchItemValidator,
+ upsertMaintenanceDispatchItem
+} from "~/modules/production";
+import type { MaintenanceDispatchItem } from "~/modules/production/types";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const formData = await request.formData();
+ const validation = await validator(maintenanceDispatchItemValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const upsertItem = await upsertMaintenanceDispatchItem(client, {
+ ...validation.data,
+ maintenanceDispatchId: dispatchId,
+ createdBy: userId,
+ updatedBy: validation.data.id ? userId : undefined
+ });
+
+ if (upsertItem.error) {
+ return data(
+ {},
+ await flash(request, error(upsertItem.error, "Failed to save item"))
+ );
+ }
+
+ return data({}, await flash(request, success("Item saved")));
+}
+
+export default function MaintenanceDispatchItemsRoute() {
+ const { dispatchId } = useParams();
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const routeData = useRouteData<{
+ items: MaintenanceDispatchItem[];
+ }>(path.to.maintenanceDispatch(dispatchId));
+
+ const items = routeData?.items ?? [];
+
+ return (
+ <VStack spacing={4}>
+ <HStack className="justify-between w-full">
+ <h2 className="text-lg font-semibold">Parts & Materials</h2>
+ </HStack>
+
+ {items.length === 0 ? (
+ <Card>
+ <CardContent className="py-8 text-center text-muted-foreground">
+ No parts or materials recorded yet.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-2">
+ {items.map((item) => (
+ <Card key={item.id}>
+ <CardContent className="py-4">
+ <div className="grid grid-cols-4 gap-4 text-sm">
+ <div>
+ <span className="text-muted-foreground">Item:</span>{" "}
+ {item.item?.name ?? item.itemId}
+ </div>
+ <div>
+ <span className="text-muted-foreground">Quantity:</span>{" "}
+ {item.quantity} {item.unitOfMeasureCode}
+ </div>
+ <div>
+ <span className="text-muted-foreground">Unit Cost:</span>{" "}
+ {item.unitCost
+ ? `$${Number(item.unitCost).toFixed(2)}`
+ : "-"}
+ </div>
+ <div>
+ <span className="text-muted-foreground">Total Cost:</span>{" "}
+ {item.totalCost
+ ? `$${Number(item.totalCost).toFixed(2)}`
+ : "-"}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx
new file mode 100644
index 0000000000..da1009b1d5
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.properties.tsx
@@ -0,0 +1,104 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { upsertMaintenanceDispatch } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("dispatchId not found");
+
+ const formData = await request.formData();
+ const field = formData.get("field") as string;
+ const value = formData.get("value") as string | null;
+ const status = formData.get("status") as string | null;
+
+ // Handle status update from header buttons
+ if (status) {
+ const updateDispatch = await upsertMaintenanceDispatch(client, {
+ id: dispatchId,
+ status: status as
+ | "Open"
+ | "Assigned"
+ | "In Progress"
+ | "Completed"
+ | "Cancelled",
+ updatedBy: userId,
+ ...(status === "In Progress" && {
+ actualStartTime: new Date().toISOString()
+ }),
+ ...(status === "Completed" && { actualEndTime: new Date().toISOString() })
+ });
+
+ if (updateDispatch.error) {
+ return data(
+ { error: updateDispatch.error },
+ await flash(
+ request,
+ error(updateDispatch.error, "Failed to update status")
+ )
+ );
+ }
+
+ return data(
+ {},
+ await flash(request, success(`Status updated to ${status}`))
+ );
+ }
+
+ // Handle field update from properties sidebar
+ if (!field) {
+ return data(
+ { error: { message: "Field is required" } },
+ await flash(request, error(null, "Field is required"))
+ );
+ }
+
+ const updateData: Record<string, unknown> = {
+ id: dispatchId,
+ updatedBy: userId
+ };
+
+ // Handle different field types
+ switch (field) {
+ case "priority":
+ case "severity":
+ case "source":
+ case "suspectedFailureModeId":
+ case "actualFailureModeId":
+ updateData[field] = value || null;
+ break;
+ case "isFailure":
+ updateData[field] = value === "true";
+ break;
+ default:
+ return data(
+ { error: { message: `Unknown field: ${field}` } },
+ await flash(request, error(null, `Unknown field: ${field}`))
+ );
+ }
+
+ const updateDispatch = await upsertMaintenanceDispatch(
+ client,
+ updateData as Parameters<typeof upsertMaintenanceDispatch>[1]
+ );
+
+ if (updateDispatch.error) {
+ return data(
+ { error: updateDispatch.error },
+ await flash(request, error(updateDispatch.error, "Failed to update"))
+ );
+ }
+
+ return data({}, await flash(request, success("Updated successfully")));
+}
+
+export default function MaintenanceDispatchPropertiesRoute() {
+ return null;
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
new file mode 100644
index 0000000000..cf91c0182a
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
@@ -0,0 +1,138 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ VStack
+} from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import {
+ Outlet,
+ redirect,
+ useLoaderData,
+ useNavigate,
+ useParams
+} from "react-router";
+import {
+ getFailureModesList,
+ getMaintenanceDispatch,
+ getMaintenanceDispatchComments,
+ getMaintenanceDispatchEvents,
+ getMaintenanceDispatchItems,
+ getMaintenanceDispatchWorkCenters
+} from "~/modules/production";
+import {
+ MaintenanceDispatchHeader,
+ MaintenanceDispatchProperties
+} from "~/modules/production/ui/Maintenance";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Maintenance",
+ to: path.to.maintenanceDispatches,
+ module: "production"
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+
+ const [dispatch, events, items, workCenters, comments, failureModes] =
+ await Promise.all([
+ getMaintenanceDispatch(client, dispatchId),
+ getMaintenanceDispatchEvents(client, dispatchId),
+ getMaintenanceDispatchItems(client, dispatchId),
+ getMaintenanceDispatchWorkCenters(client, dispatchId),
+ getMaintenanceDispatchComments(client, dispatchId),
+ getFailureModesList(client, companyId)
+ ]);
+
+ if (dispatch.error) {
+ throw redirect(
+ path.to.maintenanceDispatches,
+ await flash(
+ request,
+ error(dispatch.error, "Failed to load maintenance dispatch")
+ )
+ );
+ }
+
+ return {
+ dispatch: dispatch.data,
+ events: events.data ?? [],
+ items: items.data ?? [],
+ workCenters: workCenters.data ?? [],
+ comments: comments.data ?? [],
+ failureModes: failureModes.data ?? []
+ };
+}
+
+export default function MaintenanceDispatchRoute() {
+ const { dispatchId } = useParams();
+ const navigate = useNavigate();
+ const { events, items, comments } = useLoaderData<typeof loader>();
+
+ if (!dispatchId) throw new Error("Could not find dispatchId");
+
+ const currentPath =
+ typeof window !== "undefined" ? window.location.pathname : "";
+ const currentTab = currentPath.includes("/events")
+ ? "events"
+ : currentPath.includes("/items")
+ ? "items"
+ : currentPath.includes("/comments")
+ ? "comments"
+ : "overview";
+
+ return (
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ <MaintenanceDispatchHeader />
+ <div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
+ <div className="flex flex-grow overflow-hidden">
+ <div className="flex-1 overflow-y-auto">
+ <Tabs
+ value={currentTab}
+ onValueChange={(value) => {
+ if (value === "overview") {
+ navigate(path.to.maintenanceDispatch(dispatchId));
+ } else {
+ navigate(
+ `${path.to.maintenanceDispatch(dispatchId)}/${value}`
+ );
+ }
+ }}
+ className="w-full"
+ >
+ <TabsList className="px-4 pt-2">
+ <TabsTrigger value="overview">Overview</TabsTrigger>
+ <TabsTrigger value="events">
+ Events {events.length > 0 && `(${events.length})`}
+ </TabsTrigger>
+ <TabsTrigger value="items">
+ Items {items.length > 0 && `(${items.length})`}
+ </TabsTrigger>
+ <TabsTrigger value="comments">
+ Comments {comments.length > 0 && `(${comments.length})`}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value={currentTab} className="p-4">
+ <VStack spacing={4}>
+ <Outlet />
+ </VStack>
+ </TabsContent>
+ </Tabs>
+ </div>
+ <MaintenanceDispatchProperties />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/maintenance+/_layout.tsx b/apps/erp/app/routes/x+/maintenance+/_layout.tsx
new file mode 100644
index 0000000000..2f396e8cd2
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/_layout.tsx
@@ -0,0 +1,18 @@
+import type { MetaFunction } from "react-router";
+import { Outlet } from "react-router";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Maintenance" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: "Production",
+ to: path.to.production,
+ module: "production"
+};
+
+export default function MaintenanceRoute() {
+ return <Outlet />;
+}
diff --git a/apps/erp/app/routes/x+/production+/failure-modes.$failureModeId.tsx b/apps/erp/app/routes/x+/production+/failure-modes.$failureModeId.tsx
new file mode 100644
index 0000000000..d256176682
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/failure-modes.$failureModeId.tsx
@@ -0,0 +1,96 @@
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData, useNavigate } from "react-router";
+import {
+ failureModeValidator,
+ getFailureMode,
+ upsertFailureMode
+} from "~/modules/production";
+import FailureModeForm from "~/modules/production/ui/FailureModes/FailureModeForm";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const { failureModeId } = params;
+ if (!failureModeId) throw notFound("failureModeId not found");
+
+ const failureMode = await getFailureMode(client, failureModeId);
+
+ if (failureMode.error) {
+ throw redirect(
+ path.to.failureModes,
+ await flash(
+ request,
+ error(failureMode.error, "Failed to get failure mode")
+ )
+ );
+ }
+
+ return {
+ failureMode: failureMode.data
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(failureModeValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...d } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateFailureMode = await upsertFailureMode(client, {
+ id,
+ ...d,
+ updatedBy: userId
+ });
+
+ if (updateFailureMode.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(updateFailureMode.error, "Failed to update failure mode")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.failureModes,
+ await flash(request, success("Updated failure mode"))
+ );
+}
+
+export default function EditFailureModeRoute() {
+ const { failureMode } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: failureMode.id ?? undefined,
+ name: failureMode.name ?? ""
+ };
+
+ return (
+ <FailureModeForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/failure-modes.delete.$failureModeId.tsx b/apps/erp/app/routes/x+/production+/failure-modes.delete.$failureModeId.tsx
new file mode 100644
index 0000000000..77874eb226
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/failure-modes.delete.$failureModeId.tsx
@@ -0,0 +1,84 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteFailureMode, getFailureMode } from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+ const { failureModeId } = params;
+ if (!failureModeId) throw notFound("failureModeId not found");
+
+ const failureMode = await getFailureMode(client, failureModeId);
+ if (failureMode.error) {
+ throw redirect(
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(
+ request,
+ error(failureMode.error, "Failed to get failure mode")
+ )
+ );
+ }
+
+ return { failureMode: failureMode.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { failureModeId } = params;
+ if (!failureModeId) {
+ throw redirect(
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(request, error(params, "Failed to get a failure mode id"))
+ );
+ }
+
+ const { error: deleteFailureModeError } = await deleteFailureMode(
+ client,
+ failureModeId
+ );
+ if (deleteFailureModeError) {
+ const errorMessage =
+ deleteFailureModeError.code === "23503"
+ ? "Failure mode is used elsewhere, cannot delete"
+ : "Failed to delete failure mode";
+
+ throw redirect(
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(request, error(deleteFailureModeError, errorMessage))
+ );
+ }
+
+ throw redirect(
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted failure mode"))
+ );
+}
+
+export default function DeleteFailureModeRoute() {
+ const { failureModeId } = useParams();
+ const { failureMode } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!failureMode) return null;
+ if (!failureModeId) throw notFound("failureModeId not found");
+
+ const onCancel = () => navigate(path.to.failureModes);
+ return (
+ <ConfirmDelete
+ action={path.to.deleteFailureMode(failureModeId)}
+ name={failureMode.name}
+ text={`Are you sure you want to delete the failure mode: ${failureMode.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/failure-modes.new.tsx b/apps/erp/app/routes/x+/production+/failure-modes.new.tsx
new file mode 100644
index 0000000000..f845b35ac1
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/failure-modes.new.tsx
@@ -0,0 +1,76 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useNavigate } from "react-router";
+import { failureModeValidator, upsertFailureMode } from "~/modules/production";
+import FailureModeForm from "~/modules/production/ui/FailureModes/FailureModeForm";
+import { setCustomFields } from "~/utils/form";
+import { getParams, path, requestReferrer } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "production"
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(failureModeValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ const { id, ...d } = validation.data;
+
+ const insertFailureMode = await upsertFailureMode(client, {
+ ...d,
+ companyId,
+ createdBy: userId
+ });
+ if (insertFailureMode.error) {
+ return modal
+ ? insertFailureMode
+ : redirect(
+ requestReferrer(request) ??
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(
+ request,
+ error(insertFailureMode.error, "Failed to insert failure mode")
+ )
+ );
+ }
+
+ return modal
+ ? insertFailureMode
+ : redirect(
+ `${path.to.failureModes}?${getParams(request)}`,
+ await flash(request, success("Failure mode created"))
+ );
+}
+
+export default function NewFailureModeRoute() {
+ const navigate = useNavigate();
+ const initialValues = {
+ name: ""
+ };
+
+ return (
+ <FailureModeForm
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/failure-modes.tsx b/apps/erp/app/routes/x+/production+/failure-modes.tsx
new file mode 100644
index 0000000000..6c2a69101c
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/failure-modes.tsx
@@ -0,0 +1,46 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, useLoaderData } from "react-router";
+import { getFailureModes } from "~/modules/production";
+import FailureModesTable from "~/modules/production/ui/FailureModes/FailureModesTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Failure Modes",
+ to: path.to.failureModes
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ return await getFailureModes(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+}
+
+export default function FailureModesRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <FailureModesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance-schedules.$scheduleId.tsx b/apps/erp/app/routes/x+/production+/maintenance-schedules.$scheduleId.tsx
new file mode 100644
index 0000000000..85dbd6bb87
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance-schedules.$scheduleId.tsx
@@ -0,0 +1,102 @@
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData, useNavigate } from "react-router";
+import {
+ getMaintenanceSchedule,
+ maintenanceScheduleValidator,
+ upsertMaintenanceSchedule
+} from "~/modules/production";
+import MaintenanceScheduleForm from "~/modules/production/ui/MaintenanceSchedule/MaintenanceScheduleForm";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const { scheduleId } = params;
+ if (!scheduleId) throw notFound("scheduleId not found");
+
+ const schedule = await getMaintenanceSchedule(client, scheduleId);
+
+ if (schedule.error) {
+ throw redirect(
+ path.to.maintenanceSchedules,
+ await flash(
+ request,
+ error(schedule.error, "Failed to get maintenance schedule")
+ )
+ );
+ }
+
+ return {
+ schedule: schedule.data
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(maintenanceScheduleValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...d } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateSchedule = await upsertMaintenanceSchedule(client, {
+ id,
+ ...d,
+ updatedBy: userId
+ });
+
+ if (updateSchedule.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(updateSchedule.error, "Failed to update maintenance schedule")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.maintenanceSchedules,
+ await flash(request, success("Updated maintenance schedule"))
+ );
+}
+
+export default function EditMaintenanceScheduleRoute() {
+ const { schedule } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: schedule.id ?? undefined,
+ name: schedule.name ?? "",
+ workCenterId: schedule.workCenterId ?? "",
+ frequency: schedule.frequency ?? ("Weekly" as const),
+ priority: schedule.priority ?? ("Medium" as const),
+ estimatedDuration: schedule.estimatedDuration ?? undefined,
+ active: schedule.active ?? true
+ };
+
+ return (
+ <MaintenanceScheduleForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance-schedules.delete.$scheduleId.tsx b/apps/erp/app/routes/x+/production+/maintenance-schedules.delete.$scheduleId.tsx
new file mode 100644
index 0000000000..8a3ae12704
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance-schedules.delete.$scheduleId.tsx
@@ -0,0 +1,87 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ deleteMaintenanceSchedule,
+ getMaintenanceSchedule
+} from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+ const { scheduleId } = params;
+ if (!scheduleId) throw notFound("scheduleId not found");
+
+ const schedule = await getMaintenanceSchedule(client, scheduleId);
+ if (schedule.error) {
+ throw redirect(
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(
+ request,
+ error(schedule.error, "Failed to get maintenance schedule")
+ )
+ );
+ }
+
+ return { schedule: schedule.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { scheduleId } = params;
+ if (!scheduleId) {
+ throw redirect(
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(request, error(params, "Failed to get a schedule id"))
+ );
+ }
+
+ const { error: deleteError } = await deleteMaintenanceSchedule(
+ client,
+ scheduleId
+ );
+ if (deleteError) {
+ const errorMessage =
+ deleteError.code === "23503"
+ ? "Schedule has related dispatches, cannot delete"
+ : "Failed to delete maintenance schedule";
+
+ throw redirect(
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(request, error(deleteError, errorMessage))
+ );
+ }
+
+ throw redirect(
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted maintenance schedule"))
+ );
+}
+
+export default function DeleteMaintenanceScheduleRoute() {
+ const { scheduleId } = useParams();
+ const { schedule } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!schedule) return null;
+ if (!scheduleId) throw notFound("scheduleId not found");
+
+ const onCancel = () => navigate(path.to.maintenanceSchedules);
+ return (
+ <ConfirmDelete
+ action={path.to.deleteMaintenanceSchedule(scheduleId)}
+ name={schedule.name}
+ text={`Are you sure you want to delete the maintenance schedule: ${schedule.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance-schedules.new.tsx b/apps/erp/app/routes/x+/production+/maintenance-schedules.new.tsx
new file mode 100644
index 0000000000..ab1f0615be
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance-schedules.new.tsx
@@ -0,0 +1,86 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useNavigate } from "react-router";
+import {
+ maintenanceScheduleValidator,
+ upsertMaintenanceSchedule
+} from "~/modules/production";
+import MaintenanceScheduleForm from "~/modules/production/ui/MaintenanceSchedule/MaintenanceScheduleForm";
+import { getParams, path, requestReferrer } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "production"
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(maintenanceScheduleValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ const { id, ...d } = validation.data;
+
+ const insertSchedule = await upsertMaintenanceSchedule(client, {
+ ...d,
+ companyId,
+ createdBy: userId
+ });
+
+ if (insertSchedule.error) {
+ return modal
+ ? insertSchedule
+ : redirect(
+ requestReferrer(request) ??
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(
+ request,
+ error(insertSchedule.error, "Failed to create maintenance schedule")
+ )
+ );
+ }
+
+ return modal
+ ? insertSchedule
+ : redirect(
+ `${path.to.maintenanceSchedules}?${getParams(request)}`,
+ await flash(request, success("Maintenance schedule created"))
+ );
+}
+
+export default function NewMaintenanceScheduleRoute() {
+ const navigate = useNavigate();
+ const initialValues = {
+ name: "",
+ workCenterId: "",
+ frequency: "Weekly" as const,
+ priority: "Medium" as const,
+ estimatedDuration: undefined,
+ active: true
+ };
+
+ return (
+ <MaintenanceScheduleForm
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance-schedules.tsx b/apps/erp/app/routes/x+/production+/maintenance-schedules.tsx
new file mode 100644
index 0000000000..45eabb9e3c
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance-schedules.tsx
@@ -0,0 +1,46 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, useLoaderData } from "react-router";
+import { getMaintenanceSchedules } from "~/modules/production";
+import MaintenanceSchedulesTable from "~/modules/production/ui/MaintenanceSchedule/MaintenanceSchedulesTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Maintenance Schedules",
+ to: path.to.maintenanceSchedules
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ return await getMaintenanceSchedules(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+}
+
+export default function MaintenanceSchedulesRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <MaintenanceSchedulesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance.delete.$dispatchId.tsx b/apps/erp/app/routes/x+/production+/maintenance.delete.$dispatchId.tsx
new file mode 100644
index 0000000000..942df395be
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance.delete.$dispatchId.tsx
@@ -0,0 +1,87 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ deleteMaintenanceDispatch,
+ getMaintenanceDispatch
+} from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+ const { dispatchId } = params;
+ if (!dispatchId) throw notFound("dispatchId not found");
+
+ const dispatch = await getMaintenanceDispatch(client, dispatchId);
+ if (dispatch.error) {
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(
+ request,
+ error(dispatch.error, "Failed to get maintenance dispatch")
+ )
+ );
+ }
+
+ return { dispatch: dispatch.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { dispatchId } = params;
+ if (!dispatchId) {
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(request, error(params, "Failed to get a dispatch id"))
+ );
+ }
+
+ const { error: deleteError } = await deleteMaintenanceDispatch(
+ client,
+ dispatchId
+ );
+ if (deleteError) {
+ const errorMessage =
+ deleteError.code === "23503"
+ ? "Dispatch has related records, cannot delete"
+ : "Failed to delete maintenance dispatch";
+
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(request, error(deleteError, errorMessage))
+ );
+ }
+
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted maintenance dispatch"))
+ );
+}
+
+export default function DeleteMaintenanceDispatchRoute() {
+ const { dispatchId } = useParams();
+ const { dispatch } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!dispatch) return null;
+ if (!dispatchId) throw notFound("dispatchId not found");
+
+ const onCancel = () => navigate(path.to.maintenanceDispatches);
+ return (
+ <ConfirmDelete
+ action={path.to.deleteMaintenanceDispatch(dispatchId)}
+ name={dispatch.id}
+ 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+/production+/maintenance.new.tsx b/apps/erp/app/routes/x+/production+/maintenance.new.tsx
new file mode 100644
index 0000000000..7d33e1d5e2
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance.new.tsx
@@ -0,0 +1,57 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { upsertMaintenanceDispatch } from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "production"
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const insertDispatch = await upsertMaintenanceDispatch(client, {
+ status: "Open",
+ priority: "Medium",
+ source: "reactive",
+ companyId,
+ createdBy: userId
+ });
+
+ if (insertDispatch.error) {
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(
+ request,
+ error(insertDispatch.error, "Failed to create maintenance dispatch")
+ )
+ );
+ }
+
+ const newId = insertDispatch.data?.id;
+ if (!newId) {
+ throw redirect(
+ `${path.to.maintenanceDispatches}?${getParams(request)}`,
+ await flash(request, error(null, "Failed to get new dispatch ID"))
+ );
+ }
+
+ throw redirect(
+ path.to.maintenanceDispatch(newId),
+ await flash(request, success("Created maintenance dispatch"))
+ );
+}
+
+export default function NewMaintenanceDispatchRoute() {
+ return null;
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance.tsx b/apps/erp/app/routes/x+/production+/maintenance.tsx
new file mode 100644
index 0000000000..1f3ff685a0
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/maintenance.tsx
@@ -0,0 +1,48 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, useLoaderData } from "react-router";
+import { getMaintenanceDispatches } from "~/modules/production";
+import MaintenanceDispatchesTable from "~/modules/production/ui/Maintenance/MaintenanceDispatchesTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Maintenance",
+ to: path.to.maintenanceDispatches
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const status = searchParams.get("status") ?? undefined;
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ return await getMaintenanceDispatches(client, companyId, {
+ search,
+ status,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+}
+
+export default function MaintenanceRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <MaintenanceDispatchesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsx
index eb31b90c1c..2cadc854a1 100644
--- a/apps/erp/app/routes/x+/settings+/items.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.tsx
@@ -161,7 +161,15 @@ export default function ItemsSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "materialIds"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
@@ -192,7 +200,15 @@ export default function ItemsSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "materialUnits"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsx
index a1810dd325..ea4416e29c 100644
--- a/apps/erp/app/routes/x+/settings+/production.tsx
+++ b/apps/erp/app/routes/x+/settings+/production.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,17 @@ 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 { z } from "zod/v3";
+import { zfd } from "zod-form-data";
import { Users } from "~/components/Form";
-import { getCompanySettings } from "~/modules/settings";
+import {
+ getCompanySettings,
+ jobCompletedValidator,
+ maintenanceSettingsValidator
+} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -29,11 +40,6 @@ export const handle: Handle = {
to: path.to.productionSettings
};
-const jobCompletedValidator = z.object({
- inventoryJobCompletedNotificationGroup: z.array(z.string()).optional(),
- salesJobCompletedNotificationGroup: z.array(z.string()).optional()
-});
-
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "settings"
@@ -58,30 +64,63 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(jobCompletedValidator).validate(formData);
+ const intent = formData.get("intent");
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
+ 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 };
+
+ return { success: true, message: "Maintenance settings updated" };
}
- const update = await client
- .from("companySettings")
- .update({
- inventoryJobCompletedNotificationGroup:
- validation.data.inventoryJobCompletedNotificationGroup ?? [],
- salesJobCompletedNotificationGroup:
- validation.data.salesJobCompletedNotificationGroup ?? []
- })
- .eq("id", companyId);
+ 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 };
- if (update.error) return { success: false, message: update.error.message };
+ return { success: true, message: "Job notification settings updated" };
+ }
- return { success: true, message: "Job notification settings updated" };
+ return null;
}
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) {
@@ -113,6 +152,7 @@ export default function ProductionSettingsRoute() {
}}
fetcher={fetcher}
>
+ <input type="hidden" name="intent" value="jobCompleted" />
<CardHeader>
<CardTitle className="flex items-center gap-2">
Completed Job Notifications
@@ -142,7 +182,68 @@ export default function ProductionSettingsRoute() {
<CardFooter>
<Submit
isDisabled={fetcher.state !== "idle"}
- isLoading={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"
+ }
>
Save
</Submit>
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index db49d38923..72a262cfa9 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -235,7 +235,16 @@ export default function PurchasingSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") ===
+ "purchasePriceUpdateTiming"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
@@ -273,7 +282,16 @@ export default function PurchasingSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") ===
+ "supplierQuoteNotification"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsx
index f76361f9b4..2b4217b513 100644
--- a/apps/erp/app/routes/x+/settings+/sales.tsx
+++ b/apps/erp/app/routes/x+/settings+/sales.tsx
@@ -230,7 +230,15 @@ export default function SalesSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "digitalQuote"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
@@ -263,7 +271,15 @@ export default function SalesSettingsRoute() {
</div>
</CardContent>
<CardFooter>
- <Submit>Save</Submit>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "rfq"
+ }
+ >
+ Save
+ </Submit>
</CardFooter>
</ValidatedForm>
</Card>
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 102979da28..48fd98115f 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -49,6 +49,7 @@ export const path = {
docs: `${api}/docs`,
employeeTypes: `${api}/users/employee-types`,
emptyPermissions: `${api}/users/empty-permissions`,
+ failureModes: `${api}/production/failure-modes`,
gauges: `${api}/quality/gauges`,
generateCsvColumns: (table: string) =>
generatePath(`${api}/ai/csv/${table}/columns`),
@@ -75,6 +76,8 @@ export const path = {
kanbanJobLink: (id: string) => generatePath(`${api}/kanban/link/${id}`),
kanbanStart: (id: string) => generatePath(`${api}/kanban/start/${id}`),
locations: `${api}/resources/locations`,
+ maintenanceDispatches: `${api}/production/maintenance`,
+ maintenanceSchedules: `${api}/production/maintenance-schedules`,
materialDimensions: (formId: string) =>
generatePath(`${api}/items/dimensions/${formId}`),
materialFinishes: (substanceId: string) =>
@@ -537,6 +540,8 @@ export const path = {
generatePath(`${x}/resources/ability/${abilityId}/employee/delete/${id}`),
deleteEmployeeType: (id: string) =>
generatePath(`${x}/users/employee-types/delete/${id}`),
+ deleteFailureMode: (id: string) =>
+ generatePath(`${x}/production/failure-modes/delete/${id}`),
deleteGauge: (id: string) =>
generatePath(`${x}/quality/gauges/delete/${id}`),
deleteGaugeCalibrationRecord: (id: string) =>
@@ -596,6 +601,10 @@ export const path = {
generatePath(`${x}/quality/issue-types/delete/${id}`),
deleteKanban: (id: string) =>
generatePath(`${x}/inventory/kanbans/delete/${id}`),
+ deleteMaintenanceDispatch: (id: string) =>
+ generatePath(`${x}/production/maintenance/delete/${id}`),
+ deleteMaintenanceSchedule: (id: string) =>
+ generatePath(`${x}/production/maintenance-schedules/delete/${id}`),
deleteNoQuoteReason: (id: string) =>
generatePath(`${x}/sales/no-quote-reasons/delete/${id}`),
deleteCustomerPortal: (id: string) =>
@@ -737,7 +746,9 @@ export const path = {
externalTraining: (assignmentId: string) =>
generatePath(`/share/training/${assignmentId}`),
feedback: `${x}/feedback`,
- resourcesSettings: `${x}/settings/resources`,
+ failureMode: (id: string) =>
+ generatePath(`${x}/production/failure-modes/${id}`),
+ failureModes: `${x}/production/failure-modes`,
fiscalYears: `${x}/accounting/years`,
gauge: (id: string) => generatePath(`${x}/quality/gauges/${id}`),
gauges: `${x}/quality/gauges`,
@@ -845,6 +856,21 @@ export const path = {
login: "/login",
logout: "/logout",
logos: `${x}/settings/logos`,
+ maintenanceDispatch: (id: string) => generatePath(`${x}/maintenance/${id}`),
+ maintenanceDispatchComments: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/comments`),
+ maintenanceDispatchEvents: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/events`),
+ maintenanceDispatchItems: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/items`),
+ maintenanceDispatchProperties: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/properties`),
+ maintenanceDispatchWorkCenters: (id: string) =>
+ generatePath(`${x}/maintenance/${id}/work-centers`),
+ maintenanceDispatches: `${x}/production/maintenance`,
+ maintenanceSchedule: (id: string) =>
+ generatePath(`${x}/production/maintenance-schedules/${id}`),
+ maintenanceSchedules: `${x}/production/maintenance-schedules`,
makeMethodGet: `${x}/items/methods/get`,
makeMethodSave: `${x}/items/methods/save`,
markTrainingComplete: `${x}/resources/assignments/complete`,
@@ -939,6 +965,7 @@ export const path = {
newEmployeeAbility: (id: string) =>
generatePath(`${x}/resources/ability/${id}/employee/new`),
newEmployeeType: `${x}/users/employee-types/new`,
+ newFailureMode: `${x}/production/failure-modes/new`,
newFixture: `${x}/fixture/new`,
newFixtureSupplier: (id: string) =>
generatePath(`${x}/fixture/${id}/purchasing/new`),
@@ -966,6 +993,8 @@ export const path = {
generatePath(`${x}/job/${jobId}/materials/session/new`),
newKanban: `${x}/inventory/kanbans/new`,
newLocation: `${x}/resources/locations/new`,
+ newMaintenanceDispatch: `${x}/production/maintenance/new`,
+ newMaintenanceSchedule: `${x}/production/maintenance-schedules/new`,
newMakeMethodVersion: `${x}/items/methods/version/new`,
newMaterial: `${x}/material/new`,
newMethodMaterial: `${x}/items/methods/material/new`,
@@ -1267,6 +1296,7 @@ export const path = {
requiredActions: `${x}/quality/required-actions`,
resendInvite: `${x}/users/resend-invite`,
resources: `${x}/resources`,
+ resourcesSettings: `${x}/settings/resources`,
revision: (id: string) => generatePath(`${x}/items/revisions/${id}`),
revokeInvite: `${x}/users/revoke-invite`,
risks: `${x}/quality/risks`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index e958626490..ffe34af1a2 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -23478,6 +23478,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.previousDispatchId",
+ },
{
$ref: "#/parameters/select",
},
@@ -23594,6 +23606,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.previousDispatchId",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -23664,6 +23688,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.previousDispatchId",
+ },
{
$ref: "#/parameters/body.maintenanceDispatch",
},
@@ -26676,6 +26712,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/select",
},
@@ -26765,6 +26807,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -26808,6 +26856,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/body.maintenanceDispatchItem",
},
@@ -41544,323 +41598,548 @@ export default {
tags: ["quoteOperationTool"],
},
},
- "/quoteLines": {
+ "/maintenanceSchedule": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.quoteLines.id",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.id",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.quoteId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.name",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.quoteRevisionId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.description",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.status",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.workCenterId",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.estimatorId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.frequency",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.itemId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.priority",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.itemType",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.estimatedDuration",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.description",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.active",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.customerPartId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.lastGeneratedAt",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.customerPartRevision",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.nextDueAt",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.methodType",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.companyId",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.unitOfMeasureCode",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdBy",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.internalNotes",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdAt",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.companyId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.createdBy",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.updatedAt",
+ $ref: "#/parameters/select",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.updatedBy",
+ $ref: "#/parameters/order",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.customFields",
+ $ref: "#/parameters/range",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.modelUploadId",
+ $ref: "#/parameters/rangeUnit",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.quantity",
+ $ref: "#/parameters/offset",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.additionalCharges",
+ $ref: "#/parameters/limit",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.locationId",
+ $ref: "#/parameters/preferCount",
},
- {
- $ref: "#/parameters/rowFilter.quoteLines.noQuoteReason",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/maintenanceSchedule",
+ },
+ type: "array",
+ },
},
- {
- $ref: "#/parameters/rowFilter.quoteLines.taxPercent",
+ "206": {
+ description: "Partial Content",
},
+ },
+ tags: ["maintenanceSchedule"],
+ },
+ post: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.quoteLines.tags",
+ $ref: "#/parameters/body.maintenanceSchedule",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.unitPricePrecision",
+ $ref: "#/parameters/select",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.externalNotes",
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
},
+ },
+ tags: ["maintenanceSchedule"],
+ },
+ delete: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.quoteLines.configuration",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.id",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.itemReadableId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.name",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.thumbnailPath",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.description",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.modelId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.workCenterId",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.autodeskUrn",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.frequency",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.modelPath",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.priority",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.modelName",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.estimatedDuration",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.modelSize",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.active",
},
{
- $ref: "#/parameters/rowFilter.quoteLines.unitCost",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.lastGeneratedAt",
},
{
- $ref: "#/parameters/select",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.nextDueAt",
},
{
- $ref: "#/parameters/order",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.companyId",
},
{
- $ref: "#/parameters/range",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdBy",
},
{
- $ref: "#/parameters/rangeUnit",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdAt",
},
{
- $ref: "#/parameters/offset",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedBy",
},
{
- $ref: "#/parameters/limit",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
{
- $ref: "#/parameters/preferCount",
+ $ref: "#/parameters/preferReturn",
},
],
responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/quoteLines",
- },
- type: "array",
- },
- },
- "206": {
- description: "Partial Content",
+ "204": {
+ description: "No Content",
},
},
- tags: ["quoteLines"],
+ tags: ["maintenanceSchedule"],
},
- },
- "/salesInvoices": {
- get: {
+ patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.salesInvoices.id",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.id",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.invoiceId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.name",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.status",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.description",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.customerId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.workCenterId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.customerReference",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.frequency",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.priority",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerLocationId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.estimatedDuration",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerContactId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.active",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.paymentTermId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.lastGeneratedAt",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.postingDate",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.nextDueAt",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.dateIssued",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.companyId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.dateDue",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdBy",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.datePaid",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.createdAt",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.locationId",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.currencyCode",
+ $ref: "#/parameters/rowFilter.maintenanceSchedule.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.subtotal",
+ $ref: "#/parameters/body.maintenanceSchedule",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.totalDiscount",
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
},
+ },
+ tags: ["maintenanceSchedule"],
+ },
+ },
+ "/quoteLines": {
+ get: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.salesInvoices.totalAmount",
+ $ref: "#/parameters/rowFilter.quoteLines.id",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.totalTax",
+ $ref: "#/parameters/rowFilter.quoteLines.quoteId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.balance",
+ $ref: "#/parameters/rowFilter.quoteLines.quoteRevisionId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.exchangeRate",
+ $ref: "#/parameters/rowFilter.quoteLines.status",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.exchangeRateUpdatedAt",
+ $ref: "#/parameters/rowFilter.quoteLines.estimatorId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.opportunityId",
+ $ref: "#/parameters/rowFilter.quoteLines.itemId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.shipmentId",
+ $ref: "#/parameters/rowFilter.quoteLines.itemType",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.assignee",
+ $ref: "#/parameters/rowFilter.quoteLines.description",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.companyId",
+ $ref: "#/parameters/rowFilter.quoteLines.customerPartId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.customFields",
+ $ref: "#/parameters/rowFilter.quoteLines.customerPartRevision",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.internalNotes",
+ $ref: "#/parameters/rowFilter.quoteLines.methodType",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.externalNotes",
+ $ref: "#/parameters/rowFilter.quoteLines.unitOfMeasureCode",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.tags",
+ $ref: "#/parameters/rowFilter.quoteLines.internalNotes",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.createdAt",
+ $ref: "#/parameters/rowFilter.quoteLines.companyId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.createdBy",
+ $ref: "#/parameters/rowFilter.quoteLines.createdBy",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.updatedAt",
+ $ref: "#/parameters/rowFilter.quoteLines.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.updatedBy",
+ $ref: "#/parameters/rowFilter.quoteLines.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.thumbnailPath",
+ $ref: "#/parameters/rowFilter.quoteLines.customFields",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.itemType",
+ $ref: "#/parameters/rowFilter.quoteLines.modelUploadId",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.invoiceTotal",
+ $ref: "#/parameters/rowFilter.quoteLines.quantity",
},
{
- $ref: "#/parameters/rowFilter.salesInvoices.lines",
+ $ref: "#/parameters/rowFilter.quoteLines.additionalCharges",
},
{
- $ref: "#/parameters/select",
+ $ref: "#/parameters/rowFilter.quoteLines.locationId",
},
{
- $ref: "#/parameters/order",
+ $ref: "#/parameters/rowFilter.quoteLines.noQuoteReason",
},
{
- $ref: "#/parameters/range",
+ $ref: "#/parameters/rowFilter.quoteLines.taxPercent",
},
{
- $ref: "#/parameters/rangeUnit",
+ $ref: "#/parameters/rowFilter.quoteLines.tags",
},
{
- $ref: "#/parameters/offset",
+ $ref: "#/parameters/rowFilter.quoteLines.unitPricePrecision",
},
{
- $ref: "#/parameters/limit",
+ $ref: "#/parameters/rowFilter.quoteLines.externalNotes",
},
{
- $ref: "#/parameters/preferCount",
+ $ref: "#/parameters/rowFilter.quoteLines.configuration",
},
- ],
- responses: {
- "200": {
- description: "OK",
- schema: {
- items: {
- $ref: "#/definitions/salesInvoices",
- },
- type: "array",
- },
+ {
+ $ref: "#/parameters/rowFilter.quoteLines.itemReadableId",
},
- "206": {
- description: "Partial Content",
+ {
+ $ref: "#/parameters/rowFilter.quoteLines.thumbnailPath",
},
- },
- tags: ["salesInvoices"],
- },
- },
- "/country": {
- get: {
- parameters: [
{
- $ref: "#/parameters/rowFilter.country.name",
+ $ref: "#/parameters/rowFilter.quoteLines.modelId",
},
{
- $ref: "#/parameters/rowFilter.country.alpha2",
+ $ref: "#/parameters/rowFilter.quoteLines.autodeskUrn",
},
{
- $ref: "#/parameters/rowFilter.country.alpha3",
+ $ref: "#/parameters/rowFilter.quoteLines.modelPath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteLines.modelName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteLines.modelSize",
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteLines.unitCost",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/quoteLines",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["quoteLines"],
+ },
+ },
+ "/salesInvoices": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.invoiceId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.status",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.customerId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.customerReference",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerLocationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.invoiceCustomerContactId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.paymentTermId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.postingDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.dateIssued",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.dateDue",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.datePaid",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.currencyCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.subtotal",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.totalDiscount",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.totalAmount",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.totalTax",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.balance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.exchangeRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.exchangeRateUpdatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.opportunityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.shipmentId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.assignee",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.internalNotes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.externalNotes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.tags",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.thumbnailPath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.itemType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.invoiceTotal",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.lines",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/salesInvoices",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["salesInvoices"],
+ },
+ },
+ "/country": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.country.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.country.alpha2",
+ },
+ {
+ $ref: "#/parameters/rowFilter.country.alpha3",
},
{
$ref: "#/parameters/select",
@@ -56397,41 +56676,38 @@ export default {
tags: ["supplierProcess"],
},
},
- "/itemPostingGroup": {
+ "/maintenanceScheduleItem": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.id",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.id",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.name",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.maintenanceScheduleId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.description",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.itemId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.active",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.quantity",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.companyId",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.unitOfMeasureCode",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.createdBy",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.companyId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.createdAt",
- },
- {
- $ref: "#/parameters/rowFilter.itemPostingGroup.updatedBy",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdBy",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.updatedAt",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdAt",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.customFields",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.tags",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedAt",
},
{
$ref: "#/parameters/select",
@@ -56460,7 +56736,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/itemPostingGroup",
+ $ref: "#/definitions/maintenanceScheduleItem",
},
type: "array",
},
@@ -56469,12 +56745,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["itemPostingGroup"],
+ tags: ["maintenanceScheduleItem"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.itemPostingGroup",
+ $ref: "#/parameters/body.maintenanceScheduleItem",
},
{
$ref: "#/parameters/select",
@@ -56488,42 +56764,85 @@ export default {
description: "Created",
},
},
- tags: ["itemPostingGroup"],
+ tags: ["maintenanceScheduleItem"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.id",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.id",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.name",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.maintenanceScheduleId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.description",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.itemId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.active",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.quantity",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.companyId",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.unitOfMeasureCode",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.createdBy",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.companyId",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.createdAt",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdBy",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.updatedBy",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdAt",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.updatedAt",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.customFields",
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.itemPostingGroup.tags",
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["maintenanceScheduleItem"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.maintenanceScheduleId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceScheduleItem.updatedAt",
+ },
+ {
+ $ref: "#/parameters/body.maintenanceScheduleItem",
},
{
$ref: "#/parameters/preferReturn",
@@ -56534,9 +56853,149 @@ export default {
description: "No Content",
},
},
- tags: ["itemPostingGroup"],
+ tags: ["maintenanceScheduleItem"],
},
- patch: {
+ },
+ "/itemPostingGroup": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.tags",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/itemPostingGroup",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["itemPostingGroup"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.itemPostingGroup",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["itemPostingGroup"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemPostingGroup.tags",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["itemPostingGroup"],
+ },
+ patch: {
parameters: [
{
$ref: "#/parameters/rowFilter.itemPostingGroup.id",
@@ -58404,6 +58863,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.supplierQuoteNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceGenerateInAdvance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceAdvanceDays",
+ },
{
$ref: "#/parameters/select",
},
@@ -58508,6 +58973,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.supplierQuoteNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceGenerateInAdvance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceAdvanceDays",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -58566,6 +59037,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.supplierQuoteNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceGenerateInAdvance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companySettings.maintenanceAdvanceDays",
+ },
{
$ref: "#/parameters/body.companySettings",
},
@@ -74201,6 +74678,7 @@ export default {
"companyId",
"createdBy",
"createdAt",
+ "isFailure",
],
properties: {
id: {
@@ -74300,6 +74778,27 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ source: {
+ format: "text",
+ type: "string",
+ },
+ maintenanceScheduleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `maintenanceSchedule.id`.<fk table='maintenanceSchedule' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ isFailure: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
+ previousDispatchId: {
+ description:
+ "Note:\nThis is a Foreign Key to `maintenanceDispatch.id`.<fk table='maintenanceDispatch' column='id'/>",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -75851,6 +76350,14 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ unitCost: {
+ format: "numeric",
+ type: "number",
+ },
+ totalCost: {
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -82713,6 +83220,97 @@ export default {
},
type: "object",
},
+ maintenanceSchedule: {
+ required: [
+ "id",
+ "name",
+ "workCenterId",
+ "frequency",
+ "priority",
+ "active",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ name: {
+ format: "text",
+ type: "string",
+ },
+ description: {
+ format: "text",
+ type: "string",
+ },
+ workCenterId: {
+ description:
+ "Note:\nThis is a Foreign Key to `workCenter.id`.<fk table='workCenter' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ frequency: {
+ enum: ["Daily", "Weekly", "Monthly", "Quarterly", "Annual"],
+ format: 'public."maintenanceFrequency"',
+ type: "string",
+ },
+ priority: {
+ default: "Medium",
+ enum: ["Low", "Medium", "High", "Critical"],
+ format: 'public."maintenanceDispatchPriority"',
+ type: "string",
+ },
+ estimatedDuration: {
+ format: "integer",
+ type: "integer",
+ },
+ active: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ lastGeneratedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ nextDueAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
quoteLines: {
properties: {
id: {
@@ -90123,6 +90721,74 @@ export default {
},
type: "object",
},
+ maintenanceScheduleItem: {
+ required: [
+ "id",
+ "maintenanceScheduleId",
+ "itemId",
+ "quantity",
+ "unitOfMeasureCode",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ maintenanceScheduleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `maintenanceSchedule.id`.<fk table='maintenanceSchedule' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantity: {
+ format: "integer",
+ type: "integer",
+ },
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
itemPostingGroup: {
required: ["id", "name", "active", "companyId", "createdBy", "createdAt"],
properties: {
@@ -90980,6 +91646,8 @@ export default {
"gaugeCalibrationExpiredNotificationGroup",
"purchasePriceUpdateTiming",
"supplierQuoteNotificationGroup",
+ "maintenanceGenerateInAdvance",
+ "maintenanceAdvanceDays",
],
properties: {
id: {
@@ -91072,6 +91740,16 @@ export default {
},
type: "array",
},
+ maintenanceGenerateInAdvance: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
+ maintenanceAdvanceDays: {
+ default: 7,
+ format: "integer",
+ type: "integer",
+ },
},
type: "object",
},
@@ -103744,6 +104422,30 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.source": {
+ name: "source",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceDispatch.maintenanceScheduleId": {
+ name: "maintenanceScheduleId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceDispatch.isFailure": {
+ name: "isFailure",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceDispatch.previousDispatchId": {
+ name: "previousDispatchId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.openProductionOrders": {
name: "openProductionOrders",
description: "openProductionOrders",
@@ -105505,6 +106207,18 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatchItem.unitCost": {
+ name: "unitCost",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceDispatchItem.totalCost": {
+ name: "totalCost",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.purchaseInvoice": {
name: "purchaseInvoice",
description: "purchaseInvoice",
@@ -113260,6 +113974,105 @@ export default {
in: "query",
type: "string",
},
+ "body.maintenanceSchedule": {
+ name: "maintenanceSchedule",
+ description: "maintenanceSchedule",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/maintenanceSchedule",
+ },
+ },
+ "rowFilter.maintenanceSchedule.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.frequency": {
+ name: "frequency",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.priority": {
+ name: "priority",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.estimatedDuration": {
+ name: "estimatedDuration",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.active": {
+ name: "active",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.lastGeneratedAt": {
+ name: "lastGeneratedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.nextDueAt": {
+ name: "nextDueAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceSchedule.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.quoteLines": {
name: "quoteLines",
description: "quoteLines",
@@ -121522,6 +122335,75 @@ export default {
in: "query",
type: "string",
},
+ "body.maintenanceScheduleItem": {
+ name: "maintenanceScheduleItem",
+ description: "maintenanceScheduleItem",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/maintenanceScheduleItem",
+ },
+ },
+ "rowFilter.maintenanceScheduleItem.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.maintenanceScheduleId": {
+ name: "maintenanceScheduleId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.quantity": {
+ name: "quantity",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceScheduleItem.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.itemPostingGroup": {
name: "itemPostingGroup",
description: "itemPostingGroup",
@@ -122545,6 +123427,18 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companySettings.maintenanceGenerateInAdvance": {
+ name: "maintenanceGenerateInAdvance",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.companySettings.maintenanceAdvanceDays": {
+ name: "maintenanceAdvanceDays",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d90fd486aa..c2c87a09ce 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -12449,11 +12449,15 @@ export type Database = {
createdBy: string
duration: number | null
id: string
+ isFailure: boolean
+ maintenanceScheduleId: string | null
nonConformanceId: string | null
plannedEndTime: string | null
plannedStartTime: string | null
+ previousDispatchId: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source: string | null
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
updatedAt: string | null
@@ -12470,11 +12474,15 @@ export type Database = {
createdBy: string
duration?: number | null
id?: string
+ isFailure?: boolean
+ maintenanceScheduleId?: string | null
nonConformanceId?: string | null
plannedEndTime?: string | null
plannedStartTime?: string | null
+ previousDispatchId?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source?: string | null
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
@@ -12491,11 +12499,15 @@ export type Database = {
createdBy?: string
duration?: number | null
id?: string
+ isFailure?: boolean
+ maintenanceScheduleId?: string | null
nonConformanceId?: string | null
plannedEndTime?: string | null
plannedStartTime?: string | null
+ previousDispatchId?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source?: string | null
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
@@ -12607,6 +12619,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_maintenanceScheduleId_fkey"
+ columns: ["maintenanceScheduleId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceSchedule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_nonConformanceId_fkey"
columns: ["nonConformanceId"]
@@ -12621,6 +12640,13 @@ export type Database = {
referencedRelation: "nonConformance"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_previousDispatchId_fkey"
+ columns: ["previousDispatchId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceDispatch"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_suspectedFailureModeId_fkey"
columns: ["suspectedFailureModeId"]
@@ -13016,6 +13042,8 @@ export type Database = {
itemId: string
maintenanceDispatchId: string
quantity: number
+ totalCost: number | null
+ unitCost: number | null
unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
@@ -13028,6 +13056,8 @@ export type Database = {
itemId: string
maintenanceDispatchId: string
quantity: number
+ totalCost?: number | null
+ unitCost?: number | null
unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
@@ -13040,6 +13070,8 @@ export type Database = {
itemId?: string
maintenanceDispatchId?: string
quantity?: number
+ totalCost?: number | null
+ unitCost?: number | null
unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -13469,6 +13501,353 @@ export type Database = {
},
]
}
+ maintenanceSchedule: {
+ Row: {
+ active: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: string | null
+ estimatedDuration: number | null
+ frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ id: string
+ lastGeneratedAt: string | null
+ name: string
+ nextDueAt: string | null
+ priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string
+ }
+ Insert: {
+ active?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: string | null
+ estimatedDuration?: number | null
+ frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ id?: string
+ lastGeneratedAt?: string | null
+ name: string
+ nextDueAt?: string | null
+ priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId: string
+ }
+ Update: {
+ active?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: string | null
+ estimatedDuration?: number | null
+ frequency?: Database["public"]["Enums"]["maintenanceFrequency"]
+ id?: string
+ lastGeneratedAt?: string | null
+ name?: string
+ nextDueAt?: string | null
+ priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ maintenanceScheduleItem: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ maintenanceScheduleId: string
+ quantity: number
+ unitOfMeasureCode: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ maintenanceScheduleId: string
+ quantity: number
+ unitOfMeasureCode: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ maintenanceScheduleId?: string
+ quantity?: number
+ unitOfMeasureCode?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_maintenanceScheduleId_fkey"
+ columns: ["maintenanceScheduleId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceSchedule"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
makeMethod: {
Row: {
companyId: string
@@ -52687,6 +53066,12 @@ export type Database = {
| "In Progress"
| "Completed"
| "Cancelled"
+ maintenanceFrequency:
+ | "Daily"
+ | "Weekly"
+ | "Monthly"
+ | "Quarterly"
+ | "Annual"
maintenanceSeverity:
| "Preventive"
| "OPM"
@@ -53821,6 +54206,13 @@ export const Constants = {
"Completed",
"Cancelled",
],
+ maintenanceFrequency: [
+ "Daily",
+ "Weekly",
+ "Monthly",
+ "Quarterly",
+ "Annual",
+ ],
maintenanceSeverity: [
"Preventive",
"OPM",
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 67994fcc57..165475ba75 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -1584,6 +1584,19 @@ export const groups = [
},
];
+export const failureModes: string[] = [
+ "Bearing Failure",
+ "Lubrication Failure",
+ "Electrical Fault",
+ "Leakage",
+ "Excessive Wear/Abrasion",
+ "Misalignment",
+ "Overheating",
+ "Fatigue/Crack",
+ "Blockage/Clogging",
+ "Vibration (Excessive)"
+];
+
export const nonConformanceTypes: Omit<
Database["public"]["Tables"]["nonConformanceType"]["Insert"],
"companyId"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d90fd486aa..c2c87a09ce 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -12449,11 +12449,15 @@ export type Database = {
createdBy: string
duration: number | null
id: string
+ isFailure: boolean
+ maintenanceScheduleId: string | null
nonConformanceId: string | null
plannedEndTime: string | null
plannedStartTime: string | null
+ previousDispatchId: string | null
priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source: string | null
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
updatedAt: string | null
@@ -12470,11 +12474,15 @@ export type Database = {
createdBy: string
duration?: number | null
id?: string
+ isFailure?: boolean
+ maintenanceScheduleId?: string | null
nonConformanceId?: string | null
plannedEndTime?: string | null
plannedStartTime?: string | null
+ previousDispatchId?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source?: string | null
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
@@ -12491,11 +12499,15 @@ export type Database = {
createdBy?: string
duration?: number | null
id?: string
+ isFailure?: boolean
+ maintenanceScheduleId?: string | null
nonConformanceId?: string | null
plannedEndTime?: string | null
plannedStartTime?: string | null
+ previousDispatchId?: string | null
priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
severity?: Database["public"]["Enums"]["maintenanceSeverity"] | null
+ source?: string | null
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
@@ -12607,6 +12619,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_maintenanceScheduleId_fkey"
+ columns: ["maintenanceScheduleId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceSchedule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_nonConformanceId_fkey"
columns: ["nonConformanceId"]
@@ -12621,6 +12640,13 @@ export type Database = {
referencedRelation: "nonConformance"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_previousDispatchId_fkey"
+ columns: ["previousDispatchId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceDispatch"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatch_suspectedFailureModeId_fkey"
columns: ["suspectedFailureModeId"]
@@ -13016,6 +13042,8 @@ export type Database = {
itemId: string
maintenanceDispatchId: string
quantity: number
+ totalCost: number | null
+ unitCost: number | null
unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
@@ -13028,6 +13056,8 @@ export type Database = {
itemId: string
maintenanceDispatchId: string
quantity: number
+ totalCost?: number | null
+ unitCost?: number | null
unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
@@ -13040,6 +13070,8 @@ export type Database = {
itemId?: string
maintenanceDispatchId?: string
quantity?: number
+ totalCost?: number | null
+ unitCost?: number | null
unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -13469,6 +13501,353 @@ export type Database = {
},
]
}
+ maintenanceSchedule: {
+ Row: {
+ active: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: string | null
+ estimatedDuration: number | null
+ frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ id: string
+ lastGeneratedAt: string | null
+ name: string
+ nextDueAt: string | null
+ priority: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string
+ }
+ Insert: {
+ active?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: string | null
+ estimatedDuration?: number | null
+ frequency: Database["public"]["Enums"]["maintenanceFrequency"]
+ id?: string
+ lastGeneratedAt?: string | null
+ name: string
+ nextDueAt?: string | null
+ priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId: string
+ }
+ Update: {
+ active?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: string | null
+ estimatedDuration?: number | null
+ frequency?: Database["public"]["Enums"]["maintenanceFrequency"]
+ id?: string
+ lastGeneratedAt?: string | null
+ name?: string
+ nextDueAt?: string | null
+ priority?: Database["public"]["Enums"]["maintenanceDispatchPriority"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceSchedule_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ maintenanceScheduleItem: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ maintenanceScheduleId: string
+ quantity: number
+ unitOfMeasureCode: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ maintenanceScheduleId: string
+ quantity: number
+ unitOfMeasureCode: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ maintenanceScheduleId?: string
+ quantity?: number
+ unitOfMeasureCode?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_maintenanceScheduleId_fkey"
+ columns: ["maintenanceScheduleId"]
+ isOneToOne: false
+ referencedRelation: "maintenanceSchedule"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceScheduleItem_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
makeMethod: {
Row: {
companyId: string
@@ -52687,6 +53066,12 @@ export type Database = {
| "In Progress"
| "Completed"
| "Cancelled"
+ maintenanceFrequency:
+ | "Daily"
+ | "Weekly"
+ | "Monthly"
+ | "Quarterly"
+ | "Annual"
maintenanceSeverity:
| "Preventive"
| "OPM"
@@ -53821,6 +54206,13 @@ export const Constants = {
"Completed",
"Cancelled",
],
+ maintenanceFrequency: [
+ "Daily",
+ "Weekly",
+ "Monthly",
+ "Quarterly",
+ "Annual",
+ ],
maintenanceSeverity: [
"Preventive",
"OPM",
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index 11b9eb8c0a..0db3168837 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -8,6 +8,7 @@ import {
accounts,
currencies,
customerStatuses,
+ failureModes,
fiscalYearSettings,
gaugeTypes,
groupCompanyTemplate,
@@ -112,7 +113,7 @@ serve(async (req: Request) => {
throw new Error("Failed to insert admin employee type");
// get the modules
- const modules = await trx.selectFrom("modules").select("name").execute();
+ const modules = await trx.selectFrom("modules").select("name").execute() as { name: string }[];
// create employee type permissions for admin
const employeeTypePermissions = modules.reduce<
@@ -121,6 +122,7 @@ serve(async (req: Request) => {
if (module.name) {
acc.push({
employeeTypeId: employeeTypeId,
+ // @ts-expect-error - it's legit, chill typescript
module: module.name,
create: [companyId],
update: [companyId],
@@ -204,6 +206,11 @@ serve(async (req: Request) => {
)
.execute();
+ await trx
+ .insertInto("maintenanceFailureMode")
+ .values(failureModes.map((name) => ({ name, companyId, createdBy: "system" })))
+ .execute();
+
await trx
.insertInto("nonConformanceType")
.values(nonConformanceTypes.map((nc) => ({ ...nc, companyId })))
diff --git a/packages/database/supabase/migrations/20251216021152_maintenance.sql b/packages/database/supabase/migrations/20251216021152_maintenance.sql
index 974b82c059..9a86f031a6 100644
--- a/packages/database/supabase/migrations/20251216021152_maintenance.sql
+++ b/packages/database/supabase/migrations/20251216021152_maintenance.sql
@@ -25,6 +25,46 @@ CREATE TABLE "maintenanceFailureMode" (
CONSTRAINT "maintenanceFailureMode_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
+CREATE POLICY "SELECT" ON "public"."maintenanceFailureMode"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('production_view')
+ )::text[]
+ )
+);
+CREATE POLICY "INSERT" ON "maintenanceFailureMode"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('production_create')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "maintenanceFailureMode"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('production_update')
+ )::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "maintenanceFailureMode"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission('production_delete')
+ )::text[]
+ )
+ );
+
DO $$ BEGIN
CREATE TYPE "maintenanceDispatchPriority" AS ENUM (
'Low',
diff --git a/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql b/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql
new file mode 100644
index 0000000000..bc393ed30e
--- /dev/null
+++ b/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql
@@ -0,0 +1,110 @@
+-- Add source and schedule link to maintenanceDispatch
+ALTER TABLE "maintenanceDispatch"
+ ADD COLUMN IF NOT EXISTS "source" TEXT,
+ ADD COLUMN IF NOT EXISTS "maintenanceScheduleId" TEXT,
+ ADD COLUMN IF NOT EXISTS "isFailure" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN IF NOT EXISTS "previousDispatchId" TEXT;
+
+-- Add unit cost to maintenanceDispatchItem
+ALTER TABLE "maintenanceDispatchItem"
+ ADD COLUMN IF NOT EXISTS "unitCost" NUMERIC;
+
+-- Recreate maintenanceDispatchItem with totalCost as generated column
+-- First, drop and recreate the table to add the generated column
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'maintenanceDispatchItem'
+ AND column_name = 'totalCost'
+ ) THEN
+ ALTER TABLE "maintenanceDispatchItem"
+ ADD COLUMN "totalCost" NUMERIC GENERATED ALWAYS AS ("quantity" * "unitCost") STORED;
+ END IF;
+END $$;
+
+-- Maintenance frequency enum
+DO $$ BEGIN
+ CREATE TYPE "maintenanceFrequency" AS ENUM (
+ 'Daily',
+ 'Weekly',
+ 'Monthly',
+ 'Quarterly',
+ 'Annual'
+ );
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+
+-- Maintenance schedule table
+CREATE TABLE IF NOT EXISTS "maintenanceSchedule" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "workCenterId" TEXT NOT NULL,
+ "frequency" "maintenanceFrequency" NOT NULL,
+ "priority" "maintenanceDispatchPriority" NOT NULL DEFAULT 'Medium',
+ "estimatedDuration" INTEGER,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "lastGeneratedAt" TIMESTAMP WITH TIME ZONE,
+ "nextDueAt" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "maintenanceSchedule_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "maintenanceSchedule_workCenterId_fkey" FOREIGN KEY ("workCenterId") REFERENCES "workCenter"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceSchedule_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceSchedule_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceSchedule_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_workCenterId_idx" ON "maintenanceSchedule" ("workCenterId");
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_companyId_idx" ON "maintenanceSchedule" ("companyId");
+CREATE INDEX IF NOT EXISTS "maintenanceSchedule_active_idx" ON "maintenanceSchedule" ("active");
+
+-- Maintenance schedule items (parts required for scheduled maintenance)
+CREATE TABLE IF NOT EXISTS "maintenanceScheduleItem" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "maintenanceScheduleId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "quantity" INTEGER NOT NULL,
+ "unitOfMeasureCode" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "maintenanceScheduleItem_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "maintenanceScheduleItem_maintenanceScheduleId_fkey" FOREIGN KEY ("maintenanceScheduleId") REFERENCES "maintenanceSchedule"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceScheduleItem_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceScheduleItem_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceScheduleItem_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceScheduleItem_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_maintenanceScheduleId_idx" ON "maintenanceScheduleItem" ("maintenanceScheduleId");
+CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_itemId_idx" ON "maintenanceScheduleItem" ("itemId");
+CREATE INDEX IF NOT EXISTS "maintenanceScheduleItem_companyId_idx" ON "maintenanceScheduleItem" ("companyId");
+
+-- Add foreign key for maintenanceScheduleId on maintenanceDispatch
+ALTER TABLE "maintenanceDispatch"
+ ADD CONSTRAINT "maintenanceDispatch_maintenanceScheduleId_fkey"
+ FOREIGN KEY ("maintenanceScheduleId") REFERENCES "maintenanceSchedule"("id")
+ ON DELETE SET NULL ON UPDATE CASCADE;
+
+ALTER TABLE "maintenanceDispatch"
+ ADD CONSTRAINT "maintenanceDispatch_previousDispatchId_fkey"
+ FOREIGN KEY ("previousDispatchId") REFERENCES "maintenanceDispatch"("id")
+ ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- Company settings for maintenance scheduling
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "maintenanceGenerateInAdvance" BOOLEAN NOT NULL DEFAULT false;
+
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "maintenanceAdvanceDays" INTEGER NOT NULL DEFAULT 7;
+