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: end shift button in mes

Brad Barbinbbe2d589cf48
diff --git a/apps/mes/app/components/EndShift.tsx b/apps/mes/app/components/EndShift.tsx
new file mode 100644
index 0000000000..d6aeefeed5
--- /dev/null
+++ b/apps/mes/app/components/EndShift.tsx
@@ -0,0 +1,164 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Button,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Spinner,
+ toast,
+ useDisclosure,
+} from "@carbon/react";
+import { getLocalTimeZone } from "@internationalized/date";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { flushSync } from "react-dom";
+import { FaFlagCheckered } from "react-icons/fa6";
+import { useUser } from "~/hooks";
+import type { action } from "~/routes/x+/end-shift.tsx";
+import {
+ getActiveJobOperationsByEmployee,
+ type Operation,
+} from "~/services/jobs.service";
+import { path } from "~/utils/path";
+
+export const EndShift = ({ isCollapsed }: { isCollapsed: boolean }) => {
+ const confirmModal = useDisclosure();
+ const fetcher = useFetcher<typeof action>();
+ const user = useUser();
+ const { carbon } = useCarbon();
+ const [operations, setOperations] = useState<Operation[]>([]);
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ if (fetcher.data?.success === true) {
+ confirmModal.onClose();
+ toast.success(fetcher.data?.message ?? "Shift ended");
+ }
+
+ if (fetcher.data?.success === false) {
+ toast.error(fetcher.data?.message ?? "Failed to end shift");
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data?.success]);
+
+ console.log({ fetcher });
+
+ const openModal = async () => {
+ flushSync(() => {
+ setLoading(true);
+ confirmModal.onOpen();
+ });
+
+ if (!carbon) return;
+ const { data, error } = await getActiveJobOperationsByEmployee(carbon, {
+ employeeId: user.id,
+ companyId: user.company.id,
+ });
+ if (error) {
+ toast.error("Failed to fetch active operations");
+ }
+ setOperations((data ?? []) as Operation[]);
+ setLoading(false);
+ };
+
+ return (
+ <>
+ {isCollapsed ? (
+ <IconButton
+ variant="destructive"
+ size="lg"
+ icon={<FaFlagCheckered className="h-4 w-4" />}
+ aria-label="End Shift"
+ onClick={openModal}
+ />
+ ) : (
+ <Button size="lg" variant="destructive" onClick={openModal}>
+ End Shift
+ </Button>
+ )}
+ {confirmModal.isOpen && (
+ <Modal
+ open={confirmModal.isOpen}
+ onOpenChange={(open) => !open && confirmModal.onClose()}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>End Shift</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to end all production events? This will
+ end all active operations without completing or finishing them.
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ {loading ? (
+ <div className="flex items-center justify-center w-full h-24">
+ <Spinner />
+ </div>
+ ) : operations?.length === 0 ? (
+ <div className="flex items-center justify-center w-full h-24 text-muted-foreground">
+ No active operations
+ </div>
+ ) : (
+ <div className="flex flex-col gap-4">
+ {operations.map((operation) => (
+ <div
+ key={operation.id}
+ className="flex items-start justify-between p-4 rounded-lg border"
+ >
+ <div className="flex flex-col gap-1">
+ <div className="font-medium">
+ {operation.jobReadableId}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ {operation.description}
+ </div>
+ </div>
+ <div className="flex flex-col gap-1">
+ <div className="text-sm text-muted-foreground">
+ {operation.itemReadableId}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </ModalBody>
+ <fetcher.Form
+ method="post"
+ action={path.to.endShift}
+ className="w-full"
+ >
+ <ModalFooter>
+ <Button
+ type="button"
+ onClick={confirmModal.onClose}
+ variant="secondary"
+ >
+ Cancel
+ </Button>
+ <input
+ type="hidden"
+ name="timezone"
+ value={getLocalTimeZone()}
+ />
+ <Button
+ type="submit"
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ variant="destructive"
+ >
+ End Shift
+ </Button>
+ </ModalFooter>
+ </fetcher.Form>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+};
diff --git a/apps/mes/app/components/Feedback.tsx b/apps/mes/app/components/Feedback.tsx
index 8437cbada5..378fc2d1bc 100644
--- a/apps/mes/app/components/Feedback.tsx
+++ b/apps/mes/app/components/Feedback.tsx
@@ -11,6 +11,7 @@ import {
Button,
File,
HStack,
+ IconButton,
Popover,
PopoverContent,
PopoverTrigger,
@@ -22,13 +23,14 @@ import { useFetcher, useLocation } from "@remix-run/react";
import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
import { useEffect, useRef, useState } from "react";
-import { LuImage } from "react-icons/lu";
+import { LuImage, LuMessageCircle } from "react-icons/lu";
import { feedbackValidator } from "~/models/feedback";
import type { action } from "~/routes/x+/feedback";
import { path } from "~/utils/path";
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes
-const Feedback = () => {
+
+const Feedback = ({ isCollapsed }: { isCollapsed: boolean }) => {
const fetcher = useFetcher<typeof action>();
const location = useLocation();
const popoverTriggerRef = useRef<HTMLButtonElement>(null);
@@ -82,9 +84,18 @@ const Feedback = () => {
return (
<Popover>
<PopoverTrigger ref={popoverTriggerRef} asChild>
- <Button variant="secondary" size="lg">
- Feedback
- </Button>
+ {isCollapsed ? (
+ <IconButton
+ variant="secondary"
+ icon={<LuMessageCircle className="h-4 w-4" />}
+ size="lg"
+ aria-label="Feedback"
+ />
+ ) : (
+ <Button variant="secondary" size="lg">
+ Feedback
+ </Button>
+ )}
</PopoverTrigger>
<PopoverContent className="w-[380px] ">
<ValidatedForm
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index b46202afd9..777c4f9424 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -13,6 +13,7 @@ import {
Toaster,
TooltipProvider,
} from "@carbon/react";
+import type { ShouldRevalidateFunction } from "@remix-run/react";
import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
@@ -21,6 +22,7 @@ import { useEffect, useRef, useState } from "react";
import { LuActivity, LuClock, LuInbox } from "react-icons/lu";
import type { ImperativePanelHandle } from "react-resizable-panels";
import { AvatarMenu, Nav } from "~/components";
+import { EndShift } from "~/components/EndShift";
import Feedback from "~/components/Feedback";
import { useMediaQuery } from "~/hooks";
import {
@@ -34,6 +36,20 @@ import {
import { defaultLayout } from "~/utils/layout";
import { path } from "~/utils/path";
+export const shouldRevalidate: ShouldRevalidateFunction = ({
+ currentUrl,
+ defaultShouldRevalidate,
+}) => {
+ if (
+ currentUrl.pathname.startsWith("/refresh-session") ||
+ currentUrl.pathname.startsWith("/switch-company")
+ ) {
+ return true;
+ }
+
+ return defaultShouldRevalidate;
+};
+
export async function loader({ request }: LoaderFunctionArgs) {
const { accessToken, companyId, expiresAt, expiresIn, userId } =
await requireAuthSession(request, { verify: true });
@@ -206,8 +222,16 @@ export default function AuthenticatedRoute() {
]}
/>
</div>
- <div className="flex flex-col p-2">
- <Feedback />
+ <div
+ className={cn(
+ "flex flex-col gap-2",
+ isCollapsed ? "p-1" : "p-2"
+ )}
+ >
+ {activeEvents > 0 && (
+ <EndShift isCollapsed={isCollapsed} />
+ )}
+ <Feedback isCollapsed={isCollapsed} />
</div>
</div>
</ResizablePanel>
diff --git a/apps/mes/app/routes/x+/end-shift.tsx b/apps/mes/app/routes/x+/end-shift.tsx
new file mode 100644
index 0000000000..6bf88240b6
--- /dev/null
+++ b/apps/mes/app/routes/x+/end-shift.tsx
@@ -0,0 +1,26 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getLocalTimeZone, now } from "@internationalized/date";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { endProductionEvents } from "~/services/jobs.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+ const formData = await request.formData();
+ const timezone = formData.get("timezone") as string | null;
+
+ const updates = await endProductionEvents(client, {
+ companyId,
+ employeeId: userId,
+ endTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),
+ });
+
+ if (updates.error) {
+ return json(
+ { success: false, message: updates.error.message },
+ { status: 500 }
+ );
+ }
+
+ return json({ success: true, message: "Successfully ended shift" });
+}
diff --git a/apps/mes/app/services/jobs.service.ts b/apps/mes/app/services/jobs.service.ts
index b3a0924982..c4d19ad0de 100644
--- a/apps/mes/app/services/jobs.service.ts
+++ b/apps/mes/app/services/jobs.service.ts
@@ -432,6 +432,19 @@ export async function endProductionEvent(
.select("*");
}
+export async function endProductionEvents(
+ client: SupabaseClient<Database>,
+ args: { companyId: string; employeeId: string; endTime: string }
+) {
+ return client
+ .from("productionEvent")
+ .update({
+ endTime: args.endTime,
+ })
+ .eq("employeeId", args.employeeId)
+ .eq("companyId", args.companyId);
+}
+
export async function startProductionEvent(
client: SupabaseClient<Database>,
data: Omit<
diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.ts
index e7d7291661..de8eed6ff5 100644
--- a/apps/mes/app/services/location.server.ts
+++ b/apps/mes/app/services/location.server.ts
@@ -1,3 +1,4 @@
+import { notFound } from "@carbon/auth";
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import * as cookie from "cookie";
@@ -67,7 +68,7 @@ export async function getLocationAndWorkCenter(
}
}
- if (!location) throw new Error("Failed to get a valid location");
+ if (!location) throw notFound("Failed to get a valid location");
if (!workCenter) {
const workCenters = await client
@@ -81,7 +82,7 @@ export async function getLocationAndWorkCenter(
}
}
- if (!workCenter) throw new Error("Failed to get a valid work center");
+ if (!workCenter) throw notFound("Failed to get a valid work center");
if (updated) {
setLocationAndWorkCenter(companyId, location, workCenter);
}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index d83d8343fb..de6524f7e6 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -25,6 +25,7 @@ export const path = {
authenticatedRoot: x,
callback: "/callback",
complete: `${x}/complete`,
+ endShift: `${x}/end-shift`,
feedback: `${x}/feedback`,
finish: `${x}/finish`,
forgotPassword: "/forgot-password",