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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add actions for starting and stopping events
Brad Barbinf9b5b4ec18c6
diff --git a/apps/carbon/app/services/mode.server.ts b/apps/carbon/app/services/mode.server.tsindex 7c772021f5..c5f8184432 100644--- a/apps/carbon/app/services/mode.server.ts+++ b/apps/carbon/app/services/mode.server.ts@@ -1,3 +1,4 @@+import { DOMAIN } from "@carbon/auth";import * as cookie from "cookie";import type { Mode } from "~/types/validators";@@ -16,6 +17,10 @@ export function setMode(mode: Mode | "system") {if (mode === "system") {return cookie.serialize(cookieName, "", { path: "/", maxAge: -1 });} else {- return cookie.serialize(cookieName, mode, { path: "/", maxAge: 31536000 });+ return cookie.serialize(cookieName, mode, {+ path: "/",+ maxAge: 31536000,+ domain: DOMAIN,+ });}}diff --git a/apps/carbon/app/services/theme.server.ts b/apps/carbon/app/services/theme.server.tsindex 6e24b6f0dc..1dee416ab8 100644--- a/apps/carbon/app/services/theme.server.ts+++ b/apps/carbon/app/services/theme.server.ts@@ -1,3 +1,4 @@+import { DOMAIN } from "@carbon/auth";import * as cookie from "cookie";const cookieName = "theme";@@ -22,5 +23,9 @@ export function getTheme(request: Request): Theme {}export function setTheme(theme: string) {- return cookie.serialize(cookieName, theme, { path: "/", maxAge: 31536000 });+ return cookie.serialize(cookieName, theme, {+ path: "/",+ maxAge: 31536000,+ domain: DOMAIN,+ });}diff --git a/apps/developers/app/services/mode.server.ts b/apps/developers/app/services/mode.server.tsindex 7c772021f5..c5f8184432 100644--- a/apps/developers/app/services/mode.server.ts+++ b/apps/developers/app/services/mode.server.ts@@ -1,3 +1,4 @@+import { DOMAIN } from "@carbon/auth";import * as cookie from "cookie";import type { Mode } from "~/types/validators";@@ -16,6 +17,10 @@ export function setMode(mode: Mode | "system") {if (mode === "system") {return cookie.serialize(cookieName, "", { path: "/", maxAge: -1 });} else {- return cookie.serialize(cookieName, mode, { path: "/", maxAge: 31536000 });+ return cookie.serialize(cookieName, mode, {+ path: "/",+ maxAge: 31536000,+ domain: DOMAIN,+ });}}diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsxindex 41318cfd3f..177ae72c08 100644--- a/apps/mes/app/components/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation.tsx@@ -61,18 +61,24 @@ import type {Operation,OperationWithDetails,ProductionEvent,+ productionEventType,StorageItem,} from "~/services/jobs.service";-import { getDocumentType } from "~/services/jobs.service";+import {+ getDocumentType,+ productionEventValidator,+} from "~/services/jobs.service";import { path } from "~/utils/path";import { useCarbon } from "@carbon/auth";+import { Hidden, useIsSubmitting, ValidatedForm } from "@carbon/form";import {convertDateStringToIsoString,convertKbToString,formatDurationMilliseconds,formatRelativeTime,} from "@carbon/utils";+import { getLocalTimeZone } from "@internationalized/date";import type { PostgrestResponse } from "@supabase/supabase-js";import { FaRedoAlt, FaTasks } from "react-icons/fa";import { FaCheck, FaOilCan, FaPause, FaPlay, FaTrash } from "react-icons/fa6";@@ -107,13 +113,14 @@ export const JobOperation = ({}: JobOperationProps) => {const {activeTab,+ eventType,fullScreen,isOverdue,progress,downloadDocument,getDocumentPath,-setActiveTab,+ setEventType,setFullScreen,} = useOperation(operation, events, job);@@ -141,40 +148,20 @@ export const JobOperation = ({)}<Heading size="h2">{operation.jobReadableId}</Heading></div>- <div className="flex flex-shrink-0 items-center justify-end gap-2">- <TabsList className="ml-auto">- <TabsTrigger value="details">Details</TabsTrigger>- <TabsTrigger- disabled={!job.autodeskUrn && !operation.itemAutodeskUrn}- value="model"- >- Model- </TabsTrigger>- <TabsTrigger- disabled={- !operation.workInstruction ||- Object.keys(operation.workInstruction).length === 0- }- value="instructions"- >- Instructions- </TabsTrigger>- </TabsList>- {!fullScreen && (- <IconButton- aria-label="Expand"- icon={<LuExpand />}- variant="secondary"- onClick={() => setFullScreen(true)}- />- )}+ <div className="hidden md:flex flex-shrink-0 items-center justify-end gap-2">+ <Navigation+ job={job}+ operation={operation}+ fullScreen={fullScreen}+ setFullScreen={setFullScreen}+ /></div></div>{!fullScreen && (<><Separator />- <div className="flex items-center justify-start px-4 py-2 h-[52px] bg-background gap-4">+ <div className="flex items-center justify-start px-4 py-2 h-[52px] bg-background gap-4 w-full overflow-y-auto">{operation.description && (<HStack className="justify-start space-x-2"><LuClipboardCheck className="text-muted-foreground" />@@ -203,9 +190,18 @@ export const JobOperation = ({<Separator /></>)}+ <div className="flex md:hidden items-center justify-start px-4 py-2 h-[52px] bg-background gap-4">+ <Navigation+ job={job}+ operation={operation}+ fullScreen={fullScreen}+ setFullScreen={setFullScreen}+ />+ </div>+ <Separator className="flex md:hidden" /><TabsContent value="details">- <ScrollArea className="h-[calc(100vh-104px)] pb-36">+ <ScrollArea className="h-[calc(100vh-156px)] md:h-[calc(100vh-104px)] pb-36"><div className="flex items-start justify-between p-4"><div className="flex flex-col flex-grow"><Heading size="h2">{operation.itemReadableId}</Heading>@@ -495,7 +491,7 @@ export const JobOperation = ({</ScrollArea></TabsContent><TabsContent value="model">- <div className="h-[calc(100vh-104px)] p-4">+ <div className="h-[calc(100vh-156px)] md:h-[calc(100vh-104px)] p-4"><AutodeskViewerurn={operation.itemAutodeskUrn ?? job.autodeskUrn}showDefaultToolbar@@ -503,7 +499,7 @@ export const JobOperation = ({</div></TabsContent><TabsContent value="instructions" className="flex flex-grow bg-card">- <ScrollArea className="h-[calc(100vh-104px)] w-full p-4 pb-36">+ <ScrollArea className="h-[calc(100vh-156px)] md:h-[calc(100vh-104px)] w-full p-4 pb-36"><divclassName="prose dark:prose-invert"dangerouslySetInnerHTML={{@@ -533,10 +529,9 @@ export const JobOperation = ({}tooltip="Scrap"/>- <PlayButton- onStart={(type) => {- alert(type);- }}+ <StartStopButton+ eventType={eventType as (typeof productionEventType)[number]}+ operation={operation}/><IconButtonWithTooltipicon={@@ -551,7 +546,7 @@ export const JobOperation = ({tooltip="Complete"/></div>- <WorkTypeToggle />+ <WorkTypeToggle value={eventType} onChange={setEventType} /></div></Controls>)}@@ -568,6 +563,7 @@ function useOperation(const { carbon } = useCarbon();const [fullScreen, setFullScreen] = useState(false);const [activeTab, setActiveTab] = useState("details");+ const [eventType, setEventType] = useState("Labor");const user = useUser();const getDocumentPath = useCallback(@@ -641,6 +637,7 @@ function useOperation(return {active,activeTab,+ eventType,fullScreen,isOverdue: operation.jobDueDate? new Date(operation.jobDueDate) < new Date()@@ -649,6 +646,7 @@ function useOperation(downloadDocument,getDocumentPath,setActiveTab,+ setEventType,setFullScreen,};}@@ -734,12 +732,18 @@ function IconButtonWithTooltip({);}-function WorkTypeToggle() {+function WorkTypeToggle({+ value,+ onChange,+}: {+ value: string;+ onChange: (type: string) => void;+}) {return (- <ToggleGroup defaultValue="labor" type="single">+ <ToggleGroup value={value} type="single" onValueChange={onChange}><ToggleGroupItemclassName="w-[110px]"- value="setup"+ value="Setup"aria-label="Toggle setup"><LuTimer className="h-4 w-4 mr-2" />@@ -747,7 +751,7 @@ function WorkTypeToggle() {</ToggleGroupItem><ToggleGroupItemclassName="w-[110px]"- value="labor"+ value="Labor"aria-label="Toggle labor"><LuHardHat className="h-4 w-4 mr-2" />@@ -755,7 +759,7 @@ function WorkTypeToggle() {</ToggleGroupItem><ToggleGroupItemclassName="w-[110px]"- value="machine"+ value="Machine"aria-label="Toggle machine"><LuHammer className="h-4 w-4 mr-2" />@@ -765,27 +769,63 @@ function WorkTypeToggle() {);}+const startStopFormId = "start-stop-form";+function StartStopButton({+ className,+ operation,+ eventType,+ ...props+}: ComponentProps<"button"> & {+ eventType: (typeof productionEventType)[number];+ operation: OperationWithDetails;+}) {+ const isActive = false; // TODO++ return (+ <ValidatedForm+ id={startStopFormId}+ action={path.to.productionEvent}+ method="post"+ validator={productionEventValidator}+ defaultValues={{+ jobOperationId: operation.id,+ timezone: getLocalTimeZone(),+ action: isActive ? "End" : "Start",+ type: eventType,+ workCenterId: operation.workCenterId ?? undefined,+ }}+ >+ <Hidden name="jobOperationId" />+ <Hidden name="timezone" />+ <Hidden name="action" />+ <Hidden name="type" />+ <Hidden name="workCenterId" />+ {isActive ? <PauseButton type="submit" /> : <PlayButton type="submit" />}+ </ValidatedForm>+ );+}+function PauseButton({ className, ...props }: ComponentProps<"button">) {+ const isSubmitting = useIsSubmitting(startStopFormId);return (<ButtonWithTooltip{...props}tooltip="Pause"- className="group w-16 h-16 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all"+ disabled={isSubmitting}+ className="group w-16 h-16 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all disabled:opacity-75 text-2xl"><FaPause className="text-accent group-hover:scale-125" /></ButtonWithTooltip>);}-function PlayButton({- className,- onStart,- ...props-}: ComponentProps<"button"> & { onStart: (type: "setup" | "run") => void }) {+function PlayButton({ className, ...props }: ComponentProps<"button">) {+ const isSubmitting = useIsSubmitting(startStopFormId);return (<button{...props}- className="group w-16 h-16 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all"+ disabled={isSubmitting}+ className="group w-16 h-16 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all disabled:opacity-75"><FaPlay className="text-accent group-hover:scale-125" /></button>@@ -833,3 +873,47 @@ function ScrapModal({ operation }: { operation: Operation }) {</ModalContent></Modal>;}++function Navigation({+ job,+ operation,+ fullScreen,+ setFullScreen,+}: {+ job: Job;+ operation: OperationWithDetails;+ fullScreen: boolean;+ setFullScreen: (value: boolean) => void;+}) {+ return (+ <>+ <TabsList className="md:ml-auto">+ <TabsTrigger value="details">Details</TabsTrigger>+ <TabsTrigger+ disabled={!job.autodeskUrn && !operation.itemAutodeskUrn}+ value="model"+ >+ Model+ </TabsTrigger>+ <TabsTrigger+ disabled={+ !operation.workInstruction ||+ Object.keys(operation.workInstruction).length === 0+ }+ value="instructions"+ >+ Instructions+ </TabsTrigger>+ </TabsList>+ {!fullScreen && (+ <IconButton+ aria-label="Expand"+ className="hidden md:flex"+ icon={<LuExpand />}+ variant="secondary"+ onClick={() => setFullScreen(true)}+ />+ )}+ </>+ );+}diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsxnew file mode 100644index 0000000000..bb945502fa--- /dev/null+++ b/apps/mes/app/routes/x+/event.tsx@@ -0,0 +1,63 @@+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 { getLocalTimeZone, now } from "@internationalized/date";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import {+ endProductionEvent,+ productionEventValidator,+ startProductionEvent,+} from "~/services/jobs.service";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "accounting",+ });++ const formData = await request.formData();+ const validation = await validator(productionEventValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { action: productionAction, timezone, ...data } = validation.data;++ if (productionAction === "Start") {+ const startEvent = await startProductionEvent(client, {+ ...data,+ startTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),+ employeeId: userId,+ companyId,+ createdBy: userId,+ });+ if (startEvent.error) {+ return json(+ {},+ await flash(request, error(startEvent.error, "Failed to start event"))+ );+ }++ return json(+ startEvent.data,+ await flash(request, success("Started operation"))+ );+ } else {+ const endEvent = await endProductionEvent(client, {+ ...data,+ endTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),+ employeeId: userId,+ });+ if (endEvent.error) {+ return json(+ {},+ await flash(request, error(endEvent.error, "Failed to end event"))+ );+ }+ }+}diff --git a/apps/mes/app/services/jobs.service.ts b/apps/mes/app/services/jobs.service.tsindex 3e1812208f..9a7b58c101 100644--- a/apps/mes/app/services/jobs.service.ts+++ b/apps/mes/app/services/jobs.service.ts@@ -1,6 +1,8 @@import type { Database } from "@carbon/database";import type { FileObject } from "@supabase/storage-js";import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";+import { z } from "zod";+import { zfd } from "zod-form-data";export type BaseOperation = NonNullable<Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]@@ -67,6 +69,29 @@ export const documentTypes = ["Other",] as const;+export const productionEventType = ["Setup", "Labor", "Machine"] as const;++export const productionEventAction = ["Start", "End"] as const;++export const productionEventValidator = z.object({+ id: zfd.text(z.string().optional()),+ jobOperationId: z+ .string()+ .min(1, { message: "Job Operation ID is required" }),+ timezone: zfd.text(z.string()),+ action: z.enum(productionEventAction, {+ errorMap: (issue, ctx) => ({+ message: "Action is required",+ }),+ }),+ type: z.enum(productionEventType, {+ errorMap: (issue, ctx) => ({+ message: "Type is required",+ }),+ }),+ workCenterId: zfd.text(z.string().optional()),+});+export async function getActiveJobOperationsByEmployee(client: SupabaseClient<Database>,args: {@@ -280,3 +305,36 @@ export async function getWorkCentersByCompany(.eq("companyId", companyId).order("name", { ascending: true });}++export async function endProductionEvent(+ client: SupabaseClient<Database>,+ data: {+ jobOperationId: string;+ employeeId: string;+ endTime: string;+ type: (typeof productionEventType)[number];+ }+) {+ return client+ .from("productionEvent")+ .update({ endTime: data.endTime, updatedBy: data.employeeId })+ .eq("jobOperationId", data.jobOperationId)+ .eq("employeeId", data.employeeId)+ .eq("type", data.type)+ .is("endTime", null);+}++export async function startProductionEvent(+ client: SupabaseClient<Database>,+ data: Omit<+ z.infer<typeof productionEventValidator>,+ "id" | "action" | "timezone"+ > & {+ startTime: string;+ employeeId: string;+ companyId: string;+ createdBy: string;+ }+) {+ return client.from("productionEvent").insert(data).select("*");+}diff --git a/apps/mes/app/services/mode.server.ts b/apps/mes/app/services/mode.server.tsindex 7c772021f5..c5f8184432 100644--- a/apps/mes/app/services/mode.server.ts+++ b/apps/mes/app/services/mode.server.ts@@ -1,3 +1,4 @@+import { DOMAIN } from "@carbon/auth";import * as cookie from "cookie";import type { Mode } from "~/types/validators";@@ -16,6 +17,10 @@ export function setMode(mode: Mode | "system") {if (mode === "system") {return cookie.serialize(cookieName, "", { path: "/", maxAge: -1 });} else {- return cookie.serialize(cookieName, mode, { path: "/", maxAge: 31536000 });+ return cookie.serialize(cookieName, mode, {+ path: "/",+ maxAge: 31536000,+ domain: DOMAIN,+ });}}diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 7c924c482d..21cdac86f6 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -30,6 +30,7 @@ export const path = {location: `${x}/location`,login: "/login",logout: "/logout",+ productionEvent: `${x}/event`,recent: `${x}/recent`,refreshSession: "/refresh-session",requestAccess: "/request-access",diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex 989dc0b4e6..182e3d1216 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -10,6 +10,7 @@"@carbon/kv": "*","@carbon/form": "*","@carbon/utils": "*",+ "@internationalized/date": "^3.5.2","@react-aria/i18n": "^3.11.0","@remix-run/dev": "~2.10.2","@remix-run/eslint-config": "~2.10.2",@@ -37,7 +38,8 @@"tailwind-scrollbar": "^3.0.5","tailwind-scrollbar-hide": "^1.1.7","tailwindcss-animate": "^1.0.7",- "zod": "^3.23.8"+ "zod": "^3.23.8",+ "zod-form-data": "*"},"devDependencies": {"@carbon/tailwind": "*",diff --git a/package-lock.json b/package-lock.jsonindex 2b08b7a2bd..4d206ffde3 100644--- a/package-lock.json+++ b/package-lock.json@@ -236,6 +236,7 @@"@carbon/logger": "*","@carbon/react": "*","@carbon/utils": "*",+ "@internationalized/date": "^3.5.2","@react-aria/i18n": "^3.11.0","@remix-run/dev": "~2.10.2","@remix-run/eslint-config": "~2.10.2",@@ -263,7 +264,8 @@"tailwind-scrollbar": "^3.0.5","tailwind-scrollbar-hide": "^1.1.7","tailwindcss-animate": "^1.0.7",- "zod": "^3.23.8"+ "zod": "^3.23.8",+ "zod-form-data": "*"},"devDependencies": {"@carbon/tailwind": "*",@@ -288,6 +290,7 @@},"apps/mes-prototype": {"version": "0.0.0",+ "extraneous": true,"dependencies": {"@carbon/database": "*","@carbon/react": "*",@@ -1150,36 +1153,6 @@"@babel/core": "^7.0.0-0"}},- "node_modules/@babel/plugin-transform-react-jsx-self": {- "version": "7.24.7",- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.24.7.tgz",- "integrity": "sha512-fOPQYbGSgH0HUp4UJO4sMBFjY6DuWq+2i8rixyUMb3CdGixs/gccURvYOAhajBdKDoGajFr3mUq5rH3phtkGzw==",- "dev": true,- "dependencies": {- "@babel/helper-plugin-utils": "^7.24.7"- },- "engines": {- "node": ">=6.9.0"- },- "peerDependencies": {- "@babel/core": "^7.0.0-0"- }- },- "node_modules/@babel/plugin-transform-react-jsx-source": {- "version": "7.24.7",- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.24.7.tgz",- "integrity": "sha512-J2z+MWzZHVOemyLweMqngXrgGC42jQ//R0KdxqkIz/OrbVIIlhFI3WigZ5fO+nwFvBlncr4MGapd8vTyc7RPNQ==",- "dev": true,- "dependencies": {- "@babel/helper-plugin-utils": "^7.24.7"- },- "engines": {- "node": ">=6.9.0"- },- "peerDependencies": {- "@babel/core": "^7.0.0-0"- }- },"node_modules/@babel/plugin-transform-react-pure-annotations": {"version": "7.24.7","resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.24.7.tgz",@@ -12063,25 +12036,6 @@"node": ">=12"}},- "node_modules/@vitejs/plugin-react": {- "version": "4.3.1",- "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.1.tgz",- "integrity": "sha512-m/V2syj5CuVnaxcUJOQRel/Wr31FFXRFlnOoq1TVtkCxsY5veGMTEmpWHndrhB2U8ScHtCQB1e+4hWYExQc6Lg==",- "dev": true,- "dependencies": {- "@babel/core": "^7.24.5",- "@babel/plugin-transform-react-jsx-self": "^7.24.5",- "@babel/plugin-transform-react-jsx-source": "^7.24.1",- "@types/babel__core": "^7.20.5",- "react-refresh": "^0.14.2"- },- "engines": {- "node": "^14.18.0 || >=16.0.0"- },- "peerDependencies": {- "vite": "^4.2.0 || ^5.0.0"- }- },"node_modules/@web3-storage/multipart-parser": {"version": "1.0.0","resolved": "https://registry.npmjs.org/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz",@@ -23405,10 +23359,6 @@"resolved": "apps/mes","link": true},- "node_modules/mes-prototype": {- "resolved": "apps/mes-prototype",- "link": true- },"node_modules/methods": {"version": "1.1.2","resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",