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: create maintenance dispatches

Brad Barbin95139af5145d
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 9ac4bfcf2c..39de01c13d 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -87,9 +87,9 @@ export const maintenanceSeverity = [
] as const;
export const maintenanceSource = [
- "scheduled",
- "reactive",
- "non-conformance"
+ "Scheduled",
+ "Reactive",
+ "Non-Conformance"
] as const;
export const procedureStatus = ["Draft", "Active", "Archived"] as const;
@@ -895,13 +895,15 @@ export const maintenanceDispatchValidator = z.object({
priority: z.enum(maintenanceDispatchPriority),
severity: z.enum(maintenanceSeverity).optional(),
source: z.enum(maintenanceSource).optional(),
+ workCenterId: zfd.text(z.string().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()
+ isFailure: z.boolean().optional(),
+ content: zfd.text(z.string().optional())
});
export const maintenanceDispatchCommentValidator = z.object({
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 665dcb5eb5..e1cbb90047 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1584,17 +1584,11 @@ export async function getMaintenanceDispatches(
) {
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" }
- )
+ .select(`*`, { count: "exact" })
.eq("companyId", companyId);
if (args?.search) {
- query = query.ilike("id", `%${args.search}%`);
+ query = query.ilike("maintenanceDispatchId", `%${args.search}%`);
}
if (args) {
@@ -2644,6 +2638,7 @@ export async function upsertMaintenanceDispatch(
client: SupabaseClient<Database>,
dispatch:
| (Omit<z.infer<typeof maintenanceDispatchValidator>, "id"> & {
+ maintenanceDispatchId: string;
companyId: string;
createdBy: string;
content?: Json;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx
new file mode 100644
index 0000000000..0c6d32e748
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchForm.tsx
@@ -0,0 +1,175 @@
+import { useCarbon } from "@carbon/auth";
+import { DateTimePicker, Select, ValidatedForm } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ Label,
+ toast,
+ VStack
+} from "@carbon/react";
+import { Editor } from "@carbon/react/Editor";
+import { nanoid } from "nanoid";
+import { useState } from "react";
+import { BsExclamationSquareFill } from "react-icons/bs";
+import type { z } from "zod/v3";
+import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
+import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
+import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
+import { Hidden, Submit, WorkCenter } from "~/components/Form";
+import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl, path } from "~/utils/path";
+import {
+ maintenanceDispatchPriority,
+ maintenanceDispatchValidator,
+ maintenanceSource
+} from "../../production.models";
+import MaintenanceSource from "./MaintenanceSource";
+
+function getPriorityIcon(
+ priority: (typeof maintenanceDispatchPriority)[number]
+) {
+ switch (priority) {
+ case "Critical":
+ return <BsExclamationSquareFill className="text-red-500" />;
+ case "High":
+ return <HighPriorityIcon />;
+ case "Medium":
+ return <MediumPriorityIcon />;
+ case "Low":
+ return <LowPriorityIcon />;
+ }
+}
+
+type MaintenanceDispatchFormProps = {
+ initialValues: z.infer<typeof maintenanceDispatchValidator>;
+ failureModes?: { id: string; name: string }[];
+};
+
+const MaintenanceDispatchForm = ({
+ initialValues,
+ failureModes = []
+}: MaintenanceDispatchFormProps) => {
+ const permissions = usePermissions();
+ const {
+ company: { id: companyId }
+ } = useUser();
+ const { carbon } = useCarbon();
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "production")
+ : !permissions.can("create", "production");
+
+ const [content, setContent] = useState<JSONContent>(
+ initialValues?.content
+ ? (JSON.parse(initialValues.content) as JSONContent)
+ : {}
+ );
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/maintenance/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ return (
+ <Card>
+ <ValidatedForm
+ validator={maintenanceDispatchValidator}
+ method="post"
+ action={path.to.newMaintenanceDispatch}
+ defaultValues={initialValues}
+ >
+ <CardHeader>
+ <CardTitle>
+ {isEditing ? "Edit" : "New"} Maintenance Dispatch
+ </CardTitle>
+ {!isEditing && (
+ <CardDescription>
+ Create a new maintenance dispatch to track equipment repairs and
+ maintenance activities
+ </CardDescription>
+ )}
+ </CardHeader>
+ <CardContent>
+ <Hidden name="id" />
+ <Hidden name="status" value="Open" />
+ <Hidden name="content" value={JSON.stringify(content)} />
+ <VStack>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 md:grid-cols-2">
+ <Select
+ name="priority"
+ label="Priority"
+ options={maintenanceDispatchPriority.map((priority) => ({
+ value: priority,
+ label: (
+ <div className="flex gap-1 items-center">
+ {getPriorityIcon(priority)}
+ <span>{priority}</span>
+ </div>
+ )
+ }))}
+ />
+ <Select
+ name="source"
+ label="Source"
+ options={maintenanceSource.map((source) => ({
+ value: source,
+ label: <MaintenanceSource source={source} />
+ }))}
+ />
+ <WorkCenter name="workCenterId" label="Work Center" />
+ <Select
+ name="suspectedFailureModeId"
+ label="Suspected Failure Mode"
+ options={failureModes.map((mode) => ({
+ value: mode.id,
+ label: mode.name
+ }))}
+ isClearable
+ />
+ <DateTimePicker
+ name="plannedStartTime"
+ label="Planned Start Time"
+ />
+ <DateTimePicker name="plannedEndTime" label="Planned End Time" />
+ <div className="md:col-span-2 flex flex-col gap-2 w-full">
+ <Label>Description</Label>
+ <Editor
+ initialValue={content}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setContent(value);
+ }}
+ className="[&_.is-empty]:text-muted-foreground min-h-[120px] py-3 px-4 border rounded-md w-full"
+ />
+ </div>
+ </div>
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+};
+
+export default MaintenanceDispatchForm;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx
index 3bafb4d292..4488c413b2 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceDispatchesTable.tsx
@@ -1,17 +1,31 @@
import { HStack, MenuIcon, MenuItem } from "@carbon/react";
+import { formatDate } from "@carbon/utils";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
-import { LuPencil, LuTrash } from "react-icons/lu";
+import {
+ LuBookMarked,
+ LuBuilding,
+ LuCalendar,
+ LuChartNoAxesColumnIncreasing,
+ LuDna,
+ LuPencil,
+ LuStar,
+ LuTrash,
+ LuUser
+} from "react-icons/lu";
import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import { useWorkCenters } from "~/components/Form/WorkCenters";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import {
maintenanceDispatchPriority,
- maintenanceDispatchStatus
+ maintenanceDispatchStatus,
+ maintenanceSource
} from "../../production.models";
import type { MaintenanceDispatch } from "../../types";
import MaintenancePriority from "./MaintenancePriority";
+import MaintenanceSource from "./MaintenanceSource";
import MaintenanceStatus from "./MaintenanceStatus";
type MaintenanceDispatchesTableProps = {
@@ -24,17 +38,39 @@ const MaintenanceDispatchesTable = memo(
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
+ const workCenters = useWorkCenters();
const columns = useMemo<ColumnDef<MaintenanceDispatch>[]>(() => {
return [
{
- accessorKey: "id",
+ accessorKey: "maintenanceDispatchId",
header: "Dispatch ID",
cell: ({ row }) => (
<Hyperlink to={path.to.maintenanceDispatch(row.original.id)}>
- {row.original.id}
+ {row.original.maintenanceDispatchId}
</Hyperlink>
- )
+ ),
+ meta: {
+ icon: <LuBookMarked />
+ }
+ },
+ {
+ accessorKey: "source",
+ header: "Source",
+ cell: (item) => {
+ const source = item.getValue<(typeof maintenanceSource)[number]>();
+ return <MaintenanceSource source={source} />;
+ },
+ meta: {
+ icon: <LuDna />,
+ filter: {
+ type: "static",
+ options: maintenanceSource.map((source) => ({
+ value: source,
+ label: <MaintenanceSource source={source} />
+ }))
+ }
+ }
},
{
accessorKey: "status",
@@ -45,6 +81,7 @@ const MaintenanceDispatchesTable = memo(
return <MaintenanceStatus status={status} />;
},
meta: {
+ icon: <LuStar />,
filter: {
type: "static",
options: maintenanceDispatchStatus.map((status) => ({
@@ -64,6 +101,7 @@ const MaintenanceDispatchesTable = memo(
return <MaintenancePriority priority={priority} />;
},
meta: {
+ icon: <LuChartNoAxesColumnIncreasing />,
filter: {
type: "static",
options: maintenanceDispatchPriority.map((priority) => ({
@@ -87,6 +125,33 @@ const MaintenanceDispatchesTable = memo(
<EmployeeAvatar employeeId={assignee.id} size="xs" />
</HStack>
);
+ },
+ meta: {
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "workCenterId",
+ header: "Work Center",
+ cell: ({ row }) => {
+ const workCenterId = row.original.workCenterId;
+ if (!workCenterId) {
+ return <span className="text-muted-foreground">Unassigned</span>;
+ }
+ const workCenter = workCenters.find(
+ (workCenter) => workCenter.value === workCenterId
+ );
+ if (!workCenter) {
+ return <span className="text-muted-foreground">Unknown</span>;
+ }
+ return (
+ <Hyperlink to={path.to.workCenter(workCenterId)}>
+ {workCenter.label}
+ </Hyperlink>
+ );
+ },
+ meta: {
+ icon: <LuBuilding />
}
},
{
@@ -94,7 +159,10 @@ const MaintenanceDispatchesTable = memo(
header: "Planned Start",
cell: ({ row }) => {
const date = row.original.plannedStartTime;
- return date ? new Date(date).toLocaleDateString() : "-";
+ return date ? formatDate(date) : "-";
+ },
+ meta: {
+ icon: <LuCalendar />
}
},
{
@@ -102,11 +170,14 @@ const MaintenanceDispatchesTable = memo(
header: "Created",
cell: ({ row }) => {
const date = row.original.createdAt;
- return date ? new Date(date).toLocaleDateString() : "-";
+ return date ? formatDate(date) : "-";
+ },
+ meta: {
+ icon: <LuCalendar />
}
}
];
- }, []);
+ }, [workCenters]);
const renderContextMenu = useCallback(
(row: MaintenanceDispatch) => {
@@ -146,7 +217,7 @@ const MaintenanceDispatchesTable = memo(
primaryAction={
permissions.can("create", "production") && (
<New
- label="Maintenance Dispatch"
+ label="Dispatch"
to={`${path.to.newMaintenanceDispatch}?${params.toString()}`}
/>
)
diff --git a/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSource.tsx b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSource.tsx
new file mode 100644
index 0000000000..d1e2606c6c
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/MaintenanceSource.tsx
@@ -0,0 +1,48 @@
+import { Badge, cn } from "@carbon/react";
+import { LuCalendarClock, LuShieldX, LuTriangleAlert } from "react-icons/lu";
+import type { maintenanceSource } from "../../production.models";
+
+type MaintenanceSourceProps = {
+ source?: (typeof maintenanceSource)[number] | null;
+ className?: string;
+};
+
+function MaintenanceSource({ source, className }: MaintenanceSourceProps) {
+ switch (source) {
+ case "Scheduled":
+ return (
+ <Badge
+ variant="outline"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuCalendarClock />
+ {source}
+ </Badge>
+ );
+ case "Reactive":
+ return (
+ <Badge
+ variant="red"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuTriangleAlert />
+ {source}
+ </Badge>
+ );
+ case "Non-Conformance":
+ return (
+ <Badge
+ variant="gray"
+ className={cn(className, "inline-flex items-center gap-1")}
+ >
+ <LuShieldX />
+ {source}
+ </Badge>
+ );
+
+ default:
+ return null;
+ }
+}
+
+export default MaintenanceSource;
diff --git a/apps/erp/app/modules/production/ui/Maintenance/Untitled b/apps/erp/app/modules/production/ui/Maintenance/Untitled
new file mode 100644
index 0000000000..10b979c5ce
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Maintenance/Untitled
@@ -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
index d7e5ec0543..f89e5ebeee 100644
--- a/apps/erp/app/modules/production/ui/Maintenance/index.ts
+++ b/apps/erp/app/modules/production/ui/Maintenance/index.ts
@@ -1,4 +1,5 @@
export { default as MaintenanceDispatchesTable } from "./MaintenanceDispatchesTable";
+export { default as MaintenanceDispatchForm } from "./MaintenanceDispatchForm";
export { default as MaintenanceDispatchHeader } from "./MaintenanceDispatchHeader";
export { default as MaintenanceDispatchProperties } from "./MaintenanceDispatchProperties";
export { default as MaintenancePriority } from "./MaintenancePriority";
diff --git a/apps/erp/app/routes/x+/maintenance+/new.tsx b/apps/erp/app/routes/x+/maintenance+/new.tsx
new file mode 100644
index 0000000000..e4da6f9569
--- /dev/null
+++ b/apps/erp/app/routes/x+/maintenance+/new.tsx
@@ -0,0 +1,126 @@
+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, useLoaderData } from "react-router";
+import {
+ getFailureModesList,
+ maintenanceDispatchValidator,
+ upsertMaintenanceDispatch
+} from "~/modules/production";
+import { MaintenanceDispatchForm } from "~/modules/production/ui/Maintenance";
+import { getNextSequence } from "~/modules/settings";
+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 }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const failureModes = await getFailureModesList(client, companyId);
+
+ return {
+ failureModes: failureModes.data ?? []
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(maintenanceDispatchValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(
+ client,
+ "maintenanceDispatch",
+ companyId
+ );
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.maintenanceDispatches,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const content = validation.data.content
+ ? JSON.parse(validation.data.content)
+ : {};
+
+ const insertDispatch = await upsertMaintenanceDispatch(client, {
+ maintenanceDispatchId: nextSequence.data,
+ status: validation.data.status,
+ priority: validation.data.priority,
+ severity: validation.data.severity || null,
+ source: validation.data.source || "Reactive",
+ workCenterId: validation.data.workCenterId || null,
+ assignee: validation.data.assignee || null,
+ suspectedFailureModeId: validation.data.suspectedFailureModeId || null,
+ plannedStartTime: validation.data.plannedStartTime || null,
+ plannedEndTime: validation.data.plannedEndTime || null,
+ content,
+ companyId,
+ createdBy: userId
+ });
+
+ if (insertDispatch.error) {
+ throw redirect(
+ path.to.maintenanceDispatches,
+ await flash(
+ request,
+ error(insertDispatch.error, "Failed to create maintenance dispatch")
+ )
+ );
+ }
+
+ const newId = insertDispatch.data?.id;
+ if (!newId) {
+ throw redirect(
+ path.to.maintenanceDispatches,
+ 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() {
+ const { failureModes } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ status: "Open" as const,
+ priority: "Medium" as const,
+ source: "Reactive" as const
+ };
+
+ return (
+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
+ <MaintenanceDispatchForm
+ initialValues={initialValues}
+ failureModes={failureModes}
+ />
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/maintenance.new.tsx b/apps/erp/app/routes/x+/production+/maintenance.new.tsx
deleted file mode 100644
index 7d33e1d5e2..0000000000
--- a/apps/erp/app/routes/x+/production+/maintenance.new.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs, 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/utils/path.ts b/apps/erp/app/utils/path.ts
index 48fd98115f..b9f9396b94 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -993,7 +993,7 @@ 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`,
+ newMaintenanceDispatch: `${x}/maintenance/new`,
newMaintenanceSchedule: `${x}/production/maintenance-schedules/new`,
newMakeMethodVersion: `${x}/items/methods/version/new`,
newMaterial: `${x}/material/new`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index ffe34af1a2..467f89742c 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -23424,6 +23424,9 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.id",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceDispatchId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.content",
},
@@ -23433,9 +23436,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.priority",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.severity",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.workCenterId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.suspectedFailureModeId",
},
@@ -23454,12 +23466,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.actualEndTime",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.duration",
},
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.nonConformanceId",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.completedAt",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.assignee",
},
@@ -23478,18 +23496,6 @@ 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",
},
@@ -23552,6 +23558,9 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.id",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceDispatchId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.content",
},
@@ -23561,9 +23570,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.priority",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.severity",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.workCenterId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.suspectedFailureModeId",
},
@@ -23582,12 +23600,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.actualEndTime",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.duration",
},
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.nonConformanceId",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.completedAt",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.assignee",
},
@@ -23606,18 +23630,6 @@ 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",
},
@@ -23634,6 +23646,9 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.id",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceDispatchId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.content",
},
@@ -23643,9 +23658,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.priority",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.source",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.severity",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.workCenterId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.maintenanceScheduleId",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.suspectedFailureModeId",
},
@@ -23664,12 +23688,18 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.actualEndTime",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.isFailure",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.duration",
},
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.nonConformanceId",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatch.completedAt",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatch.assignee",
},
@@ -23688,18 +23718,6 @@ 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",
},
@@ -26697,6 +26715,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitOfMeasureCode",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.companyId",
},
@@ -26712,12 +26736,6 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
- },
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
- },
{
$ref: "#/parameters/select",
},
@@ -26792,6 +26810,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitOfMeasureCode",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.companyId",
},
@@ -26807,12 +26831,6 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
- },
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -26841,6 +26859,12 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitOfMeasureCode",
},
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
+ },
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.companyId",
},
@@ -26856,12 +26880,6 @@ export default {
{
$ref: "#/parameters/rowFilter.maintenanceDispatchItem.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.unitCost",
- },
- {
- $ref: "#/parameters/rowFilter.maintenanceDispatchItem.totalCost",
- },
{
$ref: "#/parameters/body.maintenanceDispatchItem",
},
@@ -74672,21 +74690,27 @@ export default {
maintenanceDispatch: {
required: [
"id",
+ "maintenanceDispatchId",
"content",
"status",
"priority",
+ "source",
+ "isFailure",
"companyId",
"createdBy",
"createdAt",
- "isFailure",
],
properties: {
id: {
- default: "public.id('dispatch'::text)",
+ default: "public.id('main'::text)",
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string",
},
+ maintenanceDispatchId: {
+ format: "text",
+ type: "string",
+ },
content: {
format: "json",
},
@@ -74702,11 +74726,29 @@ export default {
format: 'public."maintenanceDispatchPriority"',
type: "string",
},
+ source: {
+ default: "Reactive",
+ enum: ["Scheduled", "Reactive", "Non-Conformance"],
+ format: 'public."maintenanceSource"',
+ type: "string",
+ },
severity: {
enum: ["Preventive", "OPM", "Maintenance Required", "OEM Required"],
format: 'public."maintenanceSeverity"',
type: "string",
},
+ workCenterId: {
+ description:
+ "Note:\nThis is a Foreign Key to `workCenter.id`.<fk table='workCenter' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ maintenanceScheduleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `maintenanceSchedule.id`.<fk table='maintenanceSchedule' column='id'/>",
+ format: "text",
+ type: "string",
+ },
suspectedFailureModeId: {
description:
"Note:\nThis is a Foreign Key to `maintenanceFailureMode.id`.<fk table='maintenanceFailureMode' column='id'/>",
@@ -74735,6 +74777,11 @@ export default {
format: "timestamp with time zone",
type: "string",
},
+ isFailure: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
duration: {
format: "integer",
type: "integer",
@@ -74745,6 +74792,10 @@ export default {
format: "text",
type: "string",
},
+ completedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
assignee: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -74778,27 +74829,6 @@ 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",
},
@@ -76323,6 +76353,14 @@ export default {
format: "text",
type: "string",
},
+ unitCost: {
+ format: "numeric",
+ type: "number",
+ },
+ totalCost: {
+ format: "numeric",
+ type: "number",
+ },
companyId: {
description:
"Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
@@ -76350,14 +76388,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- unitCost: {
- format: "numeric",
- type: "number",
- },
- totalCost: {
- format: "numeric",
- type: "number",
- },
},
type: "object",
},
@@ -104314,6 +104344,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.maintenanceDispatchId": {
+ name: "maintenanceDispatchId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceDispatch.content": {
name: "content",
required: false,
@@ -104332,12 +104368,30 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.source": {
+ name: "source",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceDispatch.severity": {
name: "severity",
required: false,
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.maintenanceDispatch.maintenanceScheduleId": {
+ name: "maintenanceScheduleId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceDispatch.suspectedFailureModeId": {
name: "suspectedFailureModeId",
required: false,
@@ -104374,6 +104428,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.isFailure": {
+ name: "isFailure",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceDispatch.duration": {
name: "duration",
required: false,
@@ -104386,6 +104446,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.maintenanceDispatch.completedAt": {
+ name: "completedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.maintenanceDispatch.assignee": {
name: "assignee",
required: false,
@@ -104422,30 +104488,6 @@ 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",
@@ -106177,6 +106219,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",
+ },
"rowFilter.maintenanceDispatchItem.companyId": {
name: "companyId",
required: false,
@@ -106207,18 +106261,6 @@ 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",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index c2c87a09ce..ed02e964aa 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -12444,24 +12444,26 @@ export type Database = {
actualStartTime: string | null
assignee: string | null
companyId: string
+ completedAt: string | null
content: Json
createdAt: string
createdBy: string
duration: number | null
id: string
isFailure: boolean
+ maintenanceDispatchId: string
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
+ source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
updatedAt: string | null
updatedBy: string | null
+ workCenterId: string | null
}
Insert: {
actualEndTime?: string | null
@@ -12469,24 +12471,26 @@ export type Database = {
actualStartTime?: string | null
assignee?: string | null
companyId: string
+ completedAt?: string | null
content?: Json
createdAt?: string
createdBy: string
duration?: number | null
id?: string
isFailure?: boolean
+ maintenanceDispatchId: string
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
+ source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
updatedBy?: string | null
+ workCenterId?: string | null
}
Update: {
actualEndTime?: string | null
@@ -12494,24 +12498,26 @@ export type Database = {
actualStartTime?: string | null
assignee?: string | null
companyId?: string
+ completedAt?: string | null
content?: Json
createdAt?: string
createdBy?: string
duration?: number | null
id?: string
isFailure?: boolean
+ maintenanceDispatchId?: string
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
+ source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
updatedBy?: string | null
+ workCenterId?: string | null
}
Relationships: [
{
@@ -12640,13 +12646,6 @@ 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"]
@@ -12689,6 +12688,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceDispatch_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
]
}
maintenanceDispatchComment: {
@@ -53077,6 +53090,7 @@ export type Database = {
| "OPM"
| "Maintenance Required"
| "OEM Required"
+ maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
makeMethodStatus: "Draft" | "Active" | "Archived"
methodOperationOrder: "After Previous" | "With Previous"
methodType: "Buy" | "Make" | "Pick"
@@ -54219,6 +54233,7 @@ export const Constants = {
"Maintenance Required",
"OEM Required",
],
+ maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],
makeMethodStatus: ["Draft", "Active", "Archived"],
methodOperationOrder: ["After Previous", "With Previous"],
methodType: ["Buy", "Make", "Pick"],
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 165475ba75..a8dd32a383 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -1833,6 +1833,15 @@ export const sequences = [
suffix: null,
next: 0,
},
+ {
+ table: "maintenanceDispatch",
+ name: "Maintenance Dispatch",
+ prefix: "MAIN",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ },
{
table: "nonConformance",
name: "Issue",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index c2c87a09ce..ed02e964aa 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -12444,24 +12444,26 @@ export type Database = {
actualStartTime: string | null
assignee: string | null
companyId: string
+ completedAt: string | null
content: Json
createdAt: string
createdBy: string
duration: number | null
id: string
isFailure: boolean
+ maintenanceDispatchId: string
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
+ source: Database["public"]["Enums"]["maintenanceSource"]
status: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId: string | null
updatedAt: string | null
updatedBy: string | null
+ workCenterId: string | null
}
Insert: {
actualEndTime?: string | null
@@ -12469,24 +12471,26 @@ export type Database = {
actualStartTime?: string | null
assignee?: string | null
companyId: string
+ completedAt?: string | null
content?: Json
createdAt?: string
createdBy: string
duration?: number | null
id?: string
isFailure?: boolean
+ maintenanceDispatchId: string
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
+ source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
updatedBy?: string | null
+ workCenterId?: string | null
}
Update: {
actualEndTime?: string | null
@@ -12494,24 +12498,26 @@ export type Database = {
actualStartTime?: string | null
assignee?: string | null
companyId?: string
+ completedAt?: string | null
content?: Json
createdAt?: string
createdBy?: string
duration?: number | null
id?: string
isFailure?: boolean
+ maintenanceDispatchId?: string
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
+ source?: Database["public"]["Enums"]["maintenanceSource"]
status?: Database["public"]["Enums"]["maintenanceDispatchStatus"]
suspectedFailureModeId?: string | null
updatedAt?: string | null
updatedBy?: string | null
+ workCenterId?: string | null
}
Relationships: [
{
@@ -12640,13 +12646,6 @@ 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"]
@@ -12689,6 +12688,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "maintenanceDispatch_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "maintenanceDispatch_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
]
}
maintenanceDispatchComment: {
@@ -53077,6 +53090,7 @@ export type Database = {
| "OPM"
| "Maintenance Required"
| "OEM Required"
+ maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"
makeMethodStatus: "Draft" | "Active" | "Archived"
methodOperationOrder: "After Previous" | "With Previous"
methodType: "Buy" | "Make" | "Pick"
@@ -54219,6 +54233,7 @@ export const Constants = {
"Maintenance Required",
"OEM Required",
],
+ maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],
makeMethodStatus: ["Draft", "Active", "Archived"],
methodOperationOrder: ["After Previous", "With Previous"],
methodType: ["Buy", "Make", "Pick"],
diff --git a/packages/database/supabase/migrations/20251216021152_maintenance.sql b/packages/database/supabase/migrations/20251216021152_maintenance.sql
index 9a86f031a6..d70edfdd98 100644
--- a/packages/database/supabase/migrations/20251216021152_maintenance.sql
+++ b/packages/database/supabase/migrations/20251216021152_maintenance.sql
@@ -1,3 +1,4 @@
+-- Maintenance dispatch status enum
DO $$ BEGIN
CREATE TYPE "maintenanceDispatchStatus" AS ENUM (
'Open',
@@ -10,6 +11,55 @@ EXCEPTION
WHEN duplicate_object THEN null;
END $$;
+-- Maintenance dispatch priority enum
+DO $$ BEGIN
+ CREATE TYPE "maintenanceDispatchPriority" AS ENUM (
+ 'Low',
+ 'Medium',
+ 'High',
+ 'Critical'
+ );
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+
+-- Maintenance severity enum
+DO $$ BEGIN
+ CREATE TYPE "maintenanceSeverity" AS ENUM (
+ 'Preventive',
+ 'OPM',
+ 'Maintenance Required',
+ 'OEM Required'
+ );
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+
+-- Maintenance source enum
+DO $$ BEGIN
+ CREATE TYPE "maintenanceSource" AS ENUM (
+ 'Scheduled',
+ 'Reactive',
+ 'Non-Conformance'
+ );
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+
+-- Maintenance frequency enum
+DO $$ BEGIN
+ CREATE TYPE "maintenanceFrequency" AS ENUM (
+ 'Daily',
+ 'Weekly',
+ 'Monthly',
+ 'Quarterly',
+ 'Annual'
+ );
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+
+-- Failure mode catalog
CREATE TABLE "maintenanceFailureMode" (
"id" TEXT NOT NULL DEFAULT id(),
"name" TEXT NOT NULL,
@@ -65,40 +115,78 @@ CREATE POLICY "DELETE" ON "maintenanceFailureMode"
)
);
-DO $$ BEGIN
- CREATE TYPE "maintenanceDispatchPriority" AS ENUM (
- 'Low',
- 'Medium',
- 'High',
- 'Critical'
- );
-EXCEPTION
- WHEN duplicate_object THEN null;
-END $$;
+-- Maintenance schedule table (must be created before maintenanceDispatch)
+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,
-DO $$ BEGIN
- CREATE TYPE "maintenanceSeverity" AS ENUM (
- 'Preventive',
- 'OPM',
- 'Maintenance Required',
- 'OEM Required'
- );
-EXCEPTION
- WHEN duplicate_object THEN null;
-END $$;
+ 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");
+
+-- Main dispatch table
CREATE TABLE "maintenanceDispatch" (
- "id" TEXT NOT NULL DEFAULT id('dispatch'),
+ "id" TEXT NOT NULL DEFAULT id('main'),
+ "maintenanceDispatchId" TEXT NOT NULL,
"content" JSON NOT NULL DEFAULT '{}',
"status" "maintenanceDispatchStatus" NOT NULL DEFAULT 'Open',
"priority" "maintenanceDispatchPriority" NOT NULL DEFAULT 'Medium',
+ "source" "maintenanceSource" NOT NULL DEFAULT 'Reactive',
"severity" "maintenanceSeverity",
+ "workCenterId" TEXT,
+ "maintenanceScheduleId" TEXT,
"suspectedFailureModeId" TEXT,
"actualFailureModeId" TEXT,
"plannedStartTime" TIMESTAMP WITH TIME ZONE,
"plannedEndTime" TIMESTAMP WITH TIME ZONE,
"actualStartTime" TIMESTAMP WITH TIME ZONE,
"actualEndTime" TIMESTAMP WITH TIME ZONE,
+ "isFailure" BOOLEAN NOT NULL DEFAULT false,
"duration" INTEGER GENERATED ALWAYS AS (
CASE
WHEN "actualEndTime" IS NULL THEN 0
@@ -106,6 +194,7 @@ CREATE TABLE "maintenanceDispatch" (
END
) STORED,
"nonConformanceId" TEXT,
+ "completedAt" TIMESTAMP WITH TIME ZONE,
"assignee" TEXT,
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
@@ -115,9 +204,11 @@ CREATE TABLE "maintenanceDispatch" (
CONSTRAINT "maintenanceDispatch_pkey" PRIMARY KEY ("id"),
CONSTRAINT "maintenanceDispatch_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceDispatch_maintenanceScheduleId_fkey" FOREIGN KEY ("maintenanceScheduleId") REFERENCES "maintenanceSchedule"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_suspectedFailureModeId_fkey" FOREIGN KEY ("suspectedFailureModeId") REFERENCES "maintenanceFailureMode"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_actualFailureModeId_fkey" FOREIGN KEY ("actualFailureModeId") REFERENCES "maintenanceFailureMode"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_nonConformanceId_fkey" FOREIGN KEY ("nonConformanceId") REFERENCES "nonConformance"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "maintenanceDispatch_workCenterId_fkey" FOREIGN KEY ("workCenterId") REFERENCES "workCenter"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "maintenanceDispatch_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
@@ -126,6 +217,7 @@ CREATE TABLE "maintenanceDispatch" (
CREATE INDEX "maintenanceDispatch_status_idx" ON "maintenanceDispatch" ("status");
CREATE INDEX "maintenanceDispatch_companyId_idx" ON "maintenanceDispatch" ("companyId");
+-- Time tracking events
CREATE TABLE "maintenanceDispatchEvent" (
"id" TEXT NOT NULL DEFAULT id(),
"maintenanceDispatchId" TEXT NOT NULL,
@@ -159,6 +251,7 @@ CREATE INDEX "maintenanceDispatchEvent_maintenanceDispatchId_idx" ON "maintenanc
CREATE INDEX "maintenanceDispatchEvent_employeeId_idx" ON "maintenanceDispatchEvent" ("employeeId");
CREATE INDEX "maintenanceDispatchEvent_companyId_idx" ON "maintenanceDispatchEvent" ("companyId");
+-- Comments on dispatches
CREATE TABLE "maintenanceDispatchComment" (
"id" TEXT NOT NULL DEFAULT id(),
"maintenanceDispatchId" TEXT NOT NULL,
@@ -178,6 +271,7 @@ CREATE TABLE "maintenanceDispatchComment" (
CREATE INDEX "maintenanceDispatchComment_maintenanceDispatchId_idx" ON "maintenanceDispatchComment" ("maintenanceDispatchId");
+-- Work centers involved in dispatch
CREATE TABLE "maintenanceDispatchWorkCenter" (
"id" TEXT NOT NULL DEFAULT id(),
"maintenanceDispatchId" TEXT NOT NULL,
@@ -200,12 +294,15 @@ CREATE INDEX "maintenanceDispatchWorkCenter_maintenanceDispatchId_idx" ON "maint
CREATE INDEX "maintenanceDispatchWorkCenter_workCenterId_idx" ON "maintenanceDispatchWorkCenter" ("workCenterId");
CREATE INDEX "maintenanceDispatchWorkCenter_companyId_idx" ON "maintenanceDispatchWorkCenter" ("companyId");
+-- Parts/materials consumed
CREATE TABLE "maintenanceDispatchItem" (
"id" TEXT NOT NULL DEFAULT id(),
"maintenanceDispatchId" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
"quantity" INTEGER NOT NULL,
"unitOfMeasureCode" TEXT NOT NULL,
+ "unitCost" NUMERIC,
+ "totalCost" NUMERIC GENERATED ALWAYS AS ("quantity" * "unitCost") STORED,
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
@@ -224,6 +321,7 @@ CREATE INDEX "maintenanceDispatchItem_maintenanceDispatchId_idx" ON "maintenance
CREATE INDEX "maintenanceDispatchItem_itemId_idx" ON "maintenanceDispatchItem" ("itemId");
CREATE INDEX "maintenanceDispatchItem_companyId_idx" ON "maintenanceDispatchItem" ("companyId");
+-- Standard replacement parts for work centers
CREATE TABLE "workCenterReplacementPart" (
"id" TEXT NOT NULL DEFAULT id(),
"workCenterId" TEXT NOT NULL,
@@ -247,3 +345,33 @@ CREATE TABLE "workCenterReplacementPart" (
CREATE INDEX "workCenterReplacementPart_workCenterId_idx" ON "workCenterReplacementPart" ("workCenterId");
CREATE INDEX "workCenterReplacementPart_itemId_idx" ON "workCenterReplacementPart" ("itemId");
CREATE INDEX "workCenterReplacementPart_companyId_idx" ON "workCenterReplacementPart" ("companyId");
+
+-- 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;
+
+-- salesRfq sequence for existing companies
+INSERT INTO "sequence" (
+ "table",
+ "name",
+ "prefix",
+ "suffix",
+ "next",
+ "size",
+ "step",
+ "companyId"
+)
+SELECT
+ 'maintenanceDispatch',
+ 'Maintenance Dispatch',
+ 'MAIN',
+ null,
+ 0,
+ 6,
+ 1,
+ id
+FROM "company"
+ON CONFLICT DO NOTHING;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql b/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql
deleted file mode 100644
index bc393ed30e..0000000000
--- a/packages/database/supabase/migrations/20251218030000_maintenance-schedules.sql
+++ /dev/null
@@ -1,110 +0,0 @@
--- 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;
-
diff --git a/packages/react/src/Date/DateTimePicker.tsx b/packages/react/src/Date/DateTimePicker.tsx
index fe13312d2f..27d6be33e7 100644
--- a/packages/react/src/Date/DateTimePicker.tsx
+++ b/packages/react/src/Date/DateTimePicker.tsx
@@ -6,12 +6,11 @@ import { useRef } from "react";
import { LuBan } from "react-icons/lu";
import { cn } from "..";
import { HStack } from "../HStack";
-import { useOutsideClick } from "../hooks";
import { InputGroup } from "../Input";
+import { Popover, PopoverContent, PopoverTrigger } from "../Popover";
import { FieldButton } from "./components/Button";
import { Calendar } from "./components/Calendar";
import DateField from "./components/DateField";
-import { Popover } from "./components/Popover";
import TimeField from "./TimePicker";
const DateTimePicker = (
@@ -28,41 +27,40 @@ const DateTimePicker = (
const { groupProps, fieldProps, buttonProps, dialogProps, calendarProps } =
useDatePicker(props, state, ref);
- useOutsideClick({
- ref,
- handler: () => state.setOpen(false)
- });
-
return (
- <div className="relative inline-flex flex-col w-full">
- <HStack className="w-full" spacing={0}>
- <InputGroup
- {...groupProps}
- ref={ref}
- className={cn("w-full inline-flex rounded-r-none", props.className)}
- >
- <div className="flex w-full px-4 py-2">
- <DateField {...fieldProps} />
- {state.isInvalid && (
- <LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />
+ <Popover open={state.isOpen} onOpenChange={state.setOpen}>
+ <div className="relative inline-flex flex-col w-full">
+ <HStack className="w-full" spacing={0}>
+ <InputGroup
+ {...groupProps}
+ ref={ref}
+ className={cn("w-full inline-flex", props.className)}
+ >
+ <div className="flex w-full px-4 py-2">
+ <DateField {...fieldProps} />
+ {state.isInvalid && (
+ <LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />
+ )}
+ </div>
+ {props.withButton !== false && (
+ <div className="flex-shrink-0 -mt-px">
+ <PopoverTrigger tabIndex={-1}>
+ <FieldButton {...buttonProps} isPressed={state.isOpen} />
+ </PopoverTrigger>
+ </div>
)}
- </div>
- </InputGroup>
- {props.withButton !== false && (
- <FieldButton {...buttonProps} isPressed={state.isOpen} />
- )}
- </HStack>
- {state.isOpen && (
- <Popover {...dialogProps} onClose={() => state.setOpen(false)}>
+ </InputGroup>
+ </HStack>
+ <PopoverContent align="end" {...dialogProps}>
<Calendar {...calendarProps} />
<TimeField
label="Time"
value={state.timeValue}
onChange={state.setTimeValue}
/>
- </Popover>
- )}
- </div>
+ </PopoverContent>
+ </div>
+ </Popover>
);
};