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 active and recent tabs to mes

Brad Barbinda12f4d8fb0a
diff --git a/apps/carbon/app/components/Layout/Topbar/Search.tsx b/apps/carbon/app/components/Layout/Topbar/Search.tsx
index 8abfc5ea82..81020bb391 100644
--- a/apps/carbon/app/components/Layout/Topbar/Search.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Search.tsx
@@ -314,8 +314,6 @@ function useGroupedSubmodules() {
const items = useItemsSubmodules();
const production = useProductionSubmodules();
const inventory = useInventorySubmodules();
- // const scheduling = useSchedulingSidebar();
- // const timecards = useTimecardsSidebar();
const sales = useSalesSubmodules();
const purchasing = usePurchasingSubmodules();
const documents = useDocumentsSubmodules();
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index a5f805f570..0ee9e5fbe8 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -530,7 +530,7 @@ const Table = <T extends object>({
right: isPinned === "right" ? column.getAfter("right") : undefined,
position: isPinned ? "sticky" : "relative",
zIndex: isPinned ? 1 : 0,
- backgroundColor: isPinned ? "hsl(var(--card))" : undefined,
+ // backgroundColor: isPinned ? "hsl(var(--card))" : undefined,
boxShadow: isPinned
? isPinned === "left"
? "4px 0 6px -2px rgba(0, 0, 0, 0.1)"
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index 2b08cc6c36..49a2e4d32e 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -57,8 +57,8 @@ const JobHeader = () => {
return path.to.jobMaterials(jobId);
case "operations":
return path.to.jobOperations(jobId);
- case "timecards":
- return path.to.jobTimecards(jobId);
+ case "events":
+ return path.to.jobProductionEvents(jobId);
default:
return path.to.jobDetails(jobId);
}
@@ -69,8 +69,8 @@ const JobHeader = () => {
return "materials";
if (location.pathname.includes(path.to.jobOperations(jobId)))
return "operations";
- if (location.pathname.includes(path.to.jobTimecards(jobId)))
- return "timecards";
+ if (location.pathname.includes(path.to.jobProductionEvents(jobId)))
+ return "events";
return "details";
};
@@ -129,7 +129,7 @@ const JobHeader = () => {
{getExplorerLabel("details")}
</DropdownMenuRadioItem>
<DropdownMenuSeparator />
- {["materials", "operations", "timecards"].map((i) => (
+ {["materials", "operations", "events"].map((i) => (
<DropdownMenuRadioItem value={i} key={i}>
<DropdownMenuIcon icon={getExplorerMenuIcon(i)} />
{getExplorerLabel(i)}
@@ -151,8 +151,8 @@ function getExplorerLabel(type: string) {
return "Materials";
case "operations":
return "Operations";
- case "timecards":
- return "Timecards";
+ case "events":
+ return "Production Events";
default:
return "Job";
}
@@ -164,7 +164,7 @@ function getExplorerMenuIcon(type: string) {
return <LuPackage />;
case "operations":
return <LuSettings />;
- case "timecards":
+ case "events":
return <LuClock />;
default:
return <LuHardHat />;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
index 9a237152f5..91b5a101af 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobOperationsTable.tsx
@@ -2,11 +2,16 @@ import { HStack } from "@carbon/react";
import { useParams } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
+import { LuCheckCircle, LuXCircle } from "react-icons/lu";
+import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
+import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
+import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { useRouteData } from "~/hooks";
import { operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
-import type { JobOperation } from "../../types";
+import type { Job, JobOperation } from "../../types";
type JobOperationsTableProps = {
data: JobOperation[];
@@ -17,6 +22,9 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
const { jobId } = useParams();
if (!jobId) throw new Error("Job ID is required");
+ const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
+ const isPaused = routeData?.job?.status === "Paused";
+
const columns = useMemo<ColumnDef<JobOperation>[]>(() => {
return [
{
@@ -24,6 +32,7 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
header: "Description",
cell: ({ row }) => (
<HStack className="py-1">
+ {getStatusIcon(isPaused ? "Paused" : row.original.status)}
<Hyperlink
to={path.to.jobMakeMethod(
jobId,
@@ -89,7 +98,7 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
cell: (item) => item.getValue(),
},
];
- }, [jobId]);
+ }, [isPaused, jobId]);
return <Table<JobOperation> count={count} columns={columns} data={data} />;
});
@@ -97,3 +106,23 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {
JobOperationsTable.displayName = "JobOperationsTable";
export default JobOperationsTable;
+
+// TODO: this might be in a shared location since it is used in the MES too
+export function getStatusIcon(status: JobOperation["status"]) {
+ switch (status) {
+ case "Ready":
+ case "Todo":
+ return <TodoStatusIcon className="text-foreground" />;
+ case "Waiting":
+ case "Canceled":
+ return <LuXCircle className="text-muted-foreground" />;
+ case "Done":
+ return <LuCheckCircle className="text-blue-600" />;
+ case "In Progress":
+ return <AlmostDoneIcon />;
+ case "Paused":
+ return <InProgressStatusIcon />;
+ default:
+ return null;
+ }
+}
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index 39a9d6f800..b32404ab0d 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -13,8 +13,6 @@ export const modulesType = [
"Purchasing",
"Resources",
"Sales",
- // "Scheduling",
- // "Timecards",
"Users",
] as const;
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 04d151d7bc..339c687ba1 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -390,7 +390,7 @@ export const path = {
generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),
jobOperationsOrder: `${x}/job/methods/operation/order`,
- jobTimecards: (id: string) => generatePath(`${x}/job/${id}/timecards`),
+ jobProductionEvents: (id: string) => generatePath(`${x}/job/${id}/events`),
jobs: `${x}/production/jobs`,
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
locations: `${x}/resources/locations`,
diff --git a/apps/mes/app/components/AvatarMenu.tsx b/apps/mes/app/components/AvatarMenu.tsx
index 0e10c9580a..853363fc5b 100644
--- a/apps/mes/app/components/AvatarMenu.tsx
+++ b/apps/mes/app/components/AvatarMenu.tsx
@@ -1,4 +1,6 @@
import {
+ Button,
+ cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuIcon,
@@ -11,11 +13,19 @@ import {
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
+ HStack,
Switch,
} from "@carbon/react";
import { Form, Link, useFetcher } from "@remix-run/react";
import { useRef, useState } from "react";
-import { LuLogOut, LuMapPin, LuMoon, LuSun, LuUser } from "react-icons/lu";
+import {
+ LuChevronsUpDown,
+ LuLogOut,
+ LuMapPin,
+ LuMoon,
+ LuSun,
+ LuUser,
+} from "react-icons/lu";
import { Avatar } from "~/components";
import { useUser } from "~/hooks";
import { useMode } from "~/hooks/useMode";
@@ -54,10 +64,25 @@ const AvatarMenu = ({
return (
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
- <DropdownMenuTrigger className="flex items-center justify-start gap-2 outline-none focus-visible:outline-none">
- <Avatar size="sm" src={user?.avatarUrl ?? undefined} name={name} />
- {!isCollapsed && (
- <span className="text-sm font-medium truncate">{name}</span>
+ <DropdownMenuTrigger className={cn(!isCollapsed && "w-full")}>
+ {isCollapsed ? (
+ <Avatar size="sm" src={user?.avatarUrl ?? undefined} name={name} />
+ ) : (
+ <Button
+ className="w-full justify-between"
+ size="lg"
+ variant="secondary"
+ >
+ <HStack spacing={2}>
+ <Avatar
+ size="xs"
+ src={user?.avatarUrl ?? undefined}
+ name={name}
+ />
+ <span>{name}</span>
+ </HStack>
+ <LuChevronsUpDown />
+ </Button>
)}
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
@@ -83,8 +108,7 @@ const AvatarMenu = ({
<DropdownMenuRadioItem
key={loc.id}
value={loc.id}
- onSelect={(e) => {
- e.preventDefault();
+ onSelect={() => {
updateLocation(loc.id);
}}
>
diff --git a/apps/mes/app/components/Icons.tsx b/apps/mes/app/components/Icons.tsx
new file mode 100644
index 0000000000..85f4e1710f
--- /dev/null
+++ b/apps/mes/app/components/Icons.tsx
@@ -0,0 +1,56 @@
+import { cn } from "@carbon/react";
+import { BsExclamationSquareFill } from "react-icons/bs";
+import { LuCheckCircle, LuXCircle } from "react-icons/lu";
+import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
+import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
+import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
+import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
+import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
+import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
+import type { Operation } from "~/services/jobs";
+
+export function StatusIcon({
+ status,
+}: {
+ status: Operation["operationStatus"];
+}) {
+ switch (status) {
+ case "Ready":
+ case "Todo":
+ return <TodoStatusIcon className="text-foreground" />;
+ case "Waiting":
+ case "Canceled":
+ return <LuXCircle className="text-muted-foreground" />;
+ case "Done":
+ return <LuCheckCircle className="text-blue-600" />;
+ case "In Progress":
+ return <AlmostDoneIcon />;
+ case "Paused":
+ return <InProgressStatusIcon />;
+ default:
+ return null;
+ }
+}
+
+export function DeadlineIcon({
+ deadlineType,
+ overdue,
+}: {
+ deadlineType: Operation["jobDeadlineType"];
+ overdue: boolean;
+}) {
+ switch (deadlineType) {
+ case "ASAP":
+ return <BsExclamationSquareFill className="text-red-500" />;
+ case "Hard Deadline":
+ return <HighPriorityIcon className={cn(overdue ? "text-red-500" : "")} />;
+ case "Soft Deadline":
+ return (
+ <MediumPriorityIcon className={cn(overdue ? "text-red-500" : "")} />
+ );
+ case "No Deadline":
+ return <LowPriorityIcon />;
+ default:
+ return null;
+ }
+}
diff --git a/apps/mes/app/components/Nav.tsx b/apps/mes/app/components/Nav.tsx
new file mode 100644
index 0000000000..c4fa7ae62f
--- /dev/null
+++ b/apps/mes/app/components/Nav.tsx
@@ -0,0 +1,74 @@
+import {
+ Button,
+ HStack,
+ IconButton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@carbon/react";
+import { Link, useLocation } from "@remix-run/react";
+import type { IconType } from "react-icons";
+
+interface NavProps {
+ isCollapsed: boolean;
+ links: {
+ title: string;
+ label?: string;
+ icon: IconType;
+ to: string;
+ }[];
+}
+
+export function Nav({ links, isCollapsed }: NavProps) {
+ const { pathname } = useLocation();
+ return (
+ <div
+ data-collapsed={isCollapsed}
+ className="group flex flex-col gap-4 py-2 data-[collapsed=true]:py-2"
+ >
+ <nav className="grid gap-1 px-2 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2">
+ {links.map((link, index) => {
+ const isSelected = pathname.includes(link.to);
+ return isCollapsed ? (
+ <Tooltip key={index} delayDuration={0}>
+ <TooltipTrigger asChild>
+ <Link to={link.to}>
+ <IconButton
+ aria-label={link.title}
+ size="lg"
+ icon={<link.icon className="h-4 w-4" />}
+ variant={isSelected ? "primary" : "ghost"}
+ />
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="flex items-center gap-4">
+ {link.title}
+ {link.label && (
+ <span className="ml-auto text-muted-foreground">
+ {link.label}
+ </span>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <Button
+ key={index}
+ className="w-full justify-between"
+ size="lg"
+ variant={isSelected ? "primary" : "ghost"}
+ asChild
+ >
+ <Link to={link.to}>
+ <HStack spacing={2}>
+ <link.icon className="mr-2 h-4 w-4" />
+ {link.title}
+ </HStack>
+ {link.label && <span className="ml-auto">{link.label}</span>}
+ </Link>
+ </Button>
+ );
+ })}
+ </nav>
+ </div>
+ );
+}
diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsx
new file mode 100644
index 0000000000..087e46034f
--- /dev/null
+++ b/apps/mes/app/components/OperationsList.tsx
@@ -0,0 +1,162 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ cn,
+ HStack,
+ ScrollArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@carbon/react";
+import {
+ convertDateStringToIsoString,
+ formatDurationMilliseconds,
+ formatRelativeTime,
+} from "@carbon/utils";
+import { Link, useParams } from "@remix-run/react";
+import { LuAlertTriangle, LuClipboardCheck, LuTimer } from "react-icons/lu";
+import type { Operation, OperationSettings } from "~/services/jobs";
+import { DeadlineIcon, StatusIcon } from "./Icons";
+
+type OperationsListProps = {
+ operations: Operation[];
+ emptyMessage?: string;
+};
+
+const settings = {
+ showCustomer: false,
+ showDescription: true,
+ showDueDate: true,
+ showDuration: true,
+ showEmployee: false,
+ showProgress: false,
+ showStatus: true,
+}; // TODO: load dynamically
+
+export function OperationsList({
+ operations,
+ emptyMessage = "No scheduled jobs",
+}: OperationsListProps) {
+ const { operationId } = useParams();
+ console.log({ operations });
+ return operations.length > 0 ? (
+ <ScrollArea className="h-[calc(100vh-120px)]">
+ <div className="flex flex-col gap-2">
+ {operations.map((operation) => (
+ <OperationCard
+ key={operation.id}
+ operation={operation}
+ isSelected={operationId === operation.id}
+ {...settings}
+ />
+ ))}
+ </div>
+ </ScrollArea>
+ ) : (
+ <div className="flex flex-col w-full h-[calc(100vh-120px)] items-center justify-center gap-4">
+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
+ <LuAlertTriangle className="h-6 w-6" />
+ </div>
+ <span className="text-lg font-mono font-light text-foreground uppercase">
+ {emptyMessage}
+ </span>
+ </div>
+ );
+}
+
+type OperationCardProps = {
+ isSelected: boolean;
+ operation: Operation;
+} & OperationSettings;
+
+function OperationCard({
+ operation,
+ isSelected = false,
+ showCustomer,
+ showDescription,
+ showDueDate,
+ showDuration,
+ showEmployee,
+ showProgress,
+ showStatus,
+}: OperationCardProps) {
+ const isOverdue =
+ operation.jobDeadlineType !== "No Deadline" && operation.jobDueDate
+ ? new Date(operation.jobDueDate) < new Date()
+ : false;
+
+ return (
+ <Link to={operation.id}>
+ <Card
+ className={cn(
+ "cursor-pointer shadow",
+ isSelected && "from-muted via-muted"
+ )}
+ >
+ <CardHeader className={cn("max-w-full p-3 border-b relative")}>
+ <div className="flex w-full max-w-full justify-between">
+ <div className="flex flex-col space-y-0">
+ {operation.itemReadableId && (
+ <span className="text-xs text-muted-foreground truncate">
+ {operation.itemReadableId}
+ </span>
+ )}
+ <span className="mr-auto font-semibold truncate">
+ {operation.jobReadableId}
+ </span>
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent className="p-3 space-y-2 text-left whitespace-pre-wrap text-sm">
+ {showDescription && operation.description && (
+ <HStack className="justify-start space-x-2">
+ <LuClipboardCheck className="text-muted-foreground" />
+ <span className="text-sm">{operation.description}</span>
+ </HStack>
+ )}
+ {showStatus && operation.operationStatus && (
+ <HStack className="justify-start space-x-2">
+ <StatusIcon status={operation.operationStatus} />
+ <span className="text-sm">{operation.operationStatus}</span>
+ </HStack>
+ )}
+ {showDuration && operation.duration && (
+ <HStack className="justify-start space-x-2">
+ <LuTimer className="text-muted-foreground" />
+ <span className="text-sm">
+ {formatDurationMilliseconds(operation.duration)}
+ </span>
+ </HStack>
+ )}
+ {showDueDate && operation.jobDeadlineType && (
+ <HStack className="justify-start space-x-2">
+ <DeadlineIcon
+ deadlineType={operation.jobDeadlineType}
+ overdue={isOverdue}
+ />
+ <Tooltip>
+ <TooltipTrigger>
+ <span
+ className={cn("text-sm", isOverdue ? "text-red-500" : "")}
+ >
+ {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)
+ ? operation.jobDeadlineType
+ : operation.jobDueDate
+ ? `Due ${formatRelativeTime(
+ convertDateStringToIsoString(operation.jobDueDate)
+ )}`
+ : "–"}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ {operation.jobDeadlineType}
+ </TooltipContent>
+ </Tooltip>
+ </HStack>
+ )}
+ </CardContent>
+ </Card>
+ </Link>
+ );
+}
diff --git a/apps/mes/app/components/index.ts b/apps/mes/app/components/index.ts
index 5c8e87793a..d7e7eca259 100644
--- a/apps/mes/app/components/index.ts
+++ b/apps/mes/app/components/index.ts
@@ -1,3 +1,7 @@
import Avatar from "./Avatar";
+import AvatarMenu from "./AvatarMenu";
+import { DeadlineIcon, StatusIcon } from "./Icons";
+import { Nav } from "./Nav";
+import { OperationsList } from "./OperationsList";
-export { Avatar };
+export { Avatar, AvatarMenu, DeadlineIcon, Nav, OperationsList, StatusIcon };
diff --git a/apps/mes/app/routes/_public+/_layout.tsx b/apps/mes/app/routes/_public+/_layout.tsx
index d77e29ca38..ffee026244 100644
--- a/apps/mes/app/routes/_public+/_layout.tsx
+++ b/apps/mes/app/routes/_public+/_layout.tsx
@@ -8,10 +8,10 @@ export default function PublicRoute() {
<div className="container relative h-full flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0">
<div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
<div className="absolute inset-0 bg-zinc-900" />
- <div className="relative z-20 flex items-center text-lg font-medium">
+ <Heading size="h1" className="relative z-20 flex items-center">
<BsHexagonFill className="w-6 h-6 mr-2" />
CarbonOS
- </div>
+ </Heading>
<div className="relative z-20 mt-auto">
<blockquote className="space-y-2">
diff --git a/apps/mes/app/routes/x+/_index.tsx b/apps/mes/app/routes/x+/_index.tsx
index d32e52de85..8b286cb833 100644
--- a/apps/mes/app/routes/x+/_index.tsx
+++ b/apps/mes/app/routes/x+/_index.tsx
@@ -6,10 +6,10 @@ import { path } from "~/utils/path";
export const loader: LoaderFunction = async ({ request }) => {
const { client, companyId, userId } = await requirePermissions(request, {});
- const [, workCenter] = await getLocationAndWorkCenter(request, client, {
+ const { workCenter } = await getLocationAndWorkCenter(request, client, {
companyId,
userId,
});
- return redirect(path.to.jobs(workCenter));
+ return redirect(path.to.workCenter(workCenter));
};
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 5e7cd28f2c..67927f1936 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -19,8 +19,9 @@ import {
destroyAuthSession,
requireAuthSession,
} from "@carbon/auth/session.server";
-import AvatarMenu from "~/components/AvatarMenu";
-import { getLocationsByCompany } from "~/services/jobs";
+import { LuActivity, LuClock, LuInbox } from "react-icons/lu";
+import { AvatarMenu, Nav } from "~/components";
+import { getActiveJobCount, getLocationsByCompany } from "~/services/jobs";
import {
getLocationAndWorkCenter,
setLocationAndWorkCenter,
@@ -50,12 +51,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw redirect(path.to.accountSettings);
}
- const [[location, workCenter, updated], locations] = await Promise.all([
+ const [storedLocations, locations, activeEvents] = await Promise.all([
getLocationAndWorkCenter(request, client, {
companyId,
userId,
}),
getLocationsByCompany(client, companyId),
+ getActiveJobCount(client, {
+ employeeId: userId,
+ companyId,
+ }),
]);
return json(
@@ -65,16 +70,20 @@ export async function loader({ request }: LoaderFunctionArgs) {
expiresIn,
expiresAt,
},
+ activeEvents: activeEvents.data ?? 0,
company,
companies: companies.data ?? [],
- location,
+ location: storedLocations.location,
locations: locations.data ?? [],
user: user.data,
},
- updated
+ storedLocations.updated
? {
headers: {
- "Set-Cookie": setLocationAndWorkCenter(location, workCenter),
+ "Set-Cookie": setLocationAndWorkCenter(
+ storedLocations.location,
+ storedLocations.workCenter
+ ),
},
}
: undefined
@@ -82,7 +91,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AuthenticatedRoute() {
- const { session, location, locations } = useLoaderData<typeof loader>();
+ const { session, activeEvents, location, locations } =
+ useLoaderData<typeof loader>();
const [isCollapsed, setIsCollapsed] = useState(false);
const transition = useNavigation();
@@ -113,7 +123,7 @@ export default function AuthenticatedRoute() {
collapsedSize={4}
collapsible={true}
minSize={15}
- maxSize={20}
+ maxSize={25}
onCollapse={() => {
setIsCollapsed(true);
}}
@@ -128,14 +138,11 @@ export default function AuthenticatedRoute() {
<div
className={cn(
"flex h-[52px] items-center justify-start bg-background",
- isCollapsed ? "h-[52px]" : "px-4"
+ isCollapsed ? "h-[52px]" : "px-2"
)}
>
<div
- className={cn(
- "flex items-center w-full",
- isCollapsed ? "justify-center" : "justify-start"
- )}
+ className={cn("flex w-full items-center justify-center")}
>
<AvatarMenu
// company={company}
@@ -146,16 +153,31 @@ export default function AuthenticatedRoute() {
/>
</div>
</div>
- <div className="flex flex-col h-[calc(100%-52px)] justify-between overflow-y-auto">
+ <div className="flex flex-col h-[calc(100%-52px)] justify-between overflow-y-auto bg-background">
<div className="flex flex-col">
<Separator />
+ <Nav
+ isCollapsed={isCollapsed}
+ links={[
+ {
+ title: "Jobs",
+ icon: LuInbox,
+ to: path.to.jobs,
+ },
+ {
+ title: "Active",
+ icon: LuActivity,
+ label: (activeEvents ?? 0).toString(),
+ to: path.to.active,
+ },
+ {
+ title: "Recent",
+ icon: LuClock,
+ to: path.to.recent,
+ },
+ ]}
+ />
</div>
- <div
- className={cn(
- "flex flex-col p-2 w-full",
- isCollapsed && "items-center justify-center "
- )}
- ></div>
</div>
</ResizablePanel>
<ResizableHandle withHandle />
diff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsx
new file mode 100644
index 0000000000..465755344d
--- /dev/null
+++ b/apps/mes/app/routes/x+/active.tsx
@@ -0,0 +1,80 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { Heading, Input, ResizablePanel, Separator, Tabs } from "@carbon/react";
+import { json, Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { useMemo, useState } from "react";
+
+import { LuSearch } from "react-icons/lu";
+import { OperationsList } from "~/components";
+import { getActiveJobOperationsByEmployee } from "~/services/jobs";
+import { makeDurationsAndProgress } from "~/utils/jobs";
+
+import { defaultLayout } from "~/utils/layout";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const [operations] = await Promise.all([
+ getActiveJobOperationsByEmployee(client, {
+ employeeId: userId,
+ companyId,
+ }),
+ ]);
+
+ return json({
+ operations: operations?.data?.map(makeDurationsAndProgress) ?? [],
+ });
+}
+
+export default function ActiveRoute() {
+ const { operations } = useLoaderData<typeof loader>();
+ const [searchTerm, setSearchTerm] = useState("");
+
+ const filteredOperations = useMemo(() => {
+ if (!searchTerm) return operations;
+ const lowercasedTerm = searchTerm.toLowerCase();
+ return operations.filter(
+ (operation) =>
+ operation.description?.toLowerCase().includes(lowercasedTerm) ||
+ operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||
+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm)
+ );
+ }, [operations, searchTerm]);
+
+ return (
+ <>
+ <ResizablePanel defaultSize={defaultLayout[1]} minSize={30}>
+ <Tabs defaultValue="current">
+ <div className="flex items-center px-4 py-2 h-[52px] bg-background">
+ <Heading size="h2">Active</Heading>
+ </div>
+ <Separator />
+ <div className="p-4">
+ <div className="relative">
+ <div className="flex justify-between gap-4">
+ <div className="flex flex-grow">
+ <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder="Search"
+ className="pl-8"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="p-4 pt-0">
+ <OperationsList
+ key="active"
+ emptyMessage="No active jobs"
+ operations={filteredOperations}
+ />
+ </div>
+ </Tabs>
+ </ResizablePanel>
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
index 29c8662b13..0ff39b22ba 100644
--- a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
+++ b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
@@ -1,13 +1,7 @@
import {
- Card,
- CardContent,
- CardHeader,
- cn,
Heading,
- HStack,
Input,
ResizablePanel,
- ScrollArea,
Select,
SelectContent,
SelectItem,
@@ -18,37 +12,21 @@ import {
TabsContent,
TabsList,
TabsTrigger,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
} from "@carbon/react";
-import {
- LuAlertTriangle,
- LuCheckCircle,
- LuClipboardCheck,
- LuSearch,
- LuTimer,
- LuXCircle,
-} from "react-icons/lu";
+import { LuSearch } from "react-icons/lu";
import { defaultLayout } from "~/utils/layout";
import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import {
- convertDateStringToIsoString,
- formatDurationMilliseconds,
- formatRelativeTime,
-} from "@carbon/utils";
-import { Link, useLoaderData, useNavigate, useParams } from "@remix-run/react";
+ Outlet,
+ useLoaderData,
+ useNavigate,
+ useParams,
+} from "@remix-run/react";
import { json, type LoaderFunctionArgs } from "@vercel/remix";
-import { BsExclamationSquareFill } from "react-icons/bs";
-import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
-import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
-import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
-import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
-import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
-import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
-import type { Operation, OperationSettings } from "~/services/jobs";
+import { useMemo, useState } from "react";
+import { OperationsList } from "~/components";
import {
getJobOperationsByWorkCenter,
getWorkCentersByLocation,
@@ -60,23 +38,15 @@ import {
import { makeDurationsAndProgress } from "~/utils/jobs";
import { path } from "~/utils/path";
-// TODO: load dynamically
-const operationSettings: OperationSettings = {
- showCustomer: false,
- showDescription: true,
- showDueDate: true,
- showDuration: true,
- showEmployee: false,
- showProgress: false,
- showStatus: true,
-};
+// TODO: it's possible that the location cookie and the work cell become out of sync.
+// we should probably include the location in the url param when using work centers
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {});
const { workCenterId } = params;
if (!workCenterId) throw notFound("workCenterId not found");
- const [location, workCenter] = await getLocationAndWorkCenter(
+ const { location, workCenter } = await getLocationAndWorkCenter(
request,
client,
{
@@ -114,250 +84,91 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export default function JobsRoute() {
const { operations, workCenters } = useLoaderData<typeof loader>();
- console.log({ operations });
+ const [searchTerm, setSearchTerm] = useState("");
+
const { workCenterId } = useParams();
if (!workCenterId) throw new Error("workCenterId not found");
const navigate = useNavigate();
+ const filteredOperations = useMemo(() => {
+ if (!searchTerm) return operations;
+ const lowercasedTerm = searchTerm.toLowerCase();
+ return operations.filter(
+ (operation) =>
+ operation.description?.toLowerCase().includes(lowercasedTerm) ||
+ operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||
+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm)
+ );
+ }, [operations, searchTerm]);
+
return (
- <ResizablePanel defaultSize={defaultLayout[1]} minSize={30}>
- <Tabs defaultValue="current">
- <div className="flex items-center px-4 py-2 h-[52px] bg-background">
- <Heading size="h2">Jobs</Heading>
- <TabsList className="ml-auto">
- <TabsTrigger value="current">Current</TabsTrigger>
- <TabsTrigger value="all">All</TabsTrigger>
- </TabsList>
- </div>
- <Separator />
- <div className="p-4">
- <div className="relative">
- <div className="flex justify-between gap-4">
- <div className="flex flex-grow">
- <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- // value={input}
- // onChange={onSearchChange}
- placeholder="Search"
- className="pl-8"
- />
- </div>
- <div className="flex flex-shrink basis-64">
- <Select
- value={workCenterId}
- onValueChange={(value) => {
- navigate(path.to.jobs(value));
- }}
- >
- <SelectTrigger aria-label="Select work cell">
- <SelectValue placeholder="Select a work cell">
- {workCenters.find((wc) => wc.id === workCenterId)?.name}
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- {workCenters.map((cell) => (
- <SelectItem key={cell.id} value={cell.id}>
- {cell.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <>
+ <ResizablePanel defaultSize={defaultLayout[1]} minSize={30}>
+ <Tabs defaultValue="current">
+ <div className="flex items-center px-4 py-2 h-[52px] bg-background">
+ <Heading size="h2">Jobs</Heading>
+ <TabsList className="ml-auto">
+ <TabsTrigger value="current">Current</TabsTrigger>
+ <TabsTrigger value="all">All</TabsTrigger>
+ </TabsList>
+ </div>
+ <Separator />
+ <div className="p-4">
+ <div className="relative">
+ <div className="flex justify-between gap-4">
+ <div className="flex flex-grow">
+ <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder="Search"
+ className="pl-8"
+ />
+ </div>
+ <div className="flex flex-shrink basis-64">
+ <Select
+ value={workCenterId}
+ onValueChange={(value) => {
+ navigate(path.to.workCenter(value));
+ }}
+ >
+ <SelectTrigger aria-label="Select work cell">
+ <SelectValue placeholder="Select a work cell">
+ {workCenters.find((wc) => wc.id === workCenterId)?.name}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {workCenters.map((cell) => (
+ <SelectItem key={cell.id} value={cell.id}>
+ {cell.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
</div>
</div>
</div>
- </div>
-
- <TabsContent value="current" className="p-4 pt-0">
- <OperationsList
- key={`current:${workCenterId}`}
- operations={operations.filter((operation) =>
- ["In Progress", "Ready", "Todo"].includes(
- operation.operationStatus
- )
- )}
- {...operationSettings}
- />
- </TabsContent>
- <TabsContent value="all" className="p-4 pt-0">
- <OperationsList
- key={`all-${workCenterId}`}
- operations={operations}
- {...operationSettings}
- />
- </TabsContent>
- </Tabs>
- </ResizablePanel>
- );
-}
-
-type OperationsListProps = OperationSettings & {
- operations: Operation[];
-};
-
-function OperationsList({ operations, ...settings }: OperationsListProps) {
- const { operationId } = useParams();
- console.log({ operations });
- return operations.length > 0 ? (
- <ScrollArea className="h-[calc(100vh-120px)]">
- <div className="flex flex-col gap-2">
- {operations.map((operation) => (
- <OperationCard
- key={operation.id}
- operation={operation}
- isSelected={operationId === operation.id}
- {...settings}
- />
- ))}
- </div>
- </ScrollArea>
- ) : (
- <div className="flex flex-col w-full h-[calc(100vh-120px)] items-center justify-center gap-4">
- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
- <LuAlertTriangle className="h-6 w-6" />
- </div>
- <span className="text-lg font-mono font-light text-foreground uppercase">
- No scheduled jobs
- </span>
- </div>
- );
-}
-
-type OperationCardProps = {
- isSelected: boolean;
- operation: Operation;
-} & OperationSettings;
-function OperationCard({
- operation,
- isSelected = false,
- showCustomer,
- showDescription,
- showDueDate,
- showDuration,
- showEmployee,
- showProgress,
- showStatus,
-}: OperationCardProps) {
- const isOverdue =
- operation.jobDeadlineType !== "No Deadline" && operation.jobDueDate
- ? new Date(operation.jobDueDate) < new Date()
- : false;
-
- return (
- <Link to={operation.id}>
- <Card
- className={cn("cursor-pointer", isSelected && "from-muted to-muted")}
- >
- <CardHeader className={cn("max-w-full p-3 border-b relative")}>
- <div className="flex w-full max-w-full justify-between">
- <div className="flex flex-col space-y-0">
- {operation.itemReadableId && (
- <span className="text-xs text-muted-foreground truncate">
- {operation.itemReadableId}
- </span>
+ <TabsContent value="current" className="p-4 pt-0">
+ <OperationsList
+ key={`current:${workCenterId}`}
+ operations={filteredOperations.filter((operation) =>
+ ["In Progress", "Ready", "Todo"].includes(
+ operation.operationStatus
+ )
)}
- <span className="mr-auto font-semibold truncate">
- {operation.jobReadableId}
- </span>
- </div>
- </div>
- </CardHeader>
- <CardContent className="p-3 space-y-2 text-left whitespace-pre-wrap text-sm">
- {showDescription && operation.description && (
- <HStack className="justify-start space-x-2">
- <LuClipboardCheck className="text-muted-foreground" />
- <span className="text-sm">{operation.description}</span>
- </HStack>
- )}
- {showStatus && operation.operationStatus && (
- <HStack className="justify-start space-x-2">
- {getStatusIcon(operation.operationStatus)}
- <span className="text-sm">{operation.operationStatus}</span>
- </HStack>
- )}
- {showDuration && operation.duration && (
- <HStack className="justify-start space-x-2">
- <LuTimer className="text-muted-foreground" />
- <span className="text-sm">
- {formatDurationMilliseconds(operation.duration)}
- </span>
- </HStack>
- )}
- {showDueDate && operation.jobDeadlineType && (
- <HStack className="justify-start space-x-2">
- {getDeadlineIcon(operation.jobDeadlineType, isOverdue)}
- <Tooltip>
- <TooltipTrigger>
- <span
- className={cn("text-sm", isOverdue ? "text-red-500" : "")}
- >
- {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)
- ? getDeadlineText(operation.jobDeadlineType)
- : operation.jobDueDate
- ? `Due ${formatRelativeTime(
- convertDateStringToIsoString(operation.jobDueDate)
- )}`
- : "–"}
- </span>
- </TooltipTrigger>
- <TooltipContent side="right">
- {getDeadlineText(operation.jobDeadlineType)}
- </TooltipContent>
- </Tooltip>
- </HStack>
- )}
- </CardContent>
- </Card>
- </Link>
+ />
+ </TabsContent>
+ <TabsContent value="all" className="p-4 pt-0">
+ <OperationsList
+ key={`all-${workCenterId}`}
+ operations={filteredOperations}
+ />
+ </TabsContent>
+ </Tabs>
+ </ResizablePanel>
+ <Outlet />
+ </>
);
}
-
-export function getStatusIcon(status: Operation["operationStatus"]) {
- switch (status) {
- case "Ready":
- case "Todo":
- return <TodoStatusIcon className="text-foreground" />;
- case "Waiting":
- case "Canceled":
- return <LuXCircle className="text-muted-foreground" />;
- case "Done":
- return <LuCheckCircle className="text-blue-600" />;
- case "In Progress":
- return <AlmostDoneIcon />;
- case "Paused":
- return <InProgressStatusIcon />;
- default:
- return null;
- }
-}
-
-export function getDeadlineIcon(
- deadlineType: Operation["jobDeadlineType"],
- overdue: boolean
-) {
- switch (deadlineType) {
- case "ASAP":
- return <BsExclamationSquareFill className="text-red-500" />;
- case "Hard Deadline":
- return <HighPriorityIcon className={cn(overdue ? "text-red-500" : "")} />;
- case "Soft Deadline":
- return (
- <MediumPriorityIcon className={cn(overdue ? "text-red-500" : "")} />
- );
- case "No Deadline":
- return <LowPriorityIcon />;
- }
-}
-
-export function getDeadlineText(deadlineType: Operation["jobDeadlineType"]) {
- switch (deadlineType) {
- case "ASAP":
- return "ASAP";
- case "Hard Deadline":
- return "Hard deadline";
- case "Soft Deadline":
- return "Soft deadline";
- case "No Deadline":
- return "No deadline";
- }
-}
diff --git a/apps/mes/app/routes/x+/jobs._index.tsx b/apps/mes/app/routes/x+/jobs._index.tsx
new file mode 100644
index 0000000000..8b286cb833
--- /dev/null
+++ b/apps/mes/app/routes/x+/jobs._index.tsx
@@ -0,0 +1,15 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunction } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { getLocationAndWorkCenter } from "~/services/location.server";
+import { path } from "~/utils/path";
+
+export const loader: LoaderFunction = async ({ request }) => {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+ const { workCenter } = await getLocationAndWorkCenter(request, client, {
+ companyId,
+ userId,
+ });
+
+ return redirect(path.to.workCenter(workCenter));
+};
diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsx
new file mode 100644
index 0000000000..d892269f21
--- /dev/null
+++ b/apps/mes/app/routes/x+/recent.tsx
@@ -0,0 +1,80 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { Heading, Input, ResizablePanel, Separator, Tabs } from "@carbon/react";
+import { json, Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { useMemo, useState } from "react";
+
+import { LuSearch } from "react-icons/lu";
+import { OperationsList } from "~/components";
+import { getRecentJobOperationsByEmployee } from "~/services/jobs";
+import { makeDurationsAndProgress } from "~/utils/jobs";
+
+import { defaultLayout } from "~/utils/layout";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const [operations] = await Promise.all([
+ getRecentJobOperationsByEmployee(client, {
+ employeeId: userId,
+ companyId,
+ }),
+ ]);
+
+ return json({
+ operations: operations?.data?.map(makeDurationsAndProgress) ?? [],
+ });
+}
+
+export default function ActiveRoute() {
+ const { operations } = useLoaderData<typeof loader>();
+ const [searchTerm, setSearchTerm] = useState("");
+
+ const filteredOperations = useMemo(() => {
+ if (!searchTerm) return operations;
+ const lowercasedTerm = searchTerm.toLowerCase();
+ return operations.filter(
+ (operation) =>
+ operation.description?.toLowerCase().includes(lowercasedTerm) ||
+ operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||
+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm)
+ );
+ }, [operations, searchTerm]);
+
+ return (
+ <>
+ <ResizablePanel defaultSize={defaultLayout[1]} minSize={30}>
+ <Tabs defaultValue="current">
+ <div className="flex items-center px-4 py-2 h-[52px] bg-background">
+ <Heading size="h2">Active</Heading>
+ </div>
+ <Separator />
+ <div className="p-4">
+ <div className="relative">
+ <div className="flex justify-between gap-4">
+ <div className="flex flex-grow">
+ <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder="Search"
+ className="pl-8"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="p-4 pt-0">
+ <OperationsList
+ key="active"
+ emptyMessage="No active jobs"
+ operations={filteredOperations}
+ />
+ </div>
+ </Tabs>
+ </ResizablePanel>
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/mes/app/services/jobs.ts b/apps/mes/app/services/jobs.ts
index 3a1e5b7fa5..f5d02efaf9 100644
--- a/apps/mes/app/services/jobs.ts
+++ b/apps/mes/app/services/jobs.ts
@@ -30,6 +30,45 @@ export type Location = NonNullable<
Awaited<ReturnType<typeof getLocationsByCompany>>["data"]
>[number];
+export async function getRecentJobOperationsByEmployee(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ }
+) {
+ return client.rpc("get_recent_job_operations_by_employee", {
+ employee_id: args.employeeId,
+ company_id: args.companyId,
+ });
+}
+
+export async function getActiveJobOperationsByEmployee(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ }
+) {
+ return client.rpc("get_active_job_operations_by_employee", {
+ employee_id: args.employeeId,
+ company_id: args.companyId,
+ });
+}
+
+export async function getActiveJobCount(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ }
+) {
+ return client.rpc("get_active_job_count", {
+ employee_id: args.employeeId,
+ company_id: args.companyId,
+ });
+}
+
export async function getJobOperationsByWorkCenter(
client: SupabaseClient<Database>,
{ locationId, workCenterId }: { locationId: string; workCenterId: string }
@@ -40,6 +79,17 @@ export async function getJobOperationsByWorkCenter(
});
}
+export async function getLocationsByCompany(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("location")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("name", { ascending: true });
+}
+
export async function getWorkCentersByLocation(
client: SupabaseClient<Database>,
locationId: string
@@ -51,12 +101,12 @@ export async function getWorkCentersByLocation(
.order("name", { ascending: true });
}
-export async function getLocationsByCompany(
+export async function getWorkCentersByCompany(
client: SupabaseClient<Database>,
companyId: string
) {
return client
- .from("location")
+ .from("workCenter")
.select("*")
.eq("companyId", companyId)
.order("name", { ascending: true });
diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.ts
index 0c164ab8db..171fd5b8ae 100644
--- a/apps/mes/app/services/location.server.ts
+++ b/apps/mes/app/services/location.server.ts
@@ -55,7 +55,7 @@ export async function getLocationAndWorkCenter(
userId: string;
companyId: string;
}
-): Promise<[string, string, boolean]> {
+) {
const { userId, companyId } = args;
let location = getLocation(request);
let workCenter = getWorkCenter(request);
@@ -102,5 +102,5 @@ export async function getLocationAndWorkCenter(
if (!workCenter) throw new Error("Failed to get a valid work center");
- return [location, workCenter, updated];
+ return { location, workCenter, updated };
}
diff --git a/apps/mes/app/utils/layout.ts b/apps/mes/app/utils/layout.ts
index 6c9e432c1a..6e8633f823 100644
--- a/apps/mes/app/utils/layout.ts
+++ b/apps/mes/app/utils/layout.ts
@@ -1 +1 @@
-export const defaultLayout = [265, 440, 655];
+export const defaultLayout = [25, 75, 100];
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 12d8bf2900..7d13aeb62a 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -11,17 +11,20 @@ const x = "/x"; // from ~/routes/x+ folder
export const path = {
to: {
accountSettings: `${ERP_URL}/x/account`,
+ active: `${x}/active`,
authenticatedRoot: x,
callback: "/callback",
forgotPassword: "/forgot-password",
healthcheck: "/healthcheck",
- jobs: (workCenter: string) => generatePath(`${x}/jobs/${workCenter}`),
+ jobs: `${x}/jobs`,
location: `${x}/location`,
login: "/login",
logout: "/logout",
+ recent: `${x}/recent`,
refreshSession: "/refresh-session",
requestAccess: "/request-access",
root: "/",
+ workCenter: (workCenter: string) => generatePath(`${x}/jobs/${workCenter}`),
},
} as const;
diff --git a/package-lock.json b/package-lock.json
index 47505ed614..0e2e4c2166 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -249,6 +249,7 @@
"@tailwindcss/typography": "^0.5.10",
"@vercel/analytics": "^1.2.2",
"@vercel/remix": "2.10.2",
+ "cookie": "0.6.0",
"framer-motion": "^11.1.7",
"isbot": "3.6.13",
"non.geist": "~1.0.3",
@@ -34310,6 +34311,18 @@
"node": ">= 0.8"
}
},
+ "node_modules/vaul": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.0.0.tgz",
+ "integrity": "sha512-TegfMkwy86RSvSiIVREG6OqgRL7agqRsKYyWYacyVUAdpcIi34QoCOED476Mbf8J5d06e1hygSdvJhehlxEBhQ==",
+ "dependencies": {
+ "@radix-ui/react-dialog": "^1.1.1"
+ },
+ "peerDependencies": {
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ }
+ },
"node_modules/vfile": {
"version": "5.3.7",
"resolved": "https://registry.npmjs.org/vfile/-/vfile-5.3.7.tgz",
@@ -35967,7 +35980,8 @@
"react-resizable-panels": "^2.1.3",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
- "tailwindcss-animate": "^1.0.7"
+ "tailwindcss-animate": "^1.0.7",
+ "vaul": "^1.0.0"
},
"devDependencies": {
"@carbon/jest": "*",
diff --git a/packages/database/src/seed/modules.ts b/packages/database/src/seed/modules.ts
index 1a4cd3a9e5..a9068ffc5a 100644
--- a/packages/database/src/seed/modules.ts
+++ b/packages/database/src/seed/modules.ts
@@ -10,7 +10,6 @@ const modules = [
"Resources",
"Sales",
"Settings",
- "Timecards",
"Users",
] as const;
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 70b51afd0b..78e6c4409f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -11487,6 +11487,199 @@ export type Database = {
},
]
}
+ productionEvent: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ duration: number | null
+ employeeId: string | null
+ endTime: string | null
+ id: string
+ jobOperationId: string
+ startTime: string
+ type: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt: string | null
+ updatedBy: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ duration?: number | null
+ employeeId?: string | null
+ endTime?: string | null
+ id?: string
+ jobOperationId: string
+ startTime: string
+ type?: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt?: string | null
+ updatedBy: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ duration?: number | null
+ employeeId?: string | null
+ endTime?: string | null
+ id?: string
+ jobOperationId?: string
+ startTime?: string
+ type?: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt?: string | null
+ updatedBy?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "productionEvent_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
purchaseInvoice: {
Row: {
assignee: string | null
@@ -28653,6 +28846,44 @@ export type Database = {
Args: Record<PropertyKey, never>
Returns: number
}
+ get_active_job_count: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: number
+ }
+ get_active_job_operations_by_employee: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_claims: {
Args: {
uid: string
@@ -28856,6 +29087,37 @@ export type Database = {
isRoot: boolean
}[]
}
+ get_recent_job_operations_by_employee: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
groups_for_user: {
Args: {
uid: string
@@ -29166,6 +29428,7 @@ export type Database = {
| "Fixture"
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
processType: "Inside" | "Outside" | "Inside and Outside"
+ productionEventType: "Setup" | "Labor" | "Machine"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 70b51afd0b..78e6c4409f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -11487,6 +11487,199 @@ export type Database = {
},
]
}
+ productionEvent: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ duration: number | null
+ employeeId: string | null
+ endTime: string | null
+ id: string
+ jobOperationId: string
+ startTime: string
+ type: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt: string | null
+ updatedBy: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ duration?: number | null
+ employeeId?: string | null
+ endTime?: string | null
+ id?: string
+ jobOperationId: string
+ startTime: string
+ type?: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt?: string | null
+ updatedBy: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ duration?: number | null
+ employeeId?: string | null
+ endTime?: string | null
+ id?: string
+ jobOperationId?: string
+ startTime?: string
+ type?: Database["public"]["Enums"]["productionEventType"] | null
+ updatedAt?: string | null
+ updatedBy?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionEvent_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "productionEvent_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionEvent_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
purchaseInvoice: {
Row: {
assignee: string | null
@@ -28653,6 +28846,44 @@ export type Database = {
Args: Record<PropertyKey, never>
Returns: number
}
+ get_active_job_count: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: number
+ }
+ get_active_job_operations_by_employee: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_claims: {
Args: {
uid: string
@@ -28856,6 +29087,37 @@ export type Database = {
isRoot: boolean
}[]
}
+ get_recent_job_operations_by_employee: {
+ Args: {
+ employee_id: string
+ company_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
groups_for_user: {
Args: {
uid: string
@@ -29166,6 +29428,7 @@ export type Database = {
| "Fixture"
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
processType: "Inside" | "Outside" | "Inside and Outside"
+ productionEventType: "Setup" | "Labor" | "Machine"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/migrations/20240927033740_job-operations-for-mes.sql b/packages/database/supabase/migrations/20240927033740_job-operations-for-mes.sql
index 0fcf0ad8c7..c60c12c514 100644
--- a/packages/database/supabase/migrations/20240927033740_job-operations-for-mes.sql
+++ b/packages/database/supabase/migrations/20240927033740_job-operations-for-mes.sql
@@ -10,6 +10,89 @@ CREATE TYPE "jobOperationStatus" AS ENUM (
'Waiting'
);
+CREATE TYPE "productionEventType" AS ENUM (
+ 'Setup',
+ 'Labor',
+ 'Machine'
+);
+
+CREATE TABLE "productionEvent" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobOperationId" TEXT NOT NULL,
+ "type" "productionEventType",
+ "startTime" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "endTime" TIMESTAMP WITH TIME ZONE,
+ "duration" INTEGER GENERATED ALWAYS AS (
+ CASE
+ WHEN "endTime" IS NULL THEN 0
+ ELSE EXTRACT(EPOCH FROM ("endTime" - "startTime"))::INTEGER
+ END
+ ) STORED,
+ "employeeId" TEXT,
+ "workCenterId" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "productionEvent_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "productionEvent_jobOperationId_fkey" FOREIGN KEY ("jobOperationId") REFERENCES "jobOperation"("id") ON DELETE CASCADE,
+ CONSTRAINT "productionEvent_employeeId_fkey" FOREIGN KEY ("employeeId") REFERENCES "user"("id") ON DELETE SET NULL,
+ CONSTRAINT "productionEvent_workCenterId_fkey" FOREIGN KEY ("workCenterId") REFERENCES "workCenter"("id") ON DELETE SET NULL,
+ CONSTRAINT "productionEvent_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "productionEvent_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,
+ CONSTRAINT "productionEvent_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT
+);
+
+-- Create separate indexes on companyId, jobOperationId, and employeeId
+CREATE INDEX "idx_productionEvent_companyId" ON "productionEvent" ("companyId");
+CREATE INDEX "idx_productionEvent_jobOperationId" ON "productionEvent" ("jobOperationId");
+CREATE INDEX "idx_productionEvent_employeeId" ON "productionEvent" ("employeeId", "companyId");
+
+
+ALTER TABLE "productionEvent" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Requests with an API key can access production events" ON "productionEvent"
+FOR ALL USING (
+ has_valid_api_key_for_company("companyId")
+);
+
+-- Policy for employees to view their own production events
+CREATE POLICY "Employees can view their own production events" ON "productionEvent"
+FOR SELECT USING (
+ auth.uid()::text = "employeeId"
+);
+
+-- Policy for users with production_view to see all production events related to the company
+CREATE POLICY "Users with production_view can see all production events" ON "productionEvent"
+FOR SELECT USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('production_view', "companyId")
+);
+
+-- Policy for users with production_create to insert production events
+CREATE POLICY "Users with production_create can insert production events" ON "productionEvent"
+FOR INSERT WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('production_create', "companyId")
+);
+
+-- Policy for users with production_update to update production events
+CREATE POLICY "Users with production_update can update production events" ON "productionEvent"
+FOR UPDATE USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('production_update', "companyId")
+);
+
+-- Policy for users with production_delete to delete production events
+CREATE POLICY "Users with production_delete can delete production events" ON "productionEvent"
+FOR DELETE USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('production_delete', "companyId")
+);
+
+
ALTER TABLE "jobOperation"
ADD COLUMN "status" "jobOperationStatus" NOT NULL DEFAULT 'Todo';
@@ -98,3 +181,165 @@ BEGIN
WHERE jo."workCenterId" = work_center_id;
END;
$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_active_job_operations_by_employee(
+ employee_id TEXT,
+ company_id TEXT
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC(10,2),
+ "setupUnit" factor,
+ "laborTime" NUMERIC(10,2),
+ "laborUnit" factor,
+ "machineTime" NUMERIC(10,2),
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "operationQuantity" NUMERIC(10,2),
+ "quantityComplete" NUMERIC(10,2),
+ "quantityScrapped" NUMERIC(10,2)
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH active_production_events AS (
+ SELECT DISTINCT "jobOperationId"
+ FROM "productionEvent"
+ WHERE "employeeId" = employee_id AND "endTime" IS NULL AND "companyId" = company_id
+ )
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate" AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ jo."status" AS "operationStatus",
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityScrapped"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ JOIN active_production_events ape ON ape."jobOperationId" = jo.id;
+END;
+$$ LANGUAGE plpgsql;
+
+
+CREATE OR REPLACE FUNCTION get_active_job_count(employee_id TEXT, company_id TEXT)
+RETURNS INTEGER
+SECURITY INVOKER
+AS $$
+DECLARE
+ active_count INTEGER;
+BEGIN
+ SELECT COUNT(DISTINCT "jobOperationId")
+ INTO active_count
+ FROM "productionEvent"
+ WHERE "employeeId" = employee_id
+ AND "companyId" = company_id
+ AND "endTime" IS NULL;
+
+ RETURN active_count;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_recent_job_operations_by_employee(
+ employee_id TEXT,
+ company_id TEXT
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC(10,2),
+ "setupUnit" factor,
+ "laborTime" NUMERIC(10,2),
+ "laborUnit" factor,
+ "machineTime" NUMERIC(10,2),
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "operationQuantity" NUMERIC(10,2),
+ "quantityComplete" NUMERIC(10,2),
+ "quantityScrapped" NUMERIC(10,2)
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH recent_production_events AS (
+ SELECT DISTINCT ON ("jobOperationId") "jobOperationId", "startTime"
+ FROM "productionEvent"
+ WHERE "employeeId" = employee_id AND "companyId" = company_id
+ ORDER BY "jobOperationId", "startTime" DESC
+ )
+ SELECT DISTINCT ON (jo."id")
+ jo."id",
+ jo."jobId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate" AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ jo."status" AS "operationStatus",
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityScrapped"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ JOIN recent_production_events rpe ON rpe."jobOperationId" = jo.id
+ ORDER BY jo."id", rpe."startTime" DESC
+ LIMIT 20;
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/react/package.json b/packages/react/package.json
index da8d08ae22..428ca4b1be 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -58,7 +58,8 @@
"react-resizable-panels": "^2.1.3",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
- "tailwindcss-animate": "^1.0.7"
+ "tailwindcss-animate": "^1.0.7",
+ "vaul": "^1.0.0"
},
"devDependencies": {
"@carbon/jest": "*",
diff --git a/packages/react/src/Table.tsx b/packages/react/src/Table.tsx
index ff13ec1b76..a05625dde6 100644
--- a/packages/react/src/Table.tsx
+++ b/packages/react/src/Table.tsx
@@ -85,7 +85,7 @@ const Th = forwardRef<
<th
ref={ref}
className={cn(
- "group-hover:bg-primary/5 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-xs text-foreground [&:has([role=checkbox])]:pr-0",
+ "group-hover:bg-muted h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-xs text-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
@@ -100,7 +100,7 @@ const Td = forwardRef<
<td
ref={ref}
className={cn(
- "group-hover:bg-primary/5 text-foreground/80 px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
+ "group-hover:bg-muted text-foreground/80 px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",
className
)}
{...props}
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 5e2c1064da..deda03733b 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -83,7 +83,6 @@ import {
import {
Drawer,
DrawerBody,
- DrawerCloseButton,
DrawerContent,
DrawerDescription,
DrawerFooter,
@@ -352,7 +351,6 @@ export {
DateTimePicker,
Drawer,
DrawerBody,
- DrawerCloseButton,
DrawerContent,
DrawerDescription,
DrawerFooter,