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.

Console Mode (#593)

Gaurav Bhattb01d93a5bc91
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 19e27c713a..cd4491d9ca 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -251,6 +251,10 @@ export const jobTravelerSettingsValidator = z.object({
jobTravelerIncludeWorkInstructions: zfd.checkbox()
});
+export const consoleSettingsValidator = z.object({
+ consoleEnabled: zfd.checkbox()
+});
+
export const quoteLineCategoryMarkupsSettingsValidator = z.object({
materialCost: zfd.numeric(z.number().min(0).default(0)),
partCost: zfd.numeric(z.number().min(0).default(0)),
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 369745eaa2..4e7b7bef6b 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -706,6 +706,124 @@ export async function updateTimeCardSetting(
.eq("id", companyId);
}
+export async function updateConsoleSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ consoleEnabled: boolean,
+ userId?: string
+) {
+ const update = await client
+ .from("companySettings")
+ .update(sanitize({ consoleEnabled }) as any)
+ .eq("id", companyId);
+
+ // When enabling, create "Console Operator" employee type if it doesn't exist
+ if (consoleEnabled) {
+ const existing = await client
+ .from("employeeType")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("name", "Console Operator")
+ .maybeSingle();
+
+ if (!existing.data) {
+ const newType = await client
+ .from("employeeType")
+ .insert({ name: "Console Operator", companyId, protected: false })
+ .select("id")
+ .single();
+
+ // Create default permissions for the Console Operator type.
+ // Only grant what's needed for MES operations — not ERP modules.
+ if (newType.data) {
+ const mesModules = [
+ // Production: start/end operations, complete, scrap, rework
+ {
+ module: "Production",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ // Inventory: issue materials, adjustments
+ {
+ module: "Inventory",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ // Resources: view work centers, locations
+ {
+ module: "Resources",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ },
+ // Items/Parts: view items for operations
+ {
+ module: "Items",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ },
+ // Quality: record defects, non-conformances
+ {
+ module: "Quality",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ // People: view employees (for console operator list)
+ {
+ module: "People",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ }
+ ];
+
+ const permissions = mesModules.map((m) => ({
+ employeeTypeId: newType.data.id,
+ module: m.module as "Accounting",
+ create: m.create ? [companyId] : [],
+ update: m.update ? [companyId] : [],
+ delete: m.delete ? [companyId] : [],
+ view: m.view ? [companyId] : []
+ }));
+
+ await client.from("employeeTypePermission").insert(permissions);
+ }
+ }
+
+ // Auto-generate a PIN for the enabling user if they don't have one
+ let generatedPin: string | null = null;
+ if (userId) {
+ const userEmployee = await client
+ .from("employee")
+ .select("id, pin" as any)
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (userEmployee.data && !(userEmployee.data as any).pin) {
+ generatedPin = Math.floor(1000 + Math.random() * 9000).toString();
+ await client
+ .from("employee")
+ .update({ pin: generatedPin } as any)
+ .eq("id", userId)
+ .eq("companyId", companyId);
+ }
+ }
+ }
+
+ return update;
+}
+
export async function updateRfqReadySetting(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
index c6dc08fa3d..7229f87bd8 100644
--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -1,4 +1,5 @@
import {
+ Badge,
Checkbox,
DropdownMenuContent,
DropdownMenuItem,
@@ -23,6 +24,7 @@ import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
+import { useSettings } from "~/hooks/useSettings";
import type { Employee } from "~/modules/users";
import {
BulkEditPermissionsForm,
@@ -48,6 +50,7 @@ const EmployeesTable = memo(
({ data, count, employeeTypes }: EmployeesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
+ const settings = useSettings();
const [params] = useUrlParams();
const employeeTypesById = useMemo(
@@ -108,7 +111,13 @@ const EmployeesTable = memo(
{
accessorKey: "email",
header: "Email",
- cell: (item) => item.getValue(),
+ cell: (item) => {
+ const email = item.getValue<string>();
+ if (email?.endsWith("@console.internal")) {
+ return <Badge variant="secondary">Console Operator</Badge>;
+ }
+ return email;
+ },
meta: {
icon: <LuMail />
}
@@ -235,6 +244,18 @@ const EmployeesTable = memo(
<MenuIcon icon={<LuPencil />} />
Edit Permissions
</MenuItem>
+ {settings.consoleEnabled && (
+ <MenuItem
+ onClick={() =>
+ navigate(
+ `${path.to.operatorResetPin(row.id!)}?${params.toString()}`
+ )
+ }
+ >
+ <MenuIcon icon={<LuShield />} />
+ Set Console PIN
+ </MenuItem>
+ )}
<MenuItem
onClick={(e) => {
setSelectedUserIds([row.id!]);
@@ -280,7 +301,8 @@ const EmployeesTable = memo(
params,
permissions,
resendInviteModal,
- revokeInviteModal
+ revokeInviteModal,
+ settings.consoleEnabled
]
);
diff --git a/apps/erp/app/modules/users/ui/useUsersSubmodules.tsx b/apps/erp/app/modules/users/ui/useUsersSubmodules.tsx
index 8d3aded54c..d6b88162ac 100644
--- a/apps/erp/app/modules/users/ui/useUsersSubmodules.tsx
+++ b/apps/erp/app/modules/users/ui/useUsersSubmodules.tsx
@@ -1,4 +1,5 @@
-import { LuFileBadge2, LuGroup, LuUsers } from "react-icons/lu";
+import { LuFileBadge2, LuGroup, LuMonitor, LuUsers } from "react-icons/lu";
+import { useSettings } from "~/hooks/useSettings";
import type { RouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -11,6 +12,12 @@ const usersRoutes: RouteGroup[] = [
to: path.to.employeeAccounts,
icon: <LuUsers />
},
+ {
+ name: "Operators",
+ to: path.to.operators,
+ icon: <LuMonitor />,
+ setting: "consoleEnabled" as any
+ },
// {
// name: "Customers",
// to: path.to.customerAccounts,
@@ -41,5 +48,16 @@ const usersRoutes: RouteGroup[] = [
];
export default function useUsersSubmodules() {
- return { groups: usersRoutes };
+ const settings = useSettings();
+
+ return {
+ groups: usersRoutes.map((group) => ({
+ ...group,
+ routes: group.routes.filter(
+ (route) =>
+ !route.setting ||
+ settings[route.setting as keyof typeof settings] === true
+ )
+ }))
+ };
}
diff --git a/apps/erp/app/modules/users/users.models.ts b/apps/erp/app/modules/users/users.models.ts
index 7dba89fe64..50e3fdddd5 100644
--- a/apps/erp/app/modules/users/users.models.ts
+++ b/apps/erp/app/modules/users/users.models.ts
@@ -28,6 +28,21 @@ export const createEmployeeValidator = z.object({
locationId: z.string().min(1, { message: "Location is required" })
});
+export const createOperatorValidator = z.object({
+ firstName: z.string().min(1, { message: "First name is required" }),
+ lastName: z.string().min(1, { message: "Last name is required" }),
+ locationId: z.string().min(1, { message: "Location is required" }),
+ pin: z.string().regex(/^\d{4}$/, "PIN must be 4 digits")
+});
+
+export const convertOperatorValidator = z.object({
+ email: z
+ .string()
+ .min(1, { message: "Email is required" })
+ .email("Must be a valid email"),
+ employeeType: z.string().min(1, { message: "Employee type is required" })
+});
+
export const createSupplierAccountValidator = z.object({
id: z.string().min(1, "Supplier contact is required"),
supplier: z.string().min(1, { message: "Supplier is required" })
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 5e6eccc10a..4c9351cc6e 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -746,6 +746,229 @@ async function insertUser(
return client.from("user").upsert([user]).select("*");
}
+/**
+ * Creates a console-only operator: a lightweight user record that can pin in
+ * at MES terminals without needing email, password, or Supabase Auth.
+ *
+ * Uses a synthetic email ({uuid}@console.internal) to satisfy the NOT NULL
+ * constraint. No auth.users entry is created — operators cannot log in.
+ */
+export async function createConsoleOperator(
+ client: SupabaseClient<Database>,
+ {
+ firstName,
+ lastName,
+ employeeType,
+ locationId,
+ companyId,
+ createdBy
+ }: {
+ firstName: string;
+ lastName: string;
+ employeeType: string;
+ locationId: string;
+ companyId: string;
+ createdBy: string;
+ }
+): Promise<
+ | { success: false; message: string }
+ | { success: true; userId: string; name: string }
+> {
+ const serviceRole = getCarbonServiceRole();
+ const userId = crypto.randomUUID();
+ const syntheticEmail = `${userId}@console.internal`;
+
+ // 1. Insert user record (no Supabase Auth)
+ // Note: isConsoleOperator field added by migration 20260319000000_console-mode.sql
+ // Type will be available after db:generate runs
+ const userInsert = await serviceRole
+ .from("user")
+ .insert({
+ id: userId,
+ email: syntheticEmail,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ active: true,
+ isConsoleOperator: true
+ } as any)
+ .select("*")
+ .single();
+
+ if (userInsert.error) {
+ return { success: false, message: userInsert.error.message };
+ }
+
+ // 2. Insert employee (auto-active, no invite needed)
+ const employeeInsert = await insertEmployee(client, {
+ id: userId,
+ employeeTypeId: employeeType,
+ active: true,
+ companyId
+ });
+
+ if (employeeInsert.error) {
+ // Cleanup: remove user
+ await serviceRole.from("user").delete().eq("id", userId);
+ return { success: false, message: employeeInsert.error.message };
+ }
+
+ // 3. Insert employeeJob
+ const jobInsert = await insertEmployeeJob(client, {
+ id: userId,
+ companyId,
+ locationId
+ });
+
+ if (jobInsert.error) {
+ // Cleanup
+ await serviceRole.from("employee").delete().eq("id", userId);
+ await serviceRole.from("user").delete().eq("id", userId);
+ return { success: false, message: jobInsert.error.message };
+ }
+
+ // 4. Add to userToCompany (for billing/plan counting)
+ const companyLink = await serviceRole
+ .from("userToCompany")
+ .insert({ userId, companyId, role: "employee" as const })
+ .select("*")
+ .single();
+
+ if (companyLink.error) {
+ // Non-critical — operator still works without this
+ console.error(
+ "Failed to link console operator to company:",
+ companyLink.error
+ );
+ }
+
+ return {
+ success: true,
+ userId,
+ name: `${firstName} ${lastName}`
+ };
+}
+
+/**
+ * Converts a console-only operator to a full user by adding a Supabase Auth
+ * account and updating their email to a real one.
+ */
+export async function convertConsoleOperatorToUser(
+ client: SupabaseClient<Database>,
+ {
+ userId,
+ email,
+ employeeType,
+ companyId,
+ createdBy
+ }: {
+ userId: string;
+ email: string;
+ employeeType: string;
+ companyId: string;
+ createdBy: string;
+ }
+): Promise<{ success: false; message: string } | { success: true }> {
+ const serviceRole = getCarbonServiceRole();
+
+ // Verify the user is a console operator
+ // Note: isConsoleOperator field added by migration 20260319000000_console-mode.sql
+ const existingUser = await serviceRole
+ .from("user")
+ .select("*")
+ .eq("id", userId)
+ .single();
+
+ if (existingUser.error || !(existingUser.data as any)?.isConsoleOperator) {
+ return { success: false, message: "User is not a console operator" };
+ }
+
+ // Check email isn't already taken
+ const emailCheck = await serviceRole
+ .from("user")
+ .select("id")
+ .eq("email", email.toLowerCase())
+ .maybeSingle();
+
+ if (emailCheck.data) {
+ return { success: false, message: "Email is already in use" };
+ }
+
+ // Create Supabase Auth account with the same user ID
+ const createAuth = await serviceRole.auth.admin.createUser({
+ id: userId,
+ email: email.toLowerCase(),
+ password: crypto.randomUUID(),
+ email_confirm: true
+ });
+
+ if (createAuth.error) {
+ return { success: false, message: createAuth.error.message };
+ }
+
+ // Update user record: real email + no longer console operator
+ const updateUser = await serviceRole
+ .from("user")
+ .update({
+ email: email.toLowerCase(),
+ isConsoleOperator: false
+ } as any)
+ .eq("id", userId);
+
+ if (updateUser.error) {
+ // Cleanup auth
+ await deleteAuthAccount(serviceRole, userId);
+ return { success: false, message: updateUser.error.message };
+ }
+
+ // Change employee type to the selected type
+ await serviceRole
+ .from("employee")
+ .update({ employeeTypeId: employeeType })
+ .eq("id", userId)
+ .eq("companyId", companyId);
+
+ // Create invite so user gets the magic link email
+ const code = crypto.randomUUID();
+ const employee = await client
+ .from("employee")
+ .select("employeeTypeId")
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (employee.data?.employeeTypeId) {
+ const employeeTypePermissions = await getPermissionsByEmployeeType(
+ client,
+ employee.data.employeeTypeId
+ );
+
+ if (!employeeTypePermissions.error) {
+ const permissions = makePermissionsFromEmployeeType(
+ employeeTypePermissions
+ );
+
+ const inviteResult = await insertInvite(serviceRole, {
+ role: "employee",
+ permissions,
+ email: email.toLowerCase(),
+ companyId,
+ createdBy,
+ code
+ });
+
+ if (inviteResult.error) {
+ console.error(
+ "Failed to create invite for converted operator:",
+ inviteResult.error
+ );
+ }
+ }
+ }
+
+ return { success: true };
+}
+
function makePermissionsFromEmployeeType({
data
}: {
diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.ts
index c11fbb230a..182e8156e1 100644
--- a/apps/erp/app/modules/users/users.service.ts
+++ b/apps/erp/app/modules/users/users.service.ts
@@ -100,6 +100,38 @@ export async function getEmployees(
return query;
}
+/**
+ * Gets console operators — users with @console.internal emails.
+ * Uses the employees view (which joins user + employee) and filters
+ * by the synthetic email pattern since there's no FK from employee to user
+ * for PostgREST to use directly.
+ *
+ * TODO: After running db:generate, replace email pattern filter with
+ * .eq("isConsoleOperator", true) once the column is in the employees view.
+ */
+export async function getConsoleOperators(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client
+ .from("employees")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId)
+ .like("email", "%@console.internal");
+
+ if (args.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "lastName", ascending: true }
+ ]);
+ return query;
+}
+
export async function getEmployeeType(
client: SupabaseClient<Database>,
employeeTypeId: string
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 63a38d2644..b80c73c922 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -2,7 +2,8 @@ import {
CarbonEdition,
CarbonProvider,
CONTROLLED_ENVIRONMENT,
- getCarbon
+ getCarbon,
+ getMESUrl
} from "@carbon/auth";
import { setCompanyId } from "@carbon/auth/company.server";
import {
@@ -68,8 +69,14 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { accessToken, companyId, expiresAt, expiresIn, userId } =
- await requireAuthSession(request, { verify: true });
+ const authSession = await requireAuthSession(request, { verify: true });
+ const { accessToken, companyId, expiresAt, expiresIn, userId } = authSession;
+
+ // Block ERP access when console mode is active on this terminal.
+ // Console terminals should only access the MES app.
+ if (authSession.console) {
+ throw redirect(getMESUrl());
+ }
// const { computeRegion, proxyRegion } = parseVercelId(
// request.headers.get("x-vercel-id")
diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsx
index 2cadc854a1..b44ed5207e 100644
--- a/apps/erp/app/routes/x+/settings+/items.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.tsx
@@ -1,27 +1,24 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-// biome-ignore lint/suspicious/noShadowRestrictedNames: suppressed due to migration
-import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
import {
Card,
CardContent,
CardDescription,
- CardFooter,
CardHeader,
CardTitle,
Heading,
+ HStack,
ScrollArea,
+ Switch,
toast,
VStack
} from "@carbon/react";
-import { useEffect } from "react";
+import { useCallback, useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
import {
getCompanySettings,
- materialIdsValidator,
- materialUnitsValidator,
updateMaterialGeneratedIdsSetting,
updateMetricSettings
} from "~/modules/settings";
@@ -61,49 +58,26 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const intent = formData.get("intent");
- switch (intent) {
- case "materialIds":
- const idsValidation =
- await validator(materialIdsValidator).validate(formData);
-
- if (idsValidation.error) {
- return { success: false, message: "Invalid form data" };
- }
+ const enabled = formData.get("enabled") === "true";
- const materialIdsResult = await updateMaterialGeneratedIdsSetting(
+ switch (intent) {
+ case "materialIds": {
+ const result = await updateMaterialGeneratedIdsSetting(
client,
companyId,
- idsValidation.data.materialGeneratedIds
+ enabled
);
- if (materialIdsResult.error)
- return {
- success: false,
- message: materialIdsResult.error.message
- };
-
+ if (result.error)
+ return { success: false, message: result.error.message };
return { success: true, message: "Material IDs setting updated" };
+ }
- case "materialUnits":
- const unitsValidation = await validator(materialUnitsValidator).validate(
- formData
- );
-
- if (unitsValidation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
- const materialUnitsResult = await updateMetricSettings(
- client,
- companyId,
- unitsValidation.data.useMetric
- );
- if (materialUnitsResult.error)
- return {
- success: false,
- message: materialUnitsResult.error.message
- };
-
+ case "materialUnits": {
+ const result = await updateMetricSettings(client, companyId, enabled);
+ if (result.error)
+ return { success: false, message: result.error.message };
return { success: true, message: "Material units setting updated" };
+ }
}
return { success: false, message: "Invalid form data" };
@@ -113,6 +87,8 @@ export default function ItemsSettingsRoute() {
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ const isToggling = fetcher.state !== "idle";
+
useEffect(() => {
if (fetcher.data?.success === true && fetcher?.data?.message) {
toast.success(fetcher.data.message);
@@ -123,6 +99,26 @@ export default function ItemsSettingsRoute() {
}
}, [fetcher.data?.message, fetcher.data?.success]);
+ const handleMaterialIdsToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { intent: "materialIds", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
+ const handleMetricToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { intent: "materialUnits", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
return (
<ScrollArea className="w-full h-[calc(100dvh-49px)]">
<VStack
@@ -131,86 +127,63 @@ export default function ItemsSettingsRoute() {
>
<Heading size="h3">Items</Heading>
<Card>
- <ValidatedForm
- method="post"
- validator={materialIdsValidator}
- defaultValues={{
- materialGeneratedIds:
- companySettings.materialGeneratedIds ?? false
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="materialIds" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- Material IDs
- </CardTitle>
- <CardDescription>
- Generate material IDs and descriptions based on the properties
- of the material.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-8 max-w-[400px]">
- <div className="flex flex-col gap-2">
- <Boolean
- name="materialGeneratedIds"
- description="Generate IDs and descriptions for raw materials"
- />
- </div>
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "materialIds"
- }
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ <CardHeader>
+ <CardTitle>Material IDs</CardTitle>
+ <CardDescription>
+ Generate material IDs and descriptions based on the properties of
+ the material.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {companySettings.materialGeneratedIds
+ ? "Generated IDs are enabled"
+ : "Generated IDs are disabled"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {companySettings.materialGeneratedIds
+ ? "IDs and descriptions are generated for raw materials."
+ : "Enable to generate IDs and descriptions for raw materials."}
+ </span>
+ </VStack>
+ <Switch
+ checked={companySettings.materialGeneratedIds ?? false}
+ onCheckedChange={handleMaterialIdsToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ </CardContent>
</Card>
<Card>
- <ValidatedForm
- method="post"
- validator={materialUnitsValidator}
- defaultValues={{
- useMetric: (companySettings as any).useMetric ?? false
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="materialUnits" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">Metric</CardTitle>
- <CardDescription>
- Use metric system for default material dimensions.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-8 max-w-[400px]">
- <div className="flex flex-col gap-2">
- <Boolean
- name="useMetric"
- description="Use metric units for material dimensions"
- />
- </div>
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "materialUnits"
- }
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ <CardHeader>
+ <CardTitle>Metric</CardTitle>
+ <CardDescription>
+ Use metric system for default material dimensions.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {(companySettings as any).useMetric
+ ? "Metric units are enabled"
+ : "Metric units are disabled"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {(companySettings as any).useMetric
+ ? "Material dimensions use metric units."
+ : "Enable to use metric units for material dimensions."}
+ </span>
+ </VStack>
+ <Switch
+ checked={(companySettings as any).useMetric ?? false}
+ onCheckedChange={handleMetricToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ </CardContent>
</Card>
</VStack>
</ScrollArea>
diff --git a/apps/erp/app/routes/x+/settings+/people.tsx b/apps/erp/app/routes/x+/settings+/people.tsx
index b09fa3f848..cdfd9de5d7 100644
--- a/apps/erp/app/routes/x+/settings+/people.tsx
+++ b/apps/erp/app/routes/x+/settings+/people.tsx
@@ -1,27 +1,37 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-// biome-ignore lint/suspicious/noShadowRestrictedNames: Boolean is a component name
-import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
import {
Badge,
+ Button,
Card,
CardContent,
CardDescription,
- CardFooter,
CardHeader,
CardTitle,
+ Copy,
Heading,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
ScrollArea,
+ Switch,
toast,
VStack
} from "@carbon/react";
-import { useEffect } from "react";
+
+import { useCallback, useEffect, useState } from "react";
+
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
import {
getCompanySettings,
- timeCardSettingsValidator,
+ updateConsoleSetting,
updateTimeCardSetting
} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
@@ -51,31 +61,50 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "settings"
});
const formData = await request.formData();
const intent = formData.get("intent");
+ const enabled = formData.get("enabled") === "true";
if (intent === "timeCard") {
- const validation = await validator(timeCardSettingsValidator).validate(
- formData
- );
-
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
- }
+ const update = await updateTimeCardSetting(client, companyId, enabled);
+ if (update.error) return { success: false, message: update.error.message };
+ return { success: true, message: "Timecard settings updated" };
+ }
- const update = await updateTimeCardSetting(
+ if (intent === "console") {
+ const update = await updateConsoleSetting(
client,
companyId,
- validation.data.timeCardEnabled
+ enabled,
+ userId
);
if (update.error) return { success: false, message: update.error.message };
- return { success: true, message: "Timecard settings updated" };
+ // Check if a PIN was auto-generated for the user
+ if (enabled) {
+ const userPin = await client
+ .from("employee")
+ .select("pin" as any)
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ const pin = (userPin.data as any)?.pin;
+ if (pin) {
+ return {
+ success: true,
+ message: "Console mode enabled",
+ pin
+ };
+ }
+ }
+
+ return { success: true, message: "Console mode settings updated" };
}
return { success: false, message: "Unknown intent" };
@@ -84,16 +113,45 @@ export async function action({ request }: ActionFunctionArgs) {
export default function PeopleSettingsRoute() {
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ const [showPinModal, setShowPinModal] = useState(false);
+ const [generatedPin, setGeneratedPin] = useState<string | null>(null);
+
+ const isToggling = fetcher.state !== "idle";
useEffect(() => {
- if (fetcher.data?.success === true && fetcher?.data?.message) {
- toast.success(fetcher.data.message);
+ if (fetcher.data?.success === true) {
+ if ((fetcher.data as any)?.pin) {
+ setGeneratedPin((fetcher.data as any).pin);
+ setShowPinModal(true);
+ } else if (fetcher.data?.message) {
+ toast.success(fetcher.data.message);
+ }
}
if (fetcher.data?.success === false && fetcher?.data?.message) {
toast.error(fetcher.data.message);
}
- }, [fetcher.data?.message, fetcher.data?.success]);
+ }, [fetcher.data]);
+
+ const handleConsoleToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { intent: "console", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
+ const handleTimeCardToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { intent: "timeCard", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
return (
<ScrollArea className="w-full h-[calc(100dvh-49px)]">
@@ -104,48 +162,106 @@ export default function PeopleSettingsRoute() {
<Heading size="h3">People</Heading>
<Card>
- <ValidatedForm
- method="post"
- validator={timeCardSettingsValidator}
- defaultValues={{
- timeCardEnabled: companySettings.timeCardEnabled ?? false
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="timeCard" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- Timecards
- </CardTitle>
- <CardDescription>
- Enable timecard tracking for work shifts.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex items-center justify-start gap-2">
- <Boolean
- name="timeCardEnabled"
- description="Enable Timecards"
- />
- <div>
+ <CardHeader>
+ <CardTitle>Console Mode</CardTitle>
+ <CardDescription>
+ Enable shared workstation mode for MES terminals. Operators
+ identify themselves via PIN before performing work.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {(companySettings as any).consoleEnabled
+ ? "Console mode is enabled"
+ : "Console mode is disabled"}
+ </span>
+ <HStack className="items-center gap-2">
+ <span className="text-sm text-muted-foreground">
+ {(companySettings as any).consoleEnabled
+ ? "Operators can use shared workstations with PIN authentication."
+ : "Enable to allow shared workstation mode."}
+ </span>
<Badge variant="yellow">Beta</Badge>
- </div>
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "timeCard"
- }
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ </HStack>
+ </VStack>
+ <Switch
+ checked={(companySettings as any).consoleEnabled ?? false}
+ onCheckedChange={handleConsoleToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Timecards</CardTitle>
+ <CardDescription>
+ Enable timecard tracking for work shifts.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {companySettings.timeCardEnabled
+ ? "Timecards are enabled"
+ : "Timecards are disabled"}
+ </span>
+ <HStack className="items-center gap-2">
+ <span className="text-sm text-muted-foreground">
+ {companySettings.timeCardEnabled
+ ? "Work shift tracking is active."
+ : "Enable to start tracking work shifts."}
+ </span>
+ <Badge variant="yellow">Beta</Badge>
+ </HStack>
+ </VStack>
+ <Switch
+ checked={companySettings.timeCardEnabled ?? false}
+ onCheckedChange={handleTimeCardToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ </CardContent>
</Card>
</VStack>
+
+ {showPinModal && generatedPin && (
+ <Modal open onOpenChange={(open) => !open && setShowPinModal(false)}>
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Your Console PIN</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ Console mode has been enabled. Use this PIN to identify
+ yourself at MES terminals.
+ </p>
+ <div className="flex items-center justify-center gap-3">
+ <span className="font-mono text-3xl tracking-[0.4em]">
+ {generatedPin}
+ </span>
+ <Copy text={generatedPin} />
+ </div>
+ <p className="text-xs text-muted-foreground text-center">
+ Remember this PIN. You will need it to exit console mode on
+ MES terminals.
+ </p>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button onClick={() => setShowPinModal(false)}>Done</Button>
+ </HStack>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
</ScrollArea>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsx
index 4d9b06a48c..f341dcbec7 100644
--- a/apps/erp/app/routes/x+/settings+/production.tsx
+++ b/apps/erp/app/routes/x+/settings+/production.tsx
@@ -1,8 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-// biome-ignore lint/suspicious/noShadowRestrictedNames: Boolean is a component name
-import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
+import { Submit, ValidatedForm, validator } from "@carbon/form";
import {
Card,
CardContent,
@@ -11,19 +10,20 @@ import {
CardHeader,
CardTitle,
Heading,
+ HStack,
Label,
ScrollArea,
+ Switch,
toast,
VStack
} from "@carbon/react";
-import { useEffect } from "react";
+import { useCallback, useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
import { Users } from "~/components/Form";
import {
getCompanySettings,
jobCompletedValidator,
- jobTravelerSettingsValidator,
updateJobTravelerWorkInstructions
} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
@@ -85,18 +85,11 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (intent === "jobTraveler") {
- const validation = await validator(jobTravelerSettingsValidator).validate(
- formData
- );
-
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
+ const enabled = formData.get("enabled") === "true";
const update = await updateJobTravelerWorkInstructions(
client,
companyId,
- validation.data.jobTravelerIncludeWorkInstructions
+ enabled
);
if (update.error) return { success: false, message: update.error.message };
@@ -110,6 +103,7 @@ export async function action({ request }: ActionFunctionArgs) {
export default function ProductionSettingsRoute() {
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ const toggleFetcher = useFetcher<typeof action>();
useEffect(() => {
if (fetcher.data?.success === true && fetcher?.data?.message) {
@@ -121,6 +115,25 @@ export default function ProductionSettingsRoute() {
}
}, [fetcher.data?.message, fetcher.data?.success]);
+ useEffect(() => {
+ if (toggleFetcher.data?.success === true && toggleFetcher?.data?.message) {
+ toast.success(toggleFetcher.data.message);
+ }
+ if (toggleFetcher.data?.success === false && toggleFetcher?.data?.message) {
+ toast.error(toggleFetcher.data.message);
+ }
+ }, [toggleFetcher.data?.message, toggleFetcher.data?.success]);
+
+ const handleJobTravelerToggle = useCallback(
+ (checked: boolean) => {
+ toggleFetcher.submit(
+ { intent: "jobTraveler", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [toggleFetcher]
+ );
+
return (
<ScrollArea className="w-full h-[calc(100dvh-49px)]">
<VStack
@@ -182,44 +195,35 @@ export default function ProductionSettingsRoute() {
</Card>
<Card>
- <ValidatedForm
- method="post"
- validator={jobTravelerSettingsValidator}
- defaultValues={{
- jobTravelerIncludeWorkInstructions:
- companySettings.jobTravelerIncludeWorkInstructions ?? false
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="jobTraveler" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- Job Traveler
- </CardTitle>
- <CardDescription>
- Configure the content displayed on job traveler PDFs.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-2 max-w-[400px]">
- <Boolean
- name="jobTravelerIncludeWorkInstructions"
- description="Include Work Instructions"
- />
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") === "jobTraveler"
+ <CardHeader>
+ <CardTitle>Job Traveler</CardTitle>
+ <CardDescription>
+ Configure the content displayed on job traveler PDFs.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {companySettings.jobTravelerIncludeWorkInstructions
+ ? "Work instructions are included"
+ : "Work instructions are not included"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {companySettings.jobTravelerIncludeWorkInstructions
+ ? "Job traveler PDFs include work instructions."
+ : "Enable to include work instructions on job traveler PDFs."}
+ </span>
+ </VStack>
+ <Switch
+ checked={
+ companySettings.jobTravelerIncludeWorkInstructions ?? false
}
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ onCheckedChange={handleJobTravelerToggle}
+ disabled={toggleFetcher.state !== "idle"}
+ />
+ </HStack>
+ </CardContent>
</Card>
</VStack>
</ScrollArea>
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index b0db1f70c1..7ceaeee2bb 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -1,15 +1,7 @@
import { error, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import {
- // biome-ignore lint/suspicious/noShadowRestrictedNames: suppressed due to migration
- Boolean,
- Input,
- Select,
- Submit,
- ValidatedForm,
- validator
-} from "@carbon/form";
+import { Input, Select, Submit, ValidatedForm, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
Badge,
@@ -45,7 +37,6 @@ import {
getAccountsPayableBillingAddress,
getCompanySettings,
getTerms,
- includeThumbnailsOnPurchasingPdfsValidator,
purchasePriceUpdateTimingTypes,
purchasePriceUpdateTimingValidator,
supplierQuoteNotificationValidator,
@@ -193,25 +184,19 @@ export async function action({ request }: ActionFunctionArgs) {
message: "Supplier quote notification setting updated"
};
- case "pdfs":
- const thumbnailsValidation = await validator(
- includeThumbnailsOnPurchasingPdfsValidator
- ).validate(formData);
-
- if (thumbnailsValidation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
+ case "pdfs": {
+ const pdfEnabled = formData.get("enabled") === "true";
const thumbnailsResult = await updatePurchasingPdfThumbnails(
client,
companyId,
- thumbnailsValidation.data.includeThumbnailsOnPurchasingPdfs
+ pdfEnabled
);
if (thumbnailsResult.error)
return { success: false, message: thumbnailsResult.error.message };
return { success: true, message: "PDF settings updated" };
+ }
case "accountsPayableBillingAddress":
const apBillingValidation = await validator(
@@ -632,43 +617,40 @@ export default function PurchasingSettingsRoute() {
</ValidatedForm>
</Card>
<Card>
- <ValidatedForm
- method="post"
- validator={includeThumbnailsOnPurchasingPdfsValidator}
- defaultValues={{
- includeThumbnailsOnPurchasingPdfs:
- companySettings.includeThumbnailsOnPurchasingPdfs ?? true
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="pdfs" />
- <CardHeader>
- <CardTitle>PDFs</CardTitle>
- <CardDescription>
- Show part thumbnails on purchase orders.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-2 max-w-[400px]">
- <Boolean
- name="includeThumbnailsOnPurchasingPdfs"
- description="Include Thumbnails in PDFs"
- />
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") ===
- "includeThumbnailsOnPurchasingPdfs"
+ <CardHeader>
+ <CardTitle>PDFs</CardTitle>
+ <CardDescription>
+ Show part thumbnails on purchase orders.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {companySettings.includeThumbnailsOnPurchasingPdfs
+ ? "Thumbnails are included"
+ : "Thumbnails are not included"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {companySettings.includeThumbnailsOnPurchasingPdfs
+ ? "Part thumbnails are shown on purchase order PDFs."
+ : "Enable to show part thumbnails on purchase order PDFs."}
+ </span>
+ </VStack>
+ <Switch
+ checked={
+ companySettings.includeThumbnailsOnPurchasingPdfs ?? true
}
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ onCheckedChange={(checked) => {
+ toggleFetcher.submit(
+ { intent: "pdfs", enabled: String(checked) },
+ { method: "POST" }
+ );
+ }}
+ disabled={toggleFetcher.state !== "idle"}
+ />
+ </HStack>
+ </CardContent>
</Card>
</VStack>
</ScrollArea>
diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsx
index 917b118526..2c1a365d1c 100644
--- a/apps/erp/app/routes/x+/settings+/sales.tsx
+++ b/apps/erp/app/routes/x+/settings+/sales.tsx
@@ -48,7 +48,6 @@ import {
getAccountsReceivableBillingAddress,
getCompanySettings,
getTerms,
- includeThumbnailsOnSalesPdfsValidator,
quoteLineCategoryMarkupsSettingsValidator,
rfqReadyValidator,
updateAccountsReceivableAddressSetting,
@@ -137,25 +136,19 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, message: "Digital quote setting updated" };
- case "pdfs":
- const thumbnailsValidation = await validator(
- includeThumbnailsOnSalesPdfsValidator
- ).validate(formData);
-
- if (thumbnailsValidation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
+ case "pdfs": {
+ const pdfEnabled = formData.get("enabled") === "true";
const thumbnailsResult = await updateSalesPdfThumbnails(
client,
companyId,
- thumbnailsValidation.data.includeThumbnailsOnSalesPdfs
+ pdfEnabled
);
if (thumbnailsResult.error)
return { success: false, message: thumbnailsResult.error.message };
return { success: true, message: "PDF settings updated" };
+ }
case "rfq":
const rfqValidation =
@@ -605,44 +598,39 @@ export default function SalesSettingsRoute() {
</Card>
<Card>
- <ValidatedForm
- method="post"
- validator={includeThumbnailsOnSalesPdfsValidator}
- defaultValues={{
- includeThumbnailsOnSalesPdfs:
- companySettings.includeThumbnailsOnSalesPdfs ?? true
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="pdfs" />
- <CardHeader>
- <CardTitle>PDFs</CardTitle>
- <CardDescription>
- Show part thumbnails on quotes, sales orders, sales invoices,
- and shipments.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-2 max-w-[400px]">
- <Boolean
- name="includeThumbnailsOnSalesPdfs"
- description="Include Thumbnails in PDFs"
- />
- </div>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={fetcher.state !== "idle"}
- isLoading={
- fetcher.state !== "idle" &&
- fetcher.formData?.get("intent") ===
- "includeThumbnailsOnSalesPdfs"
- }
- >
- Save
- </Submit>
- </CardFooter>
- </ValidatedForm>
+ <CardHeader>
+ <CardTitle>PDFs</CardTitle>
+ <CardDescription>
+ Show part thumbnails on quotes, sales orders, sales invoices, and
+ shipments.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {companySettings.includeThumbnailsOnSalesPdfs
+ ? "Thumbnails are included"
+ : "Thumbnails are not included"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {companySettings.includeThumbnailsOnSalesPdfs
+ ? "Part thumbnails are shown on sales PDFs."
+ : "Enable to show part thumbnails on sales PDFs."}
+ </span>
+ </VStack>
+ <Switch
+ checked={companySettings.includeThumbnailsOnSalesPdfs ?? true}
+ onCheckedChange={(checked) => {
+ toggleFetcher.submit(
+ { intent: "pdfs", enabled: String(checked) },
+ { method: "POST" }
+ );
+ }}
+ disabled={toggleFetcher.state !== "idle"}
+ />
+ </HStack>
+ </CardContent>
</Card>
<CategoryMarkupsCard
companySettings={companySettings}
diff --git a/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx b/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx
new file mode 100644
index 0000000000..de5437aa0a
--- /dev/null
+++ b/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx
@@ -0,0 +1,163 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { ValidatedForm, validationError, validator } from "@carbon/form";
+import {
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ useMount,
+ VStack
+} from "@carbon/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useFetcher, useLoaderData, useNavigate } from "react-router";
+import { Input, Select, Submit } from "~/components/Form";
+import { convertOperatorValidator } from "~/modules/users/users.models";
+import { convertConsoleOperatorToUser } from "~/modules/users/users.server";
+import type { getEmployeeTypes } from "~/modules/users/users.service";
+import type { Result } from "~/types";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "users"
+ });
+
+ const { operatorId } = params;
+ if (!operatorId) throw new Error("Operator ID is required");
+
+ const user = await client
+ .from("user")
+ .select("id, firstName, lastName, email")
+ .eq("id", operatorId)
+ .single();
+
+ if (user.error || !user.data) {
+ throw redirect(
+ path.to.operators,
+ await flash(request, error(user.error, "Operator not found"))
+ );
+ }
+
+ return { operator: user.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "users"
+ });
+
+ const { operatorId } = params;
+ if (!operatorId) throw new Error("Operator ID is required");
+
+ const validation = await validator(convertOperatorValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const result = await convertConsoleOperatorToUser(client, {
+ userId: operatorId,
+ email: validation.data.email,
+ employeeType: validation.data.employeeType,
+ companyId,
+ createdBy: userId
+ });
+
+ if (!result.success) {
+ throw redirect(
+ path.to.operators,
+ await flash(request, error(result, result.message))
+ );
+ }
+
+ throw redirect(
+ path.to.employeeAccounts,
+ await flash(
+ request,
+ success("Operator converted to full user. Invite email sent.")
+ )
+ );
+}
+
+export default function ConvertOperatorRoute() {
+ const { operator } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ const formFetcher = useFetcher<Result>();
+ const employeeTypeFetcher =
+ useFetcher<Awaited<ReturnType<typeof getEmployeeTypes>>>();
+
+ useMount(() => {
+ employeeTypeFetcher.load(path.to.api.employeeTypes);
+ });
+
+ const employeeTypeOptions =
+ employeeTypeFetcher.data?.data
+ ?.filter((et) => et.name !== "Console Operator")
+ .map((et) => ({
+ value: et.id,
+ label: et.name
+ })) ?? [];
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) navigate(-1);
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ validator={convertOperatorValidator}
+ fetcher={formFetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalHeader>
+ <ModalTitle>Convert to Full User</ModalTitle>
+ </ModalHeader>
+
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ Convert{" "}
+ <strong>
+ {operator.firstName} {operator.lastName}
+ </strong>{" "}
+ from a console operator to a full user. They will receive an
+ email invitation and be able to log in independently.
+ </p>
+ <Input
+ name="email"
+ label="Email Address"
+ placeholder="[email protected]"
+ />
+ <Select
+ name="employeeType"
+ label="Employee Type"
+ options={employeeTypeOptions}
+ placeholder="Select Employee Type"
+ />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>
+ Convert & Send Invite
+ </Submit>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/routes/x+/users+/operators.new.tsx b/apps/erp/app/routes/x+/users+/operators.new.tsx
new file mode 100644
index 0000000000..558283adf9
--- /dev/null
+++ b/apps/erp/app/routes/x+/users+/operators.new.tsx
@@ -0,0 +1,220 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import { ValidatedForm, validationError, validator } from "@carbon/form";
+import {
+ HStack,
+ IconButton,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ VStack
+} from "@carbon/react";
+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
+import { useState } from "react";
+import { LuCheck, LuCopy, LuRefreshCw } from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useFetcher, useNavigate } from "react-router";
+import { Input, Location, Submit } from "~/components/Form";
+import { useUser } from "~/hooks";
+import { createOperatorValidator } from "~/modules/users/users.models";
+import { createConsoleOperator } from "~/modules/users/users.server";
+
+function generatePin(): string {
+ return Math.floor(1000 + Math.random() * 9000).toString();
+}
+
+import type { Result } from "~/types";
+import { path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, { create: "users" });
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "users"
+ });
+
+ const validation = await validator(createOperatorValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { firstName, lastName, locationId, pin } = validation.data;
+
+ // Auto-assign "Console Operator" employee type
+ const serviceRole = getCarbonServiceRole();
+ const operatorType = await serviceRole
+ .from("employeeType")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("name", "Console Operator")
+ .single();
+
+ if (operatorType.error || !operatorType.data) {
+ throw redirect(
+ path.to.operators,
+ await flash(
+ request,
+ error(
+ null,
+ "Console Operator employee type not found. Run the migration."
+ )
+ )
+ );
+ }
+
+ const result = await createConsoleOperator(client, {
+ firstName,
+ lastName,
+ employeeType: operatorType.data.id,
+ locationId,
+ companyId,
+ createdBy: userId
+ });
+
+ if (!result.success) {
+ throw redirect(
+ path.to.operators,
+ await flash(
+ request,
+ error(result, result.message ?? "Failed to create console operator")
+ )
+ );
+ }
+
+ // Set PIN if provided (employee record is already created by createConsoleOperator)
+ if (pin) {
+ const pinUpdate = await serviceRole
+ .from("employee")
+ .update({ pin } as any)
+ .eq("id", result.userId)
+ .eq("companyId", companyId);
+
+ if (pinUpdate.error) {
+ console.error("Failed to set PIN for operator:", pinUpdate.error);
+ }
+ }
+
+ await updateSubscriptionQuantityForCompany(companyId);
+
+ throw redirect(
+ path.to.operators,
+ await flash(request, success("Console operator created successfully"))
+ );
+}
+
+export default function NewOperatorRoute() {
+ const { defaults } = useUser();
+ const navigate = useNavigate();
+ const formFetcher = useFetcher<Result>();
+ const [pinValue, setPinValue] = useState(generatePin);
+ const [copied, setCopied] = useState(false);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) navigate(-1);
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.newOperator}
+ validator={createOperatorValidator}
+ defaultValues={{
+ locationId: defaults?.locationId ?? undefined,
+ pin: pinValue
+ }}
+ fetcher={formFetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalHeader>
+ <ModalTitle>Add Console Operator</ModalTitle>
+ </ModalHeader>
+
+ <ModalBody>
+ <VStack spacing={4}>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <Input name="firstName" label="First Name" />
+ <Input name="lastName" label="Last Name" />
+ </div>
+ <Location name="locationId" label="Location" />
+ <div className="space-y-2 w-full">
+ <Label htmlFor="pin">PIN</Label>
+ <HStack>
+ <Input
+ name="pin"
+ value={pinValue}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
+ const val = e.target.value.replace(/\D/g, "").slice(0, 4);
+ setPinValue(val);
+ }}
+ maxLength={4}
+ inputMode="numeric"
+ className="font-mono text-lg tracking-[0.3em] text-center"
+ />
+ <IconButton
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Copy PIN"
+ icon={
+ copied ? (
+ <LuCheck className="text-emerald-500" />
+ ) : (
+ <LuCopy />
+ )
+ }
+ onClick={() => {
+ navigator.clipboard.writeText(pinValue);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }}
+ />
+ <IconButton
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Generate new PIN"
+ icon={<LuRefreshCw />}
+ onClick={() => {
+ const newPin = generatePin();
+ setPinValue(newPin);
+ setCopied(false);
+ }}
+ />
+ </HStack>
+ <p className="text-xs text-muted-foreground">
+ Share this PIN with the operator so they can pin in at MES
+ terminals.
+ </p>
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>
+ Create Operator
+ </Submit>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx b/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx
new file mode 100644
index 0000000000..532259d486
--- /dev/null
+++ b/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx
@@ -0,0 +1,165 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Button,
+ Copy,
+ HStack,
+ IconButton,
+ InputOTP,
+ InputOTPGroup,
+ InputOTPSlot,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ VStack
+} from "@carbon/react";
+import { useState } from "react";
+import { LuRefreshCw } from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useFetcher, useLoaderData, useNavigate } from "react-router";
+import type { Result } from "~/types";
+import { path } from "~/utils/path";
+
+function generatePin(): string {
+ return Math.floor(1000 + Math.random() * 9000).toString();
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, { update: "users" });
+
+ const { operatorId } = params;
+ if (!operatorId) throw new Error("Operator ID is required");
+
+ const user = await client
+ .from("user")
+ .select("id, firstName, lastName")
+ .eq("id", operatorId)
+ .single();
+
+ if (user.error || !user.data) {
+ throw redirect(
+ path.to.operators,
+ await flash(request, error(user.error, "Operator not found"))
+ );
+ }
+
+ return { operator: user.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {
+ update: "users"
+ });
+
+ const { operatorId } = params;
+ if (!operatorId) throw new Error("Operator ID is required");
+
+ const formData = await request.formData();
+ const newPin = formData.get("pin") as string;
+
+ if (!newPin || !/^\d{4}$/.test(newPin)) {
+ return { success: false, message: "PIN must be 4 digits" };
+ }
+
+ const serviceRole = getCarbonServiceRole();
+ const update = await serviceRole
+ .from("employee")
+ .update({ pin: newPin } as any)
+ .eq("id", operatorId)
+ .eq("companyId", companyId);
+
+ if (update.error) {
+ return { success: false, message: update.error.message };
+ }
+
+ throw redirect(
+ path.to.operators,
+ await flash(request, success("PIN reset successfully"))
+ );
+}
+
+export default function ResetPinRoute() {
+ const { operator } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ const formFetcher = useFetcher<Result>();
+ const [pinValue, setPinValue] = useState(generatePin);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) navigate(-1);
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <formFetcher.Form method="post" className="flex flex-col h-full">
+ <ModalHeader>
+ <ModalTitle>
+ Reset PIN for {operator.firstName} {operator.lastName}
+ </ModalTitle>
+ </ModalHeader>
+
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ Generate a new 4-digit PIN. Share it with the operator so they
+ can pin in at MES terminals.
+ </p>
+ <div className="space-y-2 w-full">
+ <Label>New PIN</Label>
+ <div className="flex items-center justify-center gap-3">
+ <input type="hidden" name="pin" value={pinValue} />
+ <InputOTP
+ maxLength={4}
+ value={pinValue}
+ onChange={(value) => setPinValue(value)}
+ autoFocus={false}
+ >
+ <InputOTPGroup>
+ <InputOTPSlot index={0} />
+ <InputOTPSlot index={1} />
+ <InputOTPSlot index={2} />
+ <InputOTPSlot index={3} />
+ </InputOTPGroup>
+ </InputOTP>
+ <Copy text={pinValue} size="sm" />
+ <IconButton
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Generate new PIN"
+ icon={<LuRefreshCw />}
+ onClick={() => {
+ const newPin = generatePin();
+ setPinValue(newPin);
+ }}
+ />
+ </div>
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button
+ type="submit"
+ isLoading={formFetcher.state !== "idle"}
+ isDisabled={formFetcher.state !== "idle" || pinValue.length < 4}
+ >
+ Reset PIN
+ </Button>
+ </HStack>
+ </ModalFooter>
+ </formFetcher.Form>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/routes/x+/users+/operators.tsx b/apps/erp/app/routes/x+/users+/operators.tsx
new file mode 100644
index 0000000000..a1cb2700c3
--- /dev/null
+++ b/apps/erp/app/routes/x+/users+/operators.tsx
@@ -0,0 +1,222 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Checkbox, MenuIcon, MenuItem } from "@carbon/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import {
+ LuBriefcase,
+ LuKey,
+ LuToggleRight,
+ LuUser,
+ LuUserCheck
+} from "react-icons/lu";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, redirect, useLoaderData, useNavigate } from "react-router";
+import { EmployeeAvatar, New, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { usePermissions, useUrlParams } from "~/hooks";
+import {
+ getConsoleOperators,
+ getEmployeeTypes
+} from "~/modules/users/users.service";
+import type { ListItem } from "~/types";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Operators",
+ to: path.to.operators
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "users",
+ role: "employee",
+ bypassRls: true
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [operators, employeeTypes] = await Promise.all([
+ getConsoleOperators(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters
+ }),
+ getEmployeeTypes(client, companyId)
+ ]);
+
+ if (operators.error) {
+ throw redirect(
+ path.to.users,
+ await flash(
+ request,
+ error(operators.error, "Error loading console operators")
+ )
+ );
+ }
+
+ return {
+ count: operators.count ?? 0,
+ operators: operators.data ?? [],
+ employeeTypes: employeeTypes.data ?? []
+ };
+}
+
+type Operator = NonNullable<
+ Awaited<ReturnType<typeof getConsoleOperators>>["data"]
+>[number];
+
+const OperatorsTable = memo(
+ ({
+ data,
+ count,
+ employeeTypes
+ }: {
+ data: Operator[];
+ count: number;
+ employeeTypes: ListItem[];
+ }) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const employeeTypesById = useMemo(
+ () =>
+ employeeTypes.reduce<Record<string, ListItem>>((acc, type) => {
+ acc[type.id] = type;
+ return acc;
+ }, {}),
+ [employeeTypes]
+ );
+
+ const columns = useMemo<ColumnDef<Operator>[]>(
+ () => [
+ {
+ header: "Operator",
+ cell: ({ row }) => (
+ <EmployeeAvatar size="sm" employeeId={row.original.id} />
+ ),
+ meta: {
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "firstName",
+ header: "First Name",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuUserCheck />
+ }
+ },
+ {
+ accessorKey: "lastName",
+ header: "Last Name",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuUserCheck />
+ }
+ },
+ {
+ id: "employeeTypeId",
+ header: "Employee Type",
+ cell: ({ row }) => (
+ <Enumerable
+ value={
+ employeeTypesById[row.original.employeeTypeId!]?.name ?? ""
+ }
+ />
+ ),
+ meta: {
+ icon: <LuBriefcase />
+ }
+ },
+ {
+ accessorKey: "active",
+ header: "Active",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static" as const,
+ options: [
+ { value: "true", label: "Active" },
+ { value: "false", label: "Inactive" }
+ ]
+ },
+ icon: <LuToggleRight />
+ }
+ }
+ ],
+ [employeeTypesById]
+ );
+
+ const renderContextMenu = useCallback(
+ (row: Operator) => (
+ <>
+ <MenuItem
+ onClick={() =>
+ navigate(
+ `${path.to.operatorResetPin(row.id!)}?${params.toString()}`
+ )
+ }
+ disabled={!permissions.can("update", "users")}
+ >
+ <MenuIcon icon={<LuKey />} />
+ Reset PIN
+ </MenuItem>
+ <MenuItem
+ onClick={() =>
+ navigate(`${path.to.operator(row.id!)}?${params.toString()}`)
+ }
+ disabled={!permissions.can("update", "users")}
+ >
+ <MenuIcon icon={<LuUser />} />
+ Convert to Full User
+ </MenuItem>
+ </>
+ ),
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<Operator>
+ count={count}
+ columns={columns}
+ data={data}
+ primaryAction={
+ permissions.can("create", "users") && (
+ <New label="Operator" to={`new?${params.toString()}`} />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Operators"
+ />
+ );
+ }
+);
+
+OperatorsTable.displayName = "OperatorsTable";
+
+export default function ConsoleOperatorsRoute() {
+ const { count, operators, employeeTypes } = useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <OperatorsTable
+ data={operators}
+ count={count}
+ employeeTypes={employeeTypes}
+ />
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 9b5271a86f..0e6f2176b0 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -787,6 +787,10 @@ export const path = {
employeeType: (id: string) =>
generatePath(`${x}/users/employee-types/${id}`),
employeeTypes: `${x}/users/employee-types`,
+ operators: `${x}/users/operators`,
+ operator: (id: string) => generatePath(`${x}/users/operators/${id}`),
+ operatorResetPin: (id: string) =>
+ generatePath(`${x}/users/operators/reset-pin/${id}`),
externalCustomer: (id: string) => generatePath(`/share/customer/${id}`),
externalCustomerFile: (id: string, path: string) =>
generatePath(`/share/customer/${id}/${path}`),
@@ -1031,6 +1035,7 @@ export const path = {
newDepartment: `${x}/people/departments/new`,
newDocument: `${x}/documents/new`,
newEmployee: `${x}/users/employees/new`,
+ newOperator: `${x}/users/operators/new`,
newEmployeeAbility: (id: string) =>
generatePath(`${x}/resources/ability/${id}/employee/new`),
newEmployeeType: `${x}/users/employee-types/new`,
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index ebe5a1342d..daf595513b 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -32,7 +32,7 @@ import {
useDisclosure,
useSidebar
} from "@carbon/react";
-import { ItarDisclosure, useMode } from "@carbon/remix";
+import { ItarDisclosure, useMode, useRouteData } from "@carbon/remix";
import type { ComponentProps } from "react";
import { Suspense, useRef } from "react";
import { BsFillHexagonFill } from "react-icons/bs";
@@ -45,16 +45,19 @@ import {
LuHistory,
LuLogOut,
LuMapPin,
+ LuMonitor,
LuMoon,
LuShieldCheck,
LuSun,
LuUser,
+ LuUsers,
LuWrench
} from "react-icons/lu";
import { Await, Form, Link, useFetcher, useLocation } from "react-router";
import { useUser } from "~/hooks";
import type { action } from "~/root";
import type { Location } from "~/services/types";
+import type { PinnedInUser } from "~/types";
import { ERP_URL, path } from "~/utils/path";
import { AdjustInventory } from "./AdjustInventory";
import { EndShift } from "./EndShift";
@@ -66,18 +69,24 @@ export function AppSidebar({
activeMaintenanceCount,
company,
companies,
+ consoleEnabled,
+ consoleMode,
location,
locations,
- timeCardEnabled,
openClockEntry,
+ pinnedInUser,
+ timeCardEnabled,
...props
}: ComponentProps<typeof Sidebar> & {
activeEvents: number;
activeMaintenanceCount: number;
company: Company;
companies: Company[];
+ consoleEnabled?: boolean;
+ consoleMode: boolean;
location: string;
locations: Location[];
+ pinnedInUser: PinnedInUser | null;
timeCardEnabled?: boolean;
openClockEntry?: Promise<{
data: { id: string; clockIn: string; [key: string]: unknown } | null;
@@ -119,8 +128,11 @@ export function AppSidebar({
<UserNav
company={company}
companies={companies}
+ consoleEnabled={consoleEnabled}
+ consoleMode={consoleMode}
location={location}
locations={locations}
+ pinnedInUser={pinnedInUser}
/>
</SidebarFooter>
<SidebarRail />
@@ -278,21 +290,28 @@ export function ToolsNav() {
export function UserNav({
company,
companies,
+ consoleEnabled,
+ consoleMode,
location,
- locations
+ locations,
+ pinnedInUser
}: {
company: Company;
companies: Company[];
+ consoleEnabled?: boolean;
+ consoleMode: boolean;
location: string;
locations: Location[];
+ pinnedInUser: PinnedInUser | null;
}) {
const user = useUser();
- const name = `${user.firstName} ${user.lastName}`;
+ const stationName = `${user.firstName} ${user.lastName}`;
const { isMobile } = useSidebar();
const mode = useMode();
const modeSubmitRef = useRef<HTMLButtonElement>(null);
+ const consoleSubmitRef = useRef<HTMLButtonElement>(null);
const fetcher = useFetcher<typeof action>();
@@ -307,6 +326,23 @@ export function UserNav({
const itarDisclosure = useDisclosure();
+ // useUser().id returns the effective (operator) ID — read the original station user ID directly
+ const routeData = useRouteData<{ user: { id: string } | null }>(
+ path.to.authenticatedRoot
+ );
+ const sessionUserId = routeData?.user?.id;
+ const isOperatorPinnedIn =
+ consoleMode &&
+ pinnedInUser &&
+ sessionUserId &&
+ pinnedInUser.userId !== sessionUserId;
+ const showingOperator = consoleMode && pinnedInUser;
+ const displayName = showingOperator ? pinnedInUser.name : stationName;
+ const displayAvatar = showingOperator
+ ? pinnedInUser.avatarUrl
+ : user.avatarUrl;
+ const displaySubtext = showingOperator ? "Console" : user.email;
+
return (
<SidebarMenu>
<SidebarMenuItem>
@@ -318,12 +354,12 @@ export function UserNav({
>
<Avatar
className="h-8 w-8 rounded-lg"
- src={user.avatarUrl ?? undefined}
- name={name}
+ src={displayAvatar ?? undefined}
+ name={displayName}
/>
<div className="grid flex-1 text-left text-sm leading-tight">
- <span className="truncate font-semibold">{name}</span>
- <span className="truncate text-xs">{user.email}</span>
+ <span className="truncate font-semibold">{displayName}</span>
+ <span className="truncate text-xs">{displaySubtext}</span>
</div>
<LuChevronDown className="ml-auto size-4" />
</SidebarMenuButton>
@@ -334,80 +370,107 @@ export function UserNav({
align="end"
sideOffset={4}
>
- <DropdownMenuLabel>Signed in as {name}</DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem asChild>
- <Link to={path.to.accountSettings}>
- <DropdownMenuIcon icon={<LuUser />} />
- Account Settings
- </Link>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
-
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <DropdownMenuIcon icon={<LuBuilding />} />
- Company
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuRadioGroup value={company.companyId!}>
- {companies.map((c) => {
- const logo =
- mode === "dark" ? c.logoDarkIcon : c.logoLightIcon;
- return (
- <DropdownMenuRadioItem
- key={c.companyId}
- value={c.companyId!}
- onSelect={() => {
- const form = new FormData();
- form.append("companyId", c.companyId!);
- fetcher.submit(form, {
- method: "post",
- action: path.to.switchCompany(c.companyId!)
- });
- }}
- >
- <HStack>
- <Avatar
- size="xs"
- name={c.name ?? undefined}
- src={logo ?? undefined}
- />
- <span>{c.name}</span>
- </HStack>
- </DropdownMenuRadioItem>
- );
- })}
- </DropdownMenuRadioGroup>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- {locations.length > 1 ? (
+ {/* Console mode with pinned-in operator: simplified menu */}
+ {showingOperator ? (
<>
+ <DropdownMenuLabel>{pinnedInUser.name}</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ fetcher.submit(null, {
+ method: "POST",
+ action: path.to.consolePinOut
+ });
+ }}
+ >
+ <DropdownMenuIcon icon={<LuUsers />} />
+ Switch Operator
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
+ Station: {stationName}
+ </DropdownMenuLabel>
+ </>
+ ) : (
+ <>
+ <DropdownMenuLabel>
+ Signed in as {stationName}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem asChild>
+ <Link to={path.to.accountSettings}>
+ <DropdownMenuIcon icon={<LuUser />} />
+ Account Settings
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+
<DropdownMenuSub>
<DropdownMenuSubTrigger>
- <DropdownMenuIcon icon={<LuMapPin />} />
- Location
+ <DropdownMenuIcon icon={<LuBuilding />} />
+ Company
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
- <DropdownMenuRadioGroup value={optimisticLocation}>
- {locations.map((loc) => (
- <DropdownMenuRadioItem
- key={loc.id}
- value={loc.id}
- onSelect={() => {
- updateLocation(loc.id);
- }}
- >
- {loc.name}
- </DropdownMenuRadioItem>
- ))}
+ <DropdownMenuRadioGroup value={company.companyId!}>
+ {companies.map((c) => {
+ const logo =
+ mode === "dark" ? c.logoDarkIcon : c.logoLightIcon;
+ return (
+ <DropdownMenuRadioItem
+ key={c.companyId}
+ value={c.companyId!}
+ onSelect={() => {
+ const form = new FormData();
+ form.append("companyId", c.companyId!);
+ fetcher.submit(form, {
+ method: "post",
+ action: path.to.switchCompany(c.companyId!)
+ });
+ }}
+ >
+ <HStack>
+ <Avatar
+ size="xs"
+ name={c.name ?? undefined}
+ src={logo ?? undefined}
+ />
+ <span>{c.name}</span>
+ </HStack>
+ </DropdownMenuRadioItem>
+ );
+ })}
</DropdownMenuRadioGroup>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
+ {locations.length > 1 ? (
+ <>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <DropdownMenuIcon icon={<LuMapPin />} />
+ Location
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup value={optimisticLocation}>
+ {locations.map((loc) => (
+ <DropdownMenuRadioItem
+ key={loc.id}
+ value={loc.id}
+ onSelect={() => {
+ updateLocation(loc.id);
+ }}
+ >
+ {loc.name}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
</>
- ) : null}
+ )}
<DropdownMenuItem onSelect={(e) => e.preventDefault()}>
<div className="flex items-center justify-between w-full">
<div className="flex items-center justify-start">
@@ -443,21 +506,59 @@ export function UserNav({
</div>
</div>
</DropdownMenuItem>
- <DropdownMenuSeparator />
- {CONTROLLED_ENVIRONMENT && (
- <DropdownMenuItem onClick={itarDisclosure.onOpen}>
- <DropdownMenuIcon icon={<LuShieldCheck />} />
- About
- </DropdownMenuItem>
+ {!isOperatorPinnedIn && (
+ <>
+ {consoleEnabled && (
+ <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
+ <div className="flex items-center justify-between w-full">
+ <div className="flex items-center justify-start">
+ <DropdownMenuIcon icon={<LuMonitor />} />
+ Console Mode
+ </div>
+ <div>
+ <Switch
+ checked={consoleMode}
+ onCheckedChange={() =>
+ consoleSubmitRef.current?.click()
+ }
+ />
+ <fetcher.Form
+ action={path.to.consoleToggle}
+ method="post"
+ className="sr-only"
+ >
+ <input
+ type="hidden"
+ name="consoleMode"
+ value={consoleMode ? "false" : "true"}
+ />
+ <button
+ ref={consoleSubmitRef}
+ className="sr-only"
+ type="submit"
+ />
+ </fetcher.Form>
+ </div>
+ </div>
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ {CONTROLLED_ENVIRONMENT && (
+ <DropdownMenuItem onClick={itarDisclosure.onOpen}>
+ <DropdownMenuIcon icon={<LuShieldCheck />} />
+ About
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
+ <Form method="post" action={path.to.logout}>
+ <button type="submit" className="w-full flex items-center">
+ <DropdownMenuIcon icon={<LuLogOut />} />
+ <span>Sign Out</span>
+ </button>
+ </Form>
+ </DropdownMenuItem>
+ </>
)}
- <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
- <Form method="post" action={path.to.logout}>
- <button type="submit" className="w-full flex items-center">
- <DropdownMenuIcon icon={<LuLogOut />} />
- <span>Sign Out</span>
- </button>
- </Form>
- </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
diff --git a/apps/mes/app/components/ConsolePill.tsx b/apps/mes/app/components/ConsolePill.tsx
new file mode 100644
index 0000000000..261ab663b6
--- /dev/null
+++ b/apps/mes/app/components/ConsolePill.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { Avatar } from "@carbon/react";
+import { useState } from "react";
+import { LuChevronDown } from "react-icons/lu";
+import { useRevalidator } from "react-router";
+import type { PinnedInUser } from "~/types";
+import { PinInOverlay } from "./PinInOverlay";
+
+export function ConsolePill({
+ user,
+ companyId,
+ locationEmployeeIds,
+ sessionUserId
+}: {
+ user: PinnedInUser;
+ companyId: string;
+ locationEmployeeIds: string[];
+ sessionUserId: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const revalidator = useRevalidator();
+
+ const handleDismiss = () => {
+ setOpen(false);
+ // Revalidate the layout to pick up cookie changes (pin-in/pin-out)
+ revalidator.revalidate();
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className="fixed top-3 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full border bg-card/90 backdrop-blur-md px-3 py-1.5 shadow-lg transition-all duration-200 hover:shadow-xl active:scale-[0.98] select-none"
+ >
+ <Avatar size="xs" name={user.name} src={user.avatarUrl ?? undefined} />
+ <span className="text-xs font-medium max-w-[130px] truncate">
+ {user.name}
+ </span>
+ <LuChevronDown className="h-3 w-3 text-muted-foreground" />
+ </button>
+
+ {open && (
+ <PinInOverlay
+ companyId={companyId}
+ locationEmployeeIds={locationEmployeeIds}
+ sessionUserId={sessionUserId}
+ hasPinnedUser={!!user}
+ dismissable
+ onDismiss={handleDismiss}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/mes/app/components/EndShift.tsx b/apps/mes/app/components/EndShift.tsx
index 169445fc28..70763a842f 100644
--- a/apps/mes/app/components/EndShift.tsx
+++ b/apps/mes/app/components/EndShift.tsx
@@ -30,6 +30,7 @@ export function EndShift() {
const confirmModal = useDisclosure();
const fetcher = useFetcher<typeof endShiftAction>();
const user = useUser();
+
const { carbon } = useCarbon();
const [operations, setOperations] = useState<Operation[]>([]);
const [loading, setLoading] = useState(false);
diff --git a/apps/mes/app/components/JobOperation/components/Chat.tsx b/apps/mes/app/components/JobOperation/components/Chat.tsx
index c2f213c25d..fa93321f12 100644
--- a/apps/mes/app/components/JobOperation/components/Chat.tsx
+++ b/apps/mes/app/components/JobOperation/components/Chat.tsx
@@ -32,6 +32,7 @@ export function OperationChat({
operation: OperationWithDetails;
}) {
const user = useUser();
+
const [employees] = usePeople();
const [messages, setMessages] = useState<Message[]>([]);
diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
index 82cd0b9c89..b902841268 100644
--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
@@ -47,6 +47,7 @@ export function useOperation({
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { carbon, accessToken } = useCarbon();
const user = useUser();
+
const revalidator = useRevalidator();
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const channelRef = useRef<RealtimeChannel | null>(null);
diff --git a/apps/mes/app/components/PinInOverlay.tsx b/apps/mes/app/components/PinInOverlay.tsx
new file mode 100644
index 0000000000..5c9689ab60
--- /dev/null
+++ b/apps/mes/app/components/PinInOverlay.tsx
@@ -0,0 +1,620 @@
+"use client";
+
+import {
+ Avatar,
+ Button,
+ HStack,
+ Input,
+ InputOTP,
+ InputOTPGroup,
+ InputOTPSlot,
+ Label,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ VStack
+} from "@carbon/react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ LuCheck,
+ LuCopy,
+ LuLoader,
+ LuLogOut,
+ LuPlus,
+ LuRefreshCw,
+ LuSearch,
+ LuX
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+
+const RECENT_KEY_PREFIX = "console-recent-";
+const MAX_RECENT = 5;
+
+function generatePin(): string {
+ return Math.floor(1000 + Math.random() * 9000).toString();
+}
+
+function getRecentOperators(companyId: string): string[] {
+ try {
+ const raw = localStorage.getItem(`${RECENT_KEY_PREFIX}${companyId}`);
+ return raw ? JSON.parse(raw) : [];
+ } catch {
+ return [];
+ }
+}
+
+function addRecentOperator(companyId: string, userId: string) {
+ try {
+ const recent = getRecentOperators(companyId).filter((id) => id !== userId);
+ recent.unshift(userId);
+ localStorage.setItem(
+ `${RECENT_KEY_PREFIX}${companyId}`,
+ JSON.stringify(recent.slice(0, MAX_RECENT))
+ );
+ } catch {
+ // localStorage not available
+ }
+}
+
+type Person = { id: string; name: string; avatarUrl: string | null };
+
+export function PinInOverlay({
+ companyId,
+ locationEmployeeIds,
+ sessionUserId,
+ hasPinnedUser = false,
+ dismissable = false,
+ onDismiss
+}: {
+ companyId: string;
+ locationEmployeeIds: string[];
+ sessionUserId?: string;
+ hasPinnedUser?: boolean;
+ dismissable?: boolean;
+ onDismiss?: () => void;
+}) {
+ const [people] = usePeople();
+ const [search, setSearch] = useState("");
+ const [showAddModal, setShowAddModal] = useState(false);
+ const [selectedPerson, setSelectedPerson] = useState<Person | null>(null);
+ const [pin, setPin] = useState("");
+ const [pinError, setPinError] = useState<string | null>(null);
+ const [generatedPin, setGeneratedPin] = useState(generatePin);
+ const searchRef = useRef<HTMLInputElement>(null);
+
+ const pinInFetcher = useFetcher<{ error?: string }>();
+ const pinOutFetcher = useFetcher();
+ const addOperatorFetcher = useFetcher<{
+ success: boolean;
+ message?: string;
+ operator?: Person & { pin: string };
+ }>();
+
+ const recentIds = useMemo(() => getRecentOperators(companyId), [companyId]);
+ const isAdding = addOperatorFetcher.state !== "idle";
+ const isPinning = pinInFetcher.state !== "idle";
+
+ // Escape key to close when dismissable (but not when add modal is open)
+ useEffect(() => {
+ if (!dismissable) return;
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Escape" && !showAddModal) onDismiss?.();
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [dismissable, onDismiss, showAddModal]);
+
+ const submitPinIn = useCallback(
+ (person: Person, pinValue: string) => {
+ addRecentOperator(companyId, person.id);
+ const formData = new FormData();
+ formData.append("userId", person.id);
+ formData.append("name", person.name);
+ formData.append("avatarUrl", person.avatarUrl ?? "");
+ if (pinValue) formData.append("pin", pinValue);
+ pinInFetcher.submit(formData, {
+ method: "POST",
+ action: path.to.consolePinIn
+ });
+ },
+ [companyId, pinInFetcher]
+ );
+
+ // Handle pin-in errors
+ useEffect(() => {
+ if (pinInFetcher.state === "idle" && pinInFetcher.data?.error) {
+ setPinError(pinInFetcher.data.error);
+ setPin("");
+ }
+ }, [pinInFetcher.state, pinInFetcher.data]);
+
+ // Auto-pin after successful quick-add
+ useEffect(() => {
+ if (
+ addOperatorFetcher.state === "idle" &&
+ addOperatorFetcher.data?.success &&
+ addOperatorFetcher.data.operator
+ ) {
+ const op = addOperatorFetcher.data.operator;
+ setShowAddModal(false);
+ submitPinIn(op, op.pin);
+ // Don't dismiss — the pinInFetcher completion effect handles it
+ }
+ }, [addOperatorFetcher.state, addOperatorFetcher.data, submitPinIn]);
+
+ // Focus search on mount
+ useEffect(() => {
+ searchRef.current?.focus();
+ }, []);
+
+ const stationUser = useMemo(
+ () => (sessionUserId ? people.find((p) => p.id === sessionUserId) : null),
+ [people, sessionUserId]
+ );
+
+ const operatorList = useMemo(() => {
+ const query = search.toLowerCase().trim();
+ let list = sessionUserId
+ ? people.filter((p) => p.id !== sessionUserId)
+ : people;
+ if (locationEmployeeIds.length > 0) {
+ list = list.filter((p) => locationEmployeeIds.includes(p.id));
+ }
+ const filtered = query
+ ? list.filter((p) => p.name.toLowerCase().includes(query))
+ : list;
+
+ const sorted = [...filtered].sort((a, b) => {
+ const aRecent = recentIds.indexOf(a.id);
+ const bRecent = recentIds.indexOf(b.id);
+ if (aRecent !== -1 && bRecent !== -1) return aRecent - bRecent;
+ if (aRecent !== -1) return -1;
+ if (bRecent !== -1) return 1;
+ return a.name.localeCompare(b.name);
+ });
+
+ // When searching, return flat list. When browsing, split into groups.
+ if (query) {
+ return { recent: [] as Person[], others: sorted, all: sorted };
+ }
+ const recent = sorted.filter((p) => recentIds.includes(p.id));
+ const others = sorted.filter((p) => !recentIds.includes(p.id));
+ return { recent, others, all: sorted };
+ }, [people, search, recentIds, locationEmployeeIds, sessionUserId]);
+
+ // Track if we've submitted a pin-in attempt
+ const hasSubmittedPinIn = useRef(false);
+
+ // Watch for successful pin-in completion
+ useEffect(() => {
+ if (
+ pinInFetcher.state === "submitting" ||
+ pinInFetcher.state === "loading"
+ ) {
+ hasSubmittedPinIn.current = true;
+ }
+ if (
+ hasSubmittedPinIn.current &&
+ pinInFetcher.state === "idle" &&
+ !pinInFetcher.data?.error
+ ) {
+ // Fetcher completed without error — cookie is set, dismiss overlay
+ hasSubmittedPinIn.current = false;
+ onDismiss?.();
+ }
+ }, [pinInFetcher.state, pinInFetcher.data, onDismiss]);
+
+ const handlePinComplete = useCallback(
+ (value: string) => {
+ if (selectedPerson && value.length === 4) {
+ submitPinIn(selectedPerson, value);
+ // Don't dismiss here — wait for fetcher to complete
+ }
+ },
+ [selectedPerson, submitPinIn]
+ );
+
+ const handleAddOperator = useCallback(
+ (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ const formData = new FormData(e.currentTarget);
+ addOperatorFetcher.submit(formData, {
+ method: "POST",
+ action: path.to.consoleAddOperator
+ });
+ },
+ [addOperatorFetcher]
+ );
+
+ const handleBackdropClick = useCallback(() => {
+ // Don't dismiss if add modal is open
+ if (showAddModal) return;
+ if (dismissable) onDismiss?.();
+ }, [dismissable, onDismiss, showAddModal]);
+
+ return (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm"
+ onClick={handleBackdropClick}
+ >
+ <div
+ className="w-full max-w-sm mx-4 rounded-2xl border bg-card shadow-2xl overflow-hidden relative"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Close button — top right, outside the search bar */}
+ {dismissable && (
+ <button
+ type="button"
+ onClick={onDismiss}
+ className="absolute top-2.5 right-2.5 z-10 rounded-md p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
+ >
+ <LuX className="h-4 w-4" />
+ </button>
+ )}
+
+ {/* Search */}
+ <div className="flex items-center gap-3 border-b px-4 py-3">
+ <LuSearch className="h-4 w-4 text-muted-foreground shrink-0" />
+ <input
+ ref={searchRef}
+ type="text"
+ placeholder="Search operators..."
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setSelectedPerson(null);
+ setPin("");
+ setPinError(null);
+ }}
+ className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground pr-8"
+ />
+ </div>
+
+ {/* Operator list */}
+ <div className="max-h-[240px] overflow-y-auto">
+ {operatorList.all.length === 0 ? (
+ <div className="py-8 text-center text-sm text-muted-foreground">
+ {search ? "No results" : "No operators"}
+ </div>
+ ) : (
+ <div className="py-1">
+ {operatorList.recent.length > 0 && (
+ <>
+ <p className="px-4 pt-1.5 pb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ Recent
+ </p>
+ {operatorList.recent.map((person) => (
+ <OperatorRow
+ key={person.id}
+ person={person}
+ isSelected={selectedPerson?.id === person.id}
+ onSelect={(p) => {
+ setSelectedPerson(
+ selectedPerson?.id === p.id ? null : p
+ );
+ setPin("");
+ setPinError(null);
+ }}
+ />
+ ))}
+ {operatorList.others.length > 0 && (
+ <div className="mx-4 my-1 border-t" />
+ )}
+ </>
+ )}
+ {operatorList.others.map((person) => (
+ <OperatorRow
+ key={person.id}
+ person={person}
+ isSelected={selectedPerson?.id === person.id}
+ onSelect={(p) => {
+ setSelectedPerson(selectedPerson?.id === p.id ? null : p);
+ setPin("");
+ setPinError(null);
+ }}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Station user option — for exiting console mode */}
+ {stationUser && !search && (
+ <div className="border-t">
+ <p className="px-4 pt-1.5 pb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ Station User
+ </p>
+ <OperatorRow
+ person={stationUser}
+ isSelected={selectedPerson?.id === stationUser.id}
+ onSelect={(p) => {
+ setSelectedPerson(selectedPerson?.id === p.id ? null : p);
+ setPin("");
+ setPinError(null);
+ }}
+ />
+ </div>
+ )}
+
+ {/* PIN input — below station user, above footer */}
+ {selectedPerson && (
+ <div className="border-t px-4 py-3">
+ <div className="flex flex-col items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ Enter PIN for {selectedPerson.name}
+ </p>
+ <div className="flex items-center gap-3">
+ <InputOTP
+ maxLength={4}
+ value={pin}
+ onChange={(value) => {
+ setPin(value);
+ setPinError(null);
+ }}
+ onComplete={handlePinComplete}
+ disabled={isPinning}
+ autoFocus
+ containerClassName="[&_[data-slot=input-otp-slot]]:text-[0px]"
+ >
+ <InputOTPGroup>
+ <InputOTPSlot
+ index={0}
+ className={
+ pin[0] ? "before:content-['●'] before:text-sm" : ""
+ }
+ />
+ <InputOTPSlot
+ index={1}
+ className={
+ pin[1] ? "before:content-['●'] before:text-sm" : ""
+ }
+ />
+ <InputOTPSlot
+ index={2}
+ className={
+ pin[2] ? "before:content-['●'] before:text-sm" : ""
+ }
+ />
+ <InputOTPSlot
+ index={3}
+ className={
+ pin[3] ? "before:content-['●'] before:text-sm" : ""
+ }
+ />
+ </InputOTPGroup>
+ </InputOTP>
+ {isPinning && (
+ <LuLoader className="h-4 w-4 animate-spin text-muted-foreground" />
+ )}
+ </div>
+ {pinError && (
+ <p className="text-xs text-destructive">{pinError}</p>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Footer */}
+ <div className="border-t px-3 py-2.5 flex gap-2">
+ <Button
+ variant="ghost"
+ size="md"
+ className="flex-1"
+ onClick={() => {
+ setGeneratedPin(generatePin());
+ setShowAddModal(true);
+ }}
+ >
+ <LuPlus className="mr-2 h-4 w-4" />
+ Add Operator
+ </Button>
+ {hasPinnedUser && (
+ <Button
+ variant="ghost"
+ size="md"
+ className="flex-1 text-destructive hover:text-destructive"
+ onClick={() => {
+ pinOutFetcher.submit(null, {
+ method: "POST",
+ action: path.to.consolePinOut
+ });
+ }}
+ >
+ <LuLogOut className="mr-2 h-4 w-4" />
+ Pin Out
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {showAddModal && (
+ <AddOperatorModal
+ generatedPin={generatedPin}
+ onRegeneratePin={() => setGeneratedPin(generatePin())}
+ onSubmit={handleAddOperator}
+ isAdding={isAdding}
+ error={
+ addOperatorFetcher.data?.success === false
+ ? addOperatorFetcher.data.message
+ : null
+ }
+ onClose={() => setShowAddModal(false)}
+ />
+ )}
+ </div>
+ );
+}
+
+function OperatorRow({
+ person,
+ isSelected,
+ onSelect
+}: {
+ person: Person;
+ isSelected: boolean;
+ onSelect: (person: Person) => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect(person)}
+ className={`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${
+ isSelected ? "bg-primary/5" : "hover:bg-muted/50"
+ }`}
+ >
+ <Avatar
+ size="xs"
+ name={person.name}
+ src={person.avatarUrl ?? undefined}
+ />
+ <span className="text-sm flex-1 truncate">{person.name}</span>
+ {isSelected && <LuCheck className="h-3.5 w-3.5 text-primary shrink-0" />}
+ </button>
+ );
+}
+
+function AddOperatorModal({
+ generatedPin,
+ onRegeneratePin,
+ onSubmit,
+ isAdding,
+ error,
+ onClose
+}: {
+ generatedPin: string;
+ onRegeneratePin: () => void;
+ onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
+ isAdding: boolean;
+ error: string | null | undefined;
+ onClose: () => void;
+}) {
+ const [editablePin, setEditablePin] = useState(generatedPin);
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ setEditablePin(generatedPin);
+ setCopied(false);
+ }, [generatedPin]);
+
+ return (
+ <Modal open onOpenChange={(open) => !open && onClose()}>
+ <ModalOverlay />
+ <ModalContent>
+ <form onSubmit={onSubmit} className="flex flex-col h-full">
+ <ModalHeader>
+ <ModalTitle>Add New Operator</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <div className="space-y-2">
+ <Label htmlFor="firstName">First Name</Label>
+ <Input
+ id="firstName"
+ name="firstName"
+ placeholder="Enter first name"
+ required
+ disabled={isAdding}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="lastName">Last Name</Label>
+ <Input
+ id="lastName"
+ name="lastName"
+ placeholder="Enter last name"
+ required
+ disabled={isAdding}
+ />
+ </div>
+ </div>
+ <div className="space-y-2 w-full">
+ <Label htmlFor="pin">PIN</Label>
+ <HStack>
+ <Input
+ id="pin"
+ name="pin"
+ value={editablePin}
+ onChange={(e) => {
+ const val = e.target.value.replace(/\D/g, "").slice(0, 4);
+ setEditablePin(val);
+ }}
+ maxLength={4}
+ inputMode="numeric"
+ required
+ disabled={isAdding}
+ className="font-mono text-lg tracking-[0.3em] text-center"
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ navigator.clipboard.writeText(editablePin);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }}
+ disabled={isAdding}
+ title="Copy PIN"
+ >
+ {copied ? (
+ <LuCheck className="h-4 w-4 text-emerald-500" />
+ ) : (
+ <LuCopy className="h-4 w-4" />
+ )}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onRegeneratePin}
+ disabled={isAdding}
+ title="Generate new PIN"
+ >
+ <LuRefreshCw className="h-4 w-4" />
+ </Button>
+ </HStack>
+ <p className="text-xs text-muted-foreground">
+ Share this PIN with the operator so they can pin in at the
+ terminal.
+ </p>
+ </div>
+ {error && (
+ <p className="text-sm text-destructive">
+ {error ?? "Failed to add operator"}
+ </p>
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={onClose}
+ disabled={isAdding}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ disabled={isAdding || editablePin.length < 4}
+ >
+ {isAdding ? (
+ <LuLoader className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ Add Operator
+ </Button>
+ </HStack>
+ </ModalFooter>
+ </form>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsx
index b2c9d435ce..b928194ff8 100644
--- a/apps/mes/app/components/Suggestion.tsx
+++ b/apps/mes/app/components/Suggestion.tsx
@@ -53,6 +53,7 @@ const Suggestion = () => {
} | null>(null);
const { carbon } = useCarbon();
const user = useUser();
+
const companyId = user.company.id;
useEffect(() => {
diff --git a/apps/mes/app/hooks/useUser.tsx b/apps/mes/app/hooks/useUser.tsx
index fe2014e796..d2e92c3323 100644
--- a/apps/mes/app/hooks/useUser.tsx
+++ b/apps/mes/app/hooks/useUser.tsx
@@ -26,6 +26,7 @@ export function useUser(): User {
const data = useRouteData<{
company: unknown;
user: unknown;
+ effectiveUserId?: string;
}>(path.to.authenticatedRoot);
if (
@@ -36,6 +37,7 @@ export function useUser(): User {
) {
return {
...data.user,
+ id: data.effectiveUserId ?? data.user.id,
company: data.company
};
}
diff --git a/apps/mes/app/middleware/user.ts b/apps/mes/app/middleware/user.ts
index 5368dcd422..f67f1af051 100644
--- a/apps/mes/app/middleware/user.ts
+++ b/apps/mes/app/middleware/user.ts
@@ -2,6 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { MiddlewareFunction } from "react-router";
import { redirect } from "react-router";
import { userContext } from "~/context";
+import { getConsolePinIn } from "~/services/console.server";
import { getLocation, setLocation } from "~/services/location.server";
import { path } from "~/utils/path";
@@ -9,15 +10,26 @@ export const userMiddleware: MiddlewareFunction = async ({
context,
request
}) => {
- const { client, companyId, userId } = await requirePermissions(request, {});
+ const { client, companyId, userId, consoleMode } = await requirePermissions(
+ request,
+ {}
+ );
const { location, updated } = await getLocation(request, client, {
companyId,
userId
});
+ // Read pin-in state from cookies (console mode comes from auth session)
+ const pinIn = consoleMode ? getConsolePinIn(request, companyId) : null;
+
context.set(userContext, {
locationId: location,
- companyId
+ companyId,
+ consoleMode,
+ effectiveUserId: pinIn?.userId ?? userId,
+ pinnedInUser: pinIn
+ ? { userId: pinIn.userId, name: pinIn.name, avatarUrl: pinIn.avatarUrl }
+ : null
});
if (updated) {
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 6dee82e040..0ab7b3c1d3 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -6,7 +6,7 @@ import {
getCompanies,
getUser
} from "@carbon/auth";
-
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
destroyAuthSession,
requireAuthSession
@@ -31,10 +31,13 @@ import {
useNavigate
} from "react-router";
import { AppSidebar } from "~/components";
+import { ConsolePill } from "~/components/ConsolePill";
+import { PinInOverlay } from "~/components/PinInOverlay";
import RealtimeDataProvider from "~/components/RealtimeDataProvider";
import { TimeCardWarning } from "~/components/TimeCardWarning";
import { userContext } from "~/context";
import { userMiddleware } from "~/middleware/user";
+import { refreshConsolePinIn } from "~/services/console.server";
import { getActiveMaintenanceEventsCount } from "~/services/maintenance.service";
import {
getActiveJobCount,
@@ -81,23 +84,50 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
throw redirect(path.to.accountSettings);
}
- // Get the location from middleware context
- const locationId = context.get(userContext)?.locationId;
-
- let [companyPlan, locations, activeEvents, companySettings] =
- await Promise.all([
- getStripeCustomerByCompanyId(companyId, userId),
- getLocationsByCompany(client, companyId),
- getActiveJobCount(client, {
- employeeId: userId,
- companyId
- }),
- client
- .from("companySettings")
- .select("timeCardEnabled")
- .eq("id", companyId)
- .single()
- ]);
+ // Get the location and console state from middleware context
+ const ctx = context.get(userContext);
+ const locationId = ctx?.locationId;
+ const consoleMode = ctx?.consoleMode ?? false;
+ const pinnedInUser = ctx?.pinnedInUser ?? null;
+ const effectiveUserId = ctx?.effectiveUserId ?? userId;
+
+ const serviceRole = getCarbonServiceRole();
+
+ let [
+ companyPlan,
+ locations,
+ activeEvents,
+ companySettings,
+ openClockEntry,
+ locationEmployees
+ ] = await Promise.all([
+ getStripeCustomerByCompanyId(companyId, userId),
+ getLocationsByCompany(client, companyId),
+ getActiveJobCount(client, {
+ employeeId: effectiveUserId,
+ companyId
+ }),
+ client
+ .from("companySettings")
+ .select("timeCardEnabled, consoleEnabled")
+ .eq("id", companyId)
+ .single(),
+ getOpenClockEntry(client, effectiveUserId, companyId),
+ // Get employees at current location for console mode pin-in filtering
+ consoleMode && locationId
+ ? serviceRole
+ .from("employeeJob")
+ .select("id")
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ : Promise.resolve({ data: [] as { id: string }[] })
+ ]);
+
+ const locationEmployeeIds =
+ locationEmployees.data?.map((e: { id: string }) => e.id) ?? [];
+ const timeCardEnabled =
+ (companySettings.data as any)?.timeCardEnabled ?? false;
+ const consoleEnabled = (companySettings.data as any)?.consoleEnabled ?? false;
// Get active maintenance count after we have the location
const activeMaintenanceCount = await getActiveMaintenanceEventsCount(
@@ -113,25 +143,47 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
throw new Error(`No locations found for ${company.name}`);
}
- return data({
- session: {
- accessToken,
- expiresIn,
- expiresAt
+ // Sliding window: refresh pin-in cookie on every page load
+ const headers = new Headers();
+ if (pinnedInUser && ctx) {
+ headers.append(
+ "Set-Cookie",
+ refreshConsolePinIn(companyId, {
+ userId: pinnedInUser.userId,
+ name: pinnedInUser.name,
+ avatarUrl: pinnedInUser.avatarUrl,
+ pinnedAt: Date.now()
+ })
+ );
+ }
+
+ return data(
+ {
+ session: {
+ accessToken,
+ expiresIn,
+ expiresAt
+ },
+ activeEvents: activeEvents.data ?? 0,
+ activeMaintenanceCount: activeMaintenanceCount.count ?? 0,
+ company,
+ companies: companies.data ?? [],
+ consoleEnabled,
+ consoleMode: consoleEnabled && consoleMode,
+ location: locationId,
+ locationEmployeeIds,
+ locations: locations.data ?? [],
+ openClockEntry: openClockEntry?.data
+ ? getOpenClockEntry(client, userId, companyId)
+ : null,
+ effectiveUserId,
+ pinnedInUser,
+ plan: companyPlan?.planId,
+ timeCardEnabled,
+ user: user.data
},
- activeEvents: activeEvents.data ?? 0,
- activeMaintenanceCount: activeMaintenanceCount.count ?? 0,
- company,
- companies: companies.data ?? [],
- location: locationId,
- locations: locations.data ?? [],
- plan: companyPlan?.planId,
- user: user.data,
- timeCardEnabled: companySettings.data?.timeCardEnabled ?? false,
- openClockEntry: companySettings.data?.timeCardEnabled
- ? getOpenClockEntry(client, userId, companyId)
- : null
- });
+ headers.has("Set-Cookie") ? { headers } : undefined
+ );
}
export default function AuthenticatedRoute() {
@@ -141,11 +193,15 @@ export default function AuthenticatedRoute() {
activeMaintenanceCount,
company,
companies,
+ consoleEnabled,
+ consoleMode,
location,
+ locationEmployeeIds,
locations,
- user,
+ openClockEntry,
+ pinnedInUser,
timeCardEnabled,
- openClockEntry
+ user
} = useLoaderData<typeof loader>();
const navigate = useNavigate();
@@ -189,10 +245,13 @@ export default function AuthenticatedRoute() {
activeMaintenanceCount={activeMaintenanceCount}
company={company}
companies={companies}
+ consoleEnabled={consoleEnabled}
+ consoleMode={consoleMode}
location={location}
locations={locations}
- timeCardEnabled={timeCardEnabled}
openClockEntry={openClockEntry}
+ pinnedInUser={pinnedInUser}
+ timeCardEnabled={timeCardEnabled}
/>
<Outlet />
{timeCardEnabled && (
@@ -213,6 +272,22 @@ export default function AuthenticatedRoute() {
</Await>
</Suspense>
)}
+ {consoleMode && !pinnedInUser && (
+ <PinInOverlay
+ companyId={company.companyId!}
+ locationEmployeeIds={locationEmployeeIds}
+ sessionUserId={user?.id ?? ""}
+ hasPinnedUser={false}
+ />
+ )}
+ {consoleMode && pinnedInUser && (
+ <ConsolePill
+ user={pinnedInUser}
+ companyId={company.companyId!}
+ locationEmployeeIds={locationEmployeeIds}
+ sessionUserId={user?.id ?? ""}
+ />
+ )}
</TooltipProvider>
</SidebarProvider>
</RealtimeDataProvider>
diff --git a/apps/mes/app/routes/x+/console.add-operator.tsx b/apps/mes/app/routes/x+/console.add-operator.tsx
new file mode 100644
index 0000000000..5dff40f4ba
--- /dev/null
+++ b/apps/mes/app/routes/x+/console.add-operator.tsx
@@ -0,0 +1,158 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { userContext } from "~/context";
+
+export async function action({ request, context }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {
+ create: "users"
+ });
+
+ const formData = await request.formData();
+ const firstName = (formData.get("firstName") as string)?.trim();
+ const lastName = (formData.get("lastName") as string)?.trim();
+ const pin = (formData.get("pin") as string)?.trim() || null;
+
+ if (!firstName || !lastName) {
+ return data(
+ { success: false, message: "First name and last name are required" },
+ { status: 400 }
+ );
+ }
+
+ if (!pin || !/^\d{4}$/.test(pin)) {
+ return data(
+ {
+ success: false,
+ message: "PIN is required and must be exactly 4 digits"
+ },
+ { status: 400 }
+ );
+ }
+
+ const locationId = context.get(userContext)?.locationId;
+ if (!locationId) {
+ return data(
+ { success: false, message: "No location selected" },
+ { status: 400 }
+ );
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+ const operatorId = crypto.randomUUID();
+ const syntheticEmail = `${operatorId}@console.internal`;
+
+ // Get the "Console Operator" employee type (created by migration)
+ const operatorType = await serviceRole
+ .from("employeeType")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("name", "Console Operator")
+ .single();
+
+ if (operatorType.error || !operatorType.data) {
+ return data(
+ {
+ success: false,
+ message: "Console Operator employee type not found. Contact an admin."
+ },
+ { status: 500 }
+ );
+ }
+
+ const employeeTypeId = operatorType.data.id;
+
+ // 1. Insert user record (no Supabase Auth)
+ const userInsert = await serviceRole
+ .from("user")
+ .insert({
+ id: operatorId,
+ email: syntheticEmail,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ active: true,
+ isConsoleOperator: true
+ } as any)
+ .select("id")
+ .single();
+
+ if (userInsert.error) {
+ return data(
+ { success: false, message: userInsert.error.message },
+ { status: 500 }
+ );
+ }
+
+ // 2. Parallel inserts: employee, employeeJob, userToCompany
+ const [employeeInsert, jobInsert, companyInsert] = await Promise.all([
+ serviceRole
+ .from("employee")
+ .insert({
+ id: operatorId,
+ employeeTypeId,
+ active: true,
+ companyId,
+ pin
+ } as any)
+ .select("id")
+ .single(),
+ serviceRole
+ .from("employeeJob")
+ .insert({
+ id: operatorId,
+ companyId,
+ locationId
+ })
+ .select("id")
+ .single(),
+ serviceRole
+ .from("userToCompany")
+ .insert({ userId: operatorId, companyId, role: "employee" as const })
+ .select("userId")
+ .single()
+ ]);
+
+ // 3. Check each result — rollback user if any failed
+ if (employeeInsert.error) {
+ await serviceRole.from("user").delete().eq("id", operatorId);
+ return data(
+ { success: false, message: employeeInsert.error.message },
+ { status: 500 }
+ );
+ }
+
+ if (jobInsert.error) {
+ await serviceRole.from("employee").delete().eq("id", operatorId);
+ await serviceRole.from("user").delete().eq("id", operatorId);
+ return data(
+ { success: false, message: jobInsert.error.message },
+ { status: 500 }
+ );
+ }
+
+ if (companyInsert.error) {
+ console.error(
+ "Failed to link console operator to company:",
+ companyInsert.error
+ );
+ }
+
+ const name = `${firstName} ${lastName}`;
+
+ await updateSubscriptionQuantityForCompany(companyId);
+
+ return data({
+ success: true,
+ operator: {
+ id: operatorId,
+ name,
+ avatarUrl: null,
+ pin
+ }
+ });
+}
diff --git a/apps/mes/app/routes/x+/console.pin-in.tsx b/apps/mes/app/routes/x+/console.pin-in.tsx
new file mode 100644
index 0000000000..1f146b6e79
--- /dev/null
+++ b/apps/mes/app/routes/x+/console.pin-in.tsx
@@ -0,0 +1,75 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { setConsolePinIn } from "~/services/console.server";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const userId = formData.get("userId") as string;
+ const name = formData.get("name") as string;
+ const avatarUrl = (formData.get("avatarUrl") as string) || null;
+ const pin = (formData.get("pin") as string) || null;
+
+ if (!userId || !name) {
+ return data({ error: "userId and name are required" }, { status: 400 });
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+
+ // Validate user exists and is active
+ const userCheck = await serviceRole
+ .from("user")
+ .select("id, active")
+ .eq("id", userId)
+ .single();
+
+ if (userCheck.error || !userCheck.data?.active) {
+ return data({ error: "User not found or inactive" }, { status: 400 });
+ }
+
+ const employeeCheck = await serviceRole
+ .from("employee")
+ .select("*")
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (employeeCheck.error || !employeeCheck.data) {
+ return data(
+ { error: "Employee not found in this company" },
+ { status: 400 }
+ );
+ }
+
+ const storedPin: string | null = (employeeCheck.data as any)?.pin ?? null;
+
+ if (!storedPin) {
+ return data(
+ {
+ error: "No PIN set. Please set a PIN in your account settings."
+ },
+ { status: 400 }
+ );
+ }
+
+ if (!pin || pin !== storedPin) {
+ return data({ error: "Incorrect PIN" }, { status: 400 });
+ }
+
+ throw redirect(path.to.authenticatedRoot, {
+ headers: {
+ "Set-Cookie": setConsolePinIn(companyId, {
+ userId,
+ name,
+ avatarUrl,
+ pinnedAt: Date.now()
+ })
+ }
+ });
+}
diff --git a/apps/mes/app/routes/x+/console.pin-out.tsx b/apps/mes/app/routes/x+/console.pin-out.tsx
new file mode 100644
index 0000000000..f236dc5b8d
--- /dev/null
+++ b/apps/mes/app/routes/x+/console.pin-out.tsx
@@ -0,0 +1,17 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { clearConsolePinIn } from "~/services/console.server";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {});
+
+ throw redirect(path.to.authenticatedRoot, {
+ headers: {
+ "Set-Cookie": clearConsolePinIn(companyId)
+ }
+ });
+}
diff --git a/apps/mes/app/routes/x+/console.toggle.tsx b/apps/mes/app/routes/x+/console.toggle.tsx
new file mode 100644
index 0000000000..2b047adfdb
--- /dev/null
+++ b/apps/mes/app/routes/x+/console.toggle.tsx
@@ -0,0 +1,41 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { updateSessionConsole } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { clearConsolePinIn } from "~/services/console.server";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const enabled = formData.get("consoleMode") === "true";
+
+ // Only allow enabling if company has console mode turned on
+ if (enabled) {
+ const settings = await client
+ .from("companySettings")
+ .select("consoleEnabled")
+ .eq("id", companyId)
+ .single();
+
+ if (!settings.data?.consoleEnabled) {
+ throw new Response("Console mode is not enabled", { status: 403 });
+ }
+ }
+
+ const headers = new Headers();
+ headers.append(
+ "Set-Cookie",
+ await updateSessionConsole(request, enabled ? companyId : undefined)
+ );
+
+ // When disabling console mode, also clear any active pin-in
+ if (!enabled) {
+ headers.append("Set-Cookie", clearConsolePinIn(companyId));
+ }
+
+ throw redirect(path.to.authenticatedRoot, { headers });
+}
diff --git a/apps/mes/app/routes/x+/end-shift.tsx b/apps/mes/app/routes/x+/end-shift.tsx
index a753d476ff..edad0b479e 100644
--- a/apps/mes/app/routes/x+/end-shift.tsx
+++ b/apps/mes/app/routes/x+/end-shift.tsx
@@ -1,11 +1,16 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { getLocalTimeZone, now } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
+import { clearConsolePinIn } from "~/services/console.server";
import { endProductionEvents } from "~/services/operations.service";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {});
+ const { client, companyId, userId, consoleMode } = await requirePermissions(
+ request,
+ {}
+ );
const formData = await request.formData();
const timezone = formData.get("timezone") as string | null;
@@ -22,5 +27,38 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- return { success: true, message: "Successfully ended shift" };
+ // Clock out the operator if time card is enabled
+ const serviceRole = await getCarbonServiceRole();
+ const settings = await serviceRole
+ .from("companySettings")
+ .select("*")
+ .eq("id", companyId)
+ .single();
+
+ if ((settings.data as any)?.timeCardEnabled) {
+ const clockOutResult = await serviceRole
+ .from("timeCardEntry")
+ .update({
+ clockOut: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),
+ updatedBy: userId
+ } as any)
+ .eq("employeeId", userId)
+ .eq("companyId", companyId)
+ .is("clockOut", null);
+
+ if (clockOutResult.error) {
+ console.error("Failed to clock out on end shift:", clockOutResult.error);
+ }
+ }
+
+ // In console mode, pin out the operator after ending their shift
+ const headers = new Headers();
+ if (consoleMode) {
+ headers.append("Set-Cookie", clearConsolePinIn(companyId));
+ }
+
+ return data(
+ { success: true, message: "Successfully ended shift" },
+ headers.has("Set-Cookie") ? { headers } : undefined
+ );
}
diff --git a/apps/mes/app/services/console.server.ts b/apps/mes/app/services/console.server.ts
new file mode 100644
index 0000000000..76890391c8
--- /dev/null
+++ b/apps/mes/app/services/console.server.ts
@@ -0,0 +1,63 @@
+import * as cookie from "cookie";
+
+const CONSOLE_PIN_PREFIX = "console-pin-";
+const CONSOLE_PIN_MAX_AGE = 60 * 60; // 1 hour in seconds
+const CONSOLE_PIN_MAX_AGE_MS = CONSOLE_PIN_MAX_AGE * 1000;
+
+// --- Console Pin-In State ---
+
+export interface ConsolePinIn {
+ userId: string;
+ name: string;
+ avatarUrl: string | null;
+ pinnedAt: number; // unix timestamp ms
+}
+
+export function getConsolePinIn(
+ request: Request,
+ companyId: string
+): ConsolePinIn | null {
+ const cookieHeader = request.headers.get("cookie");
+ if (!cookieHeader) return null;
+
+ const raw = cookie.parse(cookieHeader)[`${CONSOLE_PIN_PREFIX}${companyId}`];
+ if (!raw) return null;
+
+ try {
+ const parsed: ConsolePinIn = JSON.parse(raw);
+ // Check manual expiry (defense-in-depth alongside cookie maxAge)
+ const elapsed = Date.now() - parsed.pinnedAt;
+ if (elapsed > CONSOLE_PIN_MAX_AGE_MS) return null;
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
+export function setConsolePinIn(companyId: string, data: ConsolePinIn): string {
+ return cookie.serialize(
+ `${CONSOLE_PIN_PREFIX}${companyId}`,
+ JSON.stringify(data),
+ {
+ path: "/",
+ maxAge: CONSOLE_PIN_MAX_AGE
+ }
+ );
+}
+
+export function clearConsolePinIn(companyId: string): string {
+ return cookie.serialize(`${CONSOLE_PIN_PREFIX}${companyId}`, "", {
+ path: "/",
+ maxAge: 0
+ });
+}
+
+export function refreshConsolePinIn(
+ companyId: string,
+ existing: ConsolePinIn
+): string {
+ return setConsolePinIn(companyId, {
+ ...existing,
+ pinnedAt: Date.now()
+ });
+}
diff --git a/apps/mes/app/types/index.ts b/apps/mes/app/types/index.ts
index 796e228d7b..8438462ee2 100644
--- a/apps/mes/app/types/index.ts
+++ b/apps/mes/app/types/index.ts
@@ -3,7 +3,16 @@ export type ListItem = {
name: string;
};
+export type PinnedInUser = {
+ userId: string;
+ name: string;
+ avatarUrl: string | null;
+};
+
export type UserContext = {
locationId: string;
companyId: string;
+ consoleMode: boolean;
+ effectiveUserId: string;
+ pinnedInUser: PinnedInUser | null;
};
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 9217d4f96f..acab103737 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -96,6 +96,10 @@ export const path = {
companySwitch: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
complete: `${x}/complete`,
+ consoleAddOperator: `${x}/console/add-operator`,
+ consolePinIn: `${x}/console/pin-in`,
+ consolePinOut: `${x}/console/pin-out`,
+ consoleToggle: `${x}/console/toggle`,
convertEntity: (id: string) => generatePath(`${x}/entity/${id}/convert`),
endShift: `${x}/end-shift`,
endOperation: (id: string) => generatePath(`${x}/end/${id}`),
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index 0e2b3f7153..c851d525a9 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -114,6 +114,46 @@ function makeAuthSession(
};
}
+/**
+ * Determines the effective user based on console mode and pin-in state.
+ * If console mode is on and an operator is pinned in, returns
+ * the operator's ID. Otherwise returns the session user's ID.
+ *
+ * Console mode is read from the auth session; pin-in state is
+ * still read from the `console-pin-{companyId}` cookie.
+ */
+function getEffectiveUser(
+ request: Request,
+ companyId: string,
+ sessionUserId: string,
+ consoleMode: boolean
+): string {
+ if (!consoleMode) return sessionUserId;
+
+ const cookieHeader = request.headers.get("cookie");
+ if (!cookieHeader) return sessionUserId;
+
+ // Parse only the pin-in cookie we need
+ const cookies = Object.fromEntries(
+ cookieHeader.split(";").map((c) => {
+ const [key, ...rest] = c.trim().split("=");
+ return [key, decodeURIComponent(rest.join("="))];
+ })
+ );
+
+ const pinRaw = cookies[`console-pin-${companyId}`];
+ if (!pinRaw) return sessionUserId;
+
+ try {
+ const pinIn = JSON.parse(pinRaw);
+ const elapsed = Date.now() - pinIn.pinnedAt;
+ if (elapsed > 3600000) return sessionUserId;
+ return pinIn.userId ?? sessionUserId;
+ } catch {
+ return sessionUserId;
+ }
+}
+
export async function requirePermissions(
request: Request,
requiredPermissions: {
@@ -129,6 +169,8 @@ export async function requirePermissions(
companyId: string;
email: string;
userId: string;
+ sessionUserId: string;
+ consoleMode: boolean;
}> {
const apiKey = request.headers.get("carbon-key");
if (apiKey) {
@@ -203,13 +245,16 @@ export async function requirePermissions(
client,
companyId,
userId,
- email: ""
+ sessionUserId: userId,
+ email: "",
+ consoleMode: false
};
}
}
- const { accessToken, companyId, email, userId } =
- await requireAuthSession(request);
+ const authSession = await requireAuthSession(request);
+ const { accessToken, companyId, email, userId } = authSession;
+ const consoleMode = authSession.console === companyId;
const myClaims = await getUserClaims(userId, companyId);
@@ -222,7 +267,9 @@ export async function requirePermissions(
: getCarbon(accessToken),
companyId,
email,
- userId
+ userId: getEffectiveUser(request, companyId, userId, consoleMode),
+ sessionUserId: userId,
+ consoleMode
};
}
@@ -277,7 +324,9 @@ export async function requirePermissions(
: getCarbon(accessToken),
companyId,
email,
- userId
+ userId: getEffectiveUser(request, companyId, userId, consoleMode),
+ sessionUserId: userId,
+ consoleMode
};
}
diff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.ts
index a5ea4bffb0..df832b6a78 100644
--- a/packages/auth/src/services/session.server.ts
+++ b/packages/auth/src/services/session.server.ts
@@ -171,6 +171,11 @@ export async function refreshAuthSession(
authSession?.companyId
);
+ // Preserve console mode across token refresh
+ if (refreshedAuthSession && authSession?.console) {
+ refreshedAuthSession.console = authSession.console;
+ }
+
if (!refreshedAuthSession) {
const redirectUrl = `${path.to.login}?${makeRedirectToFromHere(request)}`;
@@ -204,6 +209,23 @@ export async function refreshAuthSession(
return refreshedAuthSession;
}
+export async function updateSessionConsole(
+ request: Request,
+ consoleCompanyId: string | undefined
+) {
+ const session = await getSession(request);
+ const authSession = await getAuthSession(request);
+
+ if (authSession) {
+ session.set(SESSION_KEY, {
+ ...authSession,
+ console: consoleCompanyId
+ });
+ }
+
+ return sessionStorage.commitSession(session, { maxAge: SESSION_MAX_AGE });
+}
+
export async function updateCompanySession(
request: Request,
companyId: string
diff --git a/packages/auth/src/types.ts b/packages/auth/src/types.ts
index e69d3e73da..b5ecb65ef4 100644
--- a/packages/auth/src/types.ts
+++ b/packages/auth/src/types.ts
@@ -8,6 +8,7 @@ export interface AuthSession {
email: string;
expiresIn: number;
expiresAt: number;
+ console?: string;
}
export type Company = NonNullable<
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b19658e1bf..5a03a0af14 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -38808,6 +38808,9 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active",
},
+ {
+ $ref: "#/parameters/rowFilter.employee.pin",
+ },
{
$ref: "#/parameters/select",
},
@@ -38879,6 +38882,9 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active",
},
+ {
+ $ref: "#/parameters/rowFilter.employee.pin",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -38904,6 +38910,9 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active",
},
+ {
+ $ref: "#/parameters/rowFilter.employee.pin",
+ },
{
$ref: "#/parameters/body.employee",
},
@@ -50199,6 +50208,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.flags",
},
+ {
+ $ref: "#/parameters/rowFilter.user.isConsoleOperator",
+ },
{
$ref: "#/parameters/select",
},
@@ -50300,6 +50312,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.flags",
},
+ {
+ $ref: "#/parameters/rowFilter.user.isConsoleOperator",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -50355,6 +50370,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.flags",
},
+ {
+ $ref: "#/parameters/rowFilter.user.isConsoleOperator",
+ },
{
$ref: "#/parameters/body.user",
},
@@ -63006,6 +63024,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.consoleEnabled",
+ },
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
},
@@ -63167,6 +63188,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.consoleEnabled",
+ },
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
},
@@ -63282,6 +63306,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.consoleEnabled",
+ },
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
},
@@ -87967,6 +87994,10 @@ export default {
format: "boolean",
type: "boolean",
},
+ pin: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -93654,6 +93685,7 @@ export default {
"createdAt",
"acknowledgedITAR",
"flags",
+ "isConsoleOperator",
],
properties: {
id: {
@@ -93720,6 +93752,11 @@ export default {
flags: {
format: "jsonb",
},
+ isConsoleOperator: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
},
type: "object",
},
@@ -99907,6 +99944,7 @@ export default {
"jobTravelerIncludeWorkInstructions",
"supplierApproval",
"qualityIssueTarget",
+ "consoleEnabled",
"timeCardEnabled",
],
properties: {
@@ -100098,6 +100136,11 @@ export default {
format: "integer",
type: "integer",
},
+ consoleEnabled: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
timeCardEnabled: {
default: false,
format: "boolean",
@@ -120992,6 +121035,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.employee.pin": {
+ name: "pin",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.activeMaintenanceDispatchesByLocation": {
name: "activeMaintenanceDispatchesByLocation",
description: "activeMaintenanceDispatchesByLocation",
@@ -127562,6 +127611,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.user.isConsoleOperator": {
+ name: "isConsoleOperator",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.companyAccountsReceivableBillingAddress": {
name: "companyAccountsReceivableBillingAddress",
description: "companyAccountsReceivableBillingAddress",
@@ -134648,6 +134703,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companySettings.consoleEnabled": {
+ name: "consoleEnabled",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.companySettings.timeCardEnabled": {
name: "timeCardEnabled",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 885db02121..b5e7a18ba2 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2923,6 +2923,7 @@ export type Database = {
accountsPayableEmail: string | null
accountsReceivableAddress: boolean | null
accountsReceivableEmail: string | null
+ consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
digitalQuoteEnabled: boolean
@@ -2959,6 +2960,7 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
+ consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
@@ -2995,6 +2997,7 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
+ consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
@@ -6794,18 +6797,21 @@ export type Database = {
companyId: string
employeeTypeId: string
id: string
+ pin: string | null
}
Insert: {
active?: boolean
companyId: string
employeeTypeId: string
id?: string
+ pin?: string | null
}
Update: {
active?: boolean
companyId?: string
employeeTypeId?: string
id?: string
+ pin?: string | null
}
Relationships: [
{
@@ -40619,6 +40625,7 @@ export type Database = {
flags: Json
fullName: string | null
id: string
+ isConsoleOperator: boolean
lastName: string
updatedAt: string | null
}
@@ -40635,6 +40642,7 @@ export type Database = {
flags?: Json
fullName?: string | null
id: string
+ isConsoleOperator?: boolean
lastName?: string
updatedAt?: string | null
}
@@ -40651,6 +40659,7 @@ export type Database = {
flags?: Json
fullName?: string | null
id?: string
+ isConsoleOperator?: boolean
lastName?: string
updatedAt?: string | null
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 885db02121..b5e7a18ba2 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2923,6 +2923,7 @@ export type Database = {
accountsPayableEmail: string | null
accountsReceivableAddress: boolean | null
accountsReceivableEmail: string | null
+ consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
digitalQuoteEnabled: boolean
@@ -2959,6 +2960,7 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
+ consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
@@ -2995,6 +2997,7 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
+ consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
digitalQuoteEnabled?: boolean
@@ -6794,18 +6797,21 @@ export type Database = {
companyId: string
employeeTypeId: string
id: string
+ pin: string | null
}
Insert: {
active?: boolean
companyId: string
employeeTypeId: string
id?: string
+ pin?: string | null
}
Update: {
active?: boolean
companyId?: string
employeeTypeId?: string
id?: string
+ pin?: string | null
}
Relationships: [
{
@@ -40619,6 +40625,7 @@ export type Database = {
flags: Json
fullName: string | null
id: string
+ isConsoleOperator: boolean
lastName: string
updatedAt: string | null
}
@@ -40635,6 +40642,7 @@ export type Database = {
flags?: Json
fullName?: string | null
id: string
+ isConsoleOperator?: boolean
lastName?: string
updatedAt?: string | null
}
@@ -40651,6 +40659,7 @@ export type Database = {
flags?: Json
fullName?: string | null
id?: string
+ isConsoleOperator?: boolean
lastName?: string
updatedAt?: string | null
}
diff --git a/packages/database/supabase/migrations/20260319000000_console-mode.sql b/packages/database/supabase/migrations/20260319000000_console-mode.sql
new file mode 100644
index 0000000000..8981aaaf6e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260319000000_console-mode.sql
@@ -0,0 +1,55 @@
+-- Console mode: allow creating lightweight "console operators" who can pin in at
+-- shared MES terminals without needing email, password, or Supabase Auth accounts.
+ALTER TABLE "user" ADD COLUMN "isConsoleOperator" BOOLEAN NOT NULL DEFAULT false;
+
+-- PIN for console mode authentication (4-digit numeric code).
+-- Stored on employee (per-company) so the same user could have different PINs
+-- at different companies. NULL means no PIN set.
+ALTER TABLE "employee" ADD COLUMN "pin" TEXT;
+
+-- Feature toggle: enable console mode for this company.
+-- When enabled, the "Console Operator" employee type is created,
+-- the Operators submodule appears in ERP, and the
+-- Console Mode toggle appears in MES.
+ALTER TABLE "companySettings" ADD COLUMN "consoleEnabled" BOOLEAN NOT NULL DEFAULT false;
+
+-- Update the auth trigger to use ON CONFLICT for the user insert.
+-- This handles converting console operators (who already have a public.user record)
+-- to full users (which creates an auth.users entry that fires this trigger).
+CREATE OR REPLACE FUNCTION public.create_public_user()
+RETURNS TRIGGER AS $$
+DECLARE
+ full_name TEXT;
+ name_parts TEXT[];
+BEGIN
+ full_name := NEW.raw_user_meta_data->>'name';
+
+ IF full_name IS NOT NULL THEN
+ name_parts := regexp_split_to_array(full_name, '\s+');
+ INSERT INTO public."user" ("id", "email", "active", "firstName", "lastName", "about")
+ VALUES (
+ NEW.id,
+ NEW.email,
+ true,
+ COALESCE(name_parts[1], ''),
+ COALESCE(array_to_string(name_parts[2:], ' '), ''),
+ ''
+ )
+ ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;
+ ELSE
+ INSERT INTO public."user" ("id", "email", "active", "firstName", "lastName", "about")
+ VALUES (
+ NEW.id,
+ NEW.email,
+ true,
+ '',
+ '',
+ ''
+ )
+ ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;
+ END IF;
+
+ INSERT INTO public."userPermission" (id) VALUES (NEW.id) ON CONFLICT DO NOTHING;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;