Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(mes): phone layout — app bar, More sheet, tab bar, measured bottom bars and a materials list
aashuabc7f3049cd0
diff --git a/.ai/plans/2026-10-07-mes-phone-layout.md b/.ai/plans/2026-10-07-mes-phone-layout.mdnew file mode 100644index 0000000000..95e5a3f0a5--- /dev/null+++ b/.ai/plans/2026-10-07-mes-phone-layout.md@@ -0,0 +1,80 @@+# MES phone layout — implementation plan++**Spec / source:** `.ai/specs/2026-10-07-mes-phone-layout.md`+**Branch:** `feat/mobile-redesign`++## Progress+- [x] Task 1: Schedule toolbar wraps on phones+- [x] Task 2: Board column width and card thumbnail tile+- [x] Task 3: Active and Recent card thumbnail tile+- [x] Task 4: Jobs list rows on phones+- [x] Task 5: Maintenance toolbar stacks on phones+- [x] Task 6: My Hours table scrolls inside its card on phones+- [x] Task 7: Picking detail header wraps+- [x] Task 8: Operation tabs on their own row+- [x] Task 9: Assembly and Inspection header strips scroll (no change: both already fit at 393px)+- [x] Task 10: Verify (typecheck, Biome, browser at 393px and 1280px)++## Dependencies+Tasks 1–9 are independent. Task 10 needs Tasks 1–9.++🛑 Never commit. Keep every element a screen shows. Use `max-md:` for style-only changes.++---++## Task 1: Schedule toolbar wraps on phones+**Files:** Modify `apps/mes/app/routes/x+/operations.tsx` (toolbar `HStack` under the header), and the same toolbar in `apps/mes/app/routes/x+/assigned.tsx`.+**Steps:**+1. Add `max-md:flex-wrap max-md:gap-2` to the outer toolbar `HStack` and the inner `HStack`.+2. Give the search `max-md:flex-1 max-md:min-w-0`.+**Verify:** At 393px on `/x/operations`, `document.documentElement.scrollWidth` is 393.++## Task 2: Board column width and card thumbnail tile+**Files:** Modify `apps/mes/app/components/Kanban/components/ColumnCard.tsx`, `apps/mes/app/components/Kanban/components/ItemCard.tsx`.+**Steps:**+1. Column: add `max-md:w-[300px]`.+2. Card: render the thumbnail a second time as a 40px tile (`hidden max-md:block size-10 shrink-0 rounded-md object-cover`) at the start of the header row. Give the large thumbnail wrapper `max-md:hidden`. Both obey `showThumbnail`.+**Verify:** At 393px a Schedule card is under 300px tall.++## Task 3: Active and Recent card thumbnail tile+**Files:** Modify `apps/mes/app/components/OperationsList.tsx`.+**Steps:** Apply the Task 2 thumbnail rule to the operation card.+**Verify:** At 393px on `/x/active`, two cards show in the first screen.++## Task 4: Jobs list rows on phones+**Files:** Modify `apps/mes/app/routes/x+/jobs.tsx`.+**Steps:**+1. Wrap the table in `max-md:hidden`.+2. Add a `hidden max-md:block` list. Each row is a `Link` to the job with the same 8 fields the table cells render, reusing the same cell content (status, deadline, `DateTime`, `EmployeeAvatar`).+**Verify:** At 393px every field shows; at 1280px the table is unchanged.++## Task 5: Maintenance toolbar stacks on phones+**Files:** Modify `apps/mes/app/routes/x+/maintenance.tsx`.+**Steps:** On the tabs/search `HStack` add `max-md:flex-col max-md:items-stretch`. Give the `TabsList` `max-md:w-full max-md:justify-start max-md:overflow-x-auto scrollbar-hide`.+**Verify:** At 393px no horizontal page scroll.++## Task 6: My Hours rows on phones+**Files:** Modify `apps/mes/app/routes/x+/timecard.tsx`.+**Steps:** Wrap `TableBase` in `max-md:overflow-x-auto max-md:-mx-6 max-md:px-6` and give it `max-md:min-w-[560px]`. The in-place row editor stays as it is.+**Verify:** At 393px no horizontal page scroll.++## Task 7: Picking detail header wraps+**Files:** Modify `apps/mes/app/routes/x+/picking.$pickingListId.tsx`.+**Steps:** Let the header row wrap on phones (`max-md:flex-wrap max-md:h-auto max-md:py-2`).+**Verify:** At 393px Finish is fully visible.++## Task 8: Operation tabs on their own row+**Files:** Modify `apps/mes/app/components/JobOperation/JobOperation.tsx` (header, about line 799).+**Steps:** On phones let the header wrap: the `TabsList` takes `max-md:order-last max-md:w-full max-md:ml-0 max-md:overflow-x-auto`, and the header becomes `max-md:h-auto max-md:flex-wrap max-md:py-1`.+**Verify:** At 393px all four tabs are visible or reachable by sideways scroll.++## Task 9: Assembly and Inspection header strips scroll+**Files:** Modify `apps/mes/app/components/AssemblyView.tsx`, `apps/mes/app/components/Inspection/InspectionView.tsx` (header strips).+**Steps:** Give the header control group `max-md:overflow-x-auto scrollbar-hide` and its children `shrink-0`.+**Verify:** At 393px no control is clipped; the strip scrolls.++## Task 10: Verify+1. `pnpm exec turbo run typecheck --filter=mes` — expected: success.+2. `pnpm exec biome check` on the changed files — expected: no errors.+3. Browser at 393px: re-take the screenshots of the changed screens and check `scrollWidth`.+4. Browser at 1280px: Schedule, Jobs, Operation look as before.diff --git a/.ai/plans/2026-10-07-mes-phone-round-2.md b/.ai/plans/2026-10-07-mes-phone-round-2.mdnew file mode 100644index 0000000000..6a80bac8cd--- /dev/null+++ b/.ai/plans/2026-10-07-mes-phone-round-2.md@@ -0,0 +1,2519 @@+# MES phone layout, round 2 — implementation plan++**Spec / source:** .ai/specs/2026-10-07-mes-phone-round-2.md+**Branch:** feat/mobile-redesign++## Progress+- [x] Task 1: Capture the baseline screenshots+- [x] Task 2: Add the shared TabBar to @carbon/react and point the ERP tab bar at it+- [x] Task 3: Export the queue list and add the origin helpers+- [x] Task 4: Fix the phone Navigation sheet+- [x] Task 5: Create MesAppBar+- [x] Task 6: Create MesTabBar, mount it, and turn on safe areas+- [x] Task 7: Move the 7 queue pages onto MesAppBar and rename 2 titles+- [x] Task 8: Pass the origin from every operation link+- [x] Task 9: Operation header: MesAppBar and Back to the origin+- [x] Task 10: Inspection, Assembly and Job detail headers on MesAppBar+- [x] Task 11: My Hours: app bar, bottom Clock bar and entry rows+- [x] Task 12: Board work cards in 2 columns+- [x] Task 13: List work cards in 2 columns with the right colours+- [x] Task 14: Schedule toolbar in 1 row+- [x] Task 15: Assigned, Active and Recent toolbars+- [x] Task 16: Board columns on phones+- [x] Task 17: Operation context row scrolls with the content+- [x] Task 18: Operation meters in 1 row and the grouped quantity card+- [x] Task 19: Operation dock: open on the running timer and show its labels+- [x] Task 20: Picking detail on phones+- [x] Task 21: Smaller fixes on Picking list, Jobs and Maintenance+- [x] Task 22: Inspection task screen on phones+- [x] Task 23: Operation materials as row cards on phones+- [x] Task 24: Job graph top to bottom on phones+- [x] Task 25: Maintenance dispatch: app bar, Complete button and confirmation+- [x] Task 26: Empty states on phones+- [x] Task 27: Extract strings, typecheck and Biome+- [x] Task 28: Verify in the browser at 393×852 and 1280×800++## Dependencies++Run Task 1 before any source edit. It records the "before" screenshots for acceptance criteria 16 and 17.++| Wave | Tasks (parallel inside a wave) | Needs |+|---|---|---|+| 1 | 2, 3, 4, 5, 16, 24 | Task 1 |+| 2 | 6, 7, 8, 9, 10, 20, 25 | 6 needs 2 and 3. 7, 20 and 25 need 5. 8 needs 3. 9 and 10 need 3 and 5. |+| 3 | 11, 12, 13, 14, 15, 17, 21, 22 | 11 needs 5 and 6. 12 and 13 need 8. 14, 15 and 21 need 7. 17 needs 9. 22 needs 10. |+| 4 | 18 | 17 |+| 5 | 19 | 18 |+| 6 | 23, 26 | 23 needs 19. 26 needs 14, 15 and 21. |+| 7 | 27 | 1–26 |+| 8 | 28 | 27 |++The tasks inside one wave touch disjoint files. These chains must stay in order because they edit the same file:++- `apps/mes/app/components/JobOperation/JobOperation.tsx` (about 3400 lines): 9 → 17 → 18 → 19 → 23. Never run 2 of these at the same time.+- `apps/mes/app/components/Inspection/InspectionView.tsx`: 10 → 22.+- `apps/mes/app/components/OperationsList.tsx`: 8 → 13. `ItemCard.tsx`: 8 → 12.+- `operations.tsx`: 7 → 14 → 26. `active.tsx`: 7 → 15 → 26. `jobs.tsx`, `maintenance.tsx`, `picking._index.tsx`: 7 → 21 → 26.++Notes for every task:++- 🛑 Never run `git commit`, `git stash` or `git reset`. The owner commits by hand.+- New files: the license fixer skips untracked files (it reads `git ls-files --cached`). Instead of running it, paste the 3-line AGPL header from the top of `apps/mes/app/components/MesAppBar.tsx` as the first lines of the new file.+- Line numbers come from the working tree on 2026-10-07, before this plan. After an earlier task edits the same file, find each snippet by its text.+- Phone-only styles use `max-md:`. The dock and toggle labels in Task 19 use `max-lg:`, because the spec says "below 1024px".+- At 768px and up, nothing may change except these 4 approved items:+ - the Back label and target (Tasks 8, 9);+ - the titles "Assigned" and "Jobs" (Task 7);+ - the timer toggle default (Task 19);+ - the dispatch Complete confirmation (Task 25).+- Every new user-facing string uses `useLingui().t` or `<Trans>` from `@lingui/react/macro`. Task 27 runs the extraction once.+- Never override Radix internals. Never change the green Start, the red Pause or the dock actions.+- **Correction to spec 1.5 (origin mechanism).** The spec says `state={{ from }}`. React Router drops `location.state` on every loader redirect: `startRedirectNavigation` builds the new location with only `{ _isRedirect: true }` (`node_modules/.pnpm/[email protected][email protected][email protected][email protected]/node_modules/react-router/dist/development/chunk-OB3PAWPO.mjs:2967-2969`). The operation loader redirects to Assembly and Inspection (`apps/mes/app/routes/x+/operation.$operationId.tsx:164-169`) and adds `trackedEntityId` (`:296-298`). Each of these redirects keeps `url.search`. So this plan carries the origin in a `from` search parameter instead of `state`. The behaviour is the one the spec asks for, and it also survives a reload.++---+## Task 1: Capture the baseline screenshots++**Depends on:** none+**Files:**+- Create: `${TMPDIR:-/tmp}/mes-round2/before/*.png` and `${TMPDIR:-/tmp}/mes-round2/urls.txt` (scratch, outside the repo)+- Copy from (precedent): `.claude/skills/auth/SKILL.md`++**Steps:**+1. 🛑 Do this task before any source edit. If a source file already shows a change from this plan, STOP and report.+2. Read the URLs. Run `grep '^ERP_URL' .env.local` and `grep '^MES_URL' .env.local`.+3. If the MES URL does not answer (`curl -s -o /dev/null -w '%{http_code}' "$MES_URL/login"` is not 200), STOP and report.+4. Run `mkdir -p "${TMPDIR:-/tmp}/mes-round2/before"`.+5. Log in with `agent-browser`. Follow `.claude/skills/auth/SKILL.md` steps 2 to 4 exactly. Use one browser session only.+6. Run `agent-browser set viewport 1280 800 1`.+7. Open `${MES_URL}/x/operations`. Wait 3 seconds (`agent-browser wait 3000`). Run `agent-browser screenshot "${TMPDIR:-/tmp}/mes-round2/before/desktop-schedule.png"`.+8. Do step 7 again for `/x/assigned` (`desktop-assigned.png`) and `/x/jobs` (`desktop-jobs.png`).+9. Find an operation link on Schedule: `agent-browser eval '[...document.querySelectorAll("a[href*=\"/x/operation/\"]")].slice(0,15).map(a=>a.getAttribute("href"))'`.+10. Open the first link. Wait 3 seconds. Run `agent-browser eval 'location.pathname'`.+11. If the path starts with `/x/operation/`, save it as `OPERATION_URL`. Screenshot `desktop-operation.png`.+12. Open the next links one by one. Save the first one that lands on `/x/inspection/` as `INSPECTION_URL`. Screenshot `desktop-inspection.png`. If none of the 15 does, write `INSPECTION_URL=none` and continue.+13. Open `/x/picking`. Click the first card. Save the URL as `PICKING_URL`. Screenshot `desktop-picking-detail.png`.+14. Write the 3 URLs into `${TMPDIR:-/tmp}/mes-round2/urls.txt`, one `NAME=value` per line.+15. Run `agent-browser set viewport 393 852 1`. Open `${ERP_URL}/x`. Wait 3 seconds. Screenshot `erp-tabbar-393.png`.+16. Run `agent-browser close`.++**Verify:**+```bash+ls "${TMPDIR:-/tmp}/mes-round2/before" && cat "${TMPDIR:-/tmp}/mes-round2/urls.txt"+# Expected: desktop-schedule.png, desktop-assigned.png, desktop-jobs.png, desktop-operation.png,+# desktop-picking-detail.png, erp-tabbar-393.png (and desktop-inspection.png when found);+# urls.txt has OPERATION_URL, INSPECTION_URL and PICKING_URL lines.+```++**Out of scope:** Any source edit. Any second browser session.++---+## Task 2: Add the shared TabBar to @carbon/react and point the ERP tab bar at it++**Depends on:** 1+**Files:**+- Create: `packages/react/src/TabBar.tsx`+- Modify: `packages/react/src/index.tsx` — import and export `TabBar`, `TabBarItem`+- Modify: `apps/erp/app/components/Layout/Mobile/MobileTabBar.tsx` — use the shared parts+- Copy from (precedent): `apps/erp/app/components/Layout/Mobile/MobileTabBar.tsx:21-53` (`tabClassName`, `Tab`) and `:84-90` (the `<nav>` classes)++**Steps:**+1. Create `packages/react/src/TabBar.tsx` with this content (the SPDX header comes in step 6):+```tsx+import type { HTMLAttributes, ReactNode } from "react";+import { Link } from "react-router";+import { cn } from "./utils/cn";++const tabBarItemClassName =+ "flex min-h-11 min-w-0 flex-1 flex-col items-center justify-center gap-0.5 text-[10.5px] font-medium leading-none outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50";++/** The phone bottom tab bar. Hidden at md and up. */+export function TabBar({+ className,+ children,+ ...props+}: HTMLAttributes<HTMLElement>) {+ return (+ <nav+ className={cn(+ "md:hidden flex shrink-0 items-stretch border-t border-border bg-card/92 px-1 pt-1 pb-safe backdrop-blur",+ className+ )}+ {...props}+ >+ {children}+ </nav>+ );+}++type TabBarItemProps = {+ icon: ReactNode;+ label: string;+ isActive?: boolean;+ /** A count on the icon. Hidden when 0 or missing. */+ count?: number;+ /** A pill behind the icon of the active tab. */+ pill?: boolean;+} & ({ to: string; onClick?: never } | { to?: never; onClick: () => void });++/** One tab: a link when `to` is set, else a button. */+export function TabBarItem({+ icon,+ label,+ isActive = false,+ count,+ pill = false,+ to,+ onClick+}: TabBarItemProps) {+ const content = (+ <>+ <span+ className={cn(+ "relative flex items-center justify-center [&>svg]:size-5",+ pill ? "h-7 w-12 rounded-full" : "size-6",+ pill && isActive && "bg-active",+ isActive ? "text-foreground" : "text-muted-foreground"+ )}+ >+ {icon}+ {count ? (+ <span className="absolute -top-1 left-1/2 ml-1 h-4 min-w-4 rounded-full bg-primary px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground tabular-nums">+ {count}+ </span>+ ) : null}+ </span>+ <span+ className={cn(+ "max-w-full truncate",+ isActive ? "text-foreground" : "text-muted-foreground"+ )}+ >+ {label}+ </span>+ </>+ );++ if (to !== undefined) {+ return (+ <Link+ to={to}+ className={tabBarItemClassName}+ aria-current={isActive ? "page" : undefined}+ >+ {content}+ </Link>+ );+ }++ return (+ <button type="button" className={tabBarItemClassName} onClick={onClick}>+ {content}+ </button>+ );+}+```+2. In `packages/react/src/index.tsx`, after line 352 (`import { Tabs, TabsContent, TabsList, TabsTrigger } from "./Tabs";`), add `import { TabBar, TabBarItem } from "./TabBar";`.+3. In the same file, in the `export {` list, add `TabBar,` and `TabBarItem,` before ` Table,` (line 664).+4. In `MobileTabBar.tsx`, delete `tabClassName` and the `Tab` function (lines 21-53).+5. Change the imports of `MobileTabBar.tsx`:+ - `import { cn } from "@carbon/react";` → `import { cn, TabBar, TabBarItem } from "@carbon/react";`+ - Delete `import type { ReactNode } from "react";`.+ - `import { Link, useLocation } from "react-router";` → `import { useLocation } from "react-router";`+6. Replace the `<nav …>…</nav>` block (lines 84-144) with:+```tsx+ <TabBar aria-label={t`Main`} className={cn(hidden && "hidden")}>+ <TabBarItem+ to={path.to.authenticatedRoot}+ icon={<LuHouse />}+ label={t`Home`}+ isActive={isHome}+ />+ <TabBarItem+ icon={<LuSearch />}+ label={t`Search`}+ onClick={openSearchModal}+ />+ <TabBarItem+ icon={<LuSquarePen />}+ label={t`Create`}+ isActive={sheet === "create"}+ onClick={() => setSheet("create")}+ />+ <TabBarItem+ icon={<LuLayoutGrid />}+ label={t`Modules`}+ isActive={sheet === "modules"}+ onClick={() => setSheet("modules")}+ />+ <TabBarItem+ icon={+ <Avatar+ path={user.avatarUrl}+ name={`${user.firstName} ${user.lastName}`}+ size="xs"+ />+ }+ label={t`Profile`}+ isActive={sheet === "profile"}+ onClick={() => setSheet("profile")}+ />+ </TabBar>+```+7. Add the license header: `pnpm --filter @carbon/checks license-headers -- "$PWD/packages/react/src/TabBar.tsx"`.+8. Sort the imports: `pnpm exec biome check --write packages/react/src/index.tsx`.++**Verify:**+```bash+head -1 packages/react/src/TabBar.tsx+# Expected: // SPDX-License-Identifier: AGPL-3.0-only+pnpm exec turbo run typecheck --filter=@carbon/react --filter=erp+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check packages/react/src/TabBar.tsx packages/react/src/index.tsx apps/erp/app/components/Layout/Mobile/MobileTabBar.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The ERP sheets (`CreateSheet`, `ModulesSheet`, `ProfileSheet`), `useAppBar`, `MobileBottomChrome`. The ERP tab bar must look the same as before (checked in Task 28).++---+## Task 3: Export the queue list and add the origin helpers++**Depends on:** 1+**Files:**+- Create: `apps/mes/app/utils/origin.ts`+- Modify: `apps/mes/app/components/AppSidebar.tsx` — export `QueueKey`, `QUEUES`, `queuePath`, `useQueueTitles`, `queueKeyForPath`, `useOrigin`; add the trailing ↗ to Displays+- Copy from (precedent): `apps/mes/app/components/AppSidebar.tsx:145-174` (the current `QUEUES`, `pathOf` and `titles`)++**Steps:**+1. Create `apps/mes/app/utils/origin.ts`:+```ts+/** The query parameter that carries the page an operation was opened from. */+export const ORIGIN_PARAM = "from";++/** `to` plus `?from=<the current page>`, so Back can return to that page. */+export function withOrigin(+ to: string,+ from: { pathname: string; search: string }+): string {+ const separator = to.includes("?") ? "&" : "?";+ const value = encodeURIComponent(`${from.pathname}${from.search}`);+ return `${to}${separator}${ORIGIN_PARAM}=${value}`;+}++/** The origin page, or null. Only MES paths (`/x/…`) count. */+export function readOrigin(searchParams: URLSearchParams): string | null {+ const from = searchParams.get(ORIGIN_PARAM);+ return from?.startsWith("/x/") ? from : null;+}+```+2. Add the license header: `pnpm --filter @carbon/checks license-headers -- "$PWD/apps/mes/app/utils/origin.ts"`.+3. In `AppSidebar.tsx`, change line 29 to `import { Await, useLocation, useNavigate, useSearchParams } from "react-router";`. Line 17 already imports `useMemo`.+4. Add `LuArrowUpRight` to the `react-icons/lu` import (lines 19-28).+5. Add `import { readOrigin } from "~/utils/origin";` after the `~/utils/path` import (line 33).+6. Replace lines 145-159 (`type QueueKey …` to `const pathOf …`) with:+```ts+export type QueueKey = keyof typeof MES_NAV_SHORTCUTS;++/** The task queues, in rail order; each one's ⌥-digit comes from its key. */+export const QUEUES: { key: QueueKey; icon: typeof LuActivity; to: string }[] =+ [+ { key: "operations", icon: LuCalendarDays, to: path.to.operations },+ { key: "assigned", icon: LuClipboardList, to: path.to.assigned },+ { key: "active", icon: LuActivity, to: path.to.active },+ { key: "recent", icon: LuHistory, to: path.to.recent },+ { key: "jobs", icon: LuCirclePlay, to: path.to.jobs },+ { key: "maintenance", icon: LuWrench, to: path.to.maintenance },+ { key: "picking", icon: LuPackageCheck, to: path.to.picking }+ ];++/** `path.to.operations` carries a `?saved=1` query; activity matches on paths. */+export const queuePath = (to: string) => to.split("?")[0];++/** The queue titles. The rail, the tab bar and Back labels share them. */+export function useQueueTitles(): Record<QueueKey, string> {+ const { t } = useLingui();+ return useMemo(+ () => ({+ operations: t`Schedule`,+ assigned: t`Assigned`,+ active: t`Active`,+ recent: t`Recent`,+ jobs: t`Jobs`,+ maintenance: t`Maintenance`,+ picking: t`Picking`+ }),+ [t]+ );+}++/** The queue a path belongs to. Job detail (`/x/job/:id`) belongs to Jobs. */+export function queueKeyForPath(pathname: string): QueueKey | undefined {+ const queue = QUEUES.find((q) => pathname.startsWith(queuePath(q.to)));+ if (queue) return queue.key;+ // generatePath drops a trailing slash, so add it back for the prefix test.+ return pathname.startsWith(`${path.to.jobDag("")}/`) ? "jobs" : undefined;+}++/** Back on Operation, Assembly and Inspection: the `from` page, else Schedule. */+export function useOrigin(): { to: string; label: string } {+ const [searchParams] = useSearchParams();+ const titles = useQueueTitles();+ const from = readOrigin(searchParams);+ if (!from) return { to: path.to.operations, label: titles.operations };+ const key = queueKeyForPath(queuePath(from));+ return { to: from, label: key ? titles[key] : titles.operations };+}+```+7. In `QueueLinks` (lines 161-201), delete `const { t } = useLingui();` and the `titles` object (lines 162 and 166-174). Add `const titles = useQueueTitles();` in their place.+8. In `QueueLinks`, change `isActive={pathname.startsWith(pathOf(queue.to))}` to `isActive={pathname.startsWith(queuePath(queue.to))}`.+9. In `DisplaysLink` (lines 208-221), add this prop to `NavRailLink`, after `rel="noreferrer"`:+```tsx+ trailing={+ <LuArrowUpRight className="hidden size-4 text-muted-foreground max-md:block" />+ }+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/utils/origin.ts apps/mes/app/components/AppSidebar.tsx+# Expected: "Checked 2 files" and no errors.+head -1 apps/mes/app/utils/origin.ts+# Expected: // SPDX-License-Identifier: AGPL-3.0-only+```++**Out of scope:** The rail order, groups and shortcuts. `NavRail.tsx` (Task 4).++---+## Task 4: Fix the phone Navigation sheet++**Depends on:** 1+**Files:**+- Modify: `packages/react/src/NavRail.tsx` — phone branch only: pinned footer, inline count badge, ↗ on the brand row+- Copy from (precedent): `packages/react/src/NavRail.tsx:155-187` (the current phone branch)++**Steps:**+1. Add `import { LuArrowUpRight } from "react-icons/lu";` after line 18 (the `react` import).+2. Replace the phone branch (lines 167-187, `if (isMobile) { … }`) with:+```tsx+ if (isMobile) {+ // The footer (Clock In, My Hours, the user) stays pinned under the+ // scrolling groups, so it shows without a scroll.+ return (+ <Drawer open={openMobile} onOpenChange={setOpenMobile}>+ <DrawerContent+ position="left"+ size="content"+ className="w-[17rem] max-w-[85vw] p-0"+ >+ <DrawerTitle className="px-6 py-4">+ <Trans>Navigation</Trans>+ </DrawerTitle>+ <NavRailHoldContext.Provider value={hold}>+ <nav+ data-state="expanded"+ className="group min-h-0 flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent pb-4"+ >+ <VStack spacing={1} className="px-2">+ {header ? <div className="w-full pb-2">{header}</div> : null}+ {children}+ </VStack>+ </nav>+ {footer ? (+ <div+ data-state="expanded"+ className="group shrink-0 border-t border-border px-2 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]"+ >+ <VStack spacing={1}>{footer}</VStack>+ </div>+ ) : null}+ </NavRailHoldContext.Provider>+ </DrawerContent>+ </Drawer>+ );+ }+```+3. In `NavRailItem`, change the tag span class (line 338) from+ `"absolute top-1 right-1 min-w-4 h-4 px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-medium leading-4 text-center tabular-nums"`+ to+ `"absolute top-1 right-1 min-w-4 h-4 px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-medium leading-4 text-center tabular-nums max-md:top-1/2 max-md:right-3 max-md:h-5 max-md:min-w-5 max-md:-translate-y-1/2 max-md:text-xs max-md:leading-5"`.+4. In `NavRailItem`, change the label row `cn(…)` (lines 345-349) to add one line, so a long label stops before the badge:+```tsx+ className={cn(+ "absolute left-7 right-3 min-w-32 group-data-[state=expanded]:left-12",+ "flex items-center gap-2",+ "opacity-0 group-data-[state=expanded]:opacity-100 max-md:opacity-100",+ tag ? "max-md:right-11" : null+ )}+```+5. In `NavRailBrand`, after the label `<span …>{label}</span>` (lines 435-440), add:+```tsx+ <LuArrowUpRight+ aria-hidden+ className="hidden size-4 shrink-0 text-muted-foreground max-md:block"+ />+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/react+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check packages/react/src/NavRail.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The desktop rail (lines 189-268), hover logic, the item order and the groups. The sheet keeps every desktop item.++---+## Task 5: Create MesAppBar++**Depends on:** 1+**Files:**+- Create: `apps/mes/app/components/MesAppBar.tsx`+- Copy from (precedent): `apps/erp/app/components/Layout/Mobile/MobileAppBar.tsx:61-104` (phone bar), `apps/mes/app/routes/x+/active.tsx:74-81` (today's desktop header)++**Steps:**+1. Create `apps/mes/app/components/MesAppBar.tsx`:+```tsx+import { Button, cn, Heading, SidebarTrigger } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuChevronLeft } from "react-icons/lu";+import { Link } from "react-router";++type MesAppBarProps = {+ kind: "root" | "pushed";+ title: ReactNode;+ /** Pushed pages: the parent page name, under the title. */+ subtitle?: ReactNode;+ /** Pushed pages: where Back goes. */+ back?: { to: string };+ /** Phones: at most 2 icon actions, each 44×44. */+ actions?: ReactNode;+ /**+ * The md+ header. Omit it for today's queue header (trigger + h4 title).+ * Pass `null` when the page renders its own md+ header, or none.+ */+ desktop?: ReactNode;+ /** Extra classes for the default md+ header. */+ desktopClassName?: string;+};++/**+ * The MES page header. Below md: one 52px bar with Back (pushed pages), a+ * 17px title and up to 2 actions. From md: the header each page had before.+ */+export function MesAppBar({+ kind,+ title,+ subtitle,+ back,+ actions,+ desktop,+ desktopClassName+}: MesAppBarProps) {+ const { t } = useLingui();++ const desktopHeader =+ desktop === undefined ? (+ <header+ className={cn(+ "sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card max-md:hidden",+ desktopClassName+ )}+ >+ <div className="flex items-center gap-2 px-2">+ <SidebarTrigger />+ <Heading size="h4">{title}</Heading>+ </div>+ </header>+ ) : (+ desktop+ );++ return (+ <>+ <header className="md:hidden sticky top-0 z-20 flex h-[calc(52px+env(safe-area-inset-top))] shrink-0 items-center gap-1 border-b border-border bg-card px-1 pt-safe">+ {kind === "pushed" && back ? (+ <Button+ asChild+ isIcon+ variant="ghost"+ size="lg"+ aria-label={t`Back`}+ className="shrink-0"+ >+ <Link to={back.to}>+ <LuChevronLeft className="size-6" />+ </Link>+ </Button>+ ) : (+ <span className="w-3 shrink-0" />+ )}+ <div className="flex min-w-0 flex-1 flex-col justify-center">+ <span className="truncate text-[17px] font-semibold leading-tight text-foreground">+ {title}+ </span>+ {subtitle ? (+ <span className="truncate text-xs text-muted-foreground">+ {subtitle}+ </span>+ ) : null}+ </div>+ {actions ? (+ <div className="flex shrink-0 items-center self-stretch">+ {actions}+ </div>+ ) : null}+ </header>+ {desktopHeader}+ </>+ );+}+```+2. Add the license header: `pnpm --filter @carbon/checks license-headers -- "$PWD/apps/mes/app/components/MesAppBar.tsx"`.++**Verify:**+```bash+head -1 apps/mes/app/components/MesAppBar.tsx+# Expected: // SPDX-License-Identifier: AGPL-3.0-only+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/MesAppBar.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** Using the component on a page (Tasks 7, 9, 10, 11, 20, 25). `apps/mes/app/components/index.ts`: import the file by its path.++---+## Task 6: Create MesTabBar, mount it, and turn on safe areas++**Depends on:** 2, 3+**Files:**+- Create: `apps/mes/app/components/MesTabBar.tsx`+- Modify: `apps/mes/app/root.tsx` — `viewport-fit=cover` (line 241)+- Modify: `apps/mes/app/routes/x+/_layout.tsx` — mount the bar, pad root pages+- Modify: `apps/mes/app/styles/tailwind.css` — toasts above the bar+- Copy from (precedent): `apps/erp/app/root.tsx:262-263` (viewport meta), `apps/erp/app/styles/tailwind.css:236-244` (toast offset), `apps/erp/app/routes/x+/_layout.tsx:550-554` (tab bar mount)++**Steps:**+1. In `apps/mes/app/root.tsx` line 241, change `content="width=device-width, initial-scale=1"` to `content="width=device-width, initial-scale=1, viewport-fit=cover"`.+2. Create `apps/mes/app/components/MesTabBar.tsx`:+```tsx+import {+ cn,+ isEditableTarget,+ TabBar,+ TabBarItem,+ useSidebar+} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import { useEffect, useState } from "react";+import { LuMenu } from "react-icons/lu";+import { useLocation } from "react-router";+import { path } from "~/utils/path";+import type { QueueKey } from "./AppSidebar";+import { QUEUES, queuePath, useQueueTitles } from "./AppSidebar";++const TAB_KEYS: QueueKey[] = ["operations", "assigned", "active", "maintenance"];++// Root pages that the More tab stands for.+const MORE_PATHS = [+ path.to.recent,+ path.to.jobs,+ path.to.picking,+ path.to.timeCardPage+];++// Exact paths: `/x/picking/:id` shares the Picking prefix but is a pushed page.+const ROOT_PATHS = new Set([+ ...QUEUES.map((queue) => queuePath(queue.to)),+ path.to.timeCardPage+]);++const trimSlash = (pathname: string) => pathname.replace(/\/$/, "");++/** True on the root pages that show the tab bar. */+export function isTabBarPath(pathname: string) {+ return ROOT_PATHS.has(trimSlash(pathname));+}++const NON_TEXT_INPUTS = ["checkbox", "radio", "button", "submit", "reset"];++/**+ * Phones: Schedule · Assigned · Active · Maintenance · More, on root pages+ * only. More opens the Navigation sheet. Hidden while a text field has focus.+ */+export function MesTabBar({+ activeEvents,+ activeMaintenanceCount+}: {+ activeEvents: number;+ activeMaintenanceCount: number;+}) {+ const { t } = useLingui();+ const titles = useQueueTitles();+ const { pathname } = useLocation();+ const { setOpenMobile } = useSidebar();+ const [isTyping, setIsTyping] = useState(false);++ useEffect(() => {+ const onFocusIn = (event: FocusEvent) => {+ const target = event.target;+ setIsTyping(+ isEditableTarget(target) &&+ !(+ target instanceof HTMLInputElement &&+ NON_TEXT_INPUTS.includes(target.type)+ )+ );+ };+ const onFocusOut = () => setIsTyping(false);+ document.addEventListener("focusin", onFocusIn);+ document.addEventListener("focusout", onFocusOut);+ return () => {+ document.removeEventListener("focusin", onFocusIn);+ document.removeEventListener("focusout", onFocusOut);+ };+ }, []);++ if (!isTabBarPath(pathname)) return null;++ const current = trimSlash(pathname);+ const counts: Partial<Record<QueueKey, number>> = {+ active: activeEvents,+ maintenance: activeMaintenanceCount+ };++ return (+ <TabBar+ aria-label={t`Main`}+ data-mes-tab-bar=""+ data-visible={isTyping ? "false" : "true"}+ className={cn(+ "fixed inset-x-0 bottom-0 z-30 min-h-[calc(54px+env(safe-area-inset-bottom))]",+ isTyping && "hidden"+ )}+ >+ {QUEUES.filter((queue) => TAB_KEYS.includes(queue.key)).map((queue) => (+ <TabBarItem+ key={queue.key}+ to={queue.to}+ icon={<queue.icon />}+ label={titles[queue.key]}+ isActive={current === queuePath(queue.to)}+ count={counts[queue.key]}+ pill+ />+ ))}+ <TabBarItem+ icon={<LuMenu />}+ label={t`More`}+ isActive={MORE_PATHS.includes(current)}+ onClick={() => setOpenMobile(true)}+ pill+ />+ </TabBar>+ );+}+```+3. Add the license header: `pnpm --filter @carbon/checks license-headers -- "$PWD/apps/mes/app/components/MesTabBar.tsx"`.+4. In `_layout.tsx`, add `cn,` to the `@carbon/react` import (lines 33-43).+5. In `_layout.tsx`, add `useLocation,` to the `react-router` import (lines 61-68).+6. In `_layout.tsx`, add `import { isTabBarPath, MesTabBar } from "~/components/MesTabBar";` after line 70 (`ConsolePill` import).+7. After line 356 (`const navigate = useNavigate();`), add:+```tsx+ const { pathname } = useLocation();+ const showTabBar = isTabBarPath(pathname);+```+8. Replace the content column opening tag (line 530):+ - Before: `<div className="flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border">`+ - After:+```tsx+ <div+ className={cn(+ "flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border",+ showTabBar &&+ "max-md:pb-[calc(54px+env(safe-area-inset-bottom))]"+ )}+ >+```+9. After that column's closing `</div>` (line 535), before `<ShortcutHelp />`, add:+```tsx+ <MesTabBar+ activeEvents={activeEvents}+ activeMaintenanceCount={activeMaintenanceCount}+ />+```+10. Append to `apps/mes/app/styles/tailwind.css`:+```css+/*+ * Phones (< 768px): toasts sit above the MES tab bar while it shows.+ * Sonner's own mobileOffset only applies up to 600px.+ */+@media (width < 48rem) {+ body:has([data-mes-tab-bar][data-visible="true"])+ [data-sonner-toaster][data-y-position="bottom"] {+ bottom: calc(54px + env(safe-area-inset-bottom) + 16px);+ }+}+```++**Verify:**+```bash+grep -n 'viewport-fit=cover' apps/mes/app/root.tsx+# Expected: one match on the viewport meta line.+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/MesTabBar.tsx apps/mes/app/routes/x+/_layout.tsx apps/mes/app/root.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The shell scroll model (`_layout.tsx:489`). Per-user tab settings. The tab bar on pushed pages.++---+## Task 7: Move the 7 queue pages onto MesAppBar and rename 2 titles++**Depends on:** 5+**Files:**+- Modify: `apps/mes/app/routes/x+/operations.tsx` — header lines 571-578+- Modify: `apps/mes/app/routes/x+/assigned.tsx` — header lines 240-247, title "Assigned"+- Modify: `apps/mes/app/routes/x+/active.tsx` — header lines 74-81+- Modify: `apps/mes/app/routes/x+/recent.tsx` — header lines 74-81+- Modify: `apps/mes/app/routes/x+/jobs.tsx` — header lines 125-132, title "Jobs"+- Modify: `apps/mes/app/routes/x+/maintenance.tsx` — header lines 409-416+- Modify: `apps/mes/app/routes/x+/picking._index.tsx` — header lines 47-54+- Copy from (precedent): `apps/mes/app/components/MesAppBar.tsx` (Task 5)++**Steps:**+1. In each of the 7 files, add `import { MesAppBar } from "~/components/MesAppBar";` to the `~/components…` imports.+2. In each file, replace the whole `<header …>…</header>` block with one `MesAppBar` line from this table:++| File | Replacement |+|---|---|+| `operations.tsx` | `<MesAppBar kind="root" title={<Trans>Schedule</Trans>} />` |+| `assigned.tsx` | `<MesAppBar kind="root" title={<Trans>Assigned</Trans>} desktopClassName="overflow-y-scroll scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent" />` |+| `active.tsx` | `<MesAppBar kind="root" title={<Trans>Active</Trans>} />` |+| `recent.tsx` | `<MesAppBar kind="root" title={<Trans>Recent</Trans>} />` |+| `jobs.tsx` | `<MesAppBar kind="root" title={<Trans>Jobs</Trans>} />` |+| `maintenance.tsx` | `<MesAppBar kind="root" title={<Trans>Maintenance</Trans>} />` |+| `picking._index.tsx` | `<MesAppBar kind="root" title={<Trans>Picking</Trans>} />` |++3. In each of the 7 files, remove `Heading` and `SidebarTrigger` from the `@carbon/react` import. No other line in these files uses them (checked with `grep -c '<Heading'` and `grep -c '<SidebarTrigger'`: 1 each, the header).++**Verify:**+```bash+grep -n 'Assigned to Me\|Open Jobs' apps/mes/app/routes/x+/assigned.tsx apps/mes/app/routes/x+/jobs.tsx+# Expected: no output.+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/routes/x+/operations.tsx apps/mes/app/routes/x+/assigned.tsx apps/mes/app/routes/x+/active.tsx apps/mes/app/routes/x+/recent.tsx apps/mes/app/routes/x+/jobs.tsx apps/mes/app/routes/x+/maintenance.tsx apps/mes/app/routes/x+/picking._index.tsx+# Expected: "Checked 7 files" and no errors.+```++**Out of scope:** The toolbars (Tasks 14, 15) and the empty states (Task 26). The Maintenance tab label "Assigned to Me" (`maintenance.tsx:442`) is a tab, not a page title, so it stays.++---+## Task 8: Pass the origin from every operation link++**Depends on:** 3+**Files:**+- Modify: `apps/mes/app/components/OperationsList.tsx` — Link at lines 115-118+- Modify: `apps/mes/app/components/Kanban/components/ItemCard.tsx` — Link at lines 116-118+- Modify: `apps/mes/app/components/JobDag/JobOperationNode.tsx` — `navigate` at lines 52-54+- Modify: `apps/mes/app/routes/x+/batch.$batchId.tsx` — redirect at line 33 keeps the query+- Copy from (precedent): `apps/mes/app/routes/x+/operation.$operationId.tsx:164-169` (redirects that keep `url.search`)++**Steps:**+1. `OperationsList.tsx`: change `import { Link } from "react-router";` to `import { Link, useLocation } from "react-router";`. Add `import { withOrigin } from "~/utils/origin";`.+2. In `OperationCard`, after `const { formatRelativeTime } = useDateFormatter();` (line 100), add `const location = useLocation();`.+3. Change `to={path.to.operation(operation.id)}` (line 116) to `to={withOrigin(path.to.operation(operation.id), location)}`.+4. `ItemCard.tsx`: change `import { Link } from "react-router";` (line 37) to `import { Link, useLocation } from "react-router";`. Add `import { withOrigin } from "~/utils/origin";`.+5. In `ItemCard`, before `const isBatch = …` (line 113), add `const location = useLocation();`.+6. Change lines 116-118:+ - Before: `to={isBatch ? path.to.batch(item.batchId!) : path.to.operation(item.id)}`+ - After: `to={withOrigin(isBatch ? path.to.batch(item.batchId!) : path.to.operation(item.id), location)}`+7. `JobOperationNode.tsx`: change `import { useNavigate } from "react-router";` to `import { useLocation, useNavigate } from "react-router";`. Add `import { withOrigin } from "~/utils/origin";`.+8. After `const navigate = useNavigate();` (line 40), add `const location = useLocation();`.+9. Replace both `navigate(path.to.operation(d.id))` calls (lines 52 and 54) with `navigate(withOrigin(path.to.operation(d.id), location))`.+10. `batch.$batchId.tsx` line 33:+ - Before: `throw redirect(path.to.operation(firstMember.id));`+ - After: `throw redirect(path.to.operation(firstMember.id) + new URL(request.url).search);`++**Verify:**+```bash+grep -n 'withOrigin' apps/mes/app/components/OperationsList.tsx apps/mes/app/components/Kanban/components/ItemCard.tsx apps/mes/app/components/JobDag/JobOperationNode.tsx+# Expected: 1 import and at least 1 call per file.+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/OperationsList.tsx apps/mes/app/components/Kanban/components/ItemCard.tsx apps/mes/app/components/JobDag/JobOperationNode.tsx "apps/mes/app/routes/x+/batch.\$batchId.tsx"+# Expected: "Checked 4 files" and no errors.+```++**Out of scope:** The batch member links inside the Operation page (`?scope=job`). They keep no origin; Back then goes to Schedule.++---+## Task 9: Operation header: MesAppBar and Back to the origin++**Depends on:** 3, 5+**Files:**+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — header lines 801-837+- Copy from (precedent): `apps/mes/app/components/MesAppBar.tsx`++**Steps:**+1. Add these imports after line 145 (`import ItemThumbnail from "../ItemThumbnail";`):+```tsx+import { useOrigin } from "../AppSidebar";+import { MesAppBar } from "../MesAppBar";+```+2. After line 321 (`const [params, setParams] = useUrlParams();`), add `const origin = useOrigin();`.+3. Replace lines 801-814 (from `<header className="[grid-area:header] …">` to the closing `</div>` of the Back group):+ - Before:+```tsx+ <header className="[grid-area:header] flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b px-2 max-md:h-auto max-md:py-1">+ <HStack className="w-full justify-between max-md:flex-wrap max-md:gap-y-1">+ <div className="flex items-center gap-0">+ <SidebarTrigger />++ <Button+ variant="ghost"+ leftIcon={<LuChevronLeft />}+ onClick={() => navigate(path.to.operations)}+ className="pl-2"+ >+ <Trans>Schedule</Trans>+ </Button>+ </div>+```+ - After:+```tsx+ <div className="[grid-area:header] flex min-w-0 flex-col">+ <MesAppBar+ kind="pushed"+ title={+ scope === "batch" && batch+ ? batch.readableId+ : operation.jobReadableId+ }+ subtitle={origin.label}+ back={{ to: origin.to }}+ desktop={null}+ />+ <header className="flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b px-2 max-md:h-auto max-md:py-1">+ <HStack className="w-full justify-between max-md:flex-wrap max-md:gap-y-1">+ <div className="flex items-center gap-0 max-md:hidden">+ <SidebarTrigger />++ <Button+ variant="ghost"+ leftIcon={<LuChevronLeft />}+ onClick={() => navigate(origin.to)}+ className="pl-2"+ >+ {origin.label}+ </Button>+ </div>+```+4. After the header's closing `</header>` (line 837), add `</div>` to close the new wrapper.+5. Leave the `TabsList` block (lines 815-835) as it is. On phones it is the row under the app bar.++**Verify:**+```bash+grep -c 'navigate(path.to.operations)' apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: 2 (was 3). The batch-completion call (line 395) and the serial-modal cancel (line 3342) stay.+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: "Checked 1 file" and no errors (run `pnpm exec biome format --write` on the file if only formatting differs).+```++**Out of scope:** The context row (Task 17), the dock (Task 19), the tabs.++---+## Task 10: Inspection, Assembly and Job detail headers on MesAppBar++**Depends on:** 3, 5+**Files:**+- Modify: `apps/mes/app/components/Inspection/InspectionView.tsx` — header lines 617-723+- Modify: `apps/mes/app/components/AssemblyView.tsx` — header lines 1629-1702+- Modify: `apps/mes/app/routes/x+/job.$jobId.tsx` — header lines 72-83+- Copy from (precedent): `apps/mes/app/components/MesAppBar.tsx`, `apps/mes/app/components/JobOperation/JobOperation.tsx` (Task 9 result)++**Steps:**+1. `InspectionView.tsx`: add `import { useOrigin } from "~/components/AppSidebar";` and `import { MesAppBar } from "~/components/MesAppBar";` after line 57 (`import { useUser } from "~/hooks";`).+2. After line 176 (`const { t } = useLingui();`), add `const origin = useOrigin();`.+3. Change the header open tag (line 617) to `<header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border max-md:hidden">`.+4. Before that header (after the `{/* ── HEADER ── */}` comment, line 616), add:+```tsx+ <MesAppBar+ kind="pushed"+ title={inspection.inspectionId}+ subtitle={origin.label}+ back={{ to: origin.to }}+ desktop={null}+ actions={+ <>+ <Badge variant={statusBadgeVariant} className="mr-1">+ {inspection.status}+ </Badge>+ <IconButton+ aria-label={t`More actions`}+ variant="ghost"+ size="lg"+ icon={<LuEllipsisVertical />}+ onClick={actionsSheet.onOpen}+ />+ {workTypes.map((wt) => (+ <TimerControl+ key={wt}+ operationId={operationId}+ workCenterId={operation.workCenterId ?? undefined}+ openEvent={openEventForWorkType(wt)}+ workType={wt}+ />+ ))}+ </>+ }+ />+```+5. `AssemblyView.tsx`: add `import { useOrigin } from "~/components/AppSidebar";` and `import { MesAppBar } from "~/components/MesAppBar";` after line 92 (`TrackingTypeIcon` import).+6. After line 542 (`const { t } = useLingui();` inside `AssemblyView`), add `const origin = useOrigin();`.+7. Cut lines 1668-1701 (the `{operation ? (<button … Complete …` block, the `{operation ? (<button aria-label="More actions" …` block and the `{operation ? headerWorkTypes.map(…TimerControl…) : null}` block). Paste them, unchanged, into a const before `return (` (line 1626):+```tsx+ // The header's actions; the md+ header and the phone app bar share them.+ const headerActions = (+ <>+ {/* paste the 3 cut blocks here, unchanged */}+ </>+ );+```+8. Where the 3 blocks were (after the `Flag issue` button), put `{headerActions}`.+9. Change the header open tag (line 1629) to `<header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border max-md:hidden">`.+10. Before that header, add:+```tsx+ <MesAppBar+ kind="pushed"+ title={job?.itemReadableIdWithRevision ?? "—"}+ subtitle={origin.label}+ back={{ to: origin.to }}+ desktop={null}+ actions={headerActions}+ />+```+11. `job.$jobId.tsx`: add `import { Trans } from "@lingui/react/macro";` and `import { MesAppBar } from "~/components/MesAppBar";`.+12. Change the header open tag (line 72) to `<header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card max-md:hidden">`.+13. Before that header, add:+```tsx+ <MesAppBar+ kind="pushed"+ title={readableId}+ subtitle={<Trans>Jobs</Trans>}+ back={{ to: path.to.jobs }}+ desktop={null}+ />+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/Inspection/InspectionView.tsx apps/mes/app/components/AssemblyView.tsx "apps/mes/app/routes/x+/job.\$jobId.tsx"+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The Inspection meta bar, matrix and bottom bar (Task 22). The 3D viewers. The Assembly steps bar. The hard-coded English "Complete"/"Done"/"Flag issue" in `AssemblyView.tsx` (existing strings, not new).++---+## Task 11: My Hours: app bar, bottom Clock bar and entry rows++**Depends on:** 5, 6+**Files:**+- Modify: `apps/mes/app/routes/x+/timecard.tsx` — render (lines 224-536)+- Copy from (precedent): `apps/mes/app/routes/x+/jobs.tsx:234-279` (phone list rows), `apps/mes/app/routes/x+/timecard.tsx:489-534` (modal), `packages/react/src/Card.tsx:237-258` (sticky footer classes)++**Steps:**+1. Add `import { MesAppBar } from "~/components/MesAppBar";`.+2. Before `return (` (line 224), add 3 render helpers. Move the existing JSX into them; do not change it:+```tsx+ const renderClockForm = (size: "md" | "lg", className?: string) =>+ openEntry ? (+ <fetcher.Form method="post" className={className}>+ <input type="hidden" name="intent" value="clockOut" />+ <Button+ variant="destructive"+ type="submit"+ size={size}+ className={className}+ disabled={fetcher.state !== "idle"}+ >+ <Trans>Clock Out</Trans>+ </Button>+ </fetcher.Form>+ ) : (+ <fetcher.Form method="post" className={className}>+ <input type="hidden" name="intent" value="clockIn" />+ <Button+ leftIcon={<LuPlay />}+ type="submit"+ size={size}+ className={className}+ disabled={fetcher.state !== "idle"}+ >+ <Trans>Clock In</Trans>+ </Button>+ </fetcher.Form>+ );+```+ - `renderSaveForm(entryId: string)`: move the `<fetcher.Form method="post">…</fetcher.Form>` of the edit row (lines 370-410). Replace `value={entry.id}` with `value={entryId}`.+ - `renderEntryMenu(entry: { id: string; clockIn: string; clockOut: string | null }, size: "md" | "lg")`: move the `<DropdownMenu>…</DropdownMenu>` (lines 441-471). Add `size={size}` to its `IconButton`.+3. Use the helpers in their old places:+ - `{renderClockForm("md")}` inside the header `HStack` (lines 233-257);+ - `{renderSaveForm(entry.id)}` in the table edit row;+ - `{renderEntryMenu(entry, "md")}` in the table row.+4. Wrap the page in a fragment and add the app bar. Change line 225:+ - Before: `<div className="flex flex-col h-full w-full overflow-y-auto p-4 md:p-6">`+ - After:+```tsx+ <>+ <MesAppBar kind="root" title={<Trans>My Hours</Trans>} desktop={null} />+ <div className="flex flex-col h-full w-full overflow-y-auto p-4 md:p-6 max-md:h-auto max-md:overflow-visible max-md:pb-24">+```+ Close the fragment after the final `</div>` (line 535): `</>`.+5. Hide the header Clock button on phones: change `<HStack className="gap-1">` (line 233) to `<HStack className="gap-1 max-md:hidden">`.+6. Week stepper (lines 269-304):+ - Prev: `leftIcon={<LuChevronLeft />}` → `leftIcon={<LuChevronLeft className="max-md:mr-0" />}`. Add `className="max-md:size-11 max-md:px-0"`. Wrap the label: `<span className="max-md:sr-only"><Trans>Prev</Trans></span>`.+ - Next: `rightIcon={<LuChevronRight />}` → `rightIcon={<LuChevronRight className="max-md:ml-0" />}`. Add `className="max-md:size-11 max-md:px-0"`. Wrap both `Next` labels in `<span className="max-md:sr-only">…</span>` (the `<span>` at line 295 gets the class).+ - The range `<span className="text-sm text-muted-foreground">` (line 275) → `<span className="text-sm text-muted-foreground max-md:whitespace-nowrap">`.+7. Change the table wrapper (line 306) from `<div className="max-md:overflow-x-auto max-md:-mx-6 max-md:px-6">` to `<div className="max-md:hidden">`. Remove ` max-md:min-w-[560px]` from `TableBase` (line 307).+8. After that wrapper's closing `</div>` (line 479), add the phone list:+```tsx+ {entries.length === 0 ? (+ <p className="py-8 text-center text-sm text-muted-foreground md:hidden">+ <Trans>No time entries for this week</Trans>+ </p>+ ) : (+ <ul className="-mx-4 divide-y divide-border border-y border-border md:hidden">+ {entries.map((entry) =>+ editingId === entry.id ? (+ <li key={entry.id} className="flex flex-col gap-2 px-4 py-3">+ <span className="text-sm font-medium">+ {formatDay(entry.clockIn, locale)}+ </span>+ <Input+ type="datetime-local"+ aria-label={t`Clock In`}+ value={editClockIn}+ onChange={(e) => setEditClockIn(e.target.value)}+ className="w-full"+ />+ <Input+ type="datetime-local"+ aria-label={t`Clock Out`}+ value={editClockOut}+ onChange={(e) => setEditClockOut(e.target.value)}+ className="w-full"+ />+ <HStack className="justify-end">+ {renderSaveForm(entry.id)}+ <Button variant="ghost" onClick={() => setEditingId(null)}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </li>+ ) : (+ <li key={entry.id} className="flex items-center gap-2 py-2 pl-4 pr-1">+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <div className="flex items-baseline justify-between gap-2">+ <span className="text-sm font-medium">+ {formatDay(entry.clockIn, locale)}+ </span>+ <span className="text-sm tabular-nums">+ {formatDuration(entry.clockIn, entry.clockOut)}+ </span>+ </div>+ <span className="flex items-center gap-1 text-xs text-muted-foreground">+ <DateTime value={entry.clockIn} variant="time" />+ <span aria-hidden>–</span>+ {entry.clockOut ? (+ <DateTime value={entry.clockOut} variant="time" />+ ) : (+ <Badge variant="green">+ <Trans>Active</Trans>+ </Badge>+ )}+ </span>+ </div>+ {renderEntryMenu(entry, "lg")}+ </li>+ )+ )}+ </ul>+ )}+```+9. Before the fragment's closing `</>`, add the phone Clock bar. It sits above the tab bar:+```tsx+ <div className="fixed inset-x-0 bottom-[calc(54px+env(safe-area-inset-bottom))] z-20 border-t border-border bg-card px-4 py-3 md:hidden">+ {renderClockForm("lg", "w-full")}+ </div>+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/routes/x+/timecard.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** A Clock Out confirmation (owner decision: none). The loader and action. The "Clocked in since" badge stays where it is.++---+## Task 12: Board work cards in 2 columns++**Depends on:** 8+**Files:**+- Modify: `apps/mes/app/components/Kanban/components/ItemCard.tsx` — header progress (lines 168-222), content (225-337), footer (338-353)+- Copy from (precedent): `apps/mes/app/routes/x+/jobs.tsx:264-274` (phone meta row)++**Steps:**+1. Wrap the 2 progress blocks (lines 168-222, both `{showProgress && … (<HStack className="mt-2">…)}`) in one element:+```tsx+ <div className="contents max-md:grid max-md:grid-cols-2 max-md:gap-3 max-md:[&>*:only-child]:col-span-2">+ {/* the 2 existing progress blocks, unchanged */}+ </div>+```+2. Change the `CardContent` class (line 225):+ - Before: `className="gap-2 text-left whitespace-pre-wrap text-sm"`+ - After: `className="gap-2 text-left whitespace-pre-wrap text-sm max-md:grid max-md:grid-cols-2 max-md:gap-x-3 max-md:gap-y-1.5 max-md:[&>*]:min-w-0"`+3. Add `max-md:col-span-2` to the class of the job `HStack` (line 235) and the description `HStack` (line 246).+4. Add `max-md:order-1` to the class of the active-employees `HStack` (line 311) and the scrapped `HStack` (line 330). Sales order and customer then pair up.+5. Before `</CardContent>` (line 337), add the phone assignee and tags:+```tsx+ {(item.assignee || (item.tags && item.tags.length > 0)) && (+ <div className="hidden flex-wrap items-center gap-1 text-xs max-md:order-2 max-md:col-span-2 max-md:flex">+ {item.assignee && (+ <EmployeeAvatar size="xs" employeeId={item.assignee} />+ )}+ {item.tags?.map((tag) => (+ <Badge+ key={tag}+ variant="secondary"+ className="border dark:border-none dark:shadow-button-base"+ >+ {tag}+ </Badge>+ ))}+ </div>+ )}+```+6. Change the `CardFooter` class (line 339) to `className="items-center justify-start space-2 text-xs flex-wrap max-md:hidden"`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/Kanban/components/ItemCard.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** Removing any field. The desktop card. The drag behaviour.++---+## Task 13: List work cards in 2 columns with the right colours++**Depends on:** 8+**Files:**+- Modify: `apps/mes/app/components/OperationsList.tsx` — header (lines 134, 138), content (143-220), footer (221-237)+- Copy from (precedent): `apps/mes/app/components/Kanban/components/ItemCard.tsx` (Task 12 result), `ItemCard.tsx:143` and `:160` (`text-foreground`)++**Steps:**+1. Title span (line 134): `className="mr-auto font-semibold line-clamp-2 leading-tight"` → `className="mr-auto font-semibold line-clamp-2 leading-tight max-md:text-foreground"`.+2. Quantity heading (line 138): `className="text-muted-foreground/70"` → `className="text-muted-foreground/70 max-md:text-foreground max-md:tabular-nums"`.+3. `CardContent` (line 143): `className="gap-2 text-left whitespace-pre-wrap text-sm flex-grow"` → add ` max-md:grid max-md:grid-cols-2 max-md:content-start max-md:gap-x-3 max-md:gap-y-1.5 max-md:[&>*]:min-w-0`.+4. Add `max-md:col-span-2` to the job `HStack` (line 153) and the description `HStack` (line 161).+5. Before `</CardContent>` (line 220), add the phone assignee and tags block from Task 12 step 5. Replace `item.` with `operation.` and drop `max-md:order-2`.+6. `CardFooter` (line 223): add ` max-md:hidden` to its class.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/OperationsList.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The `settings` object (line 43). Merging `OperationCard` and `ItemCard`.++---+## Task 14: Schedule toolbar in 1 row++**Depends on:** 7+**Files:**+- Modify: `apps/mes/app/routes/x+/operations.tsx` — toolbar lines 579-686, app bar actions+- Modify: `apps/mes/app/components/SearchFilter.tsx` — merge `className`, add `groupClassName`+- Modify: `apps/mes/app/components/Filter/Filter.tsx` — 40×40 icon button on phones+- Copy from (precedent): `apps/mes/app/routes/x+/operations.tsx:612-678` (Display popover), `apps/mes/app/routes/x+/maintenance.tsx:424` (`scrollbar-hide` row)++**Steps:**+1. `SearchFilter.tsx`: add `cn` to the `@carbon/react` import. Change the props type and body:+```tsx+type SearchFilterProps = InputProps & {+ param: string;+ /** Classes for the input group (the outer box). */+ groupClassName?: string;+};++const SearchFilter = ({+ param,+ size,+ className,+ groupClassName,+ ...props+}: SearchFilterProps) => {+```+ - `<InputGroup size={size}>` → `<InputGroup size={size} className={groupClassName}>`+ - `className="w-[100px] sm:w-[200px] text-sm"` → `className={cn("w-[100px] sm:w-[200px] text-sm", className)}`+2. `Filter.tsx`, "Clear Filters" button (lines 118-126): add `className="max-md:size-10 max-md:px-0"` before `{...props}`. Change `rightIcon={<LuX />}` to `rightIcon={<LuX className="max-md:ml-0" />}`. Wrap the label: `<span className="max-md:sr-only"><Trans>Clear Filters</Trans></span>`.+3. `Filter.tsx`, "Filter" button (lines 144-156): change `className={"!border-dashed border-border"}` to `className="!border-dashed border-border max-md:size-10 max-md:px-0"`. Change `rightIcon={<LuListFilter />}` to `rightIcon={<LuListFilter className="max-md:ml-0" />}`. Wrap the label: `<span className="max-md:sr-only"><Trans>Filter</Trans></span>`.+4. `operations.tsx`: add `cn` to the `@carbon/react` import (lines 11-29). The file already imports `IconButton`, `Popover`, `PopoverContent` and `PopoverTrigger`.+5. Before `return (` (line 569), add:+```tsx+ const showStationChip =+ !!peopleStation &&+ !currentFilters.some((filter) => filter.startsWith("workCenterId:"));++ const renderStationChip = (className?: string) =>+ showStationChip && peopleStation ? (+ <HStack+ spacing={0}+ className={cn("rounded-md border border-border bg-card", className)}+ >+ {/* the <span> and <IconButton> from lines 592-607, unchanged */}+ </HStack>+ ) : null;++ const displayPopoverContent = (+ <PopoverContent className="w-56">+ {/* the <VStack>…</VStack> from lines 623-676, unchanged */}+ </PopoverContent>+ );+```+6. Replace the toolbar (lines 580-686) with:+```tsx+ <HStack className="px-4 py-2 justify-between bg-card border-b border-border max-md:gap-2">+ <HStack className="max-md:min-w-0 max-md:flex-1">+ <SearchFilter+ param="search"+ size="sm"+ placeholder={t`Search`}+ groupClassName="max-md:min-w-0 max-md:flex-1"+ className="max-md:w-full"+ />+ <Filter filters={filters} />+ {renderStationChip("max-md:hidden")}+ </HStack>++ <Popover>+ <PopoverTrigger asChild>+ <Button+ leftIcon={<LuSettings2 />}+ variant="secondary"+ className="border-dashed border-border max-md:hidden"+ >+ <Trans>Display</Trans>+ </Button>+ </PopoverTrigger>+ {displayPopoverContent}+ </Popover>+ </HStack>+ {(showStationChip || currentFilters.length > 0) && (+ <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide scroll-fade-x border-b border-border bg-card px-4 py-1.5 md:hidden [&>*]:shrink-0">+ {renderStationChip()}+ {currentFilters.length > 0 && <ActiveFilters filters={filters} />}+ </div>+ )}+ {currentFilters.length > 0 && (+ <HStack className="px-4 py-1.5 justify-between bg-card border-b border-border w-full max-md:hidden">+ <HStack>+ <ActiveFilters filters={filters} />+ </HStack>+ </HStack>+ )}+```+7. Add the Display action to the app bar (from Task 7). Replace `<MesAppBar kind="root" title={<Trans>Schedule</Trans>} />` with:+```tsx+ <MesAppBar+ kind="root"+ title={<Trans>Schedule</Trans>}+ actions={+ <Popover>+ <PopoverTrigger asChild>+ <IconButton+ aria-label={t`Display`}+ variant="ghost"+ size="lg"+ icon={<LuSettings2 />}+ />+ </PopoverTrigger>+ {displayPopoverContent}+ </Popover>+ }+ />+```+8. The chip × buttons need no change. `Button` renders `<HitArea />` (`packages/react/src/Button.tsx:255`), a 44×44 tap target below 768px (`packages/react/src/Viewport.tsx:91-96`).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/routes/x+/operations.tsx apps/mes/app/components/SearchFilter.tsx apps/mes/app/components/Filter/Filter.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The filter logic, the saved filters, the station override action. The Maintenance toolbar keeps its layout; it only gets the icon-only Filter from step 3.++---+## Task 15: Assigned, Active and Recent toolbars++**Depends on:** 7+**Files:**+- Modify: `apps/mes/app/routes/x+/assigned.tsx` — toolbar actions (lines 262-353), app bar actions+- Modify: `apps/mes/app/routes/x+/active.tsx` — toolbar (line 84), grid (line 100)+- Modify: `apps/mes/app/routes/x+/recent.tsx` — toolbar (line 84), grid (line 100)+- Copy from (precedent): `apps/mes/app/routes/x+/operations.tsx` (Task 14 result)++**Steps:**+1. `assigned.tsx`: add `IconButton` to the `@carbon/react` import.+2. Before `return (` (line 238), move the `<PopoverContent className="w-56">…</PopoverContent>` (lines 274-336) into `const displayPopoverContent = (…);`. Put `{displayPopoverContent}` in its old place.+3. Change the actions wrapper (line 262) from `<div className="flex items-center gap-2">` to `<div className="flex items-center gap-2 max-md:hidden">`.+4. Replace the `MesAppBar` line from Task 7 with:+```tsx+ <MesAppBar+ kind="root"+ title={<Trans>Assigned</Trans>}+ desktopClassName="overflow-y-scroll scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent"+ actions={+ <>+ {view === "board" && (+ <Popover>+ <PopoverTrigger asChild>+ <IconButton+ aria-label={t`Display`}+ variant="ghost"+ size="lg"+ icon={<LuSettings2 />}+ />+ </PopoverTrigger>+ {displayPopoverContent}+ </Popover>+ )}+ <IconButton+ aria-label={view === "board" ? t`List view` : t`Board view`}+ variant="ghost"+ size="lg"+ icon={view === "board" ? <LuList /> : <LuKanban />}+ onClick={() => setView(view === "board" ? "list" : "board")}+ />+ </>+ }+ />+```+5. `active.tsx` and `recent.tsx`, line 84: `<div className="w-full p-4 h-[var(--header-height)]">` → `<div className="w-full p-4 h-[var(--header-height)] max-md:h-auto max-md:pb-0">`.+6. `active.tsx` and `recent.tsx`, line 100: `<div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4">` → add ` max-md:pt-3`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/routes/x+/assigned.tsx apps/mes/app/routes/x+/active.tsx apps/mes/app/routes/x+/recent.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The search logic. A Filter on these pages (they have none today).++---+## Task 16: Board columns on phones++**Depends on:** 1+**Files:**+- Modify: `apps/mes/app/components/Kanban/components/ColumnCard.tsx` — lines 85, 105-107, 112, 162, 205+- Copy from (precedent): the same file (round-1 `max-md:w-[300px]` at line 85)++**Steps:**+1. Line 85: in the `cva` base string, change `max-md:w-[300px]` to `max-md:w-[300px] max-md:only:w-full`.+2. Lines 105-107: add a third argument to the `cn(…)` call, after the height ternary: `"max-md:h-auto"`. The column then grows with its cards and the page scrolls once, instead of the `calc(100dvh - …)` box.+3. Line 112: change `"p-4 w-full font-semibold …"` to `"p-4 max-md:py-2 w-full font-semibold …"`.+4. Line 162 (grip `IconButton`): `className="cursor-grab relative"` → `className="cursor-grab relative max-md:hidden"`.+5. Line 205: `<ScrollBar orientation="horizontal" forceMount className="h-5" />` → `<ScrollBar orientation="horizontal" forceMount className="h-5 max-md:hidden" />`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/Kanban/components/ColumnCard.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** Drag and drop. Desktop column width and height.++---+## Task 17: Operation context row scrolls with the content++**Depends on:** 9+**Files:**+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — context row (lines 839-1128), separator (1129), Details pane (1131-1135)+- Copy from (precedent): the same file++**Steps:**+1. Cut the context row element. It starts with `<div className="[grid-area:context] flex shrink-0 flex-wrap …">` (line 839) and ends at its `</div>` before `<Separator className="[grid-area:sep]" />` (line 1128).+2. Paste it into a render function before `return (` (line 787). Change only its opening tag:+```tsx+ // The job, customer, status and due row. Phones on the Details tab render+ // it inside the scrolling pane, so it scrolls away with the content.+ const renderContextRow = (className: string) => (+ <div+ className={cn(+ "flex shrink-0 flex-wrap lg:flex-nowrap items-center justify-start px-4 lg:pl-6 py-2 min-h-[var(--header-height)] bg-card gap-x-2 gap-y-1 md:gap-x-4 w-full min-w-0",+ className+ )}+ >+ {/* the pasted children, unchanged */}+ </div>+ );+```+3. Where the row was, add:+```tsx+ {renderContextRow(+ cn("[grid-area:context]", tab === "details" && "max-md:hidden")+ )}+```+4. Change the separator to `<Separator className={cn("[grid-area:sep]", tab === "details" && "max-md:hidden")} />`.+5. In the Details `TabsContent`, after `<div className="w-full min-w-0">` (line 1135), add `{renderContextRow("md:hidden border-b border-border")}`.+6. Order the items on phones. In the second `HStack` of the row (the one with `overflow-x-auto … scroll-fade-x`), add these classes to the `className` of each item `HStack`:++| Item (find by its icon) | Add |+|---|---|+| status (`OperationStatusIcon`, and the batch `LuLayers` "Released/Completing" item) | `max-md:order-1` |+| due (`DeadlineIcon`, both the batch and the job item) | `max-md:order-2` |+| customer (`LuSquareUser`, both items) | `max-md:order-3` |+| description (`LuClipboardCheck`) | `max-md:order-4` |+| duration (`LuTimer`) | `max-md:order-5` |++7. The job ⋮ `IconButton` (`aria-label="More options"`) needs no change. `Button` renders `<HitArea />` (`packages/react/src/Button.tsx:255`), a 44×44 tap target below 768px.++**Verify:**+```bash+grep -c 'renderContextRow(' apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: 3 (1 definition, 2 calls).+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The grid template at line 799. The Model, Instructions and Chat panes (the row stays in its grid area there).++---+## Task 18: Operation meters in 1 row and the grouped quantity card++**Depends on:** 17+**Files:**+- Modify: `packages/react/src/BarProgress.tsx` — new `stackOnPhone` prop+- Modify: `apps/mes/app/components/JobOperation/components/Controls.tsx` — `Times` padding (line 98)+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — meter grid (line 3056), quantity cards (lines 1263-1357)+- Copy from (precedent): `packages/react/src/Card.tsx:103-140` (`CardAttributes` phone rows)++**Steps:**+1. `BarProgress.tsx`: add to the props type and the destructure:+```tsx+ /** Phones: label above the bar, value under it, value not truncated. */+ stackOnPhone?: boolean;+```+ Default it to `false` in the destructure.+2. In the header `div` (line 161), keep the class. Change the label span class to `cn("shrink-0 text-sm font-medium text-foreground", stackOnPhone && "max-md:min-w-0 max-md:truncate max-md:text-xs")`.+3. Change the value span class to `cn("min-w-0 truncate text-xs font-mono tabular-nums text-muted-foreground", stackOnPhone && "max-md:hidden")`.+4. After the bars `div` (the one with `role="progressbar"`), add:+```tsx+ {stackOnPhone && value ? (+ <span className="mt-1 hidden break-words text-xs font-mono tabular-nums text-muted-foreground max-md:block">+ {value}+ </span>+ ) : null}+```+5. `Controls.tsx` line 98: `"min-w-0 border-t bg-background/95 px-4 py-2.5 …"` → `"min-w-0 border-t bg-background/95 px-4 py-2.5 max-md:py-1.5 …"`.+6. `JobOperation.tsx`, meter grid (line 3056):+ - Before: `<div className="grid grid-cols-2 gap-x-4 gap-y-2 sm:gap-x-6 sm:grid-cols-[repeat(auto-fit,minmax(180px,1fr))]">`+ - After: `<div className="grid gap-y-2 max-md:grid-flow-col max-md:auto-cols-[minmax(0,1fr)] max-md:gap-x-2 md:grid-cols-[repeat(auto-fit,minmax(180px,1fr))] md:gap-x-6">`+7. Add `stackOnPhone` to both `BarProgress` elements in that grid (work-type meters and the quantity meter).+8. Change the comment above the grid (lines 3054-3055) to: `{/* Labelled meters: 1 row of up to 4 on a phone, then as many columns as fit. */}`.+9. Quantity cards: change `<div className="grid gap-4 grid-cols-2 xl:grid-cols-3 w-full min-w-0">` (line 1264) to `<div className="grid gap-4 grid-cols-2 xl:grid-cols-3 w-full min-w-0 max-md:hidden">`.+10. After that grid's closing `</div>` (line 1356), add the phone grouped card:+```tsx+ <Card className="md:hidden">+ <CardContent className="max-md:rounded-xl max-md:border-0 max-md:py-1">+ <CardAttributes className="divide-y divide-border">+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Completed</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="tabular-nums">+ <Trans>+ {operation.quantityComplete} of{" "}+ {operation.targetQuantity}+ </Trans>+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Scrapped</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="tabular-nums">+ {operation.quantityScrapped}+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Due Date</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="flex flex-col items-end text-right">+ {/* a copy of the Due Date card's <VStack> children (lines 1307-1352); the md+ card keeps its own */}+ </CardAttributeValue>+ </CardAttribute>+ </CardAttributes>+ </CardContent>+ </Card>+```+11. Add `CardAttribute`, `CardAttributeLabel`, `CardAttributes`, `CardAttributeValue` to the `@carbon/react` import of `JobOperation.tsx`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/react --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check packages/react/src/BarProgress.tsx apps/mes/app/components/JobOperation/components/Controls.tsx apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** Removing a meter. The desktop cards. Other `BarProgress` callers (the prop defaults to `false`).++---+## Task 19: Operation dock: open on the running timer and show its labels++**Depends on:** 18+**Files:**+- Modify: `apps/mes/app/components/JobOperation/hooks/useOperation.tsx` — `eventType` default (lines 93-101)+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — dock row (line 2898), running label (2960-2980), icon buttons (2981-3012)+- Copy from (precedent): `apps/mes/app/components/JobOperation/hooks/useOperation.tsx:209-223` (which events count as running)++**Steps:**+1. `useOperation.tsx`, replace lines 93-101:+```tsx+ // Opens on the timer that runs, so Pause shows for it. A Setup or Labor+ // timer counts only when it is this user's; Machine counts for anyone+ // (the same rule as `activeEvents` below). Else: Setup, Machine, Labor.+ const [eventType, setEventType] = useState(() => {+ const isRunning = (type: string) =>+ events.some(+ (e) =>+ e.type === type &&+ e.endTime === null &&+ (type === "Machine" || e.employeeId === user.id)+ );+ const running = (["Setup", "Machine", "Labor"] as const).find(isRunning);+ if (running) {+ return running;+ }+ if (operation.setupDuration > 0) {+ return "Setup";+ }+ if (operation.machineDuration > 0) {+ return "Machine";+ }+ return "Labor";+ });+```+2. If TypeScript then reports a type mismatch on `setEventType`, give the state an explicit type: `useState<string>(() => …)`.+3. `JobOperation.tsx`, dock row (line 2898): `<div className="flex w-full min-w-0 items-center gap-2 lg:flex-col lg:py-2">` → `<div className="flex w-full min-w-0 items-center gap-2 lg:flex-col lg:py-2 max-lg:flex-wrap max-lg:gap-y-1">`.+4. Running label (lines 2960-2980). Replace the wrapper class and the elapsed span:+```tsx+ <div+ className={cn(+ "flex flex-col items-center gap-0.5 text-center lg:group-data-[collapsed=true]/dock:hidden",+ // Below lg: one centred line over the controls, while a timer runs.+ "max-lg:order-first max-lg:basis-full max-lg:flex-row max-lg:justify-center max-lg:gap-1",+ !runningType && "max-lg:hidden"+ )}+ >+ {runningType ? (+ <>+ {/* the existing emerald label span, unchanged */}+ <span aria-hidden className="hidden text-xs text-muted-foreground max-lg:inline">+ ·+ </span>+ <span className="font-mono text-lg tabular-nums max-lg:text-xs">+ {formatDurationMilliseconds(progress[runningType], {+ style: "short"+ })}+ </span>+ </>+ ) : (+ /* the existing "Start …" span, unchanged */+ )}+ </div>+```+5. Captions for + and ⋮ (lines 2981-3012). Wrap each `IconButtonWithTooltip` in a column with a caption:+```tsx+ <div className="flex flex-col items-center gap-0.5">+ {/* the existing IconButtonWithTooltip for Log completed, unchanged */}+ <span className="whitespace-nowrap text-xs text-muted-foreground lg:hidden">+ {isBatched ? (+ <Trans>Complete batch</Trans>+ ) : (+ <Trans>Log completed</Trans>+ )}+ </span>+ </div>+ <div className="flex flex-col items-center gap-0.5">+ {/* the existing IconButtonWithTooltip for More Actions, unchanged */}+ <span className="whitespace-nowrap text-xs text-muted-foreground lg:hidden">+ <Trans>More</Trans>+ </span>+ </div>+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/JobOperation/hooks/useOperation.tsx apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: "Checked 2 files" and no errors.+```++**Out of scope:** `StartStopButton`, `WorkTypeToggle` and the green Start / red Pause colours. The dock actions. The `exclusive` flag. The dock on Instructions and Chat (it stays hidden there).++---+## Task 20: Picking detail on phones++**Depends on:** 5+**Files:**+- Modify: `apps/mes/app/routes/x+/picking.$pickingListId.tsx` — header (163-178), main (180-194), `PickingListControls` (207-294), kit card (416-418), line item (583-631, 781-799)+- Copy from (precedent): `packages/react/src/Card.tsx:243-252` (sticky footer classes), `apps/mes/app/components/MesAppBar.tsx`++**Steps:**+1. Add `import { MesAppBar } from "~/components/MesAppBar";`.+2. Change the header open tag (line 163) to `<header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center justify-between gap-2 border-b bg-card max-md:hidden">`. Change line 169 to `<div className="flex items-center gap-3 px-3">`.+3. Before that header, add:+```tsx+ <MesAppBar+ kind="pushed"+ title={pickingList.pickingListId}+ subtitle={<Trans>Picking</Trans>}+ back={{ to: path.to.picking }}+ desktop={null}+ />+```+4. In `<main …>` (line 180), add ` max-md:pb-28` to its class. As the first child of `<VStack spacing={4} className="w-full">` (line 182), add the status row:+```tsx+ <div className="flex items-center gap-2 md:hidden">+ <PickingListStatus status={pickingList.status} />+ </div>+```+5. After `</main>` (line 194), add the bottom bar:+```tsx+ <div className="fixed inset-x-0 bottom-0 z-20 flex items-center gap-3 border-t border-border bg-card px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] md:hidden">+ <span className="shrink-0 whitespace-nowrap text-sm text-muted-foreground tabular-nums">+ {completedCount}/{lines.length} <Trans>lines</Trans>+ </span>+ <PickingListControls+ pickingListId={pickingList.id}+ status={pickingList.status}+ size="lg"+ className="min-w-0 flex-1 [&_button]:w-full"+ />+ </div>+```+6. `PickingListControls`: add 2 optional props, `size?: "md" | "lg"` (default `"md"`) and `className?: string`. Pass `size={size}` to both buttons (lines 262, 273). Change `<HStack spacing={2}>` (line 259) to `<HStack spacing={2} className={className}>`.+7. Kit card wrapper (line 418): `<div className="border rounded-lg">` → `<div className="border rounded-lg max-md:-mx-4 max-md:rounded-none max-md:border-x-0 max-md:border-b-0">`.+8. Neutral open-quantity badge: in both badges (lines 590 and 605) change the `"bg-red-600"` branch to `"bg-red-600 max-md:bg-muted max-md:text-foreground"`.+9. Thumbnail and name (lines 624-631):+ - `<HStack spacing={4} className="min-w-0 flex-1">` → `<HStack spacing={4} className="min-w-0 flex-1 max-md:space-x-3">`+ - Wrap the `ItemThumbnail` in `<div className="shrink-0 max-md:[&>*]:size-11 max-md:[&_svg]:size-7">…</div>`.+ - `<p className="w-full truncate text-base font-medium">` → `<p className="w-full truncate text-base font-medium max-md:line-clamp-2 max-md:whitespace-normal">`+10. Pick and Short (lines 781-799): add ` max-md:h-12` to the `className` of both buttons.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check "apps/mes/app/routes/x+/picking.\$pickingListId.tsx"+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The finish and short-pick logic, `IncompletePickAcknowledgeModal`, the tracked picker. The emerald (picked) and orange (short) colours.++---+## Task 21: Smaller fixes on Picking list, Jobs and Maintenance++**Depends on:** 7+**Files:**+- Modify: `apps/mes/app/routes/x+/picking._index.tsx` — rows at lines 84, 91, 100+- Modify: `apps/mes/app/routes/x+/jobs.tsx` — phone row (lines 246-263)+- Modify: `apps/mes/app/routes/x+/maintenance.tsx` — card (241-276), tabs (422-424)+- Copy from (precedent): `apps/mes/app/routes/x+/jobs.tsx:234-279` (phone rows)++**Steps:**+1. `picking._index.tsx`: in the 3 label/value rows, change `<HStack className="justify-between text-sm">` to `<HStack className="justify-between text-sm max-md:w-full">`.+2. `jobs.tsx` line 250: `<span className="text-sm text-muted-foreground tabular-nums">` → `<span className="text-sm text-foreground tabular-nums">`.+3. `jobs.tsx` lines 254-263, replace with one line:+```tsx+ <div className="flex min-w-0 gap-1 text-sm">+ <span className="shrink-0">+ {job.itemReadableIdWithRevision ?? "—"}+ </span>+ {job.name && (+ <span className="truncate text-muted-foreground">+ · {job.name}+ </span>+ )}+ </div>+```+4. `maintenance.tsx`: change `import { useMemo, useState } from "react";` to `import { useEffect, useMemo, useRef, useState } from "react";`.+5. In `MaintenanceRoute`, after `const [activeTab, setActiveTab] = useState("all");` (line 318), add:+```tsx+ // Phones: the tab row scrolls sideways; keep the active tab in view.+ const tabsListRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ tabsListRef.current+ ?.querySelector<HTMLElement>('[data-state="active"]')+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [activeTab]);+```+6. `TabsList` (line 424): add `ref={tabsListRef}` and add ` max-md:scroll-fade-x` to its class.+7. `MaintenanceCard`, header right side (lines 253-255). Replace `{getPriorityIcon(…)}` with:+```tsx+ <HStack spacing={2}>+ <div className="hidden items-center gap-2 max-md:flex">+ <Badge+ variant={getOeeImpactColor(dispatch.oeeImpact ?? "No Impact")}+ >+ {dispatch.oeeImpact ?? t`No Impact`}+ </Badge>+ {dispatch.assignee && (+ <EmployeeAvatar employeeId={dispatch.assignee} />+ )}+ </div>+ {getPriorityIcon(+ dispatch.priority as (typeof maintenanceDispatchPriority)[number]+ )}+ </HStack>+```+8. `MaintenanceCard`, `<CardContent>` (line 262) → `<CardContent className="max-md:hidden">`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/routes/x+/picking._index.tsx apps/mes/app/routes/x+/jobs.tsx apps/mes/app/routes/x+/maintenance.tsx+# Expected: "Checked 3 files" and no errors.+```++**Out of scope:** The desktop Jobs table. The Maintenance filters and tab content. The empty states (Task 26).++---+## Task 22: Inspection task screen on phones++**Depends on:** 10+**Files:**+- Modify: `apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx` — scroller (542), Characteristic (546, 583-616), Gauge (553-557, 618-633)+- Modify: `apps/mes/app/components/Inspection/InspectionView.tsx` — meta bar (726-749), frame (868), bottom bar (after 888), `CompletePassedButton` (1110-1144), `TimerControl` (1362)+- Copy from (precedent): `apps/mes/app/components/JobOperation/components/Controls.tsx:62` (bottom bar safe-area padding)++**Steps:**+1. Matrix scroller (line 542): `<div className="min-h-0 flex-1 overflow-auto">` → `<div className="min-h-0 flex-1 overflow-auto max-md:scroll-fade-x">`.+2. Characteristic `th` (line 546): change `min-w-[220px]` to `min-w-[220px] max-md:w-[150px] max-md:min-w-[150px]`.+3. Characteristic `td` (line 583): change `"sticky left-0 z-10 cursor-pointer border-b border-r border-border bg-card px-3 py-2 align-top"` to `"sticky left-0 z-10 cursor-pointer border-b border-r border-border bg-card px-3 py-2 align-top max-md:px-2"`. Change `<div className="flex items-start gap-3">` (line 592) to `<div className="flex items-start gap-3 max-md:gap-2">`.+4. After the `n … · Ac … · Re …` line (line 614, inside the `flex min-w-0 flex-col gap-1` div), add the phone gauge picker:+```tsx+ {hasFeatures ? (+ // Phones: the gauge sits under the characteristic.+ // The click must not toggle the active row.+ <div+ className="-mx-2 -mb-2 mt-1 hidden border-t border-border max-md:block"+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <InspectionGaugePicker+ gauges={gauges}+ characteristicLabel={row.label}+ recentGaugeIds={recentGauges}+ gaugeTypeId={row.gaugeTypeId}+ gaugeTypeName={row.gaugeTypeName}+ value={gaugeFor(row.featureId)}+ isReadOnly={isReadOnly}+ onChange={(gaugeId) =>+ persistGauge(row.featureId, gaugeId)+ }+ />+ </div>+ ) : null}+```+5. If Biome flags the wrapper `div` for a missing role, add `role="presentation"`.+6. Gauge `th` (line 554) and gauge `td` (line 619): add ` max-md:hidden` to each class.+7. `InspectionView.tsx` meta bar (line 726): `"flex h-9 shrink-0 items-center gap-3 overflow-x-auto bg-card border-b border-border px-5 scrollbar-hide"` → add ` max-md:px-4 max-md:scroll-fade-x`.+8. Meta bar spacer (line 743): `<div className="flex-1" />` → `<div className="flex-1 max-md:hidden" />`.+9. Meta bar counts span (line 744): add ` max-md:order-first` to its class.+10. Frame (line 868): `"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border bg-card"` → add ` max-md:flex-initial`.+11. `TimerControl` (line 1362): `<span className="hidden flex-col items-end leading-none sm:flex">` → `<span className="flex flex-col items-end leading-none">`. From 640px up it shows today, so md+ does not change.+12. `CompletePassedButton`: add the prop `variant?: "header" | "bar"` (default `"header"`). When `variant === "bar"`, render:+```tsx+ <fetcher.Form+ method="post"+ action={path.to.inspectionCompletePassed(inspectionId)}+ className="flex min-w-[calc(50%-0.25rem)] flex-1"+ >+ <input type="hidden" name="operationId" value={operationId} />+ <EventIdInputs eventIds={eventIds} />+ <Button+ type="submit"+ size="lg"+ variant="secondary"+ isDisabled={busy}+ leftIcon={<LuCheckCheck />}+ className="h-12 w-full text-emerald-600 dark:text-emerald-400"+ >+ <Trans>Complete passed</Trans> {count}+ </Button>+ </fetcher.Form>+```+ Keep today's markup for `"header"`.+13. After the BODY block (after line 888, before `{/* ── MODALS ── */}`), add the bottom action bar:+```tsx+ {/* Phones: the lot actions as labelled 48px buttons in thumb reach. */}+ <div className="flex shrink-0 flex-wrap gap-2 border-t border-border bg-card px-4 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:hidden [&>*]:min-w-[calc(50%-0.25rem)] [&>*]:flex-1">+ {!lotClosed && completablePassed > 0 ? (+ <CompletePassedButton+ inspectionId={inspection.id}+ operationId={operationId}+ count={completablePassed}+ eventIds={eventIds}+ variant="bar"+ />+ ) : null}+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuX />}+ isDisabled={!canReject}+ onClick={rejectDisclosure.onOpen}+ className="h-12 text-red-600 dark:text-red-400"+ >+ <Trans>Reject</Trans>+ </Button>+ {canPartial ? (+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuContrast />}+ onClick={partialDisclosure.onOpen}+ className="h-12 text-amber-600 dark:text-amber-400"+ >+ <Trans>Partial</Trans>+ </Button>+ ) : null}+ <Button+ size="lg"+ leftIcon={<LuCheck />}+ isDisabled={!canAccept}+ onClick={acceptDisclosure.onOpen}+ className="h-12"+ >+ <Trans>Accept</Trans>+ </Button>+ </div>+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/Inspection/InspectionView.tsx apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx+# Expected: "Checked 2 files" and no errors.+```++**Out of scope:** A card-per-characteristic stepper. The drawing pane branch (`showDrawing`). The modals and the save logic of the matrix.++---+## Task 23: Operation materials as row cards on phones++**Depends on:** 19+**Files:**+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — module helpers (after `PickedBreakdown`, line 298), materials block (lines 1686-2196)+- Copy from (precedent): the table cells in the same block (lines 1747-1986 and 2006-2184), `apps/mes/app/routes/x+/jobs.tsx:234-279` (phone rows)++**Steps:**+1. After the `PickedBreakdown` function (ends at line 298), add 2 module helpers. They repeat the Estimated and Actual cell logic of the table:+```tsx+type PickFields = {+ quantityPicked?: number | null;+ quantityToPick?: number | null;+ pickedByItem?: {+ itemId: string;+ itemReadableId: string;+ quantityPicked: number;+ quantityToPick: number;+ }[];+ hasExpiredConsumed?: boolean;+};++function materialEstimated(+ material: JobMaterial,+ parentIsSerial?: boolean | null+) {+ return parentIsSerial &&+ (material.requiresBatchTracking || material.requiresSerialTracking)+ ? `${material.quantity ?? material.estimatedQuantity}/${+ material.estimatedQuantity ?? material.quantity+ }`+ : (material.estimatedQuantity ?? material.quantity);+}++function materialActual(+ material: JobMaterial,+ parentIsSerial?: boolean | null+) {+ if (+ material.methodType === "Make to Order" &&+ material.requiresBatchTracking === false &&+ material.requiresSerialTracking === false+ ) {+ return (+ <MethodIcon type="Make to Order" isKit={material.kit ?? false} />+ );+ }+ return parentIsSerial &&+ (material.requiresBatchTracking || material.requiresSerialTracking)+ ? `${material.quantityIssued}/${+ material.quantity ?? material.estimatedQuantity+ }`+ : material.quantityIssued;+}+```+2. In the materials block, change `<div className="w-full overflow-hidden rounded-lg border bg-card">` (line 1688) to `<div className="w-full overflow-hidden rounded-lg border bg-card max-md:hidden">`.+3. Inside the `Await` callback, before `return (`, add a row renderer. It uses the variables of the table rows:+```tsx+ const renderMaterialRow = (+ material: JobMaterial,+ isKitChild: boolean+ ) => {+ const fields = material as JobMaterial & PickFields;+ const isRelatedToOperation =+ material.jobOperationId === operationId;+ const someRelatedMaterialIsIssued =+ baseMaterials.some(+ (m) =>+ m.itemReadableIdWithoutRevision ===+ material.itemReadableIdWithoutRevision &&+ ((m.quantityIssued ?? 0) > 0 ||+ (material.quantityIssued ?? 0) > 0)+ );+ const isTracked =+ material.requiresBatchTracking ||+ material.requiresSerialTracking;+ const openIssue = () => {+ flushSync(() => {+ setSelectedMaterial(material);+ });+ issueModal.onOpen();+ };+ const batchTotal =+ isBatched && material.itemId+ ? batchMaterialTotals?.[material.itemId]+ : undefined;+ return (+ <li+ key={`material-row-${material.id}`}+ className={cn(+ "flex items-center gap-3 px-3 py-3",+ isKitChild && "pl-8",+ !isRelatedToOperation && "opacity-50"+ )}+ >+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex items-baseline justify-between gap-2">+ <span className="truncate font-semibold">+ {getItemReadableId(+ items,+ material.itemId ?? ""+ )}+ </span>+ <span className="flex shrink-0 items-center gap-1 text-sm tabular-nums text-muted-foreground">+ {materialActual(material, parentIsSerial)}+ <span aria-hidden>/</span>+ {materialEstimated(material, parentIsSerial)}+ </span>+ </div>+ {material.description ? (+ <span className="truncate text-sm text-muted-foreground">+ {material.description}+ </span>+ ) : null}+ <div className="flex flex-wrap items-center gap-1">+ {material.requiresBatchTracking ? (+ <Badge variant="secondary">+ <TrackingTypeIcon type="Batch" className="shrink-0" />+ </Badge>+ ) : material.requiresSerialTracking ? (+ <Badge variant="secondary">+ <TrackingTypeIcon type="Serial" className="shrink-0" />+ </Badge>+ ) : null}+ {fields.hasExpiredConsumed && (+ <Badge variant="red" className="gap-1 shrink-0">+ <LuTriangleAlert className="size-3" />+ <Trans>Consumed expired</Trans>+ </Badge>+ )}+ <PickedBadge+ quantityPicked={fields.quantityPicked}+ quantityToPick={fields.quantityToPick}+ />+ </div>+ <PickedBreakdown+ materialItemId={material.itemId}+ pickedByItem={fields.pickedByItem}+ />+ {batchTotal ? (+ <span className="text-xs text-muted-foreground">+ <Trans>Batch</Trans>: {batchTotal.issued} /{" "}+ {batchTotal.required}+ </span>+ ) : null}+ </div>+ {material.methodType !== "Make to Order" &&+ !isTracked ? (+ <IconButton+ aria-label={t`Issue Material`}+ variant="secondary"+ size="lg"+ icon={<LuGitBranchPlus />}+ onClick={openIssue}+ />+ ) : isTracked && isKitChild ? (+ <IconButton+ aria-label={t`Issue Material`}+ variant="secondary"+ size="lg"+ icon={<LuQrCode />}+ onClick={openIssue}+ />+ ) : isTracked ? (+ <Button+ size="lg"+ className="shrink-0"+ variant={+ someRelatedMaterialIsIssued ||+ !isRelatedToOperation+ ? "secondary"+ : "primary"+ }+ leftIcon={<LuQrCode />}+ onClick={openIssue}+ >+ <Trans>Issue</Trans>+ </Button>+ ) : null}+ </li>+ );+ };+```+4. After the table wrapper's closing `</div>` (line 2194), before `{renderIssueModal(resolvedMaterials)}`, add the phone list:+```tsx+ <ul className="w-full divide-y divide-border rounded-lg border bg-card md:hidden">+ {baseMaterials.length === 0 ? (+ <li className="py-8 text-center text-muted-foreground">+ <Trans>No materials</Trans>+ </li>+ ) : (+ baseMaterials.flatMap((material) => [+ renderMaterialRow(material, false),+ ...(material.id+ ? (kitMaterialsByParentId[material.id] ?? [])+ : []+ ).map((child) =>+ renderMaterialRow(child, true)+ )+ ])+ )}+ </ul>+```+5. If `kitMaterialsByParentId` can be `undefined` for TypeScript, use `kitMaterialsByParentId?.[material.id]`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/JobOperation/JobOperation.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The desktop table (lines 1689-2193 stay as they are). `IssueMaterialModal`. The batch materials view (`BatchOverview`). The "Source" column (it stays desktop only).++---+## Task 24: Job graph top to bottom on phones++**Depends on:** 1+**Files:**+- Modify: `apps/mes/app/components/JobDag/JobDag.tsx` — direction (157), toolbar (184-214), minimap (234-239)+- Copy from (precedent): `packages/react/src/Viewport.tsx:65-84` (`useViewport`)++**Steps:**+1. Add `useViewport` to the `@carbon/react` import (lines 5-12). Add `import { useLingui } from "@lingui/react/macro";`.+2. In `JobDagInner`, after line 157 (`const [direction, setDirection] = useState<LayoutDirection>("LR");`), add:+```tsx+ const { t } = useLingui();+ const { isPhone } = useViewport();+ // MES has no server viewport hint, so the first render is desktop.+ // Switch a phone to top-to-bottom once, after hydration. The toggle stays.+ useEffect(() => {+ if (isPhone) setDirection("TB");+ }, [isPhone]);+```+3. Both toolbar buttons (lines 192 and 207): change `"h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5"` to `"h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5 max-md:h-11 max-md:px-3"`.+4. Line 201: replace `{direction === "LR" ? "Left to Right" : "Top to Bottom"}` with the code below. Keep 2 separate `t` calls. A ternary inside one `t` keeps the English words (`.ai/lessons.md:2216`).+```tsx+ {direction === "LR" ? t`Left to Right` : t`Top to Bottom`}+```+5. Line 212: replace the text `Fit` with:+```tsx+ {t`Fit`}+```+6. Minimap (line 238): `className="!bg-card !border-border"` → `className="!bg-card !border-border max-md:!hidden"`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/JobDag/JobDag.tsx+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The layout algorithm, node size, `DagLegend`. The canvas stays a canvas.++---+## Task 25: Maintenance dispatch: app bar, Complete button and confirmation++**Depends on:** 5+**Files:**+- Modify: `apps/mes/app/routes/x+/dispatch.$dispatchId.tsx` — header (258-276), work centre card (281-302), description (305-324), controls (327-404)+- Copy from (precedent): `apps/mes/app/routes/x+/timecard.tsx:489-534` (confirmation `Modal`)++**Steps:**+1. Add `Modal`, `ModalBody`, `ModalContent`, `ModalFooter`, `ModalHeader`, `ModalOverlay`, `ModalTitle` to the `@carbon/react` import. Change `import { useMemo } from "react";` to `import { useMemo, useState } from "react";`. Add `import { MesAppBar } from "~/components/MesAppBar";`.+2. Add a module helper after `formatDuration` (line 188):+```tsx+/** True when a rich-text document holds any visible text. */+function hasText(node: JSONContent | undefined | null): boolean {+ if (!node) return false;+ if (typeof node.text === "string" && node.text.trim().length > 0) {+ return true;+ }+ return (node.content ?? []).some(hasText);+}+```+3. In the component, after `const addPartModal = useDisclosure();` (line 215), add `const [confirmComplete, setConfirmComplete] = useState(false);`.+4. Header (line 258): add ` max-md:hidden` to the `<header>` class. Before it, add:+```tsx+ <MesAppBar+ kind="pushed"+ title={dispatch.maintenanceDispatchId}+ subtitle={<Trans>Maintenance</Trans>}+ back={{ to: path.to.maintenance }}+ desktop={null}+ />+```+5. As the first child of `<VStack spacing={4} className="max-w-2xl mx-auto">` (line 279), add the phone status row:+```tsx+ <div className="flex w-full items-center justify-between md:hidden">+ <MaintenanceStatus status={dispatch.status} />+ {getPriorityIcon(+ dispatch.priority as (typeof maintenanceDispatchPriority)[number]+ )}+ </div>+```+6. Work centre card: `<CardHeader>` (line 282) → `<CardHeader className="max-md:hidden">`. Before `<span className="text-lg font-semibold">` (line 289), add:+```tsx+ <span className="hidden text-xs text-muted-foreground max-md:block">+ <Trans>Work Center</Trans>+ </span>+```+7. Description card (line 307): `<Card className="w-full">` → `<Card className={cn("w-full", !hasText(dispatch.content as JSONContent) && "max-md:hidden")}>`. Add `cn` to the `@carbon/react` import.+8. Controls row (line 338): `<HStack spacing={4} className="justify-center w-full">` → `<HStack spacing={4} className="justify-center w-full max-md:flex-col max-md:space-x-0 max-md:gap-3">`.+9. Replace the Complete `ValidatedForm` (lines 378-399) with a button that opens the confirmation:+```tsx+ <button+ type="button"+ aria-label={t`Complete`}+ disabled={fetcher.state !== "idle"}+ onClick={() => setConfirmComplete(true)}+ className="group size-24 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:scale-105 transition-all text-accent-foreground text-3xl disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30 max-md:hidden"+ >+ <FaCheck className="group-hover:scale-110" />+ </button>+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuCheck />}+ isDisabled={fetcher.state !== "idle"}+ onClick={() => setConfirmComplete(true)}+ className="hidden w-full max-md:flex"+ >+ <Trans>Complete</Trans>+ </Button>+```+10. Before the final closing `</div>` of the component's return, add the confirmation:+```tsx+ {confirmComplete && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) setConfirmComplete(false);+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>{t`Complete ${dispatch.maintenanceDispatchId}?`}</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <Trans>This marks the dispatch as completed.</Trans>+ </ModalBody>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => setConfirmComplete(false)}+ >+ <Trans>Cancel</Trans>+ </Button>+ <Button+ isLoading={fetcher.state !== "idle"}+ onClick={() => {+ const formData = new FormData();+ formData.append("action", "Complete");+ formData.append("dispatchId", dispatch.id);+ formData.append("eventId", myActiveEvent?.id ?? "");+ fetcher.submit(formData, {+ method: "post",+ action: path.to.maintenanceEvent+ });+ setConfirmComplete(false);+ }}+ >+ <Trans>Complete</Trans>+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ )}+```+11. The removed form sent the same 3 fields (`action`, `dispatchId`, `eventId`), which `maintenance-event.tsx:30-33` reads. If `eventValidator` or `ValidatedForm` become unused, keep them (the Start form still uses both).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check "apps/mes/app/routes/x+/dispatch.\$dispatchId.tsx"+# Expected: "Checked 1 file" and no errors.+```++**Out of scope:** The Start/Pause round button (it stays big and round). The time entries and spare parts cards. `maintenance-event.tsx`.++---+## Task 26: Empty states on phones++**Depends on:** 14, 15, 21+**Files:**+- Create: `apps/mes/app/components/MesEmptyState.tsx`+- Modify: `apps/mes/app/routes/x+/active.tsx` (lines 103-124), `operations.tsx` (697-718), `jobs.tsx` (281-302), `picking._index.tsx` (115-124), `maintenance.tsx` (`EmptyState`, lines 279-301, and its 4 default calls)+- Copy from (precedent): `apps/mes/app/routes/x+/active.tsx:116-123` (today's empty markup)++**Steps:**+1. Create `apps/mes/app/components/MesEmptyState.tsx`:+```tsx+import { cn } from "@carbon/react";+import type { ReactNode } from "react";+import { LuInbox, LuTriangleAlert } from "react-icons/lu";++type MesEmptyStateProps = {+ title: ReactNode;+ action?: ReactNode;+ /** The page's container classes (height, padding). */+ className?: string;+};++/**+ * An empty list. From md up: today's dark round icon and mono caption.+ * Phones: a muted icon tile and a 17px title. No new text (owner rule).+ */+export function MesEmptyState({+ title,+ action,+ className+}: MesEmptyStateProps) {+ return (+ <div+ className={cn(+ "flex flex-col items-center justify-center gap-4 max-md:h-auto max-md:gap-2 max-md:px-6 max-md:py-12 max-md:text-center",+ className+ )}+ >+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background max-md:rounded-xl max-md:bg-muted max-md:text-muted-foreground">+ <LuTriangleAlert className="h-6 w-6 max-md:hidden" />+ <LuInbox className="hidden h-6 w-6 max-md:block" />+ </div>+ <span className="text-xs font-mono font-light text-foreground uppercase max-md:mt-2 max-md:font-sans max-md:text-[17px] max-md:font-semibold max-md:normal-case">+ {title}+ </span>+ {action}+ </div>+ );+}+```+2. Add the license header: `pnpm --filter @carbon/checks license-headers -- "$PWD/apps/mes/app/components/MesEmptyState.tsx"`.+3. In each page below, import `MesEmptyState` from `~/components/MesEmptyState`. Replace each empty block with the call in the table. `className` keeps the page's old container classes, so md+ stays the same.++| Page | Old block | New call |+|---|---|---|+| `active.tsx` | search empty (103-114) | `<MesEmptyState className="flex-1 w-full h-[calc(100%-var(--header-height)*2)]" title={<Trans>No results exist</Trans>} action={<Button onClick={() => setSearchTerm("")}><Trans>Clear Search</Trans></Button>} />` |+| `active.tsx` | default (116-123) | `<MesEmptyState className="flex-1 w-full h-[calc(100%-var(--header-height)*2)]" title={<Trans>No active operations</Trans>} />` |+| `operations.tsx` | filter empty (698-708) | `<MesEmptyState className="w-full h-full" title={<Trans>No results</Trans>} action={<Button onClick={clearFilters}><Trans>Clear Filters</Trans></Button>} />` |+| `operations.tsx` | default (710-717) | `<MesEmptyState className="w-full h-full" title={<Trans>No work centers exist</Trans>} />` |+| `jobs.tsx` | search empty (282-292) | `<MesEmptyState className="py-16" title={<Trans>No results</Trans>} action={<Button onClick={() => setSearchTerm("")}><Trans>Clear Search</Trans></Button>} />` |+| `jobs.tsx` | default (294-301) | `<MesEmptyState className="py-16" title={<Trans>No open jobs</Trans>} />` |+| `picking._index.tsx` | default (116-123) | `<MesEmptyState className="flex-1 w-full h-[calc(100%-var(--header-height))]" title={<Trans>No picking lists assigned</Trans>} />` |++4. `maintenance.tsx`: change the local `EmptyState` to render `MesEmptyState`:+```tsx+function EmptyState({+ message,+ onClear+}: {+ message: string;+ onClear?: () => void;+}) {+ return (+ <MesEmptyState+ className="flex-1 w-full h-[calc(100dvh-var(--header-height)*2-40px)]"+ title={message}+ action={+ onClear ? (+ <Button onClick={onClear}>+ <Trans>Clear Search</Trans>+ </Button>+ ) : undefined+ }+ />+ );+}+```+5. Leave the 4 default `EmptyState` calls in `maintenance.tsx` as they are. Do not add any new string (owner rule: keep the existing strings).+6. Remove `LuTriangleAlert` from a page's `react-icons/lu` import when no other line uses it.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+pnpm exec biome check apps/mes/app/components/MesEmptyState.tsx apps/mes/app/routes/x+/active.tsx apps/mes/app/routes/x+/operations.tsx apps/mes/app/routes/x+/jobs.tsx apps/mes/app/routes/x+/picking._index.tsx apps/mes/app/routes/x+/maintenance.tsx+# Expected: "Checked 6 files" and no errors.+```++**Out of scope:** Recent and Assigned empty states (not in spec 3.5). Any title string: each keeps its existing text.++---+## Task 27: Extract strings, typecheck and Biome++**Depends on:** 1–26+**Files:**+- Modify: `packages/locale/locales/*/mes.po`, `packages/locale/locales/*/erp.po` (written by the extractor)++**Steps:**+1. Run `pnpm lingui:extract`.+2. Run `pnpm lingui:clean`. It strips the origin comments and the creation date, so the `.po` diff stays small.+3. Run the typecheck below. If it fails, fix the error in the file it names. Then run it again.+4. Run Biome on the files this plan touched (the `FILES` list below). If it reports formatting only, run the same command with `--write`.+5. Check the license headers of the 5 new files.++**Verify:**+```bash+grep -c '^msgid "More"$' packages/locale/locales/en/mes.po+# Expected: 1+pnpm exec turbo run typecheck --filter=mes --filter=erp --filter=@carbon/react+# Expected: the "Tasks:" summary line says "successful"; no "error TS" lines.+FILES="packages/react/src/TabBar.tsx packages/react/src/index.tsx packages/react/src/NavRail.tsx packages/react/src/BarProgress.tsx+apps/erp/app/components/Layout/Mobile/MobileTabBar.tsx apps/mes/app/root.tsx apps/mes/app/utils/origin.ts apps/mes/app/styles/tailwind.css+apps/mes/app/components/AppSidebar.tsx apps/mes/app/components/MesAppBar.tsx apps/mes/app/components/MesTabBar.tsx apps/mes/app/components/MesEmptyState.tsx+apps/mes/app/components/OperationsList.tsx apps/mes/app/components/SearchFilter.tsx apps/mes/app/components/Filter/Filter.tsx apps/mes/app/components/AssemblyView.tsx+apps/mes/app/components/Kanban/components/ItemCard.tsx apps/mes/app/components/Kanban/components/ColumnCard.tsx+apps/mes/app/components/JobDag/JobDag.tsx apps/mes/app/components/JobDag/JobOperationNode.tsx+apps/mes/app/components/JobOperation/JobOperation.tsx apps/mes/app/components/JobOperation/components/Controls.tsx apps/mes/app/components/JobOperation/hooks/useOperation.tsx+apps/mes/app/components/Inspection/InspectionView.tsx apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx+apps/mes/app/routes/x+/_layout.tsx apps/mes/app/routes/x+/operations.tsx apps/mes/app/routes/x+/assigned.tsx apps/mes/app/routes/x+/active.tsx+apps/mes/app/routes/x+/recent.tsx apps/mes/app/routes/x+/jobs.tsx apps/mes/app/routes/x+/maintenance.tsx apps/mes/app/routes/x+/picking._index.tsx+apps/mes/app/routes/x+/picking.\$pickingListId.tsx apps/mes/app/routes/x+/timecard.tsx apps/mes/app/routes/x+/job.\$jobId.tsx+apps/mes/app/routes/x+/dispatch.\$dispatchId.tsx apps/mes/app/routes/x+/batch.\$batchId.tsx"+pnpm exec biome check $FILES+# Expected: no errors.+head -1 packages/react/src/TabBar.tsx apps/mes/app/utils/origin.ts apps/mes/app/components/MesAppBar.tsx apps/mes/app/components/MesTabBar.tsx apps/mes/app/components/MesEmptyState.tsx+# Expected: each file's first line is // SPDX-License-Identifier: AGPL-3.0-only+```++**Out of scope:** `pnpm translate` (the owner runs it). A whole-repo `pnpm typecheck` (it runs out of memory).++---+## Task 28: Verify in the browser at 393×852 and 1280×800++**Depends on:** 27+**Files:**+- Create: `${TMPDIR:-/tmp}/mes-round2/after/*.png` (scratch)+- Copy from (precedent): `.claude/skills/auth/SKILL.md`, Task 1++**Steps:**+1. 🛑 Use one `agent-browser` session for the whole task. Close it at the end. If you pass 40 screenshots, close the session and log in again.+2. Run `mkdir -p "${TMPDIR:-/tmp}/mes-round2/after"`. Read `MES_URL` and `ERP_URL` from `.env.local` and the URLs from `${TMPDIR:-/tmp}/mes-round2/urls.txt`.+3. Log in with `.claude/skills/auth/SKILL.md` steps 2 to 4.+4. Run `agent-browser set viewport 393 852 1`.+5. On each screen below, do 3 things: wait 3 seconds, take `agent-browser screenshot "${TMPDIR:-/tmp}/mes-round2/after/<name>.png"`, and run `agent-browser eval 'document.documentElement.scrollWidth'`. The result must be `393` (AC 15).+6. Check each acceptance criterion. Record PASS or FAIL with the evidence (an eval result or a screenshot name):++| AC | Screen and check |+|---|---|+| 1 | On `/x/operations`, `/x/assigned`, `/x/active`, `/x/recent`, `/x/jobs`, `/x/maintenance`, `/x/picking`, `/x/timecard`: `agent-browser eval 'document.querySelectorAll("[data-mes-tab-bar] a, [data-mes-tab-bar] button").length'` is `5`. Tap Active: `location.pathname` is `/x/active` and the Active link has `aria-current="page"`. |+| 2 | The Maintenance tab badge shows the same number as the Maintenance row in the Navigation sheet. The Schedule tab shows no badge. |+| 3 | Tap More. The sheet lists Schedule, Assigned, Active, Recent, Jobs, Maintenance, Picking, Add Inventory, Remove Inventory, End Operations, Suggestion, Displays, in that order (`agent-browser snapshot -i`). The user row's `getBoundingClientRect().bottom` is ≤ 852. |+| 4 | On Operation, Assembly (open one if Schedule has one), Inspection, Job detail, Dispatch detail and Picking detail: `document.querySelector("[data-mes-tab-bar]")` is `null`. The `[aria-label="Back"]` element is 44×44 and its `left` is ≤ 8. |+| 5 | From `/x/active`, open an operation, tap Back: `location.pathname` is `/x/active`. Repeat at 1280×800: the header button reads "Active" and returns to `/x/active`. |+| 6 | `/x/timecard` shows the app bar, the tab bar and a full-width Clock In (or Clock Out) button above the tab bar. If the week has no entries, the whole "No time entries for this week" text is on screen. |+| 7 | On Schedule, filter to 1 work center. The column `getBoundingClientRect().width` is 393 (± 2). At least 2 cards end above y = 852 − 54. |+| 8 | On `OPERATION_URL`: if no Machine timer runs, choose Machine and tap Start, then reload. The toggle shows Machine selected, the round button is red Pause, and the dock text contains "Machine ·". Tap Pause afterwards. |+| 9 | On the Details tab: `document.querySelector('[role="tabpanel"][data-state="active"]').getBoundingClientRect().height / innerHeight` is ≥ 0.65. Scroll the pane: the job/status row moves up out of view. |+| 10 | On the Details tab, every Issue control in the phone material list is ≥ 44×44 and has `right` ≤ 393. |+| 11 | On `INSPECTION_URL` (skip if `none`): the first sample cell's `right` is ≤ 393 without a sideways scroll. Accept shows as a labelled button at the bottom. |+| 12 | On `PICKING_URL` with the list In Progress: Finish is a full-width button at the bottom. |+| 13 | On a dispatch: tap Complete. A dialog opens that names the dispatch. Tap Cancel: the dialog closes and the status is unchanged. |+| 14 | On a Job detail: the graph runs top to bottom and `.react-flow__minimap` is not visible. |+| 15 | Every screen in this table: `scrollWidth` is `393`. |+| 16 | Run `agent-browser set viewport 1280 800 1`. Screenshot Schedule, Assigned, Jobs, `OPERATION_URL`, `PICKING_URL`, `INSPECTION_URL` as `desktop-*.png`. Compare each with the same name in `before/` (`agent-browser diff screenshot --baseline "${TMPDIR:-/tmp}/mes-round2/before/desktop-<name>.png"`). Allowed differences: the titles "Assigned" and "Jobs", the Back label, live timer values. |+| 17 | Run `agent-browser set viewport 393 852 1`. Open `${ERP_URL}/x`. Compare with `before/erp-tabbar-393.png`. The tab bar must look the same. |+| 18 | Task 27 passed. |+| 19 | Not part of this plan. Keep the `after/` screenshots for the round-2 review. |++7. Run `agent-browser close`.+8. Write a short report: one line per AC with PASS or FAIL, and the screenshot folder path. If an AC fails, name the screen and the measured value. Do not change the shell scroll model to fix one.++**Verify:**+```bash+ls "${TMPDIR:-/tmp}/mes-round2/after" | wc -l+# Expected: at least 20 files.+agent-browser close 2>&1 | tail -1+# Expected: the session is already closed, or it closes now.+```++**Out of scope:** Any git commit. Any source change (report failures instead). A second browser session.diff --git a/.ai/plans/2026-10-07-mes-phone-round-3.md b/.ai/plans/2026-10-07-mes-phone-round-3.mdnew file mode 100644index 0000000000..6f935e0a1b--- /dev/null+++ b/.ai/plans/2026-10-07-mes-phone-round-3.md@@ -0,0 +1,63 @@+# MES phone layout, round 3 — implementation plan++**Spec / source:** `.ai/specs/2026-10-07-mes-phone-round-2.md` (round 3 fixes its review findings)+**Evidence:** round-2 reviews in the session scratch `mes-r2/` (`review-layout.md` 65, `review-nav.md` 74, `review-operator.md` 66, `ac-report.md`)+**Branch:** `feat/mobile-redesign`++🛑 Never commit. Adapt, never add. Keep green Start and red Pause. Phone-only changes use `max-md:` or `useViewport().isPhone`.++## Decisions taken without the owner (the owner asked for no check-ins)++| Finding | Decision | Why |+|---|---|---|+| Inspection: move Reject and Partial into ⋯ (layout P1-1) | Not done. The 3 buttons share 1 row (`flex-1`) | Spec 3.1.4 was owner-approved; 1 row fixes the height without moving actions |+| My Hours: Clock In in flow, no fixed bar (nav P1-7) | Not done. Fixed bar kept; recorded as an exception to R13.2 | Spec 1.7.2 was owner-approved |+| Finish returns to the origin, also on desktop (nav P1-1 step 3) | Done | It extends the owner-approved Back-to-origin change; flagged in the report |+| Lift a shared `AppBar` into `@carbon/react` (nav P2-10) | Deferred to a later round | A refactor, not a phone fault |+| Where extra timers go with 3 work types (nav P1-2 step 4) | Deferred | Needs an owner answer |++## Progress++### Owner: agent A — Operation and job graph (`JobOperation.tsx`, `Controls.tsx`, `packages/react/src/BarProgress.tsx`, `JobDag.tsx`, `job.$jobId.tsx`)+- [x] A1: Below 768px render the `Times` meters as the first block of the Details scroll content, after the context row; hide the `[grid-area:status]` copy with `max-md:hidden` (layout P0-2.2, nav P1-6)+- [x] A2: Below 768px show the running label as the caption under the Pause button, not as its own row (layout P0-2.1)+- [x] A3: Tab row `max-md:py-0`; tabs stay 44px (layout P0-2.3)+- [x] A4: Facts row wraps on phones: `max-md:flex-wrap max-md:overflow-visible max-md:gap-y-1` (layout P1-2)+- [x] A5: Move the job ⋮ menu into the `MesAppBar` actions on phones; the context-row copy is `md:` only (nav P2-8). Its label is already `t\`More options\``+- [x] A6: Materials: trailing control in a fixed `w-28 justify-end` slot; list full-bleed on phones (layout P2)+- [x] A7: Due Date row on 1 line on phones ("Sep 30, 2026 · Due last week") (layout P2)+- [x] A8: Job graph on phones: dagre `nodesep: 24`, `ranksep: 56`; the toolbar floats bottom-right (`max-md:absolute max-md:bottom-4 max-md:right-4`) (layout P0-3). `minZoom: 0.6` on fit is already in+- [x] A9: Operation dock carries `data-mes-bottom-bar` and `--mes-bottom-bar-h: 91px` (`Controls.tsx`) for the toast rule (B5)+### Owner: agent B — Inspection, Assembly, origin, toasts, nav sheet+- [x] B1: Inspection action bar is 1 row: 3 buttons `flex-1` instead of `min-w-[calc(50%-0.25rem)]` (`InspectionView.tsx` ~`:924`)+- [x] B2: Inspection timer `aria-label` through Lingui (`:1460`); Characteristic `th`/`td` `max-md:max-w-[150px]`, gauge picker `w-full min-w-0` (`InspectionMeasurementMatrix.tsx`); meta bar wraps on phones `max-md:h-auto max-md:flex-wrap max-md:py-1.5`+- [x] B3: Assembly: Lingui for "Complete", "Done", "More actions" and the timer labels; below 768px Complete moves to a bottom action bar like Inspection's Accept; phone title is the job ID, item ID in the subtitle (nav P1-3)+- [x] B4: Origin through actions: hidden `from` in `QuantityModal`; `complete.tsx` and `finish.tsx` redirect to the origin (nav P1-1)+- [x] B5: Toasts above every bottom bar: `data-mes-bottom-bar` + `--mes-bottom-bar-h` on the Picking footer, Inspection bar, Operation dock (attribute only — agent A owns that file, so B adds the attribute through a wrapper prop if needed, or reports it), My Hours bar; extend the toast rule in `apps/mes/app/styles/tailwind.css` (nav P1-4)+- [x] B6: Nav sheet: `scroll-fade` on the scroller, title `max-md:text-[17px] max-md:font-semibold`, remove the dead `w-[17rem] max-w-[85vw]` (`NavRail.tsx`); close the sheet when its current row is tapped (nav P1-5, P2-11, P2-15)+- [x] B7: `useOrigin` labels a job-graph origin "Job" (new Lingui string) (nav P2-12); More tab gets `aria-haspopup="dialog"` and `aria-expanded` (`TabBar.tsx`, `MesTabBar.tsx`) (nav P2-14); Console pill below the app bar on phones (nav P2-16)+### Owner: main session — cards, toolbars, list pages+- [x] M1: Schedule lone column full width: phone board is a plain snap scroller, card `max-md:max-w-none` (operator P0-1, layout P0-1)+- [x] M2: Lone-column cards align to the 16px gutter (`group/column`, `max-md:group-only/column:px-4`)+- [x] M3: Work cards: no band seam (`CardHeader max-md:pb-1`, `CardContent max-md:border-t-0 max-md:pt-1`); short duration on phones (layout P1-4)+- [x] M4: Toolbar spacing `max-md:pt-3` on Schedule and Assigned (layout P1-5)+- [x] M5: Jobs rows in 3 lines: tracking and avatar on line 1 (layout P1-6)+- [x] M6: Picking detail: status in the app bar subtitle; name `md:truncate` so 2 lines show on phones; lines full-bleed (layout P1-7)+- [x] M7: Picking phone Finish is `primary` and 48px (operator P2-1, P2-3)+- [x] M8: My Hours: card title hidden on phones; Clock In 48px (operator P2-3, P2-4). Also hide the card header when nothing is clocked in (layout P1-8)+- [x] M9: Dispatch: the Description card was blank on every width because `generateHTML` returns "" on the server and hydration keeps that markup; it now renders client-only; fold "Time Worked" into the body; Add and remove-part buttons `lg` (layout P1-3, operator P2-2)+- [x] M10: Maintenance tabs bleed to the edge; avatar name `text-xs` (layout P2)+- [x] M11: Operation: Completed value `text-2xl font-semibold`, per-piece time muted on phones, Issue labelled, quantity foreground, job ⋮ 44px and ID once, larger running label, captions and dot (operator P1-2…P1-5)+- [x] M12: Inspection status badge in the meta bar on phones; timer caption 12px (operator P1-6)+- [x] M13: Job graph fit no smaller than 0.6 on phones (operator P1-7)++### Verify (main session)+- [x] V1: `pnpm exec turbo run typecheck --filter=mes --filter=erp --filter=@carbon/react`; Biome on changed files; `pnpm lingui:extract && pnpm lingui:clean`+- [x] V2: Browser at 393×852: AC 7 passes (card bottoms 458 and 766, tab bar at 798), overflow 393 on all screens, the round-2 screenshot set re-taken into `mes-r3/`+- [x] V3: Browser at 1280×800: Schedule, Jobs, Operation, Picking, Inspection unchanged except the desktop Finish destination+- [ ] V4: Round-3 review by 3 read-only reviewers (layout, navigation, operator); repeat rounds until each scores ≥ 75++## Run notes++- Inspection phone bar: with 3 buttons in 1 row, "Complete passed N" truncated to "C". It now takes its own full-width row only when passed units wait (`--mes-bottom-bar-h` 121px); otherwise the bar is 1 row.+- Dispatch Description was blank at every width: `generateHTML` returns "" during SSR and hydration keeps it. Both rich-text blocks now render client-only.diff --git a/.ai/plans/2026-10-07-mes-phone-round-4.md b/.ai/plans/2026-10-07-mes-phone-round-4.mdnew file mode 100644index 0000000000..5f95292869--- /dev/null+++ b/.ai/plans/2026-10-07-mes-phone-round-4.md@@ -0,0 +1,60 @@+# MES phone layout, round 4 — implementation plan++**Spec / source:** `.ai/specs/2026-10-07-mes-phone-round-2.md`; round 3 is `.ai/plans/2026-10-07-mes-phone-round-3.md`+**Evidence:** round-3 reviews in the session scratch `mes-r3/`: `review-layout.md` 75, `review-nav.md` 78, `review-operator.md` 73+**Branch:** `feat/mobile-redesign`++🛑 Never commit. Adapt, never add. Keep green Start and red Pause. Phone-only changes use `max-md:` or `useViewport().isPhone`. Desktop does not change.++## Decisions taken without the owner++| Finding | Decision | Why |+|---|---|---|+| `ModalTitle` 17/600 on phones (nav P2-8) | Deferred | It changes every ERP phone sheet too; a shared-component change for a later round |+| App bar title as `h1` + tap-to-top (nav P2-9) | Deferred with the shared `AppBar` lift | One change, in one place |+| Picking status pill in the app bar subtitle (nav regression 1) | Move it to the kit card header row | The subtitle names the parent page (R2.3); status belongs in content (R18.2) |++## Progress++### Agent A — Operation dock and Assembly (`JobOperation.tsx`, `Controls.tsx`, `useOperation.tsx`, `components/JobOperation/components/Parameter.tsx`, `AssemblyView.tsx`)+- [x] A1: Dock caption on phones shows the type and the time on 2 lines ("● Machine" / "2d, 9h"); the caption timer and the toggle use the same pick order, so Pause shows the selected timer's time; update the phone bar height variable (operator P0, spec AC 8)+- [x] A2: Lingui on the Setup/Labor/Machine toggle `aria-label`s and on "Issue Material" (operator P2)+- [x] A3: Process Parameters rows on phones: `max-md:px-4 max-md:py-3`, no fixed key width, long value under its label, IDs on 1 line (layout 2)+- [x] A4: Assembly bar: ⋮ and the timer at least 44px (`max-md:min-w-11`); the timer shows its elapsed time and work type on phones; steps bar `px-4`; tabs 44px underline style like Operation; progress row into the Details scroll content on phones; subtitle is `origin.label` only, item ID in the content (operator 2, layout 4, nav 3, P2-14, P2-15)++### Agent B — Inspection, origin, nav sheet (`InspectionView.tsx`, `InspectionMeasurementMatrix.tsx`, `routes/x+/inspection-lot.$id.complete-passed.tsx`, `routes/x+/inspection-lot.$id.disposition.tsx`, `NavRail.tsx`, `ConsolePill.tsx`, `routes/x+/picking.$pickingListId.tsx`)+- [x] B1: Inspection: below md the meta bar scrolls with the matrix (not fixed); the timer sits before ⋮ (layout 1, nav 2)+- [x] B2: Inspection gauge picker uses the full cell width on phones, no "Select g…" truncation (layout 1)+- [x] B3: Inspection actions keep the origin: hidden `from` on Complete passed and the disposition forms; their actions redirect with `withOrigin` / to the origin (nav 1). Open: `DispositionModal.tsx` (Reject, Partial) still needs `<Hidden name="from">`; the action already reads it+- [x] B4: Navigation sheet: make the bottom fade visible (static fade if `scroll-fade` does not show); title `max-md:px-4` (nav 4)+- [x] B5: Console pill on phones: bottom-left above the tab bar or page bar, `max-md:top-auto max-md:bottom-[calc(var(--mes-bottom-bar-h,54px)+env(safe-area-inset-bottom)+8px)]` (nav regression 3)+- [x] B6: Picking detail: subtitle back to "Picking"; the status pill moves into the kit card header row (nav regression 1)++### Main session — Schedule, cards, dispatch+- [x] M1: Schedule toolbar `max-md:space-x-0` on both toolbar `HStack`s (layout 3)+- [x] M2: Card customer and assignee names truncate (`min-w-0` + `truncate`) in `ItemCard.tsx` and `EmployeeAvatar.tsx` (layout 3)+- [x] M3: Multi-column phone board: `px-4 scroll-px-4` on the `BoardContainer` row (layout 5)+- [x] M4: Work-card quantity gets a muted phone-only caption with the existing "Quantity" string (operator 3)+- [x] M5: Dispatch Complete `max-md:h-12` (operator 4)++### Verify (main session)+- [x] V1: Typecheck `mes`, `erp`, `@carbon/react`; Biome; `pnpm lingui:extract && pnpm lingui:clean`+- [x] V2: Browser 393×852: re-shoot into `mes-r4/`; AC 7 and AC 8; overflow 393+- [x] V3: Browser 1280×800: Schedule, Operation, Inspection, Picking, Dispatch unchanged+- [x] V4: Round-4 reviews (3 lenses); stop when each is ≥ 75++## Run notes++- Reject and Partial post through `DispositionModal.tsx`; the main session added the hidden `from` there (agent B's gap).+- AC 7: card bottoms 458 and 766, tab bar 798. AC 8: the dock reads "Machine · 2d, 10h".+- Desktop change from A1: with 2 timers running, the dock caption shows the selected timer, not always Labor.+- Round-4 reviews: layout 78, navigation 80, operator 77. All 3 are at or above 75, so the review loop stops here.+- Owner report after round 4: on phones every drawer slid in from its desktop side while laid out as a bottom sheet. `Drawer.tsx` now overrides the slide variables below md (`data-[state]` variants, so they outrank `animate-in`); every phone drawer enters from the bottom. Verified: x 0, y 100% mid-animation.++## Backlog (round-4 reviews, not done)++- Kanban-scan completion drops the origin (`end.$operationId.tsx`).+- Timer `aria-label`s name the work type; Assembly timers before ⋮ without dividers.+- Assembly Record/Skip into the phone bottom bar; 44px filter and pager; Lingui on its plain strings; tab roles.+- Operation dock 8px lighter; 8px gap between the Setup/Labor/Machine toggles.+- Inspection full characteristic names; Dispatch status into the Work Center card; Picking kit header alignment; Jobs quantity label; job-graph legend 44px.diff --git a/.ai/reviews/2026-10-08-phone-redesign-thermo-review.md b/.ai/reviews/2026-10-08-phone-redesign-thermo-review.mdnew file mode 100644index 0000000000..98dcfd6d42--- /dev/null+++ b/.ai/reviews/2026-10-08-phone-redesign-thermo-review.md@@ -0,0 +1,70 @@+# Thermo-nuclear review — phone redesign (uncommitted work on feat/mobile-redesign)++Scope: `git diff HEAD` (164 files, +8482 / −3605). Three read-only reviewers: shared phone parts, ERP screens, MES. No typecheck or build ran during the review.++## A. Shared phone parts++| # | Sev | Where | Problem | Simpler alternative |+|---|---|---|---|---|+| A1 | MAJOR | `packages/react/src/SplitButton.tsx`, `PurchaseOrderHeader.tsx`, `JobHeader.tsx` | In a bar cell the split dropdown is dropped, so each caller copies its items into the ⋯ by hand behind `isPhone`. The Job copy already drifted (extra `isDisabled`). | Give the `bar` presentation an `overflow` render function that `RecordAction` points at the overflow slot. SplitButton renders its own `dropdownItems` there. Delete both copies. |+| A2 | MAJOR | `RecordHeader.tsx` (`recordMenuSlot`), `Table.tsx` → `CompactList` → `CompactToolbar` (`mobileMenuItems`) | Three ways now put actions in an app-bar ⋯. Two of them make pages write their desktop actions twice (MakeMethodTools, JobMakeMethodTools, both planning tables). | Keep one primitive: the overflow portal slot with the `row` presentation. Pages wrap their existing desktop Button. Delete `recordMenuSlot`, `mobileMenuItems`, `menuItems`. |+| A3 | MAJOR | `Input`, `Textarea`, `InputOTP`, `Editor`, `BottomSheet`, `PickerList`, `Drawer`, `Modal` | "No autofocus on phones" exists in 8 copies; `usePickerOpenAutoFocus` keeps a dead `_optionCount`. | Two hooks in `Viewport.tsx`: `usePhoneAutoFocus(autoFocus)` and `usePhoneOpenAutoFocus(handler)`. Use them at all 8 sites; drop `_optionCount`. |+| A4 | MAJOR | `CompactToolbar.tsx` (`useHideListAppBarMenu`), `InventoryItemHeader.tsx` | A module flag with one caller works around two owners filling `AppBarActions` at once. | Make `AppBarActions` newest-wins (like `useSetAppBarOverride`). Delete the flag. |+| A5 | MAJOR | `ActionTaskList.tsx`, `ActionTaskAddModal.tsx`, `ReviewersList.tsx` | The same phone pattern twice (`trigger` enum, `isPhone` branches, "No … yet.", `pr-14` gap for the collapse button; `pr-14` now 8× in ERP). | `Card` keeps the collapse-button gap itself when `isCollapsible`. Modals take a trigger node, not an enum. |+| A6 | minor | `Panels.tsx` | `RecordFrameContext`, `RecordPanelContext` and `recordFrameSlot` signal one fact. | One context `((panel) => void) \| null`. |+| A7 | minor | `packages/react/src/HTML.tsx` | `isRichTextEmpty` duplicates `hasContent` (`packages/documents/src/pdf/blocks/resolveTerms.ts:10`); exported, unused outside; a cast. | Do not export it; replace the cast with a guard. |+| A8 | minor | `NavRail.tsx` | Phone branch rebuilds `content`; its `max-md:` classes are dead. | Build body/footer once. |+| A9 | minor | `Assignee.tsx` | Third hand-written controlled/uncontrolled `open`. | One `useControllableState`. |+| A10 | minor | `MobileAppBar.tsx` | Two title buttons duplicate the subtitle; comment names one screen. | One button. |+| A11 | minor | `RecordHeader.tsx`, `ActionPresentation.tsx`, `Button.tsx` | Names still say "sheet" after the ⋯ moved to a menu. | Rename `useOverflowSheet` → `useOverflowMenu`; fix comments. |+| A12 | minor | `PrintButton.tsx` `label`, `BarProgress.tsx` `stackOnPhone` | Props for one caller each. | Drop `label`; one `value` node with flex `order`. |++## B. ERP screens++| # | Sev | Where | Problem | Simpler alternative |+|---|---|---|---|---|+| B1 | MAJOR | `QuoteSummary.tsx` | 963 → 1026 lines, past the 1000-line limit. | Move `LinePricingOptions` (about 390 lines) to `QuoteLinePricingOptions.tsx`. |+| B2 | MAJOR | `SalesOrderSummary.tsx:404`, `PurchaseOrderSummary.tsx:137`, `QuoteSummary.tsx:215`, `InventoryStorageUnits.tsx:383` | Four hand-rolled phone line rows; dead `max-md:` classes left in desktop-only branches. | One `SummaryLineRow` component next to `CompactRow`; delete the dead classes. |+| B3 | MAJOR | `SalesOrderSummary.tsx:773`, `QuoteSummary.tsx:177` | `getLineTotal` duplicates `packages/documents/src/utils/sales-order.ts:80`; the breakdown row still inlines it; Quote holds its total formula twice. | Use the documents helper for SO everywhere; one `getQuoteLineTotal`. |+| B4 | MAJOR | Part and Job BOP/BOM (4 files) | The same 22-line empty state copied 4×; `CompactEmpty` already has the icon tile. | Generalise `CompactEmpty({ icon, title, description, action })`. |+| B5 | MAJOR | `MakeMethodTools.tsx:370`, `JobMakeMethodTools.tsx:334` | Each tool declared twice (Menubar + memoized menu item with a `biome-ignore`). | Wrap each `MenubarItem` in `<RecordAction slot="overflow">`; delete `phoneMenu`. (Same fix as A2.) |+| B6 | MAJOR | 9 detail / planning routes | The same 4 imports + `useSetAppBarOverride(useMemo(…))` in each. | A `subtitle` on each route `handle`, read by `deriveAppBar`. |+| B7 | MAJOR | `InventoryDetails.tsx`, `InventoryStorageUnits.tsx` | `variant="quantity"` branches in 14 places for one caller of five. | Use the phone layout for every caller; delete the prop. |+| B8 | minor | `PivotTree.tsx` | Second row renderer and footer ternary copied; useless alias. | Shared `PivotRowLabel` and `formatColumnTotal`. |+| B9 | minor | `JobHeader.tsx`, `PurchaseOrderHeader.tsx` | Split-button items copied as phone overflow buttons. (Same as A1.) | SplitButton fills its own items. |+| B10 | minor | `InventoryStorageUnits.tsx`, `SalesOrderSummary.tsx:417` | `storageUnitLabel` not reused; third `(line as any).assetReadableId`. | Reuse the label helper; a typed line-label helper. |+| B11 | minor | `ReportFilters`, `PivotControlBar`, `PurchasesControlBar`, `MultiPeriodStatementTree`, `ExecutivePnlSummary`, `TrialBalanceTree` | Download copied as an app-bar icon 3×; period stepper code copied 2×; Trial Balance header and `columnLabels` kept apart. | `ReportDownloadAction`; `usePeriodStepper`; build the header from `columnLabels`. |+| B12 | minor | Both planning tables | The same 25-line phone MRP code twice. | One `useMrpRecalculate(locationId)`. |++Also noted: four `[a, b].filter(Boolean).join(" · ")` hero-subtitle builders; the "Locked while the quote is …" note copied in 2 forms.++## C. MES++| # | Sev | Where | Problem | Simpler alternative |+|---|---|---|---|---|+| C1 | MAJOR | `JobOperation.tsx` (3413 → 3809 lines) | A second materials renderer (phone list) beside the desktop table, no shared row model; 4 inline casts; the issue-button condition differs (`!isTracked` vs `=== false`). | Move the materials section to `JobOperation/components/Materials.tsx` with one per-row model read by both layouts. |+| C2 | MAJOR | `MesTabBar.tsx:82` + 5 bottom bars | Bottom bar heights hard-coded (`--mes-bottom-bar-h`), `54px` repeated 7×, an effect with no deps queries the DOM every render. | One `MesBottomBar` that measures itself (ERP precedent `BottomBar` + `useCompactCssVar`). |+| C3 | MAJOR | `AdjustInventory`, `EndShift`, `Suggestion` | Each tool switches modal vs More-sheet page by hand in 3 places and builds its body twice. | One `ToolDialog` / `useToolSurface` from `MoreSheet.tsx`. |+| C4 | MAJOR | `OperationsList.tsx`, `Kanban/components/ItemCard.tsx` | The same phone card parts copied line for line. | Shared `CardThumbnail`, `QuantityStat`, `AssigneeTags`. |+| C5 | MAJOR | `AppSidebar.tsx:230` (`useOrigin`), 4 hidden `from` writers, 3 `withOrigin` ternaries | Origin logic split across files; one writer ignores `ORIGIN_PARAM`. | `utils/origin.tsx` owns `useOrigin`, `<OriginInput/>`, null-safe `withOrigin`. |+| C6 | MAJOR | `timecard.tsx:510`, `jobs.tsx` | Phone list copies the table's edit branch; the editor exists twice in the DOM. | `TimeEntryEditor` / `TimeEntrySummary`; a `JobRowData` mapper. |+| C7 | minor (regression) | `MesAppBar.tsx:47` | Desktop titles changed ("Open Jobs" → "Jobs", "Assigned to Me" → "Assigned"); `actions` mount twice (TimerControl ×2 in AssemblyView). | `desktopTitle` prop; render actions once. |+| C8 | minor | `JobOperation.tsx:1540` | Due label ×3, projected-completion badge ×2, context row and meters mount twice. | Compute once; `<ProjectedCompletion>`. |+| C9 | minor | `operations.tsx:599`, `assigned.tsx:238` | `displayPopoverContent` copied (50 lines) with casts, mounted twice. | `<DisplaySettingsPopover>`. |+| C10 | minor (regression) | `dispatch.$dispatchId.tsx` | `hasText` duplicates `isRichTextEmpty`; desktop Complete now asks for confirmation (desktop behaviour change). | Use `RichTextView`; keep the confirmation phone-only. |+| C11 | minor | `MoreSheet.tsx`, `Kanban.tsx:70`, `JobDag.tsx:166` | 3 effects mirror props into state. | Derive instead. |+| C12 | minor | `apps/mes/app/root.tsx`, `JobOperation.tsx`, `UserNav.tsx`, `InspectionView.tsx` | Commented-out devtools, trailing commas against `biome.jsonc`, inert classes, a dead branch, a copied form. | Clean up. |++## Outcomes (2026-10-08)++The majors were fixed one area at a time (shared, then ERP, then MES). Each area ended with a single typecheck. Final state: typecheck passes for `@carbon/react`, `@carbon/documents`, `erp` and `mes`. Biome reports no new findings on the changed files.++- **Done:** A1, A3, B1–B6, C1–C6. C7 and C10 (the two desktop regressions) were done first.+- **A2, partly done:** `recordMenuSlot` is deleted. The method tools wrap their Menubar items in `<RecordAction slot="overflow">`. List pages keep `mobileMenuItems` on `Table` because a list has no record header that could own an overflow slot.+- **C1:** The materials section is now `JobOperation/components/Materials.tsx`. `toMaterialGroups` builds one row model, and both layouts read it. Only one layout mounts (`useViewport`). The direct-issue rule is the desktop rule (`=== false`) on both layouts. The 4 casts are deleted: `JobMaterial` already has the pick fields. `JobOperation.tsx` went from 3809 to 3007 lines. Checked in the browser at 393 px and 1440 px, and Issue opens the modal.+- **Skipped:**+ - **A4:** making `AppBarActions` newest-wins changes every page that fills it. The flag has one caller.+ - **A5:** the `Card` collapse gap is shared by desktop cards, and desktop must not change.+ - **B7:** the four other `InventoryDetails` callers are desktop layouts.+- **Kept:** `Suggestion` keeps `useMorePage` because it has no modal form to share.+- **Not done (minor):** A6, A8–A12, B8–B12, C8, C9, C11, C12.diff --git a/.ai/specs/2026-10-07-mes-phone-layout.md b/.ai/specs/2026-10-07-mes-phone-layout.mdnew file mode 100644index 0000000000..969fb86d23--- /dev/null+++ b/.ai/specs/2026-10-07-mes-phone-layout.md@@ -0,0 +1,116 @@+# MES phone layout++> Status: in-progress+> Date: 2026-10-07+> Extends: `.ai/specs/2026-10-07-viewport-api.md` (`max-md:`, `useViewport`)+> Design source: the MES module of the mobile prototype (`local-docs/mobile-design/index.html`, specs+> `src/build/screens/mes_a.json` and `mes_b.json`, before screenshots `screenshots/mes/`)++## TL;DR++- The MES gets a phone layout below 768px. Tablet and desktop do not change.+- The work is layout only: no new features, no new data, no removed data.+- Boards and cards keep their content; the large 3D thumbnail becomes a small tile on phones.+- The Jobs table shows as list rows on phones; the My Hours table scrolls inside its card.+- Toolbars and header rows that overflow at 393px wrap or move to their own row.+- Dialogs already open as bottom sheets through the shared components, so they need no work.++## Problem++The MES at 393px (screenshots in `screenshots/mes/`) has these faults:++| Screen | Fault |+|---|---|+| Schedule, Assigned | The toolbar is wider than the screen (Search, Filter, the station chip, Display). Each card shows a 330px 3D thumbnail, so one card fills the screen. |+| Active, Recent | The same full-width thumbnail on every card. |+| Jobs | An 8-column table; the last columns are off screen. |+| Maintenance | The tab row and the search and filter share one row and overflow. |+| My Hours | A 4-column table inside a card. |+| Picking detail | The header row holds the ID, status, the line count and Finish, and clips. |+| Operation | The back link, the title and four tabs share one 52px row; "Chat" is off screen. |+| Assembly, Inspection | The header strip holds 6 controls and clips. |++## Goals++- Nothing overflows horizontally at 320px to 430px on the screens in the table.+- Every element that a screen shows on desktop is still on the phone screen.+- Tablet (768px and up) renders as it does today.++## Non-goals++- No ERP tab bar. The MES desktop has no Home, Search, Create or Modules. Round 2 adds an MES tab bar built from the sidebar's own items (`2026-10-07-mes-phone-round-2.md`).+- No new interactions: drag stays drag, and no long-press menus.+- No change to the 3D model viewers or the wall displays. Round 2 changes the Job graph direction and minimap on phones; the graph stays a canvas.+- No change to dialog content. The shared `Modal`, `Drawer` and `Popover` already render bottom sheets below 768px.+- Prototype items that add content are out of scope: graph status icons and legend, explanations on disabled buttons, the location and due date in the picking hero.++## Design++All phone styles use `max-md:`. A component tree changes only where CSS cannot do it, with `useViewport().isPhone`.++### Page header (all queue pages)++- The header keeps `SidebarTrigger` and the title. The trigger already opens the Navigation sheet on phones.++### Schedule and Assigned (board)++1. The toolbar wraps on phones (`max-md:flex-wrap`). The search and Filter stay on the first row. The station chip and Display wrap to the next row.+2. A column is `max-md:w-[300px]`, so the next column shows at the right edge. The board already snaps.+3. `ItemCard`: on phones the thumbnail is a 40px tile in the card header, beside the item. The large thumbnail is `max-md:hidden`. The Display setting `showThumbnail` still controls both.++### Active and Recent (card grid)++- `OperationsList` cards use the same thumbnail rule as `ItemCard`.++### Jobs++- Below 768px the table is hidden and a list shows the same 8 fields per job: job and quantity on line 1, item ID and description on line 2, then status, deadline, due date, tracking and assignee. The whole row links to the job. At 768px and up the table shows as today.++### Maintenance++- The tab row and the search and filter stack on phones (`max-md:flex-col max-md:items-stretch`). The tab row scrolls sideways when it does not fit.++### My Hours++- The table edits a row in place (two date-time inputs and Save). A second phone layout would copy that edit logic, so on phones the table keeps its columns and scrolls sideways inside its card (`min-w-[560px]`). The page itself does not scroll sideways.++### Picking detail++- The header wraps on phones: the ID and status on the first row, the line count and Finish on the next row.+- A line's item name truncates instead of running under the quantity badge (the name gets `w-full` inside its `items-start` column).++### Operation, Assembly, Inspection++- Operation: below 768px the tab list moves out of the header onto its own full-width row, under the header. The tab row scrolls sideways when it does not fit.+- Assembly and Inspection: no change. Both header strips already hide their labels below `sm` and fit at 393px.++## Design Decisions++| Decision | Choice | Why |+|---|---|---|+| Shell | Keep the MES header and Navigation sheet | They already work on phones; a tab bar would add destinations the MES lacks |+| Board on phones | Keep columns, 300px wide | The board already snaps; a narrower column shows the next one |+| Thumbnail | 40px tile in the header on phones | One card per screen hides the queue |+| Tables | Jobs: list rows below 768px, all fields kept. My Hours: the table scrolls inside its card | Fields off screen are lost data. My Hours edits rows in place, so a second layout would copy its edit logic |+| Interactions | No long-press, no new sheets | Owner rule: adapt, never add |+| Breakpoint API | `max-md:` and `useViewport` | The viewport spec of 2026-10-07 |++## Acceptance criteria++- [ ] At 393px, each screen in the Problem table has no horizontal page scroll (`document.documentElement.scrollWidth <= 393`).+- [ ] At 393px, a Schedule card is under 300px tall with the thumbnail on.+- [ ] At 393px, Jobs shows every job's job ID, item, quantity, status, deadline, due date, tracking and assignee.+- [ ] At 393px, the Operation page shows all four tabs; Chat can be reached.+- [ ] At 1280px, Schedule, Jobs and Operation match their pre-change screenshots.+- [ ] Typecheck passes for `mes`; Biome passes on the changed files.++## Open questions (resolved)++- [x] Ask before each step? — **Answer:** No. The owner asked for all steps to run without check-ins.+- [x] Bottom tab bar for the MES? — **Answer:** No. Recorded as an exception in the prototype (R2.1).+- [x] Prototype items that add features? — **Answer:** Dropped (see Non-goals); the owner's rule is adapt, never add.++## Changelog++- 2026-10-07: First version, from the MES prototype.+- 2026-10-07: Implemented. My Hours keeps its table (scrolls in its card); Assembly and Inspection needed no change.diff --git a/.ai/specs/2026-10-07-mes-phone-round-2.md b/.ai/specs/2026-10-07-mes-phone-round-2.mdnew file mode 100644index 0000000000..3e6302fb99--- /dev/null+++ b/.ai/specs/2026-10-07-mes-phone-round-2.md@@ -0,0 +1,283 @@+# MES phone layout, round 2++> Status: approved+> Date: 2026-10-07+> Extends: `.ai/specs/2026-10-07-mes-phone-layout.md` (round 1) and `.ai/specs/2026-10-07-viewport-api.md` (`max-md:`, `useViewport`)+> Evidence: a round-1 review of 16 screens at 393px by 3 reviewers (space and layout, navigation, operator tasks). Each scored about 40/100.+> The review files (session scratch, not committed): `mes-r1/review-layout.md`, `mes-r1/review-nav.md`, `mes-r1/review-operator.md`, `mes-r1/round1.html`.++## TL;DR++- MES phones get real app chrome: one app bar on every page and a bottom tab bar (Schedule · Assigned · Active · Maintenance · More).+- Cards, toolbars and the Operation page use the screen better: 2-column cards, a 1-row toolbar, less fixed chrome.+- Task screens show their task: Inspection cells, the material Issue button and Picking Finish move into view and into thumb reach.+- Back goes to the page you came from, and the timer toggle opens on the running timer. Both also change desktop.+- Everything else at 768px and up stays the same. No new data and no new features, except 1 approved confirmation step.++## Problem++Round 1 fixed horizontal overflow. It did not fix chrome, density or task reach. The round-1 review found these faults (scores are the average of 3 reviewers):++| Screen | Score | Main fault |+|---|---|---|+| My Hours | 16 | The page has no header and no nav button. On a phone, the user cannot leave it. The table clips mid-word. |+| Inspection | 26 | The sample-entry columns start past the right edge. 5 icon-only actions crowd the header. |+| Job detail | 31 | The graph is left-to-right in a portrait screen. Nodes are about 35px wide. The minimap covers a corner. |+| Operation | 36 | Fixed chrome takes 40% of the screen. The phone does not show which timer runs. The Issue button is off-screen. |+| Schedule | 39 | The toolbar takes 3 rows. A card is about 395px tall, so 1.4 cards fit. |+| Picking detail | 42 | No Back. Finish is a 32px button at the top. |+| Assigned, Active, Recent | 43–48 | Card fields use the left half only. The list view greys out the item name and quantity. |+| Maintenance dispatch | 46 | An unlabelled Complete sits 16px from Start and completes with no confirmation. |+| Nav sheet | 54 | Count badges float away from their rows. The footer and the user row are below the fold. |++Faults that every reviewer found:++1. The only phone navigation is a 28px icon in the top-left corner (`packages/react/src/Sidebar.tsx:300`).+2. 13 routes build their own header. Heights are 50px, 52px or auto. Titles are 14px on phones (`Heading` `h4`).+3. Operation Back always goes to Schedule (`JobOperation.tsx:806-813`).+4. Default buttons are 32px (`Button` `md`). Completing actions sit at the top of the screen.++## Goals++- A user can reach every MES section from every root page with 1 tap in the bottom third of the screen.+- Every page has the same app bar below 768px: the same height, gutter, title size and Back control.+- Each work-card screen shows at least 2 full cards above the fold at 393×852.+- On the Operation page, the scrolling content gets at least 65% of the screen height.+- Each task screen shows its primary input and its completing action without a sideways scroll.+- All interactive controls that this spec touches are at least 44px on phones.+- The round-2 review scores the screens at 75/100 or more on average.++## Non-goals++- No new data, KPIs, Scan button or inbox. The approved exceptions are the 2 desktop changes and the dispatch confirmation below.+- No Clock Out confirmation (owner decision).+- No change to the 3D model viewers, the wall displays or dialog content.+- No change to the scroll model of the app shell. The layout reviewer suspects that nested scroll areas keep the browser toolbar expanded. Nobody verified this on a device, so it stays out of this round.+- No per-user tab bar settings.+- No dock on the Instructions and Chat tabs (today's behaviour stays).++## Design++All phone styles use `max-md:`. A component tree changes only where CSS cannot do it. Use CSS (`md:hidden`) for the tab bar. The MES has no server viewport hint, so `useViewport()` renders "desktop" on the server.++### Phase 1: app chrome and navigation++#### 1.1 Safe areas++- Add `viewport-fit=cover` to the viewport meta in `apps/mes/app/root.tsx`. The ERP has it already. Without it, `pb-safe` is 0 on iPhones, and the dock and the tab bar sit on the home indicator.++#### 1.2 `MesAppBar` (new, `apps/mes/app/components/MesAppBar.tsx`)++One header component for every MES page. At 768px and up it renders the markup that each page renders today: the sidebar trigger, the title and the page actions. Below 768px:++| Part | Phone spec |+|---|---|+| Container | `sticky top-0`, 52px plus `pt-safe`, `border-b`, `bg-card`. The same on root and pushed pages. |+| Left, root page | No sidebar trigger. The tab bar and More replace it. The title starts at the 16px gutter. |+| Left, pushed page | A 44×44 Back icon button (`LuChevronLeft`, `aria-label` "Back"). It goes to the origin page (1.5), else to the parent page. |+| Title | 17px, semibold, 1 line, ellipsis. Root: the page title. Pushed: the record ID. |+| Subtitle (pushed) | 12px muted: the parent page name, for example "Assigned". It replaces the "‹ Schedule" text button. |+| Right | At most 2 icon actions, each 44×44. |++Props: `title`, `subtitle?`, `back?: { to: string }`, `actions?: ReactNode`, `kind: "root" | "pushed"`. Move these headers onto it: operations, assigned, active, recent, jobs, maintenance, picking list, picking detail, timecard, job detail, dispatch detail, operation, inspection, assembly.++#### 1.3 `MesTabBar` (new) on a shared `TabBar` (new, `packages/react/src/TabBar.tsx`)++- Lift the presentational tab markup from `apps/erp/app/components/Layout/Mobile/MobileTabBar.tsx` (the `Tab` and its class names) into `TabBar` and `TabBarItem` in `@carbon/react`. `TabBarItem` takes `icon`, `label`, `to` or `onClick`, `isActive` and an optional `count`.+- Point the ERP `MobileTabBar` at the shared parts. The ERP tab bar must look the same as before.+- Build `apps/mes/app/components/MesTabBar.tsx`:++| Tab | Icon | Target |+|---|---|---|+| Schedule | `LuCalendarDays` | `path.to.operations` |+| Assigned | `LuClipboardList` | `path.to.assigned` |+| Active | `LuActivity` | `path.to.active`, count `activeEvents` |+| Maintenance | `LuWrench` | `path.to.maintenance`, count `activeMaintenanceCount` |+| More | `LuMenu` | opens the existing Navigation sheet (`useSidebar().setOpenMobile(true)`) |++- Labels, icons and targets come from one shared list. Export `QUEUES` and the titles map from `AppSidebar.tsx`, so the rail and the tab bar cannot drift.+- Show the bar on root pages only: Schedule, Assigned, Active, Recent, Jobs, Maintenance, the Picking list and My Hours. Match the Picking list by exact path, because `/x/picking/:id` shares the prefix.+- Hide the bar on pushed pages: Operation, Assembly, Inspection, Batch, Job detail, Dispatch detail and Picking detail.+- Hide the bar while a text input has focus.+- Active tab: foreground icon and label, a pill behind the icon, `aria-current="page"`. On Recent, Jobs, Picking and My Hours, the More tab is active.+- Count: a 16px pill on the icon. Hide it at 0.+- Size: 54px plus `pb-safe`. Root page content gets bottom padding for the bar. Toasts sit above the bar.++#### 1.4 Navigation sheet (`packages/react/src/NavRail.tsx`, phone branch only)++1. Place the count badge inline at the end of its row, vertically centred.+2. Pin the footer (Clock In, My Hours, the user row) below the scrolling groups, with `pb-safe`.+3. Add a trailing `LuArrowUpRight` to the rows that leave the app (the brand row and Displays).++The sheet keeps every desktop item, in the same groups and order.++#### 1.5 Back returns to the origin (desktop too)++1. Links into an operation pass the origin page: `OperationsList.tsx`, `Kanban/components/ItemCard.tsx` and `JobDag/JobOperationNode.tsx`. Use a `?from=` search parameter with the current path.+2. Operation, Assembly and Inspection read `from`. The Back target is that path, else `path.to.operations`.+3. The Back label is the title of the origin queue, from the shared titles map. On desktop the "‹ Schedule" button shows that title.+4. The redirects in `operation.$operationId.tsx` keep the search string, so `from` survives them. React Router drops `location.state` on a loader redirect, so `state` cannot carry the origin.++#### 1.6 Page titles (desktop too)++- "Assigned to Me" becomes "Assigned" (`assigned.tsx`).+- "Open Jobs" becomes "Jobs" (`jobs.tsx`).++#### 1.7 My Hours++1. Add `MesAppBar` (root, title "My Hours").+2. Below 768px, put Clock In / Clock Out in a sticky bottom bar as a full-width `lg` button. Keep the red Clock Out and the "Clocked in since" badge.+3. Below 768px, show each entry as a row: line 1 is the day and the duration, line 2 is the clock-in and clock-out times. The ⋮ menu becomes a trailing 44px button.+4. Show the empty message outside any scroller.+5. Below 768px, Prev and Next become 44px icon buttons, so the week range fits on 1 line.++### Phase 2: space++#### 2.1 Work cards (`ItemCard.tsx`, `OperationsList.tsx`)++- Below 768px, lay the card fields out in a 2-column grid. The job and the operation description span both columns. Status and duration, deadline and date, and sales order and customer pair up.+- Move the assignee and tags into the grid. Hide the separate footer band below 768px.+- Put the 2 progress bars side by side in 1 row.+- Fix the list card colours: the title and the quantity use `text-foreground`, as on the board card.+- Keep every field that the card shows today.++#### 2.2 Toolbars (Schedule, Assigned, Active, Recent)++- Row 1: Search (full width) and Filter (40×40 icon button).+- Row 2, only when present: the station chip and the active filter chips, in a sideways-scrolling row with an edge fade. The chip × gets a 44px hit area.+- Display, and on Assigned the board/list toggle, move into the app bar's 2 action slots.+- Active and Recent: remove the fixed toolbar height that makes the search overlap the cards.++#### 2.3 Board (`ColumnCard.tsx`)++- A single column fills the width (`max-md:only:w-full`).+- Size the board with flex instead of `calc(100dvh - …)`.+- Hide the horizontal scrollbar pill and the column drag grip below 768px.+- Column header padding drops to `py-2`.++#### 2.4 Operation page (`JobOperation.tsx`, `Controls.tsx`)++1. Below 768px, the context row (job ID, customer, description, status, duration, due) moves into the scrolling content area. It scrolls away with the content.+2. Below 768px, order the context items: status, due, customer, description, duration.+3. Below 768px, the meters fit in 1 row of 4. The label sits above, the value below. Values use 12px and do not truncate.+4. The toggle opens on the running timer type (all widths). If no timer runs, keep today's order: Setup, Machine, Labor (`useOperation.tsx`).+5. Below 1024px, the dock shows the running type and elapsed time, for example "Machine · 2d 6h". This label exists today but is hidden below 1024px.+6. Below 1024px, the + and ⋮ dock buttons get 12px captions: "Log completed" and "More". Use the existing Lingui strings.+7. Below 768px, the Completed, Scrapped and Due Date cards become 1 grouped card with 3 rows.+8. The job ⋮ button gets a 44px hit area on phones.+9. The green Start, the red Pause and the dock actions do not change.++#### 2.5 Picking detail (`picking.$pickingListId.tsx`)++1. Use `MesAppBar` (pushed, title is the list ID, Back to Picking). The status pill moves to the first content row.+2. Below 768px, "N/M lines" and Finish move into a sticky bottom bar. Finish is a full-width `lg` button.+3. Remove the inner bordered wrapper below 768px, so there is 1 container level.+4. Use a smaller thumbnail and `line-clamp-2` for item names.+5. The open-quantity badge becomes a neutral pill. Emerald stays for picked and orange for short.+6. Pick and Short become 48px tall below 768px.++#### 2.6 Smaller fixes++- Picking list: the label/value rows stretch to full width, so the values right-align.+- Jobs: the item ID and the description share 1 line. Quantity uses `text-foreground`.+- Maintenance: the tab row gets an edge fade and scrolls the active tab into view. The impact pill and the avatar move into the card header.++### Phase 3: task screens++#### 3.1 Inspection (`InspectionMeasurementMatrix.tsx`, `InspectionView.tsx`)++1. Below 768px, the sticky Characteristic column is 150px wide. The Gauge picker moves into the Characteristic cell as a second line, and the Gauge column hides. Sample 1 is then visible.+2. Add an edge fade to the matrix and to the meta bar.+3. The bordered frame wraps its rows. It does not stretch to the bottom.+4. Below 768px, Accept, Reject, Partial and Complete passed move into a bottom action bar of labelled 48px buttons. Accept is the primary button.+5. The header keeps the ID, the status and the timer. The timer shows its elapsed time on phones.+6. Put the Completed / Scrap / Rework counts first in the meta bar on phones.++#### 3.2 Materials on the Operation page++- Below 768px, render each material as a row card instead of the table. Line 1 is the part ID and "Actual / Estimated". Line 2 is the description. Line 3 is the existing badges. A trailing 44px Issue button uses the existing action.+- The tracked (serial/batch) Issue branch gets the same row.+- At 768px and up, the table stays.++#### 3.3 Job detail graph (`JobDag.tsx`)++- Below 768px, the default direction is top-to-bottom. The direction toggle stays.+- Below 768px, hide the minimap.+- The graph toolbar buttons are 44px on phones.+- Wrap "Left to Right" and "Fit" in Lingui.++#### 3.4 Maintenance dispatch (`dispatch.$dispatchId.tsx`)++1. Use `MesAppBar` (pushed, Back to Maintenance).+2. Below 768px, Start/Pause stays the big round button. Complete becomes a labelled full-width secondary button below it.+3. Complete opens a confirmation (all widths, owner decision). The confirmation names the dispatch and has Cancel on the left and Complete on the right.+4. Hide the Description card when the document has no text.+5. The work-centre name becomes the card title, so the label-only band goes away.++#### 3.5 Empty states++Active, Schedule, Jobs, Picking list and Maintenance use a neutral muted icon and a 17px title on phones. Keep the existing strings. Add no new text.++## Design Decisions++| Decision | Choice | Why |+|---|---|---|+| Phone navigation | Bottom tab bar with 4 queues + More | 1 tap in the thumb zone. Uses only MES sidebar items. Owner approved. |+| Which 4 tabs | Schedule, Assigned, Active, Maintenance | The first 3 rail items, plus the 2 items with counts. Owner approved. |+| Tab bar code | Shared `TabBar` in `@carbon/react`, used by ERP and MES | The ERP tab bar imports ERP-only modules, so MES cannot use it as-is. The repo rule puts shared UI in a package. |+| Tab bar visibility | CSS (`md:hidden`), root pages only | MES has no server viewport hint. A JS switch flashes on hydrate. Pushed pages have their own bottom bars. |+| Header | One `MesAppBar` for 14 pages | 13 hand-built headers disagree on height, title size and Back. |+| Back target | The `?from=` parameter, else the parent page | Back must go where the user came from. Owner approved the desktop change. |+| Card density | 2-column grid, all fields kept | Owner chose this over a 3-line summary. Adapt, do not remove. |+| Timer toggle default | The running type, all widths | Today a phone shows Start while Machine runs. Owner approved the desktop change. |+| Materials on phones | Row cards with a visible Issue button | The table hides the Issue button off-screen. Same data, different container. |+| Inspection on phones | Narrow first column, gauge folded in | Smallest change that puts sample 1 in view. A card-per-characteristic stepper is larger. |+| Job graph | Top-to-bottom, no minimap on phones | Owner approved. The canvas stays a canvas. |+| Dispatch Complete | Confirmation at all widths | Owner approved. Complete is 1 tap from Start today. |+| Shell scroll model | No change | The browser-toolbar cause is not verified. |++## Acceptance Criteria++At 393×852 unless stated:++1. On Schedule, Assigned, Active, Recent, Jobs, Maintenance, Picking and My Hours, a 5-item tab bar shows at the bottom. A tap on Active opens `/x/active`, and the Active tab shows as current.+2. With 6 open maintenance dispatches, the Maintenance tab shows "6". With 0, it shows no badge.+3. A tap on More opens the Navigation sheet. The sheet lists Schedule, Assigned, Active, Recent, Jobs, Maintenance, Picking, Add Inventory, Remove Inventory, End Operations, Suggestion and Displays in that order. Clock In, My Hours and the user row show without a scroll.+4. On Operation, Assembly, Inspection, Job detail, Dispatch detail and Picking detail, no tab bar shows, and a 44px Back shows at the top-left.+5. Open an operation from Active, then tap Back. The app shows `/x/active`. The same flow on desktop at 1280px also returns to Active.+6. My Hours shows the app bar, the tab bar and a full-width Clock In button at the bottom. With no entries, the full empty message shows.+7. On Schedule with 1 work center, the column fills the width, and at least 2 full cards show above the fold.+8. On the Operation page with a running Machine timer, the toggle shows Machine and the dock shows a red Pause and "Machine · <elapsed>".+9. On the Operation page, the scrolling content area is at least 65% of the screen height on the Details tab. The context row scrolls away.+10. On the Operation page, every material shows an Issue button that is at least 44px and fully on screen.+11. On Inspection, the first sample input is fully visible without a sideways scroll. Accept shows as a labelled button at the bottom.+12. On Picking detail, Finish is a full-width button at the bottom.+13. On Dispatch detail, a tap on Complete opens a confirmation. Cancel closes it and the dispatch stays open.+14. On Job detail, the graph runs top-to-bottom and no minimap shows.+15. `document.documentElement.scrollWidth` is 393 on every screen in this spec.+16. At 1280×800, Schedule, Assigned, Jobs, Operation, Picking detail and Inspection match their pre-change screenshots, except for the 2 renamed titles and the Back label.+17. The ERP tab bar at 393px looks the same as before the `TabBar` extraction.+18. `pnpm exec turbo run typecheck --filter=mes --filter=erp` passes. Every new string is in Lingui.+19. A round-2 review by the same 3 reviewer lenses averages 75/100 or more.++## Open Questions++- [x] Should the MES have a bottom tab bar? — **Answer:** Yes. Schedule · Assigned · Active · Maintenance · More (owner).+- [x] Back to the origin also changes desktop. Allow it? — **Answer:** Yes (owner).+- [x] Rename "Assigned to Me" and "Open Jobs" to match the nav? — **Answer:** Yes, desktop too (owner).+- [x] Job graph top-to-bottom on phones with no minimap? — **Answer:** Yes (owner).+- [x] Add a confirmation to dispatch Complete? — **Answer:** Yes (owner).+- [x] Timer toggle opens on the running type, desktop too? — **Answer:** Yes, at all widths (owner).+- [x] Card density: 2-column with all fields, or a 3-line summary? — **Answer:** 2-column, keep all fields (owner).+- [x] Confirm Clock Out? — **Answer:** No. Clock Out stays 1 tap (owner).+- [x] Change the shell scroll model to document scroll? — **Answer:** Out of scope for this round. The cause is not verified on a device.+- [x] Run the 3 phases one at a time with a review after each, or all then review? — **Answer:** All 3 phases, then 1 round-2 review (owner).++## Research++N/A. This is layout work inside the existing MES. The design follows the phone rulebook from the ERP phone redesign (`local-docs/mobile-design/src/build/rules.html`) and the ERP phone chrome (`.ai/specs/2026-10-07-mobile-chrome-structure.md`).++## Changelog++- 2026-10-07: Draft written from the round-1 review and 8 owner answers.+- 2026-10-07: Approved. Back uses `?from=` instead of `location.state` (state does not survive loader redirects). Empty states add no new text.diff --git a/apps/mes/app/components/AdjustInventory.tsx b/apps/mes/app/components/AdjustInventory.tsxindex 73f2259ae4..73fd9919b6 100644--- a/apps/mes/app/components/AdjustInventory.tsx+++ b/apps/mes/app/components/AdjustInventory.tsx@@ -9,16 +9,8 @@ import { Combobox, Hidden, Number, Submit, ValidatedForm } from "@carbon/form";import {Button,Loading,- Modal,- ModalBody,- ModalContent,- ModalDescription,- ModalFooter,- ModalHeader,- ModalTitle,NavRailItem,toast,- useDisclosure,useMount,useRouteData,VStack@@ -31,10 +23,14 @@ import type { action as endShiftAction } from "~/routes/x+/end-shift";import { inventoryAdjustmentValidator } from "~/services/inventory.service";import { useItems } from "~/stores";import { path } from "~/utils/path";+import { ToolSurface, useToolSurface } from "./MoreSheet";export function AdjustInventory({ add }: { add: boolean }) {const { t } = useLingui();- const modal = useDisclosure();+ const surface = useToolSurface(+ add ? "add-inventory" : "remove-inventory",+ add ? t`Add Inventory` : t`Remove Inventory`+ );const fetcher = useFetcher<typeof endShiftAction>();const [items] = useItems();const [loading, setLoading] = useState(false);@@ -91,7 +87,7 @@ export function AdjustInventory({ add }: { add: boolean }) {// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.data?.success === true) {- modal.onClose();+ surface.done();toast.success(fetcher.data?.message ?? t`Inventory adjustment completed`);}@@ -112,96 +108,81 @@ export function AdjustInventory({ add }: { add: boolean }) {}));}, [items]);+ const title = add ? (+ <Trans>Add Inventory</Trans>+ ) : (+ <Trans>Remove Inventory</Trans>+ );+ const description = add ? (+ <Trans>Manually add items to inventory</Trans>+ ) : (+ <Trans>Manually remove items from inventory</Trans>+ );+ const fields = (+ <>+ <Hidden+ name="entryType"+ value={add ? "Positive Adjmt." : "Negative Adjmt."}+ />+ <Hidden name="locationId" value={routeData?.location ?? ""} />+ <VStack spacing={4}>+ <Loading isLoading={loading}>+ <Combobox+ label={t`Item`}+ name="itemId"+ onChange={onItemChange}+ options={itemOptions}+ itemHeight={44}+ />+ <Number label={t`Quantity`} name="quantity" />+ <Combobox+ label={t`Storage Unit`}+ name="storageUnitId"+ options={storageUnits}+ value={selectedStorageUnit ?? ""}+ onChange={(value) => setSelectedStorageUnit(value?.value ?? null)}+ />+ </Loading>+ </VStack>+ </>+ );+ const form = (children: ReactNode) => (+ <ValidatedForm+ method="post"+ action={path.to.inventoryAdjustment}+ validator={inventoryAdjustmentValidator}+ defaultValues={{+ itemId: "",+ quantity: 1,+ entryType: add ? "Positive Adjmt." : "Negative Adjmt."+ }}+ fetcher={fetcher}+ >+ {children}+ </ValidatedForm>+ );+return (<><NavRailItemicon={add ? <LuGitPullRequestCreateArrow /> : <LuGitBranchPlus />}- label={add ? t`Add Inventory` : t`Remove Inventory`}- onClick={modal.onOpen}+ label={surface.title}+ onClick={surface.open}+ />+ <ToolSurface+ surface={surface}+ description={description}+ body={fields}+ wrap={form}+ footer={+ <>+ <Button type="button" onClick={surface.close} variant="secondary">+ <Trans>Cancel</Trans>+ </Button>+ <Submit>{title}</Submit>+ </>+ }/>- {modal.isOpen && (- <Modal- open={modal.isOpen}- onOpenChange={(open) => !open && modal.onClose()}- >- <ModalContent>- <ValidatedForm- method="post"- action={path.to.inventoryAdjustment}- validator={inventoryAdjustmentValidator}- defaultValues={{- itemId: "",- quantity: 1,- entryType: add ? "Positive Adjmt." : "Negative Adjmt."- }}- fetcher={fetcher}- >- <ModalHeader>- <ModalTitle>- {add ? (- <Trans>Add Inventory</Trans>- ) : (- <Trans>Remove Inventory</Trans>- )}- </ModalTitle>- <ModalDescription>- {add ? (- <Trans>Manually add items to inventory</Trans>- ) : (- <Trans>Manually remove items from inventory</Trans>- )}- </ModalDescription>- </ModalHeader>- <ModalBody>- <Hidden- name="entryType"- value={add ? "Positive Adjmt." : "Negative Adjmt."}- />- <Hidden name="locationId" value={routeData?.location ?? ""} />- <VStack spacing={4}>- <Loading isLoading={loading}>- <Combobox- label={t`Item`}- name="itemId"- onChange={onItemChange}- options={itemOptions}- itemHeight={44}- />- <Number label={t`Quantity`} name="quantity" />- <Combobox- label={t`Storage Unit`}- name="storageUnitId"- options={storageUnits}- value={selectedStorageUnit ?? ""}- onChange={(value) =>- setSelectedStorageUnit(value?.value ?? null)- }- />- </Loading>- </VStack>- </ModalBody>-- <ModalFooter>- <Button- type="button"- onClick={modal.onClose}- variant="secondary"- >- <Trans>Cancel</Trans>- </Button>-- <Submit>- {add ? (- <Trans>Add Inventory</Trans>- ) : (- <Trans>Remove Inventory</Trans>- )}- </Submit>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- )}</>);}diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsxindex fb875512ce..ce8af0a164 100644--- a/apps/mes/app/components/AppSidebar.tsx+++ b/apps/mes/app/components/AppSidebar.tsx@@ -11,13 +11,15 @@ import {NavRailGroup,NavRailLink,useMode,- useShortcutKeyMap+ useShortcutKeyMap,+ useSidebar} from "@carbon/react";import { useLingui } from "@lingui/react/macro";import { Suspense, useMemo } from "react";import { BsFillHexagonFill } from "react-icons/bs";import {LuActivity,+ LuArrowUpRight,LuCalendarDays,LuCirclePlay,LuClipboardList,@@ -33,6 +35,7 @@ import type { PinnedInUser } from "~/types";import { ERP_URL, path } from "~/utils/path";import { AdjustInventory } from "./AdjustInventory";import { EndShift } from "./EndShift";+import { MoreSheet } from "./MoreSheet";import Suggestion from "./Suggestion";import { TimeCardButton } from "./TimeCardButton";import { UserNav } from "./UserNav";@@ -48,7 +51,9 @@ export function AppSidebar({locations,openClockEntry,pinnedInUser,- timeCardEnabled+ timeCardEnabled,+ moreOpen,+ onMoreOpenChange}: {activeEvents: number;activeMaintenanceCount: number;@@ -63,32 +68,83 @@ export function AppSidebar({openClockEntry?: Promise<{data: { id: string; clockIn: string; [key: string]: unknown } | null;}> | null;+ /** Phones: the More tab's sheet. */+ moreOpen: boolean;+ onMoreOpenChange: (open: boolean) => void;}) {const { t } = useLingui();+ const { isMobile } = useSidebar();++ const queues = (+ <QueueLinks+ counts={{+ active: activeEvents,+ maintenance: activeMaintenanceCount+ }}+ />+ );+ const timeCard = timeCardEnabled && (+ <Suspense fallback={<TimeCardButton openClockEntry={null} />}>+ <Await resolve={openClockEntry}>+ {(resolved) => (+ <TimeCardButton+ openClockEntry={+ resolved?.data+ ? {+ id: resolved.data.id,+ clockIn: resolved.data.clockIn+ }+ : null+ }+ />+ )}+ </Await>+ </Suspense>+ );+ const tools = (+ <>+ <NavRailGroup label={t`Inventory Adjustments`}>+ <AdjustInventory add={true} />+ <AdjustInventory add={false} />+ </NavRailGroup>+ <NavRailGroup label={t`Tools`}>+ <EndShift />+ <Suggestion />+ <DisplaysLink />+ </NavRailGroup>+ </>+ );++ // Phones: the app bar title opens the queues; More holds the rest.+ if (isMobile) {+ return (+ <>+ <NavRail>{queues}</NavRail>+ <MoreSheet+ open={moreOpen}+ onOpenChange={onMoreOpenChange}+ header={<CompanyLink company={company} />}+ company={company}+ companies={companies}+ consoleEnabled={consoleEnabled}+ consoleMode={consoleMode}+ location={location}+ locations={locations}+ pinnedInUser={pinnedInUser}+ >+ {timeCard}+ {tools}+ </MoreSheet>+ </>+ );+ }return (<NavRailheader={<CompanyLink company={company} />}footer={<>- {timeCardEnabled && (- <Suspense fallback={<TimeCardButton openClockEntry={null} />}>- <Await resolve={openClockEntry}>- {(resolved) => (- <TimeCardButton- openClockEntry={- resolved?.data- ? {- id: resolved.data.id,- clockIn: resolved.data.clockIn- }- : null- }- />- )}- </Await>- </Suspense>- )}+ {timeCard}<UserNavcompany={company}companies={companies}@@ -101,23 +157,8 @@ export function AppSidebar({</>}>- <NavRailGroup label={t`Operations`}>- <QueueLinks- counts={{- active: activeEvents,- maintenance: activeMaintenanceCount- }}- />- </NavRailGroup>- <NavRailGroup label={t`Inventory Adjustments`}>- <AdjustInventory add={true} />- <AdjustInventory add={false} />- </NavRailGroup>- <NavRailGroup label={t`Tools`}>- <EndShift />- <Suggestion />- <DisplaysLink />- </NavRailGroup>+ <NavRailGroup label={t`Operations`}>{queues}</NavRailGroup>+ {tools}</NavRail>);}@@ -142,36 +183,52 @@ function CompanyLink({ company }: { company: Company }) {);}-type QueueKey = keyof typeof MES_NAV_SHORTCUTS;+export type QueueKey = keyof typeof MES_NAV_SHORTCUTS;/** The task queues, in rail order; each one's ⌥-digit comes from its key. */-const QUEUES: { key: QueueKey; icon: typeof LuActivity; to: string }[] = [- { key: "operations", icon: LuCalendarDays, to: path.to.operations },- { key: "assigned", icon: LuClipboardList, to: path.to.assigned },- { key: "active", icon: LuActivity, to: path.to.active },- { key: "recent", icon: LuHistory, to: path.to.recent },- { key: "jobs", icon: LuCirclePlay, to: path.to.jobs },- { key: "maintenance", icon: LuWrench, to: path.to.maintenance },- { key: "picking", icon: LuPackageCheck, to: path.to.picking }-];--// `path.to.operations` carries a `?saved=1` query; activity matches on paths.-const pathOf = (to: string) => to.split("?")[0];+export const QUEUES: { key: QueueKey; icon: typeof LuActivity; to: string }[] =+ [+ { key: "operations", icon: LuCalendarDays, to: path.to.operations },+ { key: "assigned", icon: LuClipboardList, to: path.to.assigned },+ { key: "active", icon: LuActivity, to: path.to.active },+ { key: "recent", icon: LuHistory, to: path.to.recent },+ { key: "jobs", icon: LuCirclePlay, to: path.to.jobs },+ { key: "maintenance", icon: LuWrench, to: path.to.maintenance },+ { key: "picking", icon: LuPackageCheck, to: path.to.picking }+ ];-function QueueLinks({ counts }: { counts: Partial<Record<QueueKey, number>> }) {+/** `path.to.operations` carries a `?saved=1` query; activity matches on paths. */+export const queuePath = (to: string) => to.split("?")[0];++/** The queue titles. The rail, the tab bar and Back labels share them. */+export function useQueueTitles(): Record<QueueKey, string> {const { t } = useLingui();+ return useMemo(+ () => ({+ operations: t`Schedule`,+ assigned: t`Assigned`,+ active: t`Active`,+ recent: t`Recent`,+ jobs: t`Jobs`,+ maintenance: t`Maintenance`,+ picking: t`Picking`+ }),+ [t]+ );+}++/** The queue a path belongs to. Job detail (`/x/job/:id`) belongs to Jobs. */+export function queueKeyForPath(pathname: string): QueueKey | undefined {+ const queue = QUEUES.find((q) => pathname.startsWith(queuePath(q.to)));+ if (queue) return queue.key;+ // generatePath drops a trailing slash, so add it back for the prefix test.+ return pathname.startsWith(`${path.to.jobDag("")}/`) ? "jobs" : undefined;+}++function QueueLinks({ counts }: { counts: Partial<Record<QueueKey, number>> }) {const navigate = useNavigate();const { pathname } = useLocation();-- const titles: Record<QueueKey, string> = {- operations: t`Schedule`,- assigned: t`Assigned`,- active: t`Active`,- recent: t`Recent`,- jobs: t`Jobs`,- maintenance: t`Maintenance`,- picking: t`Picking`- };+ const titles = useQueueTitles();useShortcutKeyMap(useMemo(@@ -192,7 +249,7 @@ function QueueLinks({ counts }: { counts: Partial<Record<QueueKey, number>> }) {to={queue.to}icon={<queue.icon />}label={titles[queue.key]}- isActive={pathname.startsWith(pathOf(queue.to))}+ isActive={pathname.startsWith(queuePath(queue.to))}tag={counts[queue.key] ? String(counts[queue.key]) : undefined}/>))}@@ -216,6 +273,9 @@ function DisplaysLink() {externaltarget="_blank"rel="noreferrer"+ trailing={+ <LuArrowUpRight className="hidden size-4 text-muted-foreground max-md:block" />+ }/>);}diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex 3bbd08f42b..65a9ab096c 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -45,7 +45,8 @@ import {useKeyboardWedge,useMode,useRouteData,- useShortcutKeys+ useShortcutKeys,+ useViewport} from "@carbon/react";import { formatDurationMilliseconds } from "@carbon/utils";import type {@@ -56,7 +57,7 @@ import type {} from "@carbon/viewer";import { AssemblyPlayer, buildSubAssemblyPlan } from "@carbon/viewer";import { ModelPreview } from "@carbon/viewer/model-preview";-import { useLingui } from "@lingui/react/macro";+import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo, useRef, useState } from "react";import {LuArrowLeft,@@ -99,6 +100,8 @@ import { QuantityModal } from "~/components/JobOperation/components/QuantityModaimport { ReworkModal } from "~/components/JobOperation/components/ReworkModal";import { SerialSelectorModal } from "~/components/JobOperation/components/SerialSelectorModal";import { RecordModal } from "~/components/JobOperation/components/Step";+import { MesAppBar } from "~/components/MesAppBar";+import { useMesBottomBar } from "~/components/MesBottomBar";import { useRealtime, useUser } from "~/hooks";import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";import type {@@ -107,6 +110,7 @@ import type {OperationWithDetails,ProductionEvent as ProductionEventType} from "~/services/types";+import { ORIGIN_PARAM, readOrigin, useOrigin } from "~/utils/origin";import { getPrivateUrl, path } from "~/utils/path";import { deriveUnits } from "~/utils/units";@@ -534,12 +538,15 @@ export function AssemblyView({assemblyPlayback,productionQuantities = { scrap: 0, production: 0, rework: 0 }}: Props) {+ const bottomBarRef = useMesBottomBar();const user = useUser();const { carbon } = useCarbon();const mode = useMode();const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const { t } = useLingui();+ const origin = useOrigin();+ const { isPhone } = useViewport();// Which main panel is shown: the assembly details, the 3D model, or chat.const [tab, setTab] = useState<"details" | "model" | "chat">("details");@@ -1457,6 +1464,9 @@ export function AssemblyView({if (setup?.id) fd.set("setupProductionEventId", setup.id);if (labor?.id) fd.set("laborProductionEventId", labor.id);if (machine?.id) fd.set("machineProductionEventId", machine.id);+ // A finishing completion redirects back to the origin page.+ const from = readOrigin(searchParams);+ if (from) fd.set(ORIGIN_PARAM, from);completeUnitFetcher.submit(fd, {method: "post",action: path.to.complete@@ -1623,228 +1633,285 @@ export function AssemblyView({const companyLogo =mode === "dark" ? user.company.logoDarkIcon : user.company.logoLightIcon;- return (- <div className="relative flex h-dvh w-full flex-col overflow-hidden bg-background text-foreground">- {/* ── HEADER ── */}- <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border">- {/* Full-height segment matching the Flag issue / Complete / timer buttons. */}- <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />- {companyLogo ? (- <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">- <img- src={companyLogo}- alt={`${user.company.name} logo`}- className="h-7 w-auto max-w-[140px] object-contain"- />- </div>- ) : null}-- <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">- <span className="truncate text-sm font-semibold">- {job?.itemReadableIdWithRevision ?? "—"}- </span>- {operation?.description ? (+ // ── STEPS BAR (segmented, click to jump; green = done) ──+ const renderStepsBar = (className?: string) =>+ steps.length > 0 ? (+ <div+ className={cn(+ "flex min-h-9 shrink-0 items-center gap-3 bg-card border-b border-border px-5 py-1 max-md:px-4",+ className+ )}+ >+ {/* Label reflects the active filter so a filtered bar (e.g. only the completed,+ all-green steps) is never mistaken for "everything done". */}+ <span className="whitespace-nowrap text-xs text-muted-foreground">+ {stepFilter === "completed"+ ? `${doneCount} completed`+ : stepFilter === "incomplete"+ ? `${steps.length - doneCount} incomplete`+ : `${doneCount} / ${steps.length} done`}+ </span>+ <div className="flex min-w-0 flex-1 items-center gap-1">+ {openSubAssemblyId ? (<>- <span className="hidden text-muted-foreground md:inline">·</span>- <span className="hidden truncate text-sm text-foreground/90 lg:inline">- {operation.description}+ <Button+ variant="ghost"+ size="md"+ leftIcon={<LuArrowLeft />}+ onClick={closeSubAssembly}+ >+ {t`All steps`}+ </Button>+ <span className="max-w-[40%] shrink-0 truncate text-xs text-muted-foreground">+ {t`Sub-Assembly ${subAssemblyNumber(openSubAssemblyId)} · ${subAssemblyTitle(openSubAssemblyId)}`}</span>+ {openIndices+ .filter((i) => stepMatchesFilter(steps[i]))+ .map((i) => renderStepSegment(steps[i], i))}</>- ) : null}+ ) : (+ barItems.map((item) => {+ if (item.kind === "step") {+ const s = steps[item.index];+ return stepMatchesFilter(s)+ ? renderStepSegment(s, item.index)+ : null;+ }+ const members = item.indices.map((i) => steps[i]);+ const allDone = members.every(isStepDone);+ if (stepFilter === "completed" && !allDone) return null;+ if (stepFilter === "incomplete" && allDone) return null;+ const isCurrent = item.indices.includes(currentStep);+ return (+ <button+ key={item.headerId}+ type="button"+ aria-label={t`Open sub-assembly ${subAssemblyNumber(item.headerId)}: ${subAssemblyTitle(item.headerId)}`}+ title={t`Sub-Assembly ${subAssemblyNumber(item.headerId)} · ${subAssemblyTitle(item.headerId)}`}+ onClick={() => openSubAssembly(item.headerId, item.indices)}+ style={{ flexGrow: item.indices.length }}+ className={cn(+ "flex h-6 flex-1 basis-0 items-center gap-0.5 rounded-[3px] border px-1 transition-colors hover:bg-muted",+ isCurrent ? "border-foreground" : "border-border"+ )}+ >+ <LuBoxes className="size-3.5 shrink-0 text-muted-foreground" />+ {item.indices.map((i) => (+ <span+ key={steps[i].id}+ className={cn(+ "h-2 flex-1 rounded-[1px]",+ stepSegmentTone(steps[i], i)+ )}+ />+ ))}+ </button>+ );+ })+ )}+ {stepFilter === "incomplete" && doneCount === steps.length && (+ <span className="text-xs text-emerald-500">All steps done</span>+ )}+ {stepFilter === "completed" && doneCount === 0 && (+ <span className="text-xs text-muted-foreground">+ No completed steps yet+ </span>+ )}</div>+ {/* Filter which steps the bar emphasizes (all / completed / incomplete). */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Filter steps"+ variant={stepFilter === "all" ? "ghost" : "active"}+ size="sm"+ icon={<LuListFilter />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuRadioGroup+ value={stepFilter}+ onValueChange={(v) =>+ setStepFilter(v as "all" | "completed" | "incomplete")+ }+ >+ <DropdownMenuRadioItem value="all">+ Show all+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="completed">+ Show completed+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="incomplete">+ Show incomplete+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">+ {currentStep + 1} / {steps.length}+ </span>+ {/* Unit pager — fallback for narrow screens (< lg) where the left sidebar+ is hidden; on lg+ the richer sidebar UnitNavigator takes over. Assembly+ builds one at a time, but the operator can page back to review or fix a+ prior unit's step records — mirrors the operation view. */}+ {isMultiQuantity && (+ <div className="flex items-center gap-0.5 lg:hidden">+ <IconButton+ aria-label="Previous unit"+ variant="ghost"+ size="sm"+ icon={<LuChevronLeft />}+ isDisabled={currentUnitIndex <= 0}+ onClick={() => goToUnit(currentUnitIndex - 1)}+ />+ <Badge+ variant="secondary"+ className="whitespace-nowrap tabular-nums"+ >+ Unit {Math.min(currentUnitIndex + 1, unitCount)} / {unitCount}+ </Badge>+ <IconButton+ aria-label="Next unit"+ variant="ghost"+ size="sm"+ icon={<LuChevronRight />}+ isDisabled={currentUnitIndex >= maxNavigableUnitIndex}+ onClick={() => goToUnit(currentUnitIndex + 1)}+ />+ </div>+ )}+ </div>+ ) : null;- <div className="flex-1" />+ // Phones: the item ID and the steps bar scroll with the Details content,+ // and sit over the tab content on Model and Chat. md+ keeps the bar above.+ const detailsShown = !(+ (tab === "model" && modelPath) ||+ (tab === "chat" && operation)+ );+ const phoneItemId = operation?.jobReadableId+ ? job?.itemReadableIdWithRevision+ : null;+ const renderPhoneContext = () =>+ phoneItemId || steps.length > 0 ? (+ <div className="flex shrink-0 flex-col border-b border-border bg-card md:hidden">+ {phoneItemId ? (+ <span+ className={cn(+ "truncate px-4 pt-2 text-sm font-medium",+ steps.length === 0 && "pb-2"+ )}+ >+ {phoneItemId}+ </span>+ ) : null}+ {renderStepsBar("border-b-0")}+ </div>+ ) : null;- {/* Full-height segmented actions — same treatment as the timer button:- flush, no rounded corners, a left-border divider, hover highlight. */}+ // The header's actions; the md+ header and the phone app bar share them.+ const headerActions = (+ <>+ {/* Phones: Complete sits in the bottom action bar instead. */}+ {operation ? (<buttontype="button"- onClick={qualityModal.onOpen}- className="hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex"+ onClick={completeModal.onOpen}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] max-md:hidden md:gap-2 md:px-4">- <LuFlag className="size-4" />- Flag issue+ <LuCheck className="size-4" />+ <Trans>Complete</Trans></button>- {operation ? (- <button- type="button"- onClick={completeModal.onOpen}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"- >- <LuCheck className="size-4" />- <span className="hidden sm:inline">Complete</span>- <span className="sm:hidden">Done</span>- </button>- ) : null}- {operation ? (- <button- type="button"- aria-label="More actions"- onClick={actionsSheet.onOpen}- className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:px-4"- >- <LuEllipsisVertical className="size-4" />- </button>- ) : null}+ ) : null}+ {operation ? (+ <button+ type="button"+ aria-label={t`More actions`}+ onClick={actionsSheet.onOpen}+ className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] max-md:min-w-11 md:px-4"+ >+ <LuEllipsisVertical className="size-4" />+ </button>+ ) : null}++ {operation+ ? headerWorkTypes.map((wt) => (+ <TimerControl+ key={wt}+ operation={operation}+ openEvent={openEventForWorkType(wt)}+ workType={wt}+ trackedEntityId={isTracked ? currentEntity?.id : undefined}+ unitIndex={currentUnitIndex}+ />+ ))+ : null}+ </>+ );- {operation- ? headerWorkTypes.map((wt) => (- <TimerControl- key={wt}- operation={operation}- openEvent={openEventForWorkType(wt)}- workType={wt}- trackedEntityId={isTracked ? currentEntity?.id : undefined}- unitIndex={currentUnitIndex}+ return (+ <div className="relative flex h-dvh w-full flex-col overflow-hidden bg-background text-foreground">+ {/* ── HEADER ── */}+ <MesAppBar+ kind="pushed"+ title={+ operation?.jobReadableId ?? job?.itemReadableIdWithRevision ?? "—"+ }+ subtitle={origin.label}+ back={{ to: origin.to }}+ desktop={null}+ actions={headerActions}+ />+ {/* Phones use the app bar above; one header mounts so its timers do too. */}+ {!isPhone && (+ <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border max-md:hidden">+ {/* Full-height segment matching the Flag issue / Complete / timer buttons. */}+ <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />+ {companyLogo ? (+ <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">+ <img+ src={companyLogo}+ alt={`${user.company.name} logo`}+ className="h-7 w-auto max-w-[140px] object-contain"/>- ))- : null}- </header>-- {/* ── STEPS BAR (segmented, click to jump; green = done) ── */}- {steps.length > 0 && (- <div className="flex min-h-9 shrink-0 items-center gap-3 bg-card border-b border-border px-5 py-1">- {/* Label reflects the active filter so a filtered bar (e.g. only the completed,- all-green steps) is never mistaken for "everything done". */}- <span className="whitespace-nowrap text-xs text-muted-foreground">- {stepFilter === "completed"- ? `${doneCount} completed`- : stepFilter === "incomplete"- ? `${steps.length - doneCount} incomplete`- : `${doneCount} / ${steps.length} done`}- </span>- <div className="flex min-w-0 flex-1 items-center gap-1">- {openSubAssemblyId ? (+ </div>+ ) : null}++ <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">+ <span className="truncate text-sm font-semibold">+ {job?.itemReadableIdWithRevision ?? "—"}+ </span>+ {operation?.description ? (<>- <Button- variant="ghost"- size="md"- leftIcon={<LuArrowLeft />}- onClick={closeSubAssembly}- >- {t`All steps`}- </Button>- <span className="max-w-[40%] shrink-0 truncate text-xs text-muted-foreground">- {t`Sub-Assembly ${subAssemblyNumber(openSubAssemblyId)} · ${subAssemblyTitle(openSubAssemblyId)}`}+ <span className="hidden text-muted-foreground md:inline">+ ·+ </span>+ <span className="hidden truncate text-sm text-foreground/90 lg:inline">+ {operation.description}</span>- {openIndices- .filter((i) => stepMatchesFilter(steps[i]))- .map((i) => renderStepSegment(steps[i], i))}</>- ) : (- barItems.map((item) => {- if (item.kind === "step") {- const s = steps[item.index];- return stepMatchesFilter(s)- ? renderStepSegment(s, item.index)- : null;- }- const members = item.indices.map((i) => steps[i]);- const allDone = members.every(isStepDone);- if (stepFilter === "completed" && !allDone) return null;- if (stepFilter === "incomplete" && allDone) return null;- const isCurrent = item.indices.includes(currentStep);- return (- <button- key={item.headerId}- type="button"- aria-label={t`Open sub-assembly ${subAssemblyNumber(item.headerId)}: ${subAssemblyTitle(item.headerId)}`}- title={t`Sub-Assembly ${subAssemblyNumber(item.headerId)} · ${subAssemblyTitle(item.headerId)}`}- onClick={() => openSubAssembly(item.headerId, item.indices)}- style={{ flexGrow: item.indices.length }}- className={cn(- "flex h-6 flex-1 basis-0 items-center gap-0.5 rounded-[3px] border px-1 transition-colors hover:bg-muted",- isCurrent ? "border-foreground" : "border-border"- )}- >- <LuBoxes className="size-3.5 shrink-0 text-muted-foreground" />- {item.indices.map((i) => (- <span- key={steps[i].id}- className={cn(- "h-2 flex-1 rounded-[1px]",- stepSegmentTone(steps[i], i)- )}- />- ))}- </button>- );- })- )}- {stepFilter === "incomplete" && doneCount === steps.length && (- <span className="text-xs text-emerald-500">All steps done</span>- )}- {stepFilter === "completed" && doneCount === 0 && (- <span className="text-xs text-muted-foreground">- No completed steps yet- </span>- )}+ ) : null}</div>- {/* Filter which steps the bar emphasizes (all / completed / incomplete). */}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="Filter steps"- variant={stepFilter === "all" ? "ghost" : "active"}- size="sm"- icon={<LuListFilter />}- />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuRadioGroup- value={stepFilter}- onValueChange={(v) =>- setStepFilter(v as "all" | "completed" | "incomplete")- }- >- <DropdownMenuRadioItem value="all">- Show all- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="completed">- Show completed- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="incomplete">- Show incomplete- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">- {currentStep + 1} / {steps.length}- </span>- {/* Unit pager — fallback for narrow screens (< lg) where the left sidebar- is hidden; on lg+ the richer sidebar UnitNavigator takes over. Assembly- builds one at a time, but the operator can page back to review or fix a- prior unit's step records — mirrors the operation view. */}- {isMultiQuantity && (- <div className="flex items-center gap-0.5 lg:hidden">- <IconButton- aria-label="Previous unit"- variant="ghost"- size="sm"- icon={<LuChevronLeft />}- isDisabled={currentUnitIndex <= 0}- onClick={() => goToUnit(currentUnitIndex - 1)}- />- <Badge- variant="secondary"- className="whitespace-nowrap tabular-nums"- >- Unit {Math.min(currentUnitIndex + 1, unitCount)} / {unitCount}- </Badge>- <IconButton- aria-label="Next unit"- variant="ghost"- size="sm"- icon={<LuChevronRight />}- isDisabled={currentUnitIndex >= maxNavigableUnitIndex}- onClick={() => goToUnit(currentUnitIndex + 1)}- />- </div>- )}- </div>++ <div className="flex-1" />++ {/* Full-height segmented actions — same treatment as the timer button:+ flush, no rounded corners, a left-border divider, hover highlight. */}+ <button+ type="button"+ onClick={qualityModal.onOpen}+ className="hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex"+ >+ <LuFlag className="size-4" />+ Flag issue+ </button>+ {headerActions}+ </header>)}+ {renderStepsBar("max-md:hidden")}+ {!detailsShown && renderPhoneContext()}+{/* ── BODY ── stacks vertically (page scrolls) on phones/tablets,three columns side-by-side on lg+. ── */}<div className="flex flex-1 flex-col overflow-y-auto lg:flex-row lg:overflow-hidden">@@ -2072,7 +2139,8 @@ export function AssemblyView({{/* ── MAIN: tabbed — details (image + step) · model · chat ── */}<main className="flex w-full flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden">{/* Tab bar */}- <div className="flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5">+ {/* Phones: 44px underline tabs, as on the operation page. */}+ <div className="flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5 max-md:gap-5 max-md:px-4 max-md:py-0 max-md:[&>*]:flex-1"><TabButtonactive={tab === "details"}onClick={() => setTab("details")}@@ -2110,6 +2178,7 @@ export function AssemblyView({</div>) : (<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ {renderPhoneContext()}<div className="flex shrink-0 flex-col gap-2 border-b border-border p-4">{selected === "playback" &&playbackAvailable &&@@ -2531,6 +2600,24 @@ export function AssemblyView({</aside></div>+ {/* Phones: the completing action in thumb reach. */}+ {operation ? (+ <div+ ref={bottomBarRef}+ data-mes-bottom-bar+ className="flex shrink-0 border-t border-border bg-card px-4 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:hidden"+ >+ <Button+ size="lg"+ leftIcon={<LuCheck />}+ onClick={completeModal.onOpen}+ className="h-12 flex-1"+ >+ <Trans>Complete</Trans>+ </Button>+ </div>+ ) : null}+{issueModal.isOpen && (<IssueMaterialModaloperationId={operationId}@@ -2881,7 +2968,13 @@ function TimerControl({trackedEntityId?: string;unitIndex?: number;}) {+ const { t } = useLingui();const fetcher = useFetcher();+ const workTypeLabels = {+ Setup: t`Setup`,+ Labor: t`Labor`,+ Machine: t`Machine`+ } as const;// Optimistic state: the moment Start/End is submitted, flip immediately// instead of waiting for the (slow) post-production-event round-trip. This@@ -2931,10 +3024,10 @@ function TimerControl({<buttondisabled={fetcher.state !== "idle"}type="submit"- aria-label={active ? "Pause timer" : "Start timer"}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"+ aria-label={active ? t`Pause timer` : t`Start timer`}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] max-md:min-w-11 max-md:justify-center md:gap-2 md:px-4">- <span className="hidden flex-col items-end leading-none sm:flex">+ <span className="flex flex-col items-end leading-none"><span className="text-sm font-medium tabular-nums">{/* The clock moves between the server render and hydration, so theelapsed time is only rendered in the browser. */}@@ -2942,8 +3035,8 @@ function TimerControl({{() => formatElapsed(elapsed)}</ClientOnly></span>- <span className="text-[9px] uppercase tracking-wider text-muted-foreground">- {workType}+ <span className="text-[9px] max-md:text-xs uppercase tracking-wider text-muted-foreground">+ {workTypeLabels[workType]}</span></span>{active ? (@@ -3530,9 +3623,10 @@ function TabButton({onClick={onClick}className={cn("rounded-md px-3 py-1 text-xs font-medium transition-colors",+ "max-md:min-h-11 max-md:min-w-11 max-md:rounded-none max-md:border-b-2 max-md:border-transparent max-md:px-0 max-md:text-[15px]",active- ? "bg-foreground text-background"- : "text-muted-foreground hover:bg-muted hover:text-foreground"+ ? "bg-foreground text-background max-md:border-foreground max-md:bg-transparent max-md:text-foreground"+ : "text-muted-foreground hover:bg-muted hover:text-foreground max-md:hover:bg-transparent")}>{children}diff --git a/apps/mes/app/components/ConsolePill.tsx b/apps/mes/app/components/ConsolePill.tsxindex ab8614452a..2791cbed6d 100644--- a/apps/mes/app/components/ConsolePill.tsx+++ b/apps/mes/app/components/ConsolePill.tsx@@ -36,7 +36,7 @@ export function ConsolePill({<buttontype="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-[box-shadow,transform] duration-200 hover:shadow-xl active:scale-[0.98] select-none"+ className="fixed top-3 left-1/2 -translate-x-1/2 z-40 max-md:top-auto max-md:left-4 max-md:translate-x-0 max-md:bottom-[calc(var(--mes-bottom-bar-h,calc(54px+env(safe-area-inset-bottom)))+8px)] flex items-center gap-2 rounded-full border bg-card/90 backdrop-blur-md px-3 py-1.5 shadow-lg transition-[box-shadow,transform] 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">diff --git a/apps/mes/app/components/EmployeeAvatar.tsx b/apps/mes/app/components/EmployeeAvatar.tsxindex 7e9461ee10..21e9ee642e 100644--- a/apps/mes/app/components/EmployeeAvatar.tsx+++ b/apps/mes/app/components/EmployeeAvatar.tsx@@ -25,9 +25,9 @@ const EmployeeAvatar = ({if (employeeId === "system") {return (- <HStack className="truncate no-underline hover:no-underline">+ <HStack className="min-w-0 truncate no-underline hover:no-underline"><Avatar size={size ?? "xs"} path={undefined} />- {withName && <span>System</span>}+ {withName && <span className="truncate">System</span>}</HStack>);}@@ -39,13 +39,13 @@ const EmployeeAvatar = ({}return (- <HStack className="truncate no-underline hover:no-underline">+ <HStack className="min-w-0 truncate no-underline hover:no-underline"><Avatarsize={size ?? "xs"}path={person.avatarUrl ?? undefined}name={person?.name ?? ""}/>- {withName && <span>{person.name}</span>}+ {withName && <span className="truncate">{person.name}</span>}</HStack>);};diff --git a/apps/mes/app/components/EndShift.tsx b/apps/mes/app/components/EndShift.tsxindex fed4b46467..0a49fb8e82 100644--- a/apps/mes/app/components/EndShift.tsx+++ b/apps/mes/app/components/EndShift.tsx@@ -5,20 +5,7 @@"use client";import { useCarbon } from "@carbon/auth";-import {- Button,- Modal,- ModalBody,- ModalContent,- ModalDescription,- ModalFooter,- ModalHeader,- ModalTitle,- NavRailItem,- Spinner,- toast,- useDisclosure-} from "@carbon/react";+import { Button, NavRailItem, Spinner, toast } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useState } from "react";import { flushSync } from "react-dom";@@ -29,10 +16,11 @@ import type { action as endShiftAction } from "~/routes/x+/end-shift";import { getActiveJobOperationsByEmployee } from "~/services/operations.service";import type { Operation } from "~/services/types";import { path } from "~/utils/path";+import { ToolSurface, useToolSurface } from "./MoreSheet";export function EndShift() {const { t } = useLingui();- const confirmModal = useDisclosure();+ const surface = useToolSurface("end-operations", t`End Operations`);const fetcher = useFetcher<typeof endShiftAction>();const user = useUser();@@ -43,7 +31,7 @@ export function EndShift() {// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.data?.success === true) {- confirmModal.onClose();+ surface.done();toast.success(fetcher.data?.message ?? t`Operations ended`);}@@ -55,7 +43,7 @@ export function EndShift() {const openModal = async () => {flushSync(() => {setLoading(true);- confirmModal.onOpen();+ surface.open();});if (!carbon) return;@@ -70,6 +58,58 @@ export function EndShift() {setLoading(false);};+ const description = (+ <Trans>+ Are you sure you want to end all production events? This will end all+ active operations without completing or finishing them.+ </Trans>+ );+ const list = loading ? (+ <div className="flex items-center justify-center w-full h-24">+ <Spinner />+ </div>+ ) : operations?.length === 0 ? (+ <div className="flex items-center justify-center w-full h-24 text-muted-foreground">+ <Trans>No active operations</Trans>+ </div>+ ) : (+ <div className="flex flex-col gap-4">+ {operations.map((operation) => (+ <div+ key={operation.id}+ className="flex items-start justify-between p-4 rounded-lg border"+ >+ <div className="flex flex-col gap-1">+ <div className="font-medium">{operation.jobReadableId}</div>+ <div className="text-sm text-muted-foreground">+ {operation.description}+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <div className="text-sm text-muted-foreground">+ {operation.itemReadableId}+ </div>+ </div>+ </div>+ ))}+ </div>+ );+ const actions = (+ <>+ <Button type="button" onClick={surface.close} variant="secondary">+ <Trans>Cancel</Trans>+ </Button>+ <Button+ type="submit"+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ variant="destructive"+ >+ <Trans>End Operations</Trans>+ </Button>+ </>+ );+return (<><NavRailItem@@ -77,84 +117,17 @@ export function EndShift() {label={t`End Operations`}onClick={openModal}/>- {confirmModal.isOpen && (- <Modal- open={confirmModal.isOpen}- onOpenChange={(open) => !open && confirmModal.onClose()}- >- <ModalContent>- <ModalHeader>- <ModalTitle>- <Trans>End Operations</Trans>- </ModalTitle>- <ModalDescription>- <Trans>- Are you sure you want to end all production events? This will- end all active operations without completing or finishing- them.- </Trans>- </ModalDescription>- </ModalHeader>- <ModalBody>- {loading ? (- <div className="flex items-center justify-center w-full h-24">- <Spinner />- </div>- ) : operations?.length === 0 ? (- <div className="flex items-center justify-center w-full h-24 text-muted-foreground">- <Trans>No active operations</Trans>- </div>- ) : (- <div className="flex flex-col gap-4">- {operations.map((operation) => (- <div- key={operation.id}- className="flex items-start justify-between p-4 rounded-lg border"- >- <div className="flex flex-col gap-1">- <div className="font-medium">- {operation.jobReadableId}- </div>- <div className="text-sm text-muted-foreground">- {operation.description}- </div>- </div>- <div className="flex flex-col gap-1">- <div className="text-sm text-muted-foreground">- {operation.itemReadableId}- </div>- </div>- </div>- ))}- </div>- )}- </ModalBody>- <fetcher.Form- method="post"- action={path.to.endShift}- className="w-full"- >- <ModalFooter>- <Button- type="button"- onClick={confirmModal.onClose}- variant="secondary"- >- <Trans>Cancel</Trans>- </Button>- <Button- type="submit"- isDisabled={fetcher.state !== "idle"}- isLoading={fetcher.state !== "idle"}- variant="destructive"- >- <Trans>End Operations</Trans>- </Button>- </ModalFooter>- </fetcher.Form>- </ModalContent>- </Modal>- )}+ <ToolSurface+ surface={surface}+ description={description}+ body={list}+ footer={actions}+ wrap={(children) => (+ <fetcher.Form method="post" action={path.to.endShift}>+ {children}+ </fetcher.Form>+ )}+ /></>);}diff --git a/apps/mes/app/components/Filter/Filter.tsx b/apps/mes/app/components/Filter/Filter.tsxindex 8a188a2c20..c22c4650b1 100644--- a/apps/mes/app/components/Filter/Filter.tsx+++ b/apps/mes/app/components/Filter/Filter.tsx@@ -116,13 +116,16 @@ const Filter = forwardRef<HTMLButtonElement, FilterProps>(return hasFilters && !open && trigger !== "icon" ? (<HStack><Button- rightIcon={<LuX />}+ rightIcon={<LuX className="max-md:ml-0" />}ref={ref}variant="secondary"onClick={clearFilters}+ className="max-md:size-10 max-md:px-0"{...props}>- <Trans>Clear Filters</Trans>+ <span className="max-md:sr-only">+ <Trans>Clear Filters</Trans>+ </span></Button></HStack>) : (@@ -142,17 +145,19 @@ const Filter = forwardRef<HTMLButtonElement, FilterProps>(</Button>) : (<Button- rightIcon={<LuListFilter />}+ rightIcon={<LuListFilter className="max-md:ml-0" />}role="combobox"ref={ref}variant="secondary"onClick={() => {setOpen(true);}}- className={"!border-dashed border-border"}+ className="!border-dashed border-border max-md:size-10 max-md:px-0"{...props}>- <Trans>Filter</Trans>+ <span className="max-md:sr-only">+ <Trans>Filter</Trans>+ </span></Button>)}</PopoverTrigger>diff --git a/apps/mes/app/components/Inspection/DispositionModal.tsx b/apps/mes/app/components/Inspection/DispositionModal.tsxindex 5e5d97275d..d19a3547e7 100644--- a/apps/mes/app/components/Inspection/DispositionModal.tsx+++ b/apps/mes/app/components/Inspection/DispositionModal.tsx@@ -40,6 +40,7 @@ import { useFetcher } from "react-router";import ScrapReason from "~/components/JobOperation/components/ScrapReason";import { inspectionDispositionValidator } from "~/services/models";import type { IssueTypeListItem } from "~/services/types";+import { OriginInput } from "~/utils/origin";import { path } from "~/utils/path";export type FailedFeatureSummary = {@@ -212,6 +213,7 @@ const DispositionModal = ({</ModalHeader><ModalBody><Hidden name="decision" value={decision} />+ <OriginInput /><Hidden name="operationId" value={operationId} />{isSerial ? (<>diff --git a/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx b/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsxindex b7995a2973..3343115ddd 100644--- a/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx+++ b/apps/mes/app/components/Inspection/InspectionMeasurementMatrix.tsx@@ -539,11 +539,11 @@ const InspectionMeasurementMatrix = ({}return (- <div className="min-h-0 flex-1 overflow-auto">+ <div className="min-h-0 flex-1 overflow-auto max-md:scroll-fade-x"><table className="w-full border-separate border-spacing-0 text-sm"><thead className="sticky top-0 z-20"><tr>- <th className="sticky left-0 z-30 min-w-[220px] border-b border-r border-border bg-card px-3 py-2 text-left font-medium text-muted-foreground">+ <th className="sticky left-0 z-30 min-w-[220px] max-md:w-[150px] max-md:min-w-[150px] max-md:max-w-[150px] border-b border-r border-border bg-card px-3 py-2 text-left font-medium text-muted-foreground">{hasFeatures ? (<span>{t`Characteristic`}</span>) : (@@ -551,7 +551,7 @@ const InspectionMeasurementMatrix = ({)}</th>{hasFeatures && (- <th className="min-w-[140px] border-b border-r border-border bg-card px-3 py-2 text-left font-medium text-muted-foreground">+ <th className="min-w-[140px] border-b border-r border-border bg-card px-3 py-2 text-left font-medium text-muted-foreground max-md:hidden">{t`Gauge`}</th>)}@@ -580,7 +580,7 @@ const InspectionMeasurementMatrix = ({><tdclassName={cn(- "sticky left-0 z-10 cursor-pointer border-b border-r border-border bg-card px-3 py-2 align-top",+ "sticky left-0 z-10 cursor-pointer border-b border-r border-border bg-card px-3 py-2 align-top max-md:max-w-[150px] max-md:px-2",isActive && "bg-accent")}onClick={() =>@@ -589,7 +589,7 @@ const InspectionMeasurementMatrix = ({: undefined}>- <div className="flex items-start gap-3">+ <div className="flex items-start gap-3 max-md:gap-2">{row.featureId !== OVERALL_ROW_ID ? (<div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted font-mono text-sm font-semibold text-foreground tabular-nums">{row.label}@@ -614,9 +614,31 @@ const InspectionMeasurementMatrix = ({</div></div></div>+ {hasFeatures ? (+ // Phones: the gauge sits under the characteristic.+ // The click must not toggle the active row.+ <div+ className="-mx-2 -mb-2 mt-2 hidden min-w-0 border-t border-border max-md:block [&>*]:min-w-0"+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <InspectionGaugePicker+ gauges={gauges}+ characteristicLabel={row.label}+ recentGaugeIds={recentGauges}+ gaugeTypeId={row.gaugeTypeId}+ gaugeTypeName={row.gaugeTypeName}+ value={gaugeFor(row.featureId)}+ isReadOnly={isReadOnly}+ onChange={(gaugeId) =>+ persistGauge(row.featureId, gaugeId)+ }+ />+ </div>+ ) : null}</td>{hasFeatures && (- <td className="h-px border-b border-r border-border p-0 align-middle">+ <td className="h-px border-b border-r border-border p-0 align-middle max-md:hidden"><InspectionGaugePickergauges={gauges}characteristicLabel={row.label}diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsxindex bc8e2e7b85..f60057a3de 100644--- a/apps/mes/app/components/Inspection/InspectionView.tsx+++ b/apps/mes/app/components/Inspection/InspectionView.tsx@@ -23,6 +23,7 @@ import {Spinner,useDisclosure,useMode,+ useViewport,VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";@@ -54,6 +55,8 @@ import { useFetcher } from "react-router";import { QualityIssueModal } from "~/components/JobOperation/components/QualityIssueModal";import { QuantityModal } from "~/components/JobOperation/components/QuantityModal";import { ReworkModal } from "~/components/JobOperation/components/ReworkModal";+import { MesAppBar } from "~/components/MesAppBar";+import { useMesBottomBar } from "~/components/MesBottomBar";import { useUser } from "~/hooks";import type {InspectionGauge,@@ -67,6 +70,7 @@ import type {ProductionEvent,TrackedEntity} from "~/services/types";+import { OriginInput, useOrigin } from "~/utils/origin";import { path } from "~/utils/path";import type { AllocatableUnit, FailedFeatureSummary } from "./DispositionModal";import DispositionModal from "./DispositionModal";@@ -173,7 +177,10 @@ export function InspectionView({linkedProductionQuantity,jobId}: InspectionViewProps) {+ const bottomBarRef = useMesBottomBar();const { t } = useLingui();+ const origin = useOrigin();+ const { isPhone } = useViewport();const user = useUser();const mode = useMode();@@ -427,6 +434,7 @@ export function InspectionView({Math.max(0, passes - linkedProductionQuantity),Math.max(0, opRemaining));+ const showCompletePassed = !lotClosed && completablePassed > 0;// What Accept will complete: the open remainder, minus failed units.const acceptRemaining = isSerial@@ -614,235 +622,295 @@ export function InspectionView({return (<div className="relative flex h-dvh w-full flex-col overflow-hidden bg-background text-foreground">{/* ── HEADER ── */}- <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border">- <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />- {companyLogo ? (- <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">- <img- src={companyLogo}- alt={`${user.company.name} logo`}- className="h-7 w-auto max-w-[140px] object-contain"+ <MesAppBar+ kind="pushed"+ title={inspection.inspectionId}+ subtitle={origin.label}+ back={{ to: origin.to }}+ desktop={null}+ actions={+ <>+ {workTypes.map((wt) => (+ <TimerControl+ key={wt}+ operationId={operationId}+ workCenterId={operation.workCenterId ?? undefined}+ openEvent={openEventForWorkType(wt)}+ workType={wt}+ />+ ))}+ <IconButton+ aria-label={t`More actions`}+ variant="ghost"+ size="lg"+ icon={<LuEllipsisVertical />}+ onClick={actionsSheet.onOpen}/>- </div>- ) : null}-- <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">- <span className="truncate text-sm font-semibold">- {inspection.inspectionId}- </span>- <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>- <span className="hidden text-muted-foreground md:inline">·</span>- <span className="hidden truncate text-sm text-foreground/90 md:inline">- {inspection.itemReadableId ?? job?.itemReadableIdWithRevision}- </span>- {operation?.description ? (- <>- <span className="hidden text-muted-foreground lg:inline">·</span>- <span className="hidden truncate text-sm text-foreground/90 lg:inline">- {operation.description}- </span>- </>+ </>+ }+ />+ {/* Phones use the app bar above; one header mounts so its timers do too. */}+ {!isPhone && (+ <header className="flex h-[52px] shrink-0 items-center bg-card border-b border-border max-md:hidden">+ <SidebarTrigger className="h-full w-auto shrink-0 rounded-none border-r border-border px-2 hover:bg-accent md:px-4" />+ {companyLogo ? (+ <div className="hidden h-full shrink-0 items-center border-r border-border px-4 sm:flex">+ <img+ src={companyLogo}+ alt={`${user.company.name} logo`}+ className="h-7 w-auto max-w-[140px] object-contain"+ />+ </div>) : null}- </div>- <div className="flex-1" />+ <div className="flex h-full min-w-0 items-center gap-2 border-r border-border px-3 md:px-5">+ <span className="truncate text-sm font-semibold">+ {inspection.inspectionId}+ </span>+ <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>+ <span className="hidden text-muted-foreground md:inline">·</span>+ <span className="hidden truncate text-sm text-foreground/90 md:inline">+ {inspection.itemReadableId ?? job?.itemReadableIdWithRevision}+ </span>+ {operation?.description ? (+ <>+ <span className="hidden text-muted-foreground lg:inline">+ ·+ </span>+ <span className="hidden truncate text-sm text-foreground/90 lg:inline">+ {operation.description}+ </span>+ </>+ ) : null}+ </div>++ <div className="flex-1" />- {isSerial && !lotClosed ? (+ {isSerial && !lotClosed ? (+ <button+ type="button"+ onClick={scannerDisclosure.onOpen}+ className={cn(+ "hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex",+ !allSamplesLoaded && "text-primary"+ )}+ >+ <LuScan className="size-4" />+ <Trans>Add Sample</Trans>+ </button>+ ) : null}+ {!lotClosed && completablePassed > 0 ? (+ <CompletePassedButton+ inspectionId={inspection.id}+ operationId={operationId}+ count={completablePassed}+ eventIds={eventIds}+ />+ ) : null}<buttontype="button"- onClick={scannerDisclosure.onOpen}- className={cn(- "hidden h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4 lg:flex",- !allSamplesLoaded && "text-primary"- )}+ onClick={rejectDisclosure.onOpen}+ disabled={!canReject}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-red-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-red-400 md:gap-2 md:px-4">- <LuScan className="size-4" />- <Trans>Add Sample</Trans>+ <LuX className="size-4" />+ <span className="hidden sm:inline">+ <Trans>Reject</Trans>+ </span></button>- ) : null}- {!lotClosed && completablePassed > 0 ? (- <CompletePassedButton- inspectionId={inspection.id}- operationId={operationId}- count={completablePassed}- eventIds={eventIds}- />- ) : null}- <button- type="button"- onClick={rejectDisclosure.onOpen}- disabled={!canReject}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-red-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-red-400 md:gap-2 md:px-4"- >- <LuX className="size-4" />- <span className="hidden sm:inline">- <Trans>Reject</Trans>- </span>- </button>- {canPartial ? (+ {canPartial ? (+ <button+ type="button"+ onClick={partialDisclosure.onOpen}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-amber-600 transition-colors hover:bg-accent active:scale-[0.98] dark:text-amber-400 md:gap-2 md:px-4"+ >+ <LuContrast className="size-4" />+ <span className="hidden sm:inline">+ <Trans>Partial</Trans>+ </span>+ </button>+ ) : null}<buttontype="button"- onClick={partialDisclosure.onOpen}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-amber-600 transition-colors hover:bg-accent active:scale-[0.98] dark:text-amber-400 md:gap-2 md:px-4"+ onClick={acceptDisclosure.onOpen}+ disabled={!canAccept}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-emerald-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-emerald-400 md:gap-2 md:px-4">- <LuContrast className="size-4" />+ <LuCheck className="size-4" /><span className="hidden sm:inline">- <Trans>Partial</Trans>+ <Trans>Accept</Trans></span></button>- ) : null}- <button- type="button"- onClick={acceptDisclosure.onOpen}- disabled={!canAccept}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 text-sm font-medium text-emerald-600 transition-colors hover:bg-accent active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:text-emerald-400 md:gap-2 md:px-4"- >- <LuCheck className="size-4" />- <span className="hidden sm:inline">- <Trans>Accept</Trans>+ <button+ type="button"+ aria-label={t`More actions`}+ onClick={actionsSheet.onOpen}+ className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:px-4"+ >+ <LuEllipsisVertical className="size-4" />+ </button>++ {workTypes.map((wt) => (+ <TimerControl+ key={wt}+ operationId={operationId}+ workCenterId={operation.workCenterId ?? undefined}+ openEvent={openEventForWorkType(wt)}+ workType={wt}+ />+ ))}+ </header>+ )}++ {/* Phones: the meta bar scrolls away with the body. */}+ <div className="contents max-md:flex max-md:min-h-0 max-md:flex-1 max-md:flex-col max-md:overflow-y-auto">+ {/* ── META BAR ── */}+ <div className="flex h-9 shrink-0 items-center gap-3 overflow-x-auto bg-card border-b border-border px-5 scrollbar-hide max-md:h-auto max-md:flex-wrap max-md:gap-x-3 max-md:gap-y-1 max-md:px-4 max-md:py-1.5">+ <Badge variant={statusBadgeVariant} className="shrink-0 md:hidden">+ {inspection.status}+ </Badge>+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">+ {inspected} / {inspection.sampleSize} <Trans>inspected</Trans> · Ac{" "}+ {inspection.acceptanceNumber} · Re {inspection.rejectionNumber}+ {inspection.codeLetter ? ` · ${inspection.codeLetter}` : ""}</span>- </button>- <button- type="button"- aria-label={t`More actions`}- onClick={actionsSheet.onOpen}- className="flex h-full shrink-0 items-center justify-center border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:px-4"- >- <LuEllipsisVertical className="size-4" />- </button>-- {workTypes.map((wt) => (- <TimerControl- key={wt}- operationId={operationId}- workCenterId={operation.workCenterId ?? undefined}- openEvent={openEventForWorkType(wt)}- workType={wt}- />- ))}- </header>-- {/* ── META BAR ── */}- <div className="flex h-9 shrink-0 items-center gap-3 overflow-x-auto bg-card border-b border-border px-5 scrollbar-hide">- <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">- {inspected} / {inspection.sampleSize} <Trans>inspected</Trans> · Ac{" "}- {inspection.acceptanceNumber} · Re {inspection.rejectionNumber}- {inspection.codeLetter ? ` · ${inspection.codeLetter}` : ""}- </span>- <span className="whitespace-nowrap text-xs text-muted-foreground">- {planSummary}- </span>- <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">- <Trans>Lot</Trans> {inspection.lotSize}- </span>- {documentName ? (- <span className="truncate text-xs text-muted-foreground">- {documentName}+ <span className="whitespace-nowrap text-xs text-muted-foreground">+ {planSummary}</span>- ) : null}- <div className="flex-1" />- <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">- <Trans>Completed</Trans> {productionQuantities.production} ·{" "}- <Trans>Scrap</Trans> {productionQuantities.scrap} ·{" "}- <Trans>Rework</Trans> {productionQuantities.rework}- </span>- </div>+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">+ <Trans>Lot</Trans> {inspection.lotSize}+ </span>+ {documentName ? (+ <span className="truncate text-xs text-muted-foreground max-md:max-w-full">+ {documentName}+ </span>+ ) : null}+ <div className="flex-1 max-md:hidden" />+ <span className="whitespace-nowrap text-xs text-muted-foreground tabular-nums max-md:order-first">+ <Trans>Completed</Trans> {productionQuantities.production} ·{" "}+ <Trans>Scrap</Trans> {productionQuantities.scrap} ·{" "}+ <Trans>Rework</Trans> {productionQuantities.rework}+ </span>+ </div>- {/* ── BODY ── */}- {showDrawing ? (- <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">- <div- ref={stackRef}- className="flex min-h-0 flex-1 flex-col gap-0 overflow-hidden"- >- {/* PDF viewer — pinned height while the features table is expanded */}+ {/* ── BODY ── */}+ {showDrawing ? (+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2"><div- className={cn(- "flex min-h-0 min-w-full flex-col overflow-hidden rounded-lg border bg-muted",- gridExpanded ? "shrink-0" : "min-h-[220px] flex-1"- )}- style={{- ...(gridExpanded ? { height: pdfPaneHeightPx } : undefined),- minWidth: "100%"- }}+ ref={stackRef}+ className="flex min-h-0 flex-1 flex-col gap-0 overflow-hidden">- <ClientOnly- fallback={- <div className="flex h-full items-center justify-center">- <Spinner />- </div>- }- >- {() => (- <Suspense- fallback={- <div className="flex h-full items-center justify-center">- <Spinner />- </div>- }- >- <InspectionDrawingPane- pdfUrl={pdfUrl!}- balloons={drawingBalloons}- activeFeatureId={activeFeatureId}- onBalloonClick={setActiveFeatureId}- />- </Suspense>- )}- </ClientOnly>- </div>-- {gridExpanded ? (+ {/* PDF viewer — pinned height while the features table is expanded */}<div- role="separator"- aria-orientation="horizontal"- aria-label={t`Drag to resize drawing and characteristics`}- aria-valuenow={Math.round(pdfPaneHeightPx)}className={cn(- "group flex h-2 shrink-0 cursor-row-resize touch-none items-center justify-center rounded-md px-2 hover:bg-muted/80",- isResizingSplit && "bg-muted"+ "flex min-h-0 min-w-full flex-col overflow-hidden rounded-lg border bg-muted",+ gridExpanded ? "shrink-0" : "min-h-[220px] flex-1")}- onMouseDown={onSplitResizeMouseDown}+ style={{+ ...(gridExpanded ? { height: pdfPaneHeightPx } : undefined),+ minWidth: "100%"+ }}>- <span className="h-1 w-14 shrink-0 rounded-full bg-muted-foreground/40 group-hover:bg-muted-foreground/65" />+ <ClientOnly+ fallback={+ <div className="flex h-full items-center justify-center">+ <Spinner />+ </div>+ }+ >+ {() => (+ <Suspense+ fallback={+ <div className="flex h-full items-center justify-center">+ <Spinner />+ </div>+ }+ >+ <InspectionDrawingPane+ pdfUrl={pdfUrl!}+ balloons={drawingBalloons}+ activeFeatureId={activeFeatureId}+ onBalloonClick={setActiveFeatureId}+ />+ </Suspense>+ )}+ </ClientOnly></div>- ) : null}- {/* Features table — collapsible bottom panel */}- <div- className={cn(- "flex min-w-0 flex-col overflow-hidden rounded-lg border bg-card",- gridExpanded ? "min-h-0 flex-1" : "max-h-[14rem] shrink-0"- )}- style={- gridExpanded && stackHeightPx > 0- ? { minHeight: stackHeightPx * 0.5 }- : undefined- }- >- <div className="flex min-h-10 flex-shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2">- <span className="truncate text-sm font-medium text-foreground">- {t`Characteristics`}- </span>- <IconButton- type="button"- variant="ghost"- aria-expanded={gridExpanded}- aria-label={- gridExpanded- ? t`Collapse characteristics table`- : t`Expand characteristics table`- }- icon={- gridExpanded ? (- <LuChevronDown className="h-4 w-4" />- ) : (- <LuChevronUp className="h-4 w-4" />- )- }- onClick={() => setGridExpanded((v) => !v)}+ {gridExpanded ? (+ <div+ role="separator"+ aria-orientation="horizontal"+ aria-label={t`Drag to resize drawing and characteristics`}+ aria-valuenow={Math.round(pdfPaneHeightPx)}+ className={cn(+ "group flex h-2 shrink-0 cursor-row-resize touch-none items-center justify-center rounded-md px-2 hover:bg-muted/80",+ isResizingSplit && "bg-muted"+ )}+ onMouseDown={onSplitResizeMouseDown}+ >+ <span className="h-1 w-14 shrink-0 rounded-full bg-muted-foreground/40 group-hover:bg-muted-foreground/65" />+ </div>+ ) : null}++ {/* Features table — collapsible bottom panel */}+ <div+ className={cn(+ "flex min-w-0 flex-col overflow-hidden rounded-lg border bg-card",+ gridExpanded ? "min-h-0 flex-1" : "max-h-[14rem] shrink-0"+ )}+ style={+ gridExpanded && stackHeightPx > 0+ ? { minHeight: stackHeightPx * 0.5 }+ : undefined+ }+ >+ <div className="flex min-h-10 flex-shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2">+ <span className="truncate text-sm font-medium text-foreground">+ {t`Characteristics`}+ </span>+ <IconButton+ type="button"+ variant="ghost"+ aria-expanded={gridExpanded}+ aria-label={+ gridExpanded+ ? t`Collapse characteristics table`+ : t`Expand characteristics table`+ }+ icon={+ gridExpanded ? (+ <LuChevronDown className="h-4 w-4" />+ ) : (+ <LuChevronUp className="h-4 w-4" />+ )+ }+ onClick={() => setGridExpanded((v) => !v)}+ />+ </div>+ <InspectionMeasurementMatrix+ inspectionId={inspection.id}+ isReadOnly={lotClosed}+ isSerial={isSerial}+ features={features}+ samples={samples}+ measurements={measurements}+ gauges={gauges}+ recentGaugeIds={recentGaugeIds}+ maxSampleSize={maxSampleSize}+ lotSize={inspection.lotSize}+ lotAcceptanceNumber={inspection.acceptanceNumber}+ lotRejectionNumber={inspection.rejectionNumber}+ activeFeatureId={activeFeatureId}+ onActiveFeatureChange={setActiveFeatureId}+ onMeasurementSaved={onMeasurementSaved}/></div>+ </div>+ </div>+ ) : (+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2 max-md:flex-none max-md:overflow-visible">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border bg-card max-md:flex-initial"><InspectionMeasurementMatrixinspectionId={inspection.id}isReadOnly={lotClosed}@@ -862,30 +930,64 @@ export function InspectionView({/></div></div>- </div>- ) : (- <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-2">- <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border bg-card">- <InspectionMeasurementMatrix+ )}+ </div>++ {/* Phones: the lot actions as labelled 48px buttons in thumb reach. */}+ <div+ ref={bottomBarRef}+ data-mes-bottom-bar+ className="flex shrink-0 flex-wrap gap-2 border-t border-border bg-card px-4 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:hidden [&>button]:min-w-0 [&>button]:flex-1"+ >+ {/* Its label carries a count, so it takes a row of its own. */}+ {showCompletePassed ? (+ <div className="basis-full [&>*]:w-full">+ <CompletePassedButtoninspectionId={inspection.id}- isReadOnly={lotClosed}- isSerial={isSerial}- features={features}- samples={samples}- measurements={measurements}- gauges={gauges}- recentGaugeIds={recentGaugeIds}- maxSampleSize={maxSampleSize}- lotSize={inspection.lotSize}- lotAcceptanceNumber={inspection.acceptanceNumber}- lotRejectionNumber={inspection.rejectionNumber}- activeFeatureId={activeFeatureId}- onActiveFeatureChange={setActiveFeatureId}- onMeasurementSaved={onMeasurementSaved}+ operationId={operationId}+ count={completablePassed}+ eventIds={eventIds}+ variant="bar"/></div>- </div>- )}+ ) : null}+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuX />}+ isDisabled={!canReject}+ onClick={rejectDisclosure.onOpen}+ className="h-12 text-red-600 dark:text-red-400"+ >+ <span className="truncate">+ <Trans>Reject</Trans>+ </span>+ </Button>+ {canPartial ? (+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuContrast />}+ onClick={partialDisclosure.onOpen}+ className="h-12 text-amber-600 dark:text-amber-400"+ >+ <span className="truncate">+ <Trans>Partial</Trans>+ </span>+ </Button>+ ) : null}+ <Button+ size="lg"+ leftIcon={<LuCheck />}+ isDisabled={!canAccept}+ onClick={acceptDisclosure.onOpen}+ className="h-12"+ >+ <span className="truncate">+ <Trans>Accept</Trans>+ </span>+ </Button>+ </div>{/* ── MODALS ── */}{scannerDisclosure.isOpen && (@@ -1111,16 +1213,44 @@ function CompletePassedButton({inspectionId,operationId,count,- eventIds+ eventIds,+ variant = "header"}: {inspectionId: string;operationId: string;count: number;eventIds: ProductionEventIdFields;+ variant?: "header" | "bar";}) {const fetcher = useFetcher();const busy = fetcher.state !== "idle";+ if (variant === "bar") {+ return (+ <fetcher.Form+ method="post"+ action={path.to.inspectionCompletePassed(inspectionId)}+ className="flex min-w-0 flex-1"+ >+ <input type="hidden" name="operationId" value={operationId} />+ <EventIdInputs eventIds={eventIds} />+ <OriginInput />+ <Button+ type="submit"+ size="lg"+ variant="secondary"+ isDisabled={busy}+ leftIcon={<LuCheckCheck />}+ className="h-12 w-full text-emerald-600 dark:text-emerald-400"+ >+ <span className="truncate">+ <Trans>Complete passed</Trans> {count}+ </span>+ </Button>+ </fetcher.Form>+ );+ }+return (<fetcher.Formmethod="post"@@ -1129,6 +1259,7 @@ function CompletePassedButton({><input type="hidden" name="operationId" value={operationId} /><EventIdInputs eventIds={eventIds} />+ <OriginInput /><buttontype="submit"disabled={busy}@@ -1212,6 +1343,7 @@ function AcceptLotModal({<input type="hidden" name="decision" value="Accept" /><input type="hidden" name="operationId" value={operationId} /><EventIdInputs eventIds={eventIds} />+ <OriginInput /><Buttontype="submit"isLoading={fetcher.state !== "idle"}@@ -1322,6 +1454,7 @@ function TimerControl({openEvent: { id: string; startTime: string } | null;workType: WorkType;}) {+ const { t } = useLingui();const fetcher = useFetcher();// Optimistic state: flip the moment Start/End is submitted instead of@@ -1356,10 +1489,10 @@ function TimerControl({<buttondisabled={fetcher.state !== "idle"}type="submit"- aria-label={active ? "Pause timer" : "Start timer"}- className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"+ aria-label={active ? t`Pause timer` : t`Start timer`}+ className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] max-md:border-l-0 md:gap-2 md:px-4">- <span className="hidden flex-col items-end leading-none sm:flex">+ <span className="flex flex-col items-end leading-none"><span className="text-sm font-medium tabular-nums">{/* The clock moves between the server render and hydration, so theelapsed time is only rendered in the browser. */}@@ -1367,7 +1500,7 @@ function TimerControl({{() => formatElapsed(elapsed)}</ClientOnly></span>- <span className="text-[9px] uppercase tracking-wider text-muted-foreground">+ <span className="text-[9px] max-md:text-xs uppercase tracking-wider text-muted-foreground">{workType}</span></span>diff --git a/apps/mes/app/components/JobDag/JobDag.tsx b/apps/mes/app/components/JobDag/JobDag.tsxindex 9dad7e9c72..324fd443d5 100644--- a/apps/mes/app/components/JobDag/JobDag.tsx+++ b/apps/mes/app/components/JobDag/JobDag.tsx@@ -8,9 +8,11 @@ import {Popover,PopoverContent,PopoverTrigger,+ useViewport,VStack} from "@carbon/react";import Dagre from "@dagrejs/dagre";+import { useLingui } from "@lingui/react/macro";import {Background,type Edge,@@ -77,13 +79,15 @@ type Props = {function computeLayout(operations: Operation[],dependencies: Dependency[],- direction: LayoutDirection+ direction: LayoutDirection,+ compact: boolean): { nodes: Node[]; edges: Edge[] } {const g = new Dagre.graphlib.Graph();g.setGraph({rankdir: direction,- nodesep: 80,- ranksep: 120,+ // Phones: tighter spacing, so less panning at the 0.6 fit.+ nodesep: compact ? 24 : 80,+ ranksep: compact ? 56 : 120,edgesep: 30,marginx: 40,marginy: 40@@ -155,11 +159,24 @@ function computeLayout(function JobDagInner({ operations, dependencies }: Props) {const [direction, setDirection] = useState<LayoutDirection>("LR");+ const { t } = useLingui();+ const { isPhone } = useViewport();+ // MES has no server viewport hint, so the first render is desktop.+ // Switch a phone to top-to-bottom once, after hydration. The toggle stays.+ useEffect(() => {+ if (isPhone) setDirection("TB");+ }, [isPhone]);const { fitView } = useReactFlow();+ // On a phone, fitting the whole graph shrinks nodes past reading size, so+ // fit no smaller than 0.6 and let the operator pan the rest.+ const fitViewOptions = useMemo(+ () => (isPhone ? { padding: 0.1, minZoom: 0.6 } : { padding: 0.1 }),+ [isPhone]+ );const { nodes: layoutNodes, edges: layoutEdges } = useMemo(- () => computeLayout(operations, dependencies, direction),- [operations, dependencies, direction]+ () => computeLayout(operations, dependencies, direction, isPhone),+ [operations, dependencies, direction, isPhone]);const [nodes, setNodes, onNodesChange] = useNodesState(layoutNodes);@@ -168,28 +185,29 @@ function JobDagInner({ operations, dependencies }: Props) {useEffect(() => {setNodes(layoutNodes);setEdges(layoutEdges);- setTimeout(() => fitView({ padding: 0.1 }), 50);- }, [layoutNodes, layoutEdges, setNodes, setEdges, fitView]);+ setTimeout(() => fitView(fitViewOptions), 50);+ }, [layoutNodes, layoutEdges, setNodes, setEdges, fitView, fitViewOptions]);const toggleDirection = useCallback(() => {setDirection((d) => (d === "LR" ? "TB" : "LR"));}, []);const handleFitView = useCallback(() => {- fitView({ padding: 0.1 });- }, [fitView]);+ fitView(fitViewOptions);+ }, [fitView, fitViewOptions]);return (- <div className="flex flex-col h-full w-full">+ <div className="relative flex flex-col h-full w-full">+ {/* Phones: the toolbar floats over the canvas, bottom-right. */}<HStack- className="border-b border-border px-3 py-1.5 bg-card"+ className="border-b border-border px-3 py-1.5 bg-card max-md:absolute max-md:right-4 max-md:bottom-[calc(1rem+env(safe-area-inset-bottom))] max-md:z-20 max-md:border-0 max-md:bg-transparent max-md:p-0"spacing={2}><buttontype="button"onClick={toggleDirection}className={cn(- "h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5",+ "h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5 max-md:h-11 max-md:px-3","border border-border bg-background hover:bg-accent/60 transition-colors")}>@@ -198,18 +216,18 @@ function JobDagInner({ operations, dependencies }: Props) {) : (<LuArrowDown className="w-3.5 h-3.5" />)}- {direction === "LR" ? "Left to Right" : "Top to Bottom"}+ {direction === "LR" ? t`Left to Right` : t`Top to Bottom`}</button><buttontype="button"onClick={handleFitView}className={cn(- "h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5",+ "h-7 px-2 rounded-md text-xs font-medium flex items-center gap-1.5 max-md:h-11 max-md:px-3","border border-border bg-background hover:bg-accent/60 transition-colors")}><LuMaximize className="w-3.5 h-3.5" />- Fit+ {t`Fit`}</button></HStack>@@ -223,7 +241,7 @@ function JobDagInner({ operations, dependencies }: Props) {edgeTypes={edgeTypes}proOptions={proOptions}fitView- fitViewOptions={{ padding: 0.1 }}+ fitViewOptions={fitViewOptions}nodesDraggable={false}nodesConnectable={false}edgesFocusable={false}@@ -235,7 +253,7 @@ function JobDagInner({ operations, dependencies }: Props) {nodeStrokeWidth={3}pannablezoomable- className="!bg-card !border-border"+ className="!bg-card !border-border max-md:!hidden"/></ReactFlow><DagLegend />diff --git a/apps/mes/app/components/JobDag/JobOperationNode.tsx b/apps/mes/app/components/JobDag/JobOperationNode.tsxindex 6eda862504..7a8b80efee 100644--- a/apps/mes/app/components/JobDag/JobOperationNode.tsx+++ b/apps/mes/app/components/JobDag/JobOperationNode.tsx@@ -5,7 +5,8 @@import { Badge, BarProgress, cn } from "@carbon/react";import { Handle, type NodeProps, Position } from "@xyflow/react";import { memo } from "react";-import { useNavigate } from "react-router";+import { useLocation, useNavigate } from "react-router";+import { withOrigin } from "~/utils/origin";import { path } from "~/utils/path";type JobOperationNodeData = {@@ -38,6 +39,7 @@ function JobOperationNodeImpl({ data }: NodeProps) {const colors = STATUS_COLORS[d.status] ?? STATUS_COLORS.Todo;const isHorizontal = d.direction === "LR";const navigate = useNavigate();+ const location = useLocation();return (<>@@ -49,9 +51,10 @@ function JobOperationNodeImpl({ data }: NodeProps) {<divrole="button"tabIndex={0}- onClick={() => navigate(path.to.operation(d.id))}+ onClick={() => navigate(withOrigin(path.to.operation(d.id), location))}onKeyDown={(e) => {- if (e.key === "Enter") navigate(path.to.operation(d.id));+ if (e.key === "Enter")+ navigate(withOrigin(path.to.operation(d.id), location));}}className={cn("w-[200px] rounded-lg border-2 bg-card px-3 py-2 shadow-sm cursor-pointer hover:bg-accent/50 transition-colors",diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsxindex 007123749d..abc3266b7c 100644--- a/apps/mes/app/components/JobOperation/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx@@ -17,8 +17,14 @@ import {BottomSheet,BottomSheetBody,BottomSheetContent,+ BottomSheetHeader,+ BottomSheetTitle,Button,Card,+ CardAttribute,+ CardAttributeLabel,+ CardAttributes,+ CardAttributeValue,CardContent,CardHeader,CardTitle,@@ -65,7 +71,6 @@ import {convertDateStringToIsoString,formatDate,formatDurationMilliseconds,- getItemReadableId,MODEL_RAW_KEEP_MAX_BYTES,round} from "@carbon/utils";@@ -79,7 +84,6 @@ import { Suspense, useCallback, useEffect, useMemo, useState } from "react";import { flushSync } from "react-dom";import { FaCheck, FaPlus, FaTrash } from "react-icons/fa6";import {- LuArrowLeft,LuAxis3D,LuBarcode,LuCheck,@@ -111,11 +115,7 @@ import {OperationStatusIcon,PrintButton} from "~/components";-import {- MethodIcon,- MethodItemTypeIcon,- TrackingTypeIcon-} from "~/components/Icons";+import { MethodItemTypeIcon } from "~/components/Icons";import { useDateFormatter, useUrlParams, useUser } from "~/hooks";import type { productionEventType } from "~/services/models";import type {@@ -139,8 +139,10 @@ import type {} from "~/services/types";import { useItems } from "~/stores";import { makeDurations } from "~/utils/durations";+import { useOrigin } from "~/utils/origin";import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";import ItemThumbnail from "../ItemThumbnail";+import { MesAppBar } from "../MesAppBar";import { BatchCompleteModal } from "./components/BatchCompleteModal";import { BatchOverview } from "./components/BatchOverview";import { OperationChat } from "./components/Chat";@@ -153,6 +155,7 @@ import {} from "./components/Controls";import { IssueMaterialModal } from "./components/IssueMaterialModal";import { MaintenanceDispatch } from "./components/MaintenanceDispatch";+import { OperationMaterials } from "./components/Materials";import { ParametersListItem } from "./components/Parameter";import { QualityIssueModal } from "./components/QualityIssueModal";import { QuantityModal } from "./components/QuantityModal";@@ -219,82 +222,6 @@ type JobOperationProps = {>;};-/**- * Additive overlay badge showing how much of a material has been picked (staged at- * lineside). Picking is optional, so this renders nothing unless something has actually- * been picked — orange while partial, green once the full requirement is staged.- */-function PickedBadge({- quantityPicked,- quantityToPick-}: {- quantityPicked?: number | null;- quantityToPick?: number | null;-}) {- const picked = Number(quantityPicked ?? 0);- if (picked <= 0) return null;- const toPick = Number(quantityToPick ?? 0);- const isFullyPicked = toPick > 0 && picked >= toPick;- return (- <Badge- variant={isFullyPicked ? "green" : "orange"}- className="gap-1 shrink-0"- title="Quantity picked to lineside"- >- <LuPackageCheck className="size-3" />- {isFullyPicked ? <Trans>Picked</Trans> : `${picked}/${toPick}`}- </Badge>- );-}--function PickedBreakdown({- materialItemId,- pickedByItem-}: {- materialItemId: string | null | undefined;- pickedByItem?:- | {- itemId: string;- itemReadableId: string;- quantityPicked: number;- quantityToPick: number;- }[]- | null;-}) {- const picks = pickedByItem ?? [];- if (!picks.some((p) => p.itemId !== materialItemId)) return null;- return (- <div className="flex flex-wrap items-center gap-1 text-xs text-blue-700 dark:text-blue-300">- <span>- <Trans>Picked as</Trans>- </span>- {picks.map((pick) => {- const isFullyPicked =- pick.quantityToPick > 0 && pick.quantityPicked >= pick.quantityToPick;- return (- <Badge- key={pick.itemId}- variant={- isFullyPicked- ? "green"- : pick.quantityPicked > 0- ? "orange"- : "secondary"- }- className="gap-1 shrink-0"- >- {isFullyPicked- ? pick.quantityPicked- : `${pick.quantityPicked}/${pick.quantityToPick}`}- {" × "}- {pick.itemReadableId}- </Badge>- );- })}- </div>- );-}-export const JobOperation = ({batch,batchMaterialTotals,@@ -318,6 +245,7 @@ export const JobOperation = ({const { t } = useLingui();const { formatRelativeTime } = useDateFormatter();const [params, setParams] = useUrlParams();+ const origin = useOrigin();const trackedEntityParam = params.get("trackedEntityId");const trackedEntityId = trackedEntityParam ?? trackedEntities[0]?.id;@@ -567,9 +495,12 @@ export const JobOperation = ({labor: t`Labor`,machine: t`Machine`} as const;- const runningType = (["setup", "labor", "machine"] as const).find(- (type) => active[type]- );+ // The caption follows the toggle: the selected type's timer when it runs,+ // else the first running one in the toggle's order (Setup, Machine, Labor).+ const selectedType = eventType.toLowerCase() as keyof typeof workTypeLabels;+ const runningType = active[selectedType]+ ? selectedType+ : (["setup", "machine", "labor"] as const).find((type) => active[type]);// Chat is one job's thread, so a Chat tab left open in the job scope falls// back to Details on the batch.const tab = scope === "batch" && activeTab === "chat" ? "details" : activeTab;@@ -747,6 +678,13 @@ export const JobOperation = ({const item = items.find((it) => it.id === operation.itemId);+ const openIssueModal = (material: JobMaterial | null) => {+ flushSync(() => {+ setSelectedMaterial(material);+ });+ issueModal.onOpen();+ };+// Mounted by BOTH the per-job materials table and the batch overview —// the batch scope's Pick opens the same shared-pick modal.const renderIssueModal = (@@ -782,355 +720,482 @@ export const JobOperation = ({/>) : null;- return (- <>- <Tabs- key={`operation-${operation.id}`}- value={tab}- onValueChange={setActiveTab}- // An application shell, not a page: a grid of named areas where each- // pane scrolls on its own, so nothing is positioned or sized by hand.- // Below lg the dock is a bottom action bar; from lg it is a column- // beside the workspace and status bar. The outlet frame is only- // min-height bounded (other MES screens page-scroll), so the shell takes- // the viewport itself, less the frame's md:my-2 inset.- className="grid h-svh md:h-[calc(100svh-1rem)] min-h-0 w-full min-w-0 bg-card grid-cols-[minmax(0,1fr)] grid-rows-[auto_auto_auto_minmax(0,1fr)_auto_auto] [grid-template-areas:'header'_'context'_'sep'_'main'_'status'_'dock'] lg:grid-cols-[minmax(0,1fr)_auto] lg:grid-rows-[auto_auto_auto_minmax(0,1fr)_auto] lg:[grid-template-areas:'header_header'_'context_context'_'sep_sep'_'main_dock'_'status_dock']"+ // Labelled meters: 1 row of up to 4 on a phone, then as many columns as fit.+ // Phones show them in the Details scroll pane, so only 1 bar stays pinned.+ const meters = (+ <div className="grid gap-y-2 max-md:grid-flow-col max-md:auto-cols-[minmax(0,1fr)] max-md:gap-x-2 md:grid-cols-[repeat(auto-fit,minmax(180px,1fr))] md:gap-x-6">+ {(+ [+ {+ type: "setup",+ label: t`Setup`,+ elapsed: progress.setup,+ planned: displayOperation.setupDuration+ },+ {+ type: "labor",+ label: t`Labor`,+ elapsed: progress.labor,+ planned: displayOperation.laborDuration+ },+ {+ type: "machine",+ label: t`Machine`,+ elapsed: progress.machine,+ planned: displayOperation.machineDuration+ }+ ] as const+ )+ .filter((meter) => meter.planned > 0)+ .map((meter) => {+ // A batch with no planned time anywhere carries a 1ms+ // placeholder plan (so ratios never divide by zero). That is+ // not a plan: show elapsed time alone over an empty track.+ const hasPlan = meter.planned > 1;+ const elapsed = formatDurationMilliseconds(meter.elapsed, {+ style: "short"+ });+ return (+ <BarProgress+ key={meter.type}+ label={meter.label}+ value={+ hasPlan+ ? `${elapsed} / ${formatDurationMilliseconds(meter.planned, {+ style: "short"+ })}`+ : elapsed+ }+ gradient+ invertGradient+ stackOnPhone+ progress={hasPlan ? (meter.elapsed / meter.planned) * 100 : 0}+ activeClassName={+ meter.elapsed > meter.planned ? "bg-red-500" : "bg-emerald-500"+ }+ />+ );+ })}+ <BarProgress+ stackOnPhone+ label={isBatched ? t`Batch quantity` : t`Quantity`}+ value={`${quantityProgress.complete} / ${quantityProgress.target}`}+ segments={[+ {+ value: quantityProgress.complete,+ className: "bg-emerald-500"+ },+ {+ value: quantityProgress.reworked,+ className: "bg-yellow-500"+ },+ {+ value: quantityProgress.scrapped,+ className: "bg-red-500"+ }+ ]}+ max={quantityProgress.target || 1}+ progress={+ (quantityProgress.complete / (quantityProgress.target || 1)) * 100+ }+ />+ </div>+ );++ // The job ⋮ menu: in the context row from md, in the app bar on phones.+ const renderJobMenu = ({+ className,+ size,+ align+ }: {+ className?: string;+ size?: "lg";+ align: "start" | "end";+ }) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`More options`}+ variant="ghost"+ size={size}+ className={className}+ icon={<LuEllipsisVertical />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align={align}>+ {scope === "job" && (+ <DropdownMenuItem asChild>+ <a+ href={path.to.file.jobTraveler(operation.jobMakeMethodId)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuQrCode />} />+ <Trans>Job Traveler</Trans>+ </a>+ </DropdownMenuItem>+ )}+ {scope === "job" && (+ <DropdownMenuItem asChild>+ <Link to={path.to.jobDetail(operation.jobId)}>+ <DropdownMenuIcon icon={<LuCirclePlay />} />+ <Trans>Job Details</Trans>+ </Link>+ </DropdownMenuItem>+ )}+ {scope === "batch" && batch && (+ <DropdownMenuItem asChild>+ <a+ href={path.to.batchDetail(batch.id as string)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuLayers />} />+ <Trans>Batch Details</Trans>+ </a>+ </DropdownMenuItem>+ )}+ {scope === "batch" && batch && (+ <DropdownMenuItem asChild>+ <a+ href={path.to.file.batchList(batch.id as string)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuPrinter />} />+ <Trans>Print batch list</Trans>+ </a>+ </DropdownMenuItem>+ )}+ {item && (scope === "job" || batchFacts?.items.length === 1) && (+ <DropdownMenuItem asChild>+ <Link to={path.to.itemMaster(item?.id, item.type)}>+ <DropdownMenuIcon+ icon={<MethodItemTypeIcon type={item.type} />}+ />+ <Trans>Item Master</Trans>+ </Link>+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );++ // The job, customer, status and due row. Phones on the Details tab render+ // it inside the scrolling pane, so it scrolls away with the content.+ const renderContextRow = (className: string) => (+ <div+ className={cn(+ "flex shrink-0 flex-wrap lg:flex-nowrap items-center justify-start px-4 lg:pl-6 py-2 min-h-[var(--header-height)] bg-card gap-x-2 gap-y-1 md:gap-x-4 w-full min-w-0",+ className+ )}+ >+ <HStack+ className={cn(+ "min-w-22 shrink-0 justify-between",+ !batch && "max-md:hidden"+ )}>- <header className="[grid-area:header] flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b px-2">- <HStack className="w-full justify-between">- <div className="flex items-center gap-0">- <SidebarTrigger />-- <Button- variant="ghost"- leftIcon={<LuChevronLeft />}- onClick={() => navigate(path.to.operations)}- className="pl-2"- >- <Trans>Schedule</Trans>- </Button>- </div>- <div className="flex min-w-0 items-center gap-2 overflow-x-auto scrollbar-hide scroll-fade-x">- <TabsList className="ml-auto shrink-0">- <TabsTrigger value="details">- <Trans>Details</Trans>- </TabsTrigger>- <TabsTrigger- disabled={!job.modelPath && !operation.itemModelPath}- value="model"- >- <Trans>Model</Trans>- </TabsTrigger>- <TabsTrigger value="procedure">- <Trans>Instructions</Trans>- </TabsTrigger>- {/* Notes are kept per job operation — on the batch there is no- one thread to show, so Chat opens from a job. */}- <TabsTrigger value="chat" disabled={scope === "batch"}>- <Trans>Chat</Trans>- </TabsTrigger>- </TabsList>- </div>- </HStack>- </header>-- <div className="[grid-area:context] flex shrink-0 flex-wrap lg:flex-nowrap items-center justify-start px-4 lg:pl-6 py-2 min-h-[var(--header-height)] bg-card gap-x-2 gap-y-1 md:gap-x-4 w-full min-w-0">- <HStack className="min-w-22 shrink-0 justify-between">- {batch ? (- // One control for "which part of the batch am I looking at":- // the batch, this job, or (via the chevron) another member job.- <div className="flex shrink-0 items-center rounded-full border bg-card p-0.5 text-sm">+ {batch ? (+ // One control for "which part of the batch am I looking at":+ // the batch, this job, or (via the chevron) another member job.+ <div className="flex shrink-0 items-center rounded-full border bg-card p-0.5 text-sm">+ <button+ type="button"+ aria-pressed={scope === "batch"}+ aria-label={t`Whole batch`}+ onClick={() => setParams({ scope: "" })}+ className={cn(+ "flex items-center gap-1.5 rounded-full px-3 py-1 transition-[background-color,color,transform] active:scale-[0.98]",+ scope === "batch"+ ? "bg-accent text-foreground"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ <LuLayers className="size-3.5" />+ <span className="font-medium tabular-nums">+ {batch.readableId}+ </span>+ <span className="opacity-60">+ {t`${(batch.operations ?? []).length} jobs`}+ </span>+ {isCompleting && (+ <Badge variant="yellow" className="ml-0.5">+ <Trans>Completing</Trans>+ </Badge>+ )}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild><buttontype="button"- aria-pressed={scope === "batch"}- aria-label={t`Whole batch`}- onClick={() => setParams({ scope: "" })}+ aria-pressed={scope === "job"}+ aria-label={t`Choose a job`}className={cn(- "flex items-center gap-1.5 rounded-full px-3 py-1 transition-[background-color,color,transform] active:scale-[0.98]",- scope === "batch"+ "flex items-center gap-1 rounded-full py-1 pl-3 pr-2 font-medium transition-[background-color,color,transform] active:scale-[0.98]",+ scope === "job"? "bg-accent text-foreground": "text-muted-foreground hover:text-foreground")}>- <LuLayers className="size-3.5" />- <span className="font-medium tabular-nums">- {batch.readableId}- </span>- <span className="opacity-60">- {t`${(batch.operations ?? []).length} jobs`}- </span>- {isCompleting && (- <Badge variant="yellow" className="ml-0.5">- <Trans>Completing</Trans>- </Badge>+ {scope === "job" ? (+ operation.jobReadableId+ ) : (+ <Trans>Jobs</Trans>)}+ <LuChevronDown className="size-3.5" /></button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- aria-pressed={scope === "job"}- aria-label={t`Choose a job`}- className={cn(- "flex items-center gap-1 rounded-full py-1 pl-3 pr-2 font-medium transition-[background-color,color,transform] active:scale-[0.98]",- scope === "job"- ? "bg-accent text-foreground"- : "text-muted-foreground hover:text-foreground"- )}- >- {scope === "job" ? (- operation.jobReadableId- ) : (- <Trans>Jobs</Trans>- )}- <LuChevronDown className="size-3.5" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="min-w-[240px]">- <DropdownMenuLabel>- <Trans>Open a job in this batch</Trans>- </DropdownMenuLabel>- <DropdownMenuSeparator />- {[...(batch.operations ?? [])]- .sort((a, b) =>- (- (a.job as { jobId?: string | null } | null)?.jobId ??- ""- ).localeCompare(- (b.job as { jobId?: string | null } | null)?.jobId ??- "",- undefined,- { numeric: true }- )- )- .map((member) => {- const isOpen =- scope === "job" && member.id === operation.id;- return (- <DropdownMenuItem key={member.id} asChild>- <Link- to={`${path.to.operation(member.id)}?scope=job`}- >- <DropdownMenuIcon- icon={- isOpen ? (- <LuCheck className="text-emerald-500" />- ) : (- <LuClipboardCheck />- )- }- />- <span className="truncate">- {(- member.job as { jobId?: string | null } | null- )?.jobId ?? member.id}- {member.jobMakeMethod?.item- ?.readableIdWithRevision- ? ` — ${member.jobMakeMethod.item.readableIdWithRevision}`- : ""}- </span>- </Link>- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>- </div>- ) : (- <Heading size="h4">{operation.jobReadableId}</Heading>- )}-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="More options"- variant="ghost"- icon={<LuEllipsisVertical />}- /></DropdownMenuTrigger>- <DropdownMenuContent align="start">- {scope === "job" && (- <DropdownMenuItem asChild>- <a- href={path.to.file.jobTraveler(operation.jobMakeMethodId)}- target="_blank"- rel="noreferrer"- >- <DropdownMenuIcon icon={<LuQrCode />} />- <Trans>Job Traveler</Trans>- </a>- </DropdownMenuItem>- )}- {scope === "job" && (- <DropdownMenuItem asChild>- <Link to={path.to.jobDetail(operation.jobId)}>- <DropdownMenuIcon icon={<LuCirclePlay />} />- <Trans>Job Details</Trans>- </Link>- </DropdownMenuItem>- )}- {scope === "batch" && batch && (- <DropdownMenuItem asChild>- <a- href={path.to.batchDetail(batch.id as string)}- target="_blank"- rel="noreferrer"- >- <DropdownMenuIcon icon={<LuLayers />} />- <Trans>Batch Details</Trans>- </a>- </DropdownMenuItem>- )}- {scope === "batch" && batch && (- <DropdownMenuItem asChild>- <a- href={path.to.file.batchList(batch.id as string)}- target="_blank"- rel="noreferrer"- >- <DropdownMenuIcon icon={<LuPrinter />} />- <Trans>Print batch list</Trans>- </a>- </DropdownMenuItem>- )}- {item &&- (scope === "job" || batchFacts?.items.length === 1) && (- <DropdownMenuItem asChild>- <Link to={path.to.itemMaster(item?.id, item.type)}>- <DropdownMenuIcon- icon={<MethodItemTypeIcon type={item.type} />}- />- <Trans>Item Master</Trans>- </Link>- </DropdownMenuItem>- )}+ <DropdownMenuContent align="start" className="min-w-[240px]">+ <DropdownMenuLabel>+ <Trans>Open a job in this batch</Trans>+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ {[...(batch.operations ?? [])]+ .sort((a, b) =>+ (+ (a.job as { jobId?: string | null } | null)?.jobId ?? ""+ ).localeCompare(+ (b.job as { jobId?: string | null } | null)?.jobId ?? "",+ undefined,+ { numeric: true }+ )+ )+ .map((member) => {+ const isOpen =+ scope === "job" && member.id === operation.id;+ return (+ <DropdownMenuItem key={member.id} asChild>+ <Link to={`${path.to.operation(member.id)}?scope=job`}>+ <DropdownMenuIcon+ icon={+ isOpen ? (+ <LuCheck className="text-emerald-500" />+ ) : (+ <LuClipboardCheck />+ )+ }+ />+ <span className="truncate">+ {(member.job as { jobId?: string | null } | null)+ ?.jobId ?? member.id}+ {member.jobMakeMethod?.item?.readableIdWithRevision+ ? ` — ${member.jobMakeMethod.item.readableIdWithRevision}`+ : ""}+ </span>+ </Link>+ </DropdownMenuItem>+ );+ })}</DropdownMenuContent></DropdownMenu>- </HStack>+ </div>+ ) : (+ <Heading size="h4" className="max-md:hidden">+ {operation.jobReadableId}+ </Heading>+ )}- <HStack className="flex w-full lg:w-auto min-w-0 lg:flex-1 justify-start lg:justify-end items-center gap-3 overflow-x-auto lg:overflow-hidden scrollbar-hide scroll-fade-x [&>*]:shrink-0 lg:[&>*]:shrink">- {scope === "batch" && batchFacts- ? batchFacts.customers.length > 0 && (- <HStack className="min-w-0 justify-start space-x-2">- <LuSquareUser className="text-muted-foreground shrink-0" />- <span className="text-sm truncate">- {batchFacts.customers.length === 1- ? batchFacts.customers[0]- : t`${batchFacts.customers.length} customers`}- </span>- </HStack>- )- : job.customer?.name && (- <HStack className="min-w-0 justify-start space-x-2">- <LuSquareUser className="text-muted-foreground shrink-0" />- <span className="text-sm truncate">- {job.customer.name}- </span>- </HStack>- )}- {operation.description && (- <HStack className="min-w-0 justify-start space-x-2">- <LuClipboardCheck className="text-muted-foreground shrink-0" />+ {renderJobMenu({ className: "max-md:hidden", align: "start" })}+ </HStack>++ <HStack className="flex w-full lg:w-auto min-w-0 lg:flex-1 justify-start lg:justify-end items-center gap-3 overflow-x-auto lg:overflow-hidden scrollbar-hide scroll-fade-x [&>*]:shrink-0 lg:[&>*]:shrink max-md:flex-wrap max-md:overflow-visible max-md:gap-y-1 max-md:mask-none max-md:[&>*]:shrink">+ {scope === "batch" && batchFacts+ ? batchFacts.customers.length > 0 && (+ <HStack className="min-w-0 justify-start space-x-2 max-md:order-3">+ <LuSquareUser className="text-muted-foreground shrink-0" /><span className="text-sm truncate">- {operation.description}+ {batchFacts.customers.length === 1+ ? batchFacts.customers[0]+ : t`${batchFacts.customers.length} customers`}</span></HStack>- )}- {scope === "batch" && batch ? (- <HStack className="min-w-0 shrink-0 justify-start space-x-2">- <LuLayers className="text-muted-foreground shrink-0" />- <span className="text-sm truncate">- {isCompleting ? t`Completing` : t`Released`}- </span>+ )+ : job.customer?.name && (+ <HStack className="min-w-0 justify-start space-x-2 max-md:order-3">+ <LuSquareUser className="text-muted-foreground shrink-0" />+ <span className="text-sm truncate">{job.customer.name}</span></HStack>- ) : (- operation.operationStatus && (- <HStack className="min-w-0 shrink-0 justify-start space-x-2">- <OperationStatusIcon- status={- operation.jobStatus === "Paused"- ? "Paused"- : operation.operationStatus- }- />- <span className="text-sm truncate">- {operation.jobStatus === "Paused"- ? "Paused"- : operation.operationStatus}- </span>- </HStack>- ))}- {/* Batch mode shows the batch's planned total (shared setup +- summed work); a zero plan renders nothing rather than- "0 milliseconds". */}- {typeof displayOperation.duration === "number" &&- displayOperation.duration > 1 && (- <HStack className="min-w-0 shrink-0 justify-start space-x-2">- <LuTimer className="text-muted-foreground shrink-0" />- <span className="text-sm truncate tabular-nums">- {formatDurationMilliseconds(displayOperation.duration)}- </span>- </HStack>+ {operation.description && (+ <HStack className="min-w-0 justify-start space-x-2 max-md:order-4">+ <LuClipboardCheck className="text-muted-foreground shrink-0" />+ <span className="text-sm truncate">{operation.description}</span>+ </HStack>+ )}+ {scope === "batch" && batch ? (+ <HStack className="min-w-0 shrink-0 justify-start space-x-2 max-md:order-1">+ <LuLayers className="text-muted-foreground shrink-0" />+ <span className="text-sm truncate">+ {isCompleting ? t`Completing` : t`Released`}+ </span>+ </HStack>+ ) : (+ operation.operationStatus && (+ <HStack className="min-w-0 shrink-0 justify-start space-x-2 max-md:order-1">+ <OperationStatusIcon+ status={+ operation.jobStatus === "Paused"+ ? "Paused"+ : operation.operationStatus+ }+ />+ <span className="text-sm truncate">+ {operation.jobStatus === "Paused"+ ? "Paused"+ : operation.operationStatus}+ </span>+ </HStack>+ )+ )}+ {/* Batch mode shows the batch's planned total (shared setup ++ summed work); a zero plan renders nothing rather than+ "0 milliseconds". */}+ {typeof displayOperation.duration === "number" &&+ displayOperation.duration > 1 && (+ <HStack className="min-w-0 shrink-0 justify-start space-x-2 max-md:order-5">+ <LuTimer className="text-muted-foreground shrink-0" />+ <span className="text-sm truncate tabular-nums">+ {formatDurationMilliseconds(displayOperation.duration)}+ </span>+ </HStack>+ )}+ {scope === "batch" && batchFacts ? (+ <HStack className="min-w-0 shrink-0 justify-start space-x-2 max-md:order-2">+ <DeadlineIcon+ deadlineType={+ (batchFacts.deadline ??+ "Hard Deadline") as typeof operation.jobDeadlineType+ }+ overdue={batchOverdue}+ />+ <span+ className={cn(+ "text-sm truncate",+ batchOverdue ? "text-red-500" : "")}- {scope === "batch" && batchFacts ? (- <HStack className="min-w-0 shrink-0 justify-start space-x-2">- <DeadlineIcon- deadlineType={- (batchFacts.deadline ??- "Hard Deadline") as typeof operation.jobDeadlineType- }- overdue={batchOverdue}- />- <span- className={cn(- "text-sm truncate",- batchOverdue ? "text-red-500" : ""- )}- >- {batchFacts.dueDate- ? t`First due ${formatRelativeTime(- convertDateStringToIsoString(batchFacts.dueDate)+ >+ {batchFacts.dueDate+ ? t`First due ${formatRelativeTime(+ convertDateStringToIsoString(batchFacts.dueDate)+ )}`+ : batchFacts.deadline}+ </span>+ </HStack>+ ) : (+ operation.jobDeadlineType && (+ <HStack className="min-w-0 shrink-0 justify-start space-x-2 max-md:order-2">+ <DeadlineIcon+ deadlineType={operation.jobDeadlineType}+ overdue={isOverdue}+ />++ <span+ className={cn(+ "text-sm truncate",+ isOverdue ? "text-red-500" : ""+ )}+ >+ {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)+ ? operation.jobDeadlineType+ : operation.operationDueDate+ ? t`Due ${formatRelativeTime(+ convertDateStringToIsoString(operation.operationDueDate))}`- : batchFacts.deadline}- </span>- </HStack>- ) : (- operation.jobDeadlineType && (- <HStack className="min-w-0 shrink-0 justify-start space-x-2">- <DeadlineIcon- deadlineType={operation.jobDeadlineType}- overdue={isOverdue}- />+ : "–"}+ </span>+ </HStack>+ )+ )}+ </HStack>+ </div>+ );- <span- className={cn(- "text-sm truncate",- isOverdue ? "text-red-500" : ""- )}+ return (+ <>+ <Tabs+ key={`operation-${operation.id}`}+ value={tab}+ onValueChange={setActiveTab}+ // An application shell, not a page: a grid of named areas where each+ // pane scrolls on its own, so nothing is positioned or sized by hand.+ // Below lg the dock is a bottom action bar; from lg it is a column+ // beside the workspace and status bar. The outlet frame is only+ // min-height bounded (other MES screens page-scroll), so the shell takes+ // the viewport itself, less the frame's md:my-2 inset.+ className="grid h-svh md:h-[calc(100svh-1rem)] min-h-0 w-full min-w-0 bg-card grid-cols-[minmax(0,1fr)] grid-rows-[auto_auto_auto_minmax(0,1fr)_auto_auto] [grid-template-areas:'header'_'context'_'sep'_'main'_'status'_'dock'] lg:grid-cols-[minmax(0,1fr)_auto] lg:grid-rows-[auto_auto_auto_minmax(0,1fr)_auto] lg:[grid-template-areas:'header_header'_'context_context'_'sep_sep'_'main_dock'_'status_dock']"+ >+ <div className="[grid-area:header] flex min-w-0 flex-col">+ <MesAppBar+ kind="pushed"+ title={+ scope === "batch" && batch+ ? batch.readableId+ : operation.jobReadableId+ }+ subtitle={origin.label}+ back={{ to: origin.to }}+ actions={renderJobMenu({ size: "lg", align: "end" })}+ desktop={null}+ />+ <header className="flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b px-2 max-md:h-auto max-md:py-0">+ <HStack className="w-full justify-between max-md:flex-wrap max-md:gap-y-1">+ <div className="flex items-center gap-0 max-md:hidden">+ <SidebarTrigger />++ <Button+ variant="ghost"+ leftIcon={<LuChevronLeft />}+ onClick={() => navigate(origin.to)}+ className="pl-2"+ >+ {origin.label}+ </Button>+ </div>+ <div className="flex min-w-0 items-center gap-2 overflow-x-auto scrollbar-hide scroll-fade-x max-md:w-full">+ <TabsList className="ml-auto shrink-0 max-md:ml-0 max-md:w-full max-md:border-b-0 max-md:[&>*]:flex-1">+ <TabsTrigger value="details">+ <Trans>Details</Trans>+ </TabsTrigger>+ <TabsTrigger+ disabled={!job.modelPath && !operation.itemModelPath}+ value="model">- {["ASAP", "No Deadline"].includes(operation.jobDeadlineType)- ? operation.jobDeadlineType- : operation.operationDueDate- ? t`Due ${formatRelativeTime(- convertDateStringToIsoString(- operation.operationDueDate- )- )}`- : "–"}- </span>- </HStack>- )- )}- </HStack>+ <Trans>Model</Trans>+ </TabsTrigger>+ <TabsTrigger value="procedure">+ <Trans>Instructions</Trans>+ </TabsTrigger>+ {/* Notes are kept per job operation — on the batch there is no+ one thread to show, so Chat opens from a job. */}+ <TabsTrigger value="chat" disabled={scope === "batch"}>+ <Trans>Chat</Trans>+ </TabsTrigger>+ </TabsList>+ </div>+ </HStack>+ </header></div>- <Separator className="[grid-area:sep]" />++ {renderContextRow(+ cn("[grid-area:context]", tab === "details" && "max-md:hidden")+ )}+ <Separator+ className={cn(+ "[grid-area:sep]",+ tab === "details" && "max-md:hidden"+ )}+ /><TabsContentvalue="details"className="[grid-area:main] mt-0 h-full min-h-0 overflow-y-auto scroll-fade scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"><div className="w-full min-w-0">+ {renderContextRow("md:hidden border-b border-border")}+ <div className="border-b border-border px-4 py-3 md:hidden">+ {meters}+ </div>{isCompleting && (<div className="px-4 pt-4 lg:px-6"><Card>@@ -1193,12 +1258,7 @@ export const JobOperation = ({batch={batch}totals={batchMaterialTotals ?? {}}currentMaterials={resolvedMaterials?.materials ?? []}- onIssue={(material) => {- flushSync(() => {- setSelectedMaterial(material);- });- issueModal.onOpen();- }}+ onIssue={openIssueModal}workInstructions={batchWorkInstructions}onDownloadFile={downloadFile}/>@@ -1229,7 +1289,10 @@ export const JobOperation = ({</div></HStack><div className="flex flex-col shrink-0 items-end">- <Heading size="h2" className="font-sans">+ <Heading+ size="h2"+ className="font-sans max-md:text-base max-md:text-muted-foreground"+ >{formatDurationMilliseconds(((progress.setup ?? 0) +(progress.labor ?? 0) +@@ -1259,7 +1322,7 @@ export const JobOperation = ({</div><Separator /><div className="flex items-start p-4 lg:p-6">- <div className="grid gap-4 grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full min-w-0">+ <div className="grid gap-4 grid-cols-2 xl:grid-cols-3 w-full min-w-0 max-md:hidden"><Card><CardHeader className="flex flex-row items-center gap-2 justify-between"><CardTitle>@@ -1290,7 +1353,7 @@ export const JobOperation = ({</Heading></CardContent></Card>- <Card>+ <Card className="max-md:col-span-2"><CardHeader className="flex flex-row items-center gap-2 justify-between"><CardTitle><Trans>Due Date</Trans>@@ -1352,6 +1415,93 @@ export const JobOperation = ({</CardContent></Card></div>+ <Card className="md:hidden">+ <CardContent className="max-md:rounded-xl max-md:border-0 max-md:py-1">+ <CardAttributes className="divide-y divide-border">+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Completed</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="tabular-nums text-2xl font-semibold">+ <Trans>+ {operation.quantityComplete} of{" "}+ {operation.targetQuantity}+ </Trans>+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Scrapped</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="tabular-nums">+ {operation.quantityScrapped}+ </CardAttributeValue>+ </CardAttribute>+ <CardAttribute>+ <CardAttributeLabel>+ <Trans>Due Date</Trans>+ </CardAttributeLabel>+ <CardAttributeValue className="flex flex-col items-end gap-1 text-right">+ <span className="flex flex-wrap items-baseline justify-end gap-x-1 text-sm">+ {operation.operationDueDate ? (+ <>+ <span className="text-muted-foreground">+ <DateTime+ value={operation.operationDueDate}+ variant="date"+ />+ </span>+ <span+ aria-hidden+ className="text-muted-foreground"+ >+ ·+ </span>+ </>+ ) : null}+ <span+ className={cn(+ "font-medium",+ isOverdue && "text-red-500"+ )}+ >+ {["ASAP", "No Deadline"].includes(+ operation.jobDeadlineType+ )+ ? operation.jobDeadlineType+ : operation.operationDueDate+ ? t`Due ${formatRelativeTime(+ convertDateStringToIsoString(+ operation.operationDueDate+ )+ )}`+ : "–"}+ </span>+ </span>+ {projectedCompletionDate &&+ (isBehindTarget ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="red">+ {t`Proj. ${formatDate(+ projectedCompletionDate+ )}`}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ {t`Behind target by ${daysBehindTarget} day(s)`}+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="text-sm text-muted-foreground">+ {t`Proj. ${formatDate(projectedCompletionDate)}`}+ </span>+ ))}+ </CardAttributeValue>+ </CardAttribute>+ </CardAttributes>+ </CardContent>+ </Card></div><Suspense key={`non-conformance-actions-${operationId}`}>@@ -1640,16 +1790,11 @@ export const JobOperation = ({<Trans>Materials</Trans></Heading><Button- aria-label="Issue Material"+ aria-label={t`Issue Material`}leftIcon={<LuGitBranchPlus />}variant="secondary"size="lg"- onClick={() => {- flushSync(() => {- setSelectedMaterial(null);- });- issueModal.onOpen();- }}+ onClick={() => openIssueModal(null)}><Trans>Issue Material</Trans></Button>@@ -1659,541 +1804,20 @@ export const JobOperation = ({fallback={<TableSkeleton />}><Await resolve={materials}>- {(resolvedMaterials) => {- const baseMaterials =- resolvedMaterials?.materials.filter(- (m) => !m.isKitComponent- );-- const kitMaterialsByParentId =- resolvedMaterials?.materials- .filter((m) => m.isKitComponent ?? false)- .reduce(- (acc, material) => {- if (material.kitParentId) {- if (!acc[material.kitParentId]) {- acc[material.kitParentId] = [];- }- acc[material.kitParentId].push(material);- }- return acc;- },- {} as Record<string, JobMaterial[]>- );-- return (- <>- <div className="w-full overflow-hidden rounded-lg border bg-card">- <Table className="w-full text-base">- <Thead className="bg-muted/40">- <Tr>- <Th className="text-sm">- <Trans>Part</Trans>- </Th>- <Th className="text-sm lg:table-cell hidden">- <Trans>Source</Trans>- </Th>- <Th className="text-sm">- <Trans>Estimated</Trans>- </Th>- <Th className="text-sm">- <Trans>Actual</Trans>- </Th>- <Th className="text-right" />- </Tr>- </Thead>- <Tbody className="[&>tr]:border-b [&>tr:last-child]:border-0">- {baseMaterials.length === 0 ? (- <Tr>- <Td- colSpan={24}- className="py-8 text-muted-foreground text-center"- >- <Trans>No materials</Trans>- </Td>- </Tr>- ) : (- baseMaterials.map((material) => {- const isRelatedToOperation =- material.jobOperationId ===- operationId;-- const someRelatedMaterialIsIssued =- baseMaterials.some(- (m) =>- m.itemReadableIdWithoutRevision ===- material.itemReadableIdWithoutRevision &&- ((m.quantityIssued ?? 0) > 0 ||- (material.quantityIssued ?? 0) >- 0)- );-- const kittedChildren = material.id- ? kitMaterialsByParentId[material.id]- : [];-- return (- <>- <Tr- key={`material-${material.id}`}- className={cn(- "[&>td]:py-3",- !isRelatedToOperation &&- "opacity-50 hover:opacity-100"- )}- >- <Td className="max-w-[20vw]">- <HStack- spacing={2}- className="justify-between min-w-0"- >- <VStack- spacing={0}- className="min-w-0"- >- <span className="font-semibold text-base truncate max-w-full">- {getItemReadableId(- items,- material.itemId ?? ""- )}- </span>- <span className="text-muted-foreground text-sm truncate max-w-full">- {material.description}- </span>- <PickedBreakdown- materialItemId={- material.itemId- }- pickedByItem={- (- material as {- pickedByItem?: {- itemId: string;- itemReadableId: string;- quantityPicked: number;- quantityToPick: number;- }[];- }- ).pickedByItem- }- />- </VStack>- {material.requiresBatchTracking ? (- <Badge variant="secondary">- <TrackingTypeIcon- type="Batch"- className="shrink-0"- />- </Badge>- ) : material.requiresSerialTracking ? (- <Badge variant="secondary">- <TrackingTypeIcon- type="Serial"- className="shrink-0"- />- </Badge>- ) : null}- {(- material as {- hasExpiredConsumed?: boolean;- }- ).hasExpiredConsumed && (- <Badge- variant="red"- className="gap-1 shrink-0"- title="A consumed batch or serial is now past its expiry date."- >- <LuTriangleAlert className="size-3" />- <Trans>- Consumed expired- </Trans>- </Badge>- )}- <PickedBadge- quantityPicked={- (- material as {- quantityPicked?:- | number- | null;- }- ).quantityPicked- }- quantityToPick={- (- material as {- quantityToPick?:- | number- | null;- }- ).quantityToPick- }- />- </HStack>- </Td>- <Td className="hidden lg:table-cell">- <div className="flex flex-row items-center gap-1">- <Badge variant="secondary">- <MethodIcon- type={- material.methodType ??- ""- }- isKit={- material.kit ?? false- }- className="mr-2"- />- {material.methodType ===- "Make to Order" &&- material.kit- ? t`Kit`- : material.methodType}- </Badge>- <LuArrowLeft- className={cn(- material.methodType ===- "Make to Order"- ? "rotate-180"- : ""- )}- />- <Badge variant="secondary">- <LuGitPullRequest className="size-3 mr-1" />- {material.storageUnitName ??- (material.methodType ===- "Make to Order"- ? t`WIP`- : t`Default Storage Unit`)}- </Badge>- </div>- </Td>-- <Td>- {parentIsSerial &&- (material.requiresBatchTracking ||- material.requiresSerialTracking)- ? `${- material.quantity ??- material.estimatedQuantity- }/${- material.estimatedQuantity ??- material.quantity- }`- : (material.estimatedQuantity ??- material.quantity)}- {isBatched &&- material.itemId &&- batchMaterialTotals?.[- material.itemId- ] && (- <div className="text-xs text-muted-foreground whitespace-nowrap">- <Trans>Batch</Trans>:{" "}- {- batchMaterialTotals[- material.itemId- ].required- }- </div>- )}- </Td>- <Td>- {material.methodType ===- "Make to Order" &&- material.requiresBatchTracking ===- false &&- material.requiresSerialTracking ===- false ? (- <MethodIcon- type="Make to Order"- isKit={- material.kit ?? false- }- />- ) : parentIsSerial &&- (material.requiresBatchTracking ||- material.requiresSerialTracking) ? (- `${material.quantityIssued}/${- material.quantity ??- material.estimatedQuantity- }`- ) : (- material.quantityIssued- )}- {isBatched &&- material.itemId &&- batchMaterialTotals?.[- material.itemId- ] && (- <div className="text-xs text-muted-foreground whitespace-nowrap">- <Trans>Batch</Trans>:{" "}- {- batchMaterialTotals[- material.itemId- ].issued- }- </div>- )}- </Td>- <Td className="text-right">- {material.methodType !==- "Make to Order" &&- material.requiresBatchTracking ===- false &&- material.requiresSerialTracking ===- false && (- <IconButton- aria-label="Issue Material"- variant="ghost"- icon={<LuGitBranchPlus />}- className="h-8 w-8"- onClick={() => {- flushSync(() => {- setSelectedMaterial(- material- );- });- issueModal.onOpen();- }}- />- )}- {(material.requiresBatchTracking ||- material.requiresSerialTracking) && (- <Button- className="flex-shrink-0"- size="lg"- variant={- someRelatedMaterialIsIssued ||- !isRelatedToOperation- ? "secondary"- : "primary"- }- leftIcon={<LuQrCode />}- onClick={() => {- flushSync(() => {- setSelectedMaterial(- material- );- });- issueModal.onOpen();- }}- >- <Trans>Issue</Trans>- </Button>- )}- </Td>- </Tr>-- {kittedChildren &&- kittedChildren.map(- (kittedChild, index) => (- <Tr- key={`kittedChild-${kittedChild.id}`}- className={cn(- index ===- kittedChildren.length -- 1- ? "border-b"- : index === 0- ? "border-t"- : "",- !isRelatedToOperation &&- "opacity-50 hover:opacity-100"- )}- >- <Td className="pl-10 max-w-[20vw]">- <HStack- spacing={2}- className="justify-between min-w-0"- >- <VStack- spacing={0}- className="min-w-0"- >- <span className="font-semibold truncate max-w-full">- {getItemReadableId(- items,- kittedChild.itemId- )}- </span>- <span className="text-muted-foreground text-xs truncate max-w-full">- {- kittedChild.description- }- </span>- <PickedBreakdown- materialItemId={- kittedChild.itemId- }- pickedByItem={- (- kittedChild as {- pickedByItem?: {- itemId: string;- itemReadableId: string;- quantityPicked: number;- quantityToPick: number;- }[];- }- ).pickedByItem- }- />- </VStack>- {kittedChild.requiresBatchTracking ? (- <Badge variant="secondary">- <TrackingTypeIcon- type="Batch"- className="shrink-0"- />- </Badge>- ) : kittedChild.requiresSerialTracking ? (- <Badge variant="secondary">- <TrackingTypeIcon- type="Serial"- className="shrink-0"- />- </Badge>- ) : null}- <PickedBadge- quantityPicked={- (- kittedChild as {- quantityPicked?:- | number- | null;- }- ).quantityPicked- }- quantityToPick={- (- kittedChild as {- quantityToPick?:- | number- | null;- }- ).quantityToPick- }- />- </HStack>- </Td>- <Td className="lg:table-cell hidden">- <Badge variant="secondary">- <MethodIcon- type={- kittedChild.methodType ??- ""- }- isKit={- kittedChild.kit ??- false- }- className="mr-2"- />- {kittedChild.methodType ===- "Make to Order" &&- kittedChild.kit- ? t`Kit`- : kittedChild.methodType}- </Badge>- </Td>-- <Td>- {parentIsSerial &&- (kittedChild.requiresBatchTracking ||- kittedChild.requiresSerialTracking)- ? `${- kittedChild.quantity ??- kittedChild.estimatedQuantity- }/${- kittedChild.estimatedQuantity ??- kittedChild.quantity- }`- : (kittedChild.estimatedQuantity ??- kittedChild.quantity)}- </Td>- <Td>- {kittedChild.methodType ===- "Make to Order" &&- kittedChild.requiresBatchTracking ===- false &&- kittedChild.requiresSerialTracking ===- false ? (- <MethodIcon- type="Make to Order"- isKit={- kittedChild.kit ??- false- }- />- ) : parentIsSerial &&- (kittedChild.requiresBatchTracking ||- kittedChild.requiresSerialTracking) ? (- `${- kittedChild.quantityIssued- }/${- kittedChild.quantity ??- kittedChild.estimatedQuantity- }`- ) : (- kittedChild.quantityIssued- )}- </Td>- <Td className="text-right">- {kittedChild.methodType !==- "Make to Order" &&- kittedChild.requiresBatchTracking ===- false &&- kittedChild.requiresSerialTracking ===- false && (- <IconButton- aria-label="Issue Material"- variant="ghost"- icon={- <LuGitBranchPlus />- }- className="h-8 w-8"- onClick={() => {- flushSync(() => {- setSelectedMaterial(- kittedChild- );- });- issueModal.onOpen();- }}- />- )}- {(kittedChild.requiresBatchTracking ||- kittedChild.requiresSerialTracking) && (- <IconButton- aria-label="Issue Material"- variant="secondary"- icon={<LuQrCode />}- className="h-8 w-8"- onClick={() => {- flushSync(() => {- setSelectedMaterial(- kittedChild- );- });- issueModal.onOpen();- }}- />- )}- </Td>- </Tr>- )- )}- </>- );- })- )}- </Tbody>- </Table>- </div>- {renderIssueModal(resolvedMaterials)}- </>- );- }}+ {(resolvedMaterials) => (+ <>+ <OperationMaterials+ materials={resolvedMaterials?.materials ?? []}+ operationId={operation.id}+ parentIsSerial={parentIsSerial ?? false}+ batchMaterialTotals={+ isBatched ? batchMaterialTotals : undefined+ }+ onIssue={openIssueModal}+ />+ {renderIssueModal(resolvedMaterials)}+ </>+ )}</Await></Suspense></div>@@ -2893,7 +2517,9 @@ export const JobOperation = ({collapsed={dockCollapsed}onCollapsedChange={onDockCollapsedChange}>- <div className="flex w-full min-w-0 items-center gap-2 lg:flex-col lg:py-2">+ {/* Phones: the work-type picker on its own row, then the big+ button with what is running beside it, then Log and More. */}+ <div className="flex w-full min-w-0 items-center gap-2 lg:flex-col lg:py-2 max-lg:flex-wrap max-lg:gap-y-1 max-md:gap-y-2"><dl className="hidden w-full gap-3 rounded-lg border bg-card p-3 lg:grid lg:group-data-[collapsed=true]/dock:hidden"><div className="min-w-0"><dt className="text-xs text-muted-foreground">@@ -2935,78 +2561,112 @@ export const JobOperation = ({operation={displayOperation}value={eventType}onChange={setEventType}- className="min-w-0 flex-1 lg:flex-none"+ className="min-w-0 flex-1 lg:flex-none max-md:basis-full"/>- <StartStopButton- eventType={eventType as (typeof productionEventType)[number]}- job={job}- operation={operation}- setupProductionEvent={setupProductionEvent}- laborProductionEvent={laborProductionEvent}- machineProductionEvent={machineProductionEvent}- isTrackedActivity={- !isBatched &&- (method?.requiresSerialTracking === true ||- method?.requiresBatchTracking === true)- }- trackedEntityId={trackedEntityId}- batchId={batch?.id}- />- {/* What the big button will do, or what is running — the dock- only; the rail and the phone bar stay icon-sized. */}- <div className="hidden flex-col items-center gap-0.5 text-center lg:flex lg:group-data-[collapsed=true]/dock:hidden">- {runningType ? (- <>- <span className="flex items-center gap-1.5 text-xs font-medium text-emerald-600 dark:text-emerald-400">- <span className="size-2 animate-pulse rounded-full bg-emerald-500" />- {workTypeLabels[runningType]}- </span>- <span className="font-mono text-lg tabular-nums">- {formatDurationMilliseconds(progress[runningType], {- style: "short"- })}+ {/* From md the wrapper is invisible to layout. */}+ <div className="flex flex-col items-center gap-0.5 md:contents max-md:min-w-0 max-md:flex-1 max-md:flex-row max-md:gap-3">+ <StartStopButton+ eventType={eventType as (typeof productionEventType)[number]}+ job={job}+ operation={operation}+ setupProductionEvent={setupProductionEvent}+ laborProductionEvent={laborProductionEvent}+ machineProductionEvent={machineProductionEvent}+ isTrackedActivity={+ !isBatched &&+ (method?.requiresSerialTracking === true ||+ method?.requiresBatchTracking === true)+ }+ trackedEntityId={trackedEntityId}+ batchId={batch?.id}+ />+ {/* What the big button will do, or what is running — the dock+ only; the rail and the phone bar stay icon-sized. */}+ <div+ className={cn(+ "flex flex-col items-center gap-0.5 text-center lg:group-data-[collapsed=true]/dock:hidden",+ // Tablets: one centred line over the controls, while a timer runs.+ "md:max-lg:order-first md:max-lg:basis-full md:max-lg:flex-row md:max-lg:justify-center md:max-lg:gap-1",+ // Phones: the caption beside the button, the type over the time.+ "max-md:min-w-0 max-md:items-start max-md:gap-0 max-md:text-left max-md:whitespace-nowrap",+ !runningType && "md:max-lg:hidden"+ )}+ >+ {runningType ? (+ <>+ <span className="flex items-center gap-1.5 text-xs font-medium text-emerald-600 dark:text-emerald-400 max-md:leading-tight">+ <span className="size-2 animate-pulse rounded-full bg-emerald-500" />+ <span>{workTypeLabels[runningType]}</span>+ </span>+ <span+ aria-hidden+ className="hidden text-xs text-muted-foreground md:max-lg:inline md:max-lg:text-sm"+ >+ ·+ </span>+ <span className="font-mono text-lg tabular-nums md:max-lg:text-sm max-md:text-base max-md:font-semibold max-md:leading-tight">+ {formatDurationMilliseconds(progress[runningType], {+ style: "short"+ })}+ </span>+ </>+ ) : (+ <span className="text-sm text-muted-foreground">+ {t`Start ${workTypeLabels[+ eventType.toLowerCase() as keyof typeof workTypeLabels+ ].toLowerCase()}`}</span>- </>- ) : (- <span className="text-sm text-muted-foreground">- {t`Start ${workTypeLabels[- eventType.toLowerCase() as keyof typeof workTypeLabels- ].toLowerCase()}`}- </span>- )}+ )}+ </div></div><div className="flex flex-row lg:hidden lg:group-data-[collapsed=true]/dock:flex lg:flex-col items-center gap-2 justify-center">- <IconButtonWithTooltip- disabled={- !isBatched &&- parentIsSerial &&- trackedEntities.some(- (entity) =>- entity.id === trackedEntityId &&- `Operation ${operationId}` in- (entity.attributes as TrackedEntityAttributes)- )- }- icon={- isBatched ? (- <LuPackageCheck className="text-accent-foreground group-hover:text-accent-foreground/80" />+ <div className="flex flex-col items-center gap-0.5">+ <IconButtonWithTooltip+ disabled={+ !isBatched &&+ parentIsSerial &&+ trackedEntities.some(+ (entity) =>+ entity.id === trackedEntityId &&+ `Operation ${operationId}` in+ (entity.attributes as TrackedEntityAttributes)+ )+ }+ icon={+ isBatched ? (+ <LuPackageCheck className="text-accent-foreground group-hover:text-accent-foreground/80" />+ ) : (+ <FaPlus className="text-accent-foreground group-hover:text-accent-foreground/80" />+ )+ }+ tooltip={isBatched ? t`Complete Batch` : t`Log Completed`}+ onClick={+ isBatched+ ? batchCompleteModal.onOpen+ : completeModal.onOpen+ }+ />+ <span className="whitespace-nowrap text-xs text-muted-foreground lg:hidden max-md:hidden">+ {isBatched ? (+ <Trans>Complete batch</Trans>) : (- <FaPlus className="text-accent-foreground group-hover:text-accent-foreground/80" />- )- }- tooltip={isBatched ? t`Complete Batch` : t`Log Completed`}- onClick={- isBatched ? batchCompleteModal.onOpen : completeModal.onOpen- }- />- <IconButtonWithTooltip- icon={- <LuEllipsisVertical className="text-accent-foreground group-hover:text-accent-foreground/80" />- }- tooltip={t`More Actions`}- onClick={actionsSheet.onOpen}- />+ <Trans>Log completed</Trans>+ )}+ </span>+ </div>+ <div className="flex flex-col items-center gap-0.5">+ <IconButtonWithTooltip+ icon={+ <LuEllipsisVertical className="text-accent-foreground group-hover:text-accent-foreground/80" />+ }+ tooltip={t`More Actions`}+ onClick={actionsSheet.onOpen}+ />+ <span className="whitespace-nowrap text-xs text-muted-foreground lg:hidden max-md:hidden">+ <Trans>More</Trans>+ </span>+ </div></div><div className="hidden w-full flex-col gap-2 lg:flex lg:group-data-[collapsed=true]/dock:hidden"><Button@@ -3048,90 +2708,13 @@ export const JobOperation = ({</Controls>)}{!["chat"].includes(activeTab) && (- <Times className="[grid-area:status]">- {/* Labelled meters: two per row on a phone, then as many columns- as fit (four across a desktop). */}- <div className="grid grid-cols-2 gap-x-4 gap-y-2 sm:gap-x-6 sm:grid-cols-[repeat(auto-fit,minmax(180px,1fr))]">- {(- [- {- type: "setup",- label: t`Setup`,- elapsed: progress.setup,- planned: displayOperation.setupDuration- },- {- type: "labor",- label: t`Labor`,- elapsed: progress.labor,- planned: displayOperation.laborDuration- },- {- type: "machine",- label: t`Machine`,- elapsed: progress.machine,- planned: displayOperation.machineDuration- }- ] as const- )- .filter((meter) => meter.planned > 0)- .map((meter) => {- // A batch with no planned time anywhere carries a 1ms- // placeholder plan (so ratios never divide by zero). That is- // not a plan: show elapsed time alone over an empty track.- const hasPlan = meter.planned > 1;- const elapsed = formatDurationMilliseconds(meter.elapsed, {- style: "short"- });- return (- <BarProgress- key={meter.type}- label={meter.label}- value={- hasPlan- ? `${elapsed} / ${formatDurationMilliseconds(- meter.planned,- { style: "short" }- )}`- : elapsed- }- gradient- invertGradient- progress={- hasPlan ? (meter.elapsed / meter.planned) * 100 : 0- }- activeClassName={- meter.elapsed > meter.planned- ? "bg-red-500"- : "bg-emerald-500"- }- />- );- })}- <BarProgress- label={isBatched ? t`Batch quantity` : t`Quantity`}- value={`${quantityProgress.complete} / ${quantityProgress.target}`}- segments={[- {- value: quantityProgress.complete,- className: "bg-emerald-500"- },- {- value: quantityProgress.reworked,- className: "bg-yellow-500"- },- {- value: quantityProgress.scrapped,- className: "bg-red-500"- }- ]}- max={quantityProgress.target || 1}- progress={- (quantityProgress.complete / (quantityProgress.target || 1)) *- 100- }- />- </div>+ <Times+ className={cn(+ "[grid-area:status]",+ tab === "details" && "max-md:hidden"+ )}+ >+ {meters}</Times>)}</Tabs>@@ -3142,6 +2725,11 @@ export const JobOperation = ({}}><BottomSheetContent className="max-w-md mx-auto">+ <BottomSheetHeader>+ <BottomSheetTitle>+ <Trans>More actions</Trans>+ </BottomSheetTitle>+ </BottomSheetHeader><BottomSheetBody><div className="flex flex-col gap-2 pb-2">{isBatched && (diff --git a/apps/mes/app/components/JobOperation/components/Chat.tsx b/apps/mes/app/components/JobOperation/components/Chat.tsxindex d7dd25be5a..142b1d71c8 100644--- a/apps/mes/app/components/JobOperation/components/Chat.tsx+++ b/apps/mes/app/components/JobOperation/components/Chat.tsx@@ -149,7 +149,7 @@ export function OperationChat({};return (- <div className="flex flex-col h-[calc(100dvh-var(--header-height)*2)]">+ <div className="flex h-full min-h-0 flex-col"><ScrollArea className="flex-1 p-4"><Loading isLoading={isLoading}><div className="flex flex-col gap-3">diff --git a/apps/mes/app/components/JobOperation/components/Controls.tsx b/apps/mes/app/components/JobOperation/components/Controls.tsxindex 5ba3e72db5..067e43b68a 100644--- a/apps/mes/app/components/JobOperation/components/Controls.tsx+++ b/apps/mes/app/components/JobOperation/components/Controls.tsx@@ -29,6 +29,7 @@ import {LuX} from "react-icons/lu";import { useFetcher } from "react-router";+import { useMesBottomBar } from "~/components/MesBottomBar";import type { productionEventType } from "~/services/models";import { productionEventValidator } from "~/services/models";import type {@@ -54,10 +55,13 @@ export function Controls({collapsed?: boolean;onCollapsedChange?: (collapsed: boolean) => void;}) {+ const bottomBarRef = useMesBottomBar();const { t } = useLingui();return (<asidedata-collapsed={collapsed}+ ref={bottomBarRef}+ data-mes-bottom-bar=""className={cn("group/dock flex min-h-0 min-w-0 items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] backdrop-blur supports-[backdrop-filter]:bg-background/60","lg:w-[var(--controls-width)] lg:flex-col lg:items-stretch lg:overflow-y-auto lg:overflow-x-hidden lg:border-t-0 lg:border-l lg:p-2 lg:transition-[width] lg:duration-200 lg:data-[collapsed=true]:w-[76px]",@@ -95,7 +99,7 @@ export function Times({<TooltipProvider><divclassName={cn(- "min-w-0 border-t bg-background/95 px-4 py-2.5 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:px-6",+ "min-w-0 border-t bg-background/95 px-4 py-2.5 max-md:py-1.5 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:px-6",className)}>@@ -112,7 +116,7 @@ export const ButtonWithTooltip = forwardRef<return (<Tooltip><TooltipTrigger asChild>- <button ref={ref} {...props}>+ <button ref={ref} aria-label={tooltip} {...props}>{children}</button></TooltipTrigger>@@ -165,6 +169,7 @@ export function WorkTypeToggle({onChange: (type: string) => void;className?: string;}) {+ const { t } = useLingui();const count = useMemo(() => {let count = 0;if (operation.setupDuration > 0) {@@ -192,6 +197,8 @@ export function WorkTypeToggle({className={cn("grid w-full lg:group-data-[collapsed=true]/dock:grid-cols-1",count <= 1 && "grid-cols-1",+ // Phones: one type needs no picker; the caption names it.+ count <= 1 && "max-md:hidden",count === 2 && "grid-cols-2 lg:py-2",count === 3 && "grid-cols-3 lg:py-2",className@@ -199,49 +206,49 @@ export function WorkTypeToggle({>{operation.setupDuration > 0 && (<ToggleGroupItem- className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full max-md:h-10 max-md:flex-row max-md:gap-1.5"value="Setup"size="lg"- aria-label="Toggle setup"+ aria-label={t`Toggle setup`}>- <LuTimer className="size-6 pt-1" />- <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">+ <LuTimer className="size-6 pt-1 max-md:size-4 max-md:pt-0" />+ <span className="text-xxs max-lg:text-xs max-md:text-sm lg:group-data-[collapsed=true]/dock:sr-only"><Trans>Setup</Trans></span>{active.setup && (- <span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />+ <span className="absolute -top-1 -right-1 h-3 w-3 max-lg:size-3.5 max-lg:ring-2 max-lg:ring-background max-md:top-1.5 max-md:right-1.5 max-md:size-2 max-md:ring-0 bg-emerald-500 rounded-full" />)}</ToggleGroupItem>)}{operation.laborDuration > 0 && (<ToggleGroupItem- className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full max-md:h-10 max-md:flex-row max-md:gap-1.5"value="Labor"size="lg"- aria-label="Toggle labor"+ aria-label={t`Toggle labor`}>- <LuHardHat className="size-6 pt-1" />- <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">+ <LuHardHat className="size-6 pt-1 max-md:size-4 max-md:pt-0" />+ <span className="text-xxs max-lg:text-xs max-md:text-sm lg:group-data-[collapsed=true]/dock:sr-only"><Trans>Labor</Trans></span>{active.labor && (- <span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />+ <span className="absolute -top-1 -right-1 h-3 w-3 max-lg:size-3.5 max-lg:ring-2 max-lg:ring-background max-md:top-1.5 max-md:right-1.5 max-md:size-2 max-md:ring-0 bg-emerald-500 rounded-full" />)}</ToggleGroupItem>)}{operation.machineDuration > 0 && (<ToggleGroupItem- className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full"+ className="flex flex-col items-center relative justify-center text-center h-12 lg:h-14 w-full max-md:h-10 max-md:flex-row max-md:gap-1.5"value="Machine"size="lg"- aria-label="Toggle machine"+ aria-label={t`Toggle machine`}>- <LuHammer className="size-6 pt-1" />- <span className="text-xxs lg:group-data-[collapsed=true]/dock:sr-only">+ <LuHammer className="size-6 pt-1 max-md:size-4 max-md:pt-0" />+ <span className="text-xxs max-lg:text-xs max-md:text-sm lg:group-data-[collapsed=true]/dock:sr-only"><Trans>Machine</Trans></span>{active.machine && (- <span className="absolute -top-1 -right-1 h-3 w-3 bg-emerald-500 rounded-full" />+ <span className="absolute -top-1 -right-1 h-3 w-3 max-lg:size-3.5 max-lg:ring-2 max-lg:ring-background max-md:top-1.5 max-md:right-1.5 max-md:size-2 max-md:ring-0 bg-emerald-500 rounded-full" />)}</ToggleGroupItem>)}diff --git a/apps/mes/app/components/JobOperation/components/Materials.tsx b/apps/mes/app/components/JobOperation/components/Materials.tsxnew file mode 100644index 0000000000..8a35658d3e--- /dev/null+++ b/apps/mes/app/components/JobOperation/components/Materials.tsx@@ -0,0 +1,557 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Badge,+ Button,+ cn,+ HStack,+ IconButton,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr,+ useViewport,+ VStack+} from "@carbon/react";+import { getItemReadableId } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { Fragment } from "react";+import {+ LuArrowLeft,+ LuGitBranchPlus,+ LuGitPullRequest,+ LuPackageCheck,+ LuQrCode,+ LuTriangleAlert+} from "react-icons/lu";+import { MethodIcon, TrackingTypeIcon } from "~/components/Icons";+import type { JobMaterialPickedItem } from "~/services/inventory.service";+import type { BatchMaterialTotal } from "~/services/operations.service";+import type { JobMaterial } from "~/services/types";+import { useItems } from "~/stores";++type MaterialRow = {+ material: JobMaterial;+ isKitChild: boolean;+ /** Kit children take their parent's. */+ isRelatedToOperation: boolean;+ /** Untracked stock issues directly, tracked stock by scan; Make to Order has neither. */+ issue: "direct" | "scan" | null;+ /** The tracked issue still owed by this operation. */+ isPrimaryIssue: boolean;+ /** Batched operations, parent rows only. */+ batchTotal?: BatchMaterialTotal;+};++type MaterialGroup = { parent: MaterialRow; kitChildren: MaterialRow[] };++function toMaterialGroups({+ materials,+ operationId,+ batchMaterialTotals+}: {+ materials: JobMaterial[];+ operationId: string;+ batchMaterialTotals?: Record<string, BatchMaterialTotal> | null;+}): MaterialGroup[] {+ const baseMaterials = materials.filter((m) => !m.isKitComponent);+ const kitChildrenByParentId = new Map<string, JobMaterial[]>();+ for (const m of materials) {+ if (!m.isKitComponent || !m.kitParentId) continue;+ kitChildrenByParentId.set(m.kitParentId, [+ ...(kitChildrenByParentId.get(m.kitParentId) ?? []),+ m+ ]);+ }++ const issueOf = (material: JobMaterial): MaterialRow["issue"] => {+ if (material.requiresBatchTracking || material.requiresSerialTracking) {+ return "scan";+ }+ return material.methodType !== "Make to Order" &&+ material.requiresBatchTracking === false &&+ material.requiresSerialTracking === false+ ? "direct"+ : null;+ };++ return baseMaterials.map((material) => {+ const isRelatedToOperation = material.jobOperationId === operationId;+ const someRelatedMaterialIsIssued = baseMaterials.some(+ (m) =>+ m.itemReadableIdWithoutRevision ===+ material.itemReadableIdWithoutRevision &&+ ((m.quantityIssued ?? 0) > 0 || (material.quantityIssued ?? 0) > 0)+ );+ const issue = issueOf(material);+ return {+ parent: {+ material,+ isKitChild: false,+ isRelatedToOperation,+ issue,+ isPrimaryIssue:+ issue === "scan" &&+ isRelatedToOperation &&+ !someRelatedMaterialIsIssued,+ batchTotal: material.itemId+ ? batchMaterialTotals?.[material.itemId]+ : undefined+ },+ kitChildren: (+ (material.id && kitChildrenByParentId.get(material.id)) ||+ []+ ).map((child) => ({+ material: child,+ isKitChild: true,+ isRelatedToOperation,+ issue: issueOf(child),+ isPrimaryIssue: false+ }))+ };+ });+}++function isTracked(material: JobMaterial) {+ return material.requiresBatchTracking || material.requiresSerialTracking;+}++function estimatedQuantity(material: JobMaterial, parentIsSerial: boolean) {+ return parentIsSerial && isTracked(material)+ ? `${material.quantity ?? material.estimatedQuantity}/${+ material.estimatedQuantity ?? material.quantity+ }`+ : (material.estimatedQuantity ?? material.quantity);+}++function actualQuantity(material: JobMaterial, parentIsSerial: boolean) {+ if (+ material.methodType === "Make to Order" &&+ material.requiresBatchTracking === false &&+ material.requiresSerialTracking === false+ ) {+ return <MethodIcon type="Make to Order" isKit={material.kit ?? false} />;+ }+ return parentIsSerial && isTracked(material)+ ? `${material.quantityIssued}/${+ material.quantity ?? material.estimatedQuantity+ }`+ : material.quantityIssued;+}++/**+ * Additive overlay badge showing how much of a material has been picked (staged at+ * lineside). Picking is optional, so this renders nothing unless something has actually+ * been picked — orange while partial, green once the full requirement is staged.+ */+function PickedBadge({+ quantityPicked,+ quantityToPick+}: {+ quantityPicked?: number | null;+ quantityToPick?: number | null;+}) {+ const picked = Number(quantityPicked ?? 0);+ if (picked <= 0) return null;+ const toPick = Number(quantityToPick ?? 0);+ const isFullyPicked = toPick > 0 && picked >= toPick;+ return (+ <Badge+ variant={isFullyPicked ? "green" : "orange"}+ className="gap-1 shrink-0"+ title="Quantity picked to lineside"+ >+ <LuPackageCheck className="size-3" />+ {isFullyPicked ? <Trans>Picked</Trans> : `${picked}/${toPick}`}+ </Badge>+ );+}++function PickedBreakdown({+ materialItemId,+ pickedByItem+}: {+ materialItemId: string | null | undefined;+ pickedByItem?: JobMaterialPickedItem[] | null;+}) {+ const picks = pickedByItem ?? [];+ if (!picks.some((p) => p.itemId !== materialItemId)) return null;+ return (+ <div className="flex flex-wrap items-center gap-1 text-xs text-blue-700 dark:text-blue-300">+ <span>+ <Trans>Picked as</Trans>+ </span>+ {picks.map((pick) => {+ const isFullyPicked =+ pick.quantityToPick > 0 && pick.quantityPicked >= pick.quantityToPick;+ return (+ <Badge+ key={pick.itemId}+ variant={+ isFullyPicked+ ? "green"+ : pick.quantityPicked > 0+ ? "orange"+ : "secondary"+ }+ className="gap-1 shrink-0"+ >+ {isFullyPicked+ ? pick.quantityPicked+ : `${pick.quantityPicked}/${pick.quantityToPick}`}+ {" × "}+ {pick.itemReadableId}+ </Badge>+ );+ })}+ </div>+ );+}++function TrackingBadge({ material }: { material: JobMaterial }) {+ const type = material.requiresBatchTracking+ ? "Batch"+ : material.requiresSerialTracking+ ? "Serial"+ : null;+ if (!type) return null;+ return (+ <Badge variant="secondary">+ <TrackingTypeIcon type={type} className="shrink-0" />+ </Badge>+ );+}++function ExpiredConsumedBadge({ material }: { material: JobMaterial }) {+ if (!material.hasExpiredConsumed) return null;+ return (+ <Badge+ variant="red"+ className="gap-1 shrink-0"+ title="A consumed batch or serial is now past its expiry date."+ >+ <LuTriangleAlert className="size-3" />+ <Trans>Consumed expired</Trans>+ </Badge>+ );+}++type OperationMaterialsProps = {+ materials: JobMaterial[];+ operationId: string;+ parentIsSerial: boolean;+ /** Only for batched operations. */+ batchMaterialTotals?: Record<string, BatchMaterialTotal> | null;+ onIssue: (material: JobMaterial) => void;+};++/** The operation's materials: a table from md, a list on phones. */+export function OperationMaterials(props: OperationMaterialsProps) {+ const { isPhone } = useViewport();+ const groups = toMaterialGroups(props);+ return isPhone ? (+ <MaterialsList {...props} groups={groups} />+ ) : (+ <MaterialsTable {...props} groups={groups} />+ );+}++type LayoutProps = OperationMaterialsProps & { groups: MaterialGroup[] };++function MaterialsTable({ groups, parentIsSerial, onIssue }: LayoutProps) {+ const { t } = useLingui();+ const [items] = useItems();++ const issueButton = (row: MaterialRow) =>+ row.issue === "direct" ? (+ <IconButton+ aria-label={t`Issue Material`}+ variant="ghost"+ icon={<LuGitBranchPlus />}+ className="h-8 w-8"+ onClick={() => onIssue(row.material)}+ />+ ) : row.issue === "scan" && row.isKitChild ? (+ <IconButton+ aria-label={t`Issue Material`}+ variant="secondary"+ icon={<LuQrCode />}+ className="h-8 w-8"+ onClick={() => onIssue(row.material)}+ />+ ) : row.issue === "scan" ? (+ <Button+ className="flex-shrink-0"+ size="lg"+ variant={row.isPrimaryIssue ? "primary" : "secondary"}+ leftIcon={<LuQrCode />}+ onClick={() => onIssue(row.material)}+ >+ <Trans>Issue</Trans>+ </Button>+ ) : null;++ const methodBadge = (material: JobMaterial) => (+ <Badge variant="secondary">+ <MethodIcon+ type={material.methodType ?? ""}+ isKit={material.kit ?? false}+ className="mr-2"+ />+ {material.methodType === "Make to Order" && material.kit+ ? t`Kit`+ : material.methodType}+ </Badge>+ );++ const fadedIfUnrelated = (row: MaterialRow) =>+ !row.isRelatedToOperation && "opacity-50 hover:opacity-100";++ return (+ <div className="w-full overflow-hidden rounded-lg border bg-card">+ <Table className="w-full text-base">+ <Thead className="bg-muted/40">+ <Tr>+ <Th className="text-sm">+ <Trans>Part</Trans>+ </Th>+ <Th className="text-sm lg:table-cell hidden">+ <Trans>Source</Trans>+ </Th>+ <Th className="text-sm">+ <Trans>Estimated</Trans>+ </Th>+ <Th className="text-sm">+ <Trans>Actual</Trans>+ </Th>+ <Th className="text-right" />+ </Tr>+ </Thead>+ <Tbody className="[&>tr]:border-b [&>tr:last-child]:border-0">+ {groups.length === 0 ? (+ <Tr>+ <Td+ colSpan={24}+ className="py-8 text-muted-foreground text-center"+ >+ <Trans>No materials</Trans>+ </Td>+ </Tr>+ ) : (+ groups.map(({ parent, kitChildren }) => {+ const { material, batchTotal } = parent;+ return (+ <Fragment key={`material-${material.id}`}>+ <Tr className={cn("[&>td]:py-3", fadedIfUnrelated(parent))}>+ <Td className="max-w-[20vw]">+ <HStack spacing={2} className="justify-between min-w-0">+ <VStack spacing={0} className="min-w-0">+ <span className="font-semibold text-base truncate max-w-full">+ {getItemReadableId(items, material.itemId ?? "")}+ </span>+ <span className="text-muted-foreground text-sm truncate max-w-full">+ {material.description}+ </span>+ <PickedBreakdown+ materialItemId={material.itemId}+ pickedByItem={material.pickedByItem}+ />+ </VStack>+ <TrackingBadge material={material} />+ <ExpiredConsumedBadge material={material} />+ <PickedBadge+ quantityPicked={material.quantityPicked}+ quantityToPick={material.quantityToPick}+ />+ </HStack>+ </Td>+ <Td className="hidden lg:table-cell">+ <div className="flex flex-row items-center gap-1">+ {methodBadge(material)}+ <LuArrowLeft+ className={cn(+ material.methodType === "Make to Order"+ ? "rotate-180"+ : ""+ )}+ />+ <Badge variant="secondary">+ <LuGitPullRequest className="size-3 mr-1" />+ {material.storageUnitName ??+ (material.methodType === "Make to Order"+ ? t`WIP`+ : t`Default Storage Unit`)}+ </Badge>+ </div>+ </Td>+ <Td>+ {estimatedQuantity(material, parentIsSerial)}+ {batchTotal && (+ <div className="text-xs text-muted-foreground whitespace-nowrap">+ <Trans>Batch</Trans>: {batchTotal.required}+ </div>+ )}+ </Td>+ <Td>+ {actualQuantity(material, parentIsSerial)}+ {batchTotal && (+ <div className="text-xs text-muted-foreground whitespace-nowrap">+ <Trans>Batch</Trans>: {batchTotal.issued}+ </div>+ )}+ </Td>+ <Td className="text-right">{issueButton(parent)}</Td>+ </Tr>++ {kitChildren.map((child, index) => (+ <Tr+ key={`kittedChild-${child.material.id}`}+ className={cn(+ index === kitChildren.length - 1+ ? "border-b"+ : index === 0+ ? "border-t"+ : "",+ fadedIfUnrelated(child)+ )}+ >+ <Td className="pl-10 max-w-[20vw]">+ <HStack spacing={2} className="justify-between min-w-0">+ <VStack spacing={0} className="min-w-0">+ <span className="font-semibold truncate max-w-full">+ {getItemReadableId(+ items,+ child.material.itemId ?? ""+ )}+ </span>+ <span className="text-muted-foreground text-xs truncate max-w-full">+ {child.material.description}+ </span>+ <PickedBreakdown+ materialItemId={child.material.itemId}+ pickedByItem={child.material.pickedByItem}+ />+ </VStack>+ <TrackingBadge material={child.material} />+ <PickedBadge+ quantityPicked={child.material.quantityPicked}+ quantityToPick={child.material.quantityToPick}+ />+ </HStack>+ </Td>+ <Td className="lg:table-cell hidden">+ {methodBadge(child.material)}+ </Td>+ <Td>+ {estimatedQuantity(child.material, parentIsSerial)}+ </Td>+ <Td>{actualQuantity(child.material, parentIsSerial)}</Td>+ <Td className="text-right">{issueButton(child)}</Td>+ </Tr>+ ))}+ </Fragment>+ );+ })+ )}+ </Tbody>+ </Table>+ </div>+ );+}++function MaterialsList({ groups, parentIsSerial, onIssue }: LayoutProps) {+ const { t } = useLingui();+ const [items] = useItems();++ const renderRow = (row: MaterialRow) => {+ const { material, batchTotal } = row;+ return (+ <li+ key={`material-row-${material.id}`}+ className={cn(+ "flex items-center gap-3 px-4 py-3",+ row.isKitChild && "pl-8",+ !row.isRelatedToOperation && "opacity-50"+ )}+ >+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex items-baseline justify-between gap-2">+ <span className="truncate font-semibold">+ {getItemReadableId(items, material.itemId ?? "")}+ </span>+ <span className="flex shrink-0 items-center gap-1 text-sm tabular-nums text-foreground font-medium">+ {actualQuantity(material, parentIsSerial)}+ <span aria-hidden>/</span>+ {estimatedQuantity(material, parentIsSerial)}+ </span>+ </div>+ {material.description ? (+ <span className="truncate text-sm text-muted-foreground">+ {material.description}+ </span>+ ) : null}+ <div className="flex flex-wrap items-center gap-1">+ <TrackingBadge material={material} />+ <ExpiredConsumedBadge material={material} />+ <PickedBadge+ quantityPicked={material.quantityPicked}+ quantityToPick={material.quantityToPick}+ />+ </div>+ <PickedBreakdown+ materialItemId={material.itemId}+ pickedByItem={material.pickedByItem}+ />+ {batchTotal ? (+ <span className="text-xs text-muted-foreground">+ <Trans>Batch</Trans>: {batchTotal.issued} / {batchTotal.required}+ </span>+ ) : null}+ </div>+ {/* A fixed slot, so the quantities line up. */}+ <div className="flex min-w-28 shrink-0 justify-end">+ {row.issue === "scan" && row.isKitChild ? (+ <IconButton+ aria-label={t`Issue Material`}+ variant="secondary"+ size="lg"+ icon={<LuQrCode />}+ onClick={() => onIssue(material)}+ />+ ) : row.issue ? (+ <Button+ size="lg"+ className="shrink-0"+ variant={row.isPrimaryIssue ? "primary" : "secondary"}+ leftIcon={+ row.issue === "scan" ? <LuQrCode /> : <LuGitBranchPlus />+ }+ onClick={() => onIssue(material)}+ >+ <Trans>Issue</Trans>+ </Button>+ ) : null}+ </div>+ </li>+ );+ };++ return (+ <ul className="-mx-4 w-[calc(100%+2rem)] divide-y divide-border border-y bg-card">+ {groups.length === 0 ? (+ <li className="py-8 text-center text-muted-foreground">+ <Trans>No materials</Trans>+ </li>+ ) : (+ groups.flatMap(({ parent, kitChildren }) => [+ renderRow(parent),+ ...kitChildren.map(renderRow)+ ])+ )}+ </ul>+ );+}diff --git a/apps/mes/app/components/JobOperation/components/Parameter.tsx b/apps/mes/app/components/JobOperation/components/Parameter.tsxindex 30a3ab0840..27d270a3b4 100644--- a/apps/mes/app/components/JobOperation/components/Parameter.tsx+++ b/apps/mes/app/components/JobOperation/components/Parameter.tsx@@ -19,9 +19,16 @@ export function ParametersListItem({if (!operationId) return null;return (- <div className={cn("border-b p-6 hover:bg-muted/30", className)}>- <div className="flex flex-1 justify-between items-center w-full">- <HStack spacing={4} className="w-2/3">+ <div+ className={cn(+ "border-b p-6 hover:bg-muted/30 max-md:px-4 max-md:py-3",+ className+ )}+ >+ {/* Phones: the key takes its own width, and a value that does not fit+ beside it drops below as a whole, so an ID stays on 1 line. */}+ <div className="flex flex-1 justify-between items-center w-full max-md:flex-wrap max-md:gap-x-4 max-md:gap-y-1">+ <HStack spacing={4} className="w-2/3 max-md:w-auto max-md:min-w-0"><HStack spacing={4} className="flex-1"><div className="bg-muted border rounded-full flex items-center justify-center p-2"><LuActivity />@@ -29,7 +36,7 @@ export function ParametersListItem({<p className="text-foreground text-sm font-medium">{key}</p></HStack></HStack>- <div className="flex items-center justify-end gap-2">+ <div className="flex items-center justify-end gap-2 max-md:ml-auto"><pclassName={cn("text-foreground",diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsxindex b9cbe87894..53c798f334 100644--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx@@ -38,6 +38,7 @@ import type {ProductionEvent,ProductionQuantity} from "~/services/types";+import { OriginInput } from "~/utils/origin";import { path } from "~/utils/path";import ScrapReason from "./ScrapReason";@@ -78,6 +79,7 @@ export function QuantityModal({onClose: () => void;}) {const { t } = useLingui();+ // The action's redirect keeps the page the operation was opened from.const fetcher = useAction<ProductionQuantity>({onSettled: () => {if (submitted.current) {@@ -204,6 +206,7 @@ export function QuantityModal({<Hidden name="setupProductionEventId" /><Hidden name="laborProductionEventId" /><Hidden name="machineProductionEventId" />+ <OriginInput /><VStack spacing={2}>{hasUnissuedTrackedMaterials && type === "complete" && (<Alert variant="destructive">diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsxindex 02ac154234..cd16ae4fd5 100644--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx@@ -90,7 +90,21 @@ export function useOperation({);const [activeTab, setActiveTab] = useState("details");- const [eventType, setEventType] = useState(() => {+ // Opens on the timer that runs, so Pause shows for it. A Setup or Labor+ // timer counts only when it is this user's; Machine counts for anyone+ // (the same rule as `activeEvents` below). Else: Setup, Machine, Labor.+ const [eventType, setEventType] = useState<string>(() => {+ const isRunning = (type: string) =>+ events.some(+ (e) =>+ e.type === type &&+ e.endTime === null &&+ (type === "Machine" || e.employeeId === user.id)+ );+ const running = (["Setup", "Machine", "Labor"] as const).find(isRunning);+ if (running) {+ return running;+ }if (operation.setupDuration > 0) {return "Setup";}diff --git a/apps/mes/app/components/Kanban/Kanban.tsx b/apps/mes/app/components/Kanban/Kanban.tsxindex 80bdfbd643..c8b70cca6e 100644--- a/apps/mes/app/components/Kanban/Kanban.tsx+++ b/apps/mes/app/components/Kanban/Kanban.tsx@@ -64,6 +64,17 @@ const Kanban = ({return columns.map((col) => col.id);});+ // A filter change brings in columns the order has never seen (clearing a+ // work-center filter); add them at the end, or they never render.+ useEffect(() => {+ setColumnOrder((order) => {+ const missing = columns+ .filter((col) => !order.includes(col.id))+ .map((col) => col.id);+ return missing.length ? [...order, ...missing] : order;+ });+ }, [columns]);+// Update localStorage when column order changesuseEffect(() => {localStorage.setItem(COLUMN_ORDER_KEY, JSON.stringify(columnOrder));diff --git a/apps/mes/app/components/Kanban/components/ColumnCard.tsx b/apps/mes/app/components/Kanban/components/ColumnCard.tsxindex 3d827a4418..ebff2906c4 100644--- a/apps/mes/app/components/Kanban/components/ColumnCard.tsx+++ b/apps/mes/app/components/Kanban/components/ColumnCard.tsx@@ -10,7 +10,8 @@ import {ScrollBar,Tooltip,TooltipContent,- TooltipTrigger+ TooltipTrigger,+ useViewport} from "@carbon/react";import { formatDurationMilliseconds } from "@carbon/utils";import { useDndContext } from "@dnd-kit/core";@@ -82,7 +83,7 @@ export function ColumnCard({};const variants = cva(- "w-[350px] max-w-full flex flex-col flex-shrink-0 snap-center rounded-none bg-card/30 border-0 border-r",+ "group/column w-[350px] max-md:w-[300px] max-md:only:w-full max-w-full flex flex-col flex-shrink-0 snap-center rounded-none bg-card/30 border-0 border-r",{variants: {dragging: {@@ -104,12 +105,15 @@ export function ColumnCard({})} flex flex-col p-[1px] pt-0`,currentFilters.length > 0? `h-[calc(100dvh-var(--header-height)*2-var(--filters-height))]`- : `h-[calc(100dvh-var(--header-height)*2)]`+ : `h-[calc(100dvh-var(--header-height)*2)]`,+ // Phones: the column fills the board, so its header stays put while+ // its cards scroll under it, as on desktop.+ "max-md:h-full")}><divclassName={cn(- "p-4 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 z-1 border-b",+ "p-4 max-md:py-2 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 z-1 border-b",column.isBlocked && column.blockingDispatchId? "bg-destructive text-destructive-foreground": "bg-card"@@ -159,11 +163,11 @@ export function ColumnCard({variant={"ghost"}{...attributes}{...listeners}- className="cursor-grab relative"+ className="cursor-grab relative max-md:hidden"/></div><ScrollArea className="flex-grow">- <div className="flex flex-col gap-2 p-2">+ <div className="flex flex-col gap-2 p-2 max-md:group-only/column:px-4 max-md:group-only/column:gap-3"><SortableContext items={itemsIds}>{items.map((item) => (<ItemCard@@ -183,6 +187,7 @@ export function ColumnCard({export function BoardContainer({ children }: { children: React.ReactNode }) {const dndContext = useDndContext();+ const { isPhone } = useViewport();const variations = cva("relative px-0 flex lg:justify-center", {variants: {@@ -193,6 +198,24 @@ export function BoardContainer({ children }: { children: React.ReactNode }) {}});+ // Radix's ScrollArea viewport sizes its content to fit, so a lone column+ // can't stretch to the screen; phones get a plain snap scroller instead.+ if (isPhone) {+ return (+ <div+ className={cn(+ "flex h-full w-full overflow-x-auto scroll-px-4 scrollbar-hide",+ dndContext.active ? "snap-none" : "snap-x snap-mandatory"+ )}+ >+ {/* More than 1 column: keep the board off the screen edges. */}+ <div className="flex h-full w-full gap-0 items-start flex-row justify-start p-0 [&:has(>:nth-child(2))]:px-4">+ {children}+ </div>+ </div>+ );+ }+return (<ScrollAreaclassName={variations({@@ -202,7 +225,11 @@ export function BoardContainer({ children }: { children: React.ReactNode }) {<div className="flex gap-0 items-start flex-row justify-start p-0">{children}</div>- <ScrollBar orientation="horizontal" forceMount className="h-5" />+ <ScrollBar+ orientation="horizontal"+ forceMount+ className="h-5 max-md:hidden"+ /></ScrollArea>);}diff --git a/apps/mes/app/components/Kanban/components/ItemCard.tsx b/apps/mes/app/components/Kanban/components/ItemCard.tsxindex 1051b20342..460f63b057 100644--- a/apps/mes/app/components/Kanban/components/ItemCard.tsx+++ b/apps/mes/app/components/Kanban/components/ItemCard.tsx@@ -10,17 +10,13 @@ import {CardFooter,CardHeader,cn,- Heading,HStack,Tooltip,TooltipContent,TooltipTrigger,useRouteData} from "@carbon/react";-import {- convertDateStringToIsoString,- formatDurationMilliseconds-} from "@carbon/utils";+import { convertDateStringToIsoString } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { cva } from "class-variance-authority";import {@@ -34,12 +30,18 @@ import {LuTriangleAlert} from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";-import { Link } from "react-router";+import { Link, useLocation } from "react-router";import { DateTime, OperationStatusIcon } from "~/components";import Avatar from "~/components/Avatar";-import EmployeeAvatar from "~/components/EmployeeAvatar";import { DeadlineIcon } from "~/components/Icons";+import {+ AssigneeTags,+ OperationDuration,+ PhoneThumbnail,+ QuantityStat+} from "~/components/OperationCardParts";import { useDateFormatter } from "~/hooks";+import { withOrigin } from "~/utils/origin";import { getPrivateUrl, path } from "~/utils/path";import type { DisplaySettings, Item } from "../types";@@ -110,24 +112,31 @@ export function ItemCard({? Array.from(progressByItemId[item.id].employees!): undefined;+ const location = useLocation();const isBatch = (item.batchSize ?? 0) > 1 && !!item.batchId;return (<Link- to={isBatch ? path.to.batch(item.batchId!) : path.to.operation(item.id)}+ to={withOrigin(+ isBatch ? path.to.batch(item.batchId!) : path.to.operation(item.id),+ location+ )}><CardclassName={cn(- "max-w-[330px]",+ "max-w-[330px] max-md:max-w-none",item.hasConflict && "border-red-500 border-2",cardVariants({status: status}))}>- <CardHeader className="flex flex-col justify-between relative gap-2">+ <CardHeader className="flex flex-col justify-between relative gap-2 max-md:pb-1"><div className="flex w-full max-w-full justify-between items-start gap-2">- <div className="flex flex-col space-y-0 min-w-0">+ {showThumbnail && item.thumbnailPath && (+ <PhoneThumbnail path={item.thumbnailPath} alt={item.title} />+ )}+ <div className="flex flex-col space-y-0 min-w-0 max-md:flex-1">{item.itemReadableId && (<span className="text-xs text-muted-foreground line-clamp-1">{isBatch ? item.batchReadableId : item.itemReadableId}@@ -150,74 +159,76 @@ export function ItemCard({</TooltipContent></Tooltip>)}- <Heading size="h4" className="text-foreground">+ <QuantityStat className="text-foreground">{isBatch? `×${item.batchSize} · ${item.targetQuantity}`: item.targetQuantity}- </Heading>+ </QuantityStat></HStack></div>- {showProgress &&- Number.isFinite(progress) &&- Number.isFinite(item?.duration) &&- Number(progress) >= 0 &&- Number(item?.duration) > 0 && (- <HStack className="mt-2">- <BarProgress- gradient- invertGradient- activeClassName={- progress > (item.duration ?? 0)- ? "bg-red-500"- : status === "Paused"- ? "bg-yellow-500"- : "bg-emerald-500"- }- progress={Math.min(- progress && item.duration- ? (progress / item.duration) * 100- : 0,- 100- )}- />- <LuTimer className="text-muted-foreground w-4 h-4" />- </HStack>- )}- {showProgress &&- Number.isFinite(item.quantity) &&- Number(item.quantity) > 0 && (- <HStack className="mt-2">- <BarProgress- segments={[- {- value: item.quantityCompleted ?? 0,- className: "bg-emerald-500"- },- {- value: item.quantityReworked ?? 0,- className: "bg-yellow-500"- },- {- value: item.quantityScrapped ?? 0,- className: "bg-red-500"+ <div className="contents max-md:grid max-md:grid-cols-2 max-md:gap-3 max-md:[&>*:only-child]:col-span-2">+ {showProgress &&+ Number.isFinite(progress) &&+ Number.isFinite(item?.duration) &&+ Number(progress) >= 0 &&+ Number(item?.duration) > 0 && (+ <HStack className="mt-2">+ <BarProgress+ gradient+ invertGradient+ activeClassName={+ progress > (item.duration ?? 0)+ ? "bg-red-500"+ : status === "Paused"+ ? "bg-yellow-500"+ : "bg-emerald-500"}- ]}- max={item.targetQuantity || 1}- progress={- item.quantityCompleted && item.targetQuantity- ? (item.quantityCompleted / item.targetQuantity) * 100- : 0- }- />- <LuCircleCheck className="text-muted-foreground w-4 h-4" />- </HStack>- )}+ progress={Math.min(+ progress && item.duration+ ? (progress / item.duration) * 100+ : 0,+ 100+ )}+ />+ <LuTimer className="text-muted-foreground w-4 h-4" />+ </HStack>+ )}+ {showProgress &&+ Number.isFinite(item.quantity) &&+ Number(item.quantity) > 0 && (+ <HStack className="mt-2">+ <BarProgress+ segments={[+ {+ value: item.quantityCompleted ?? 0,+ className: "bg-emerald-500"+ },+ {+ value: item.quantityReworked ?? 0,+ className: "bg-yellow-500"+ },+ {+ value: item.quantityScrapped ?? 0,+ className: "bg-red-500"+ }+ ]}+ max={item.targetQuantity || 1}+ progress={+ item.quantityCompleted && item.targetQuantity+ ? (item.quantityCompleted / item.targetQuantity) * 100+ : 0+ }+ />+ <LuCircleCheck className="text-muted-foreground w-4 h-4" />+ </HStack>+ )}+ </div></CardHeader>- <CardContent className="gap-2 text-left whitespace-pre-wrap text-sm">+ <CardContent className="gap-2 text-left whitespace-pre-wrap text-sm max-md:border-t-0 max-md:pt-1 max-md:grid max-md:grid-cols-2 max-md:gap-x-3 max-md:gap-y-1.5 max-md:[&>*]:min-w-0">{showThumbnail && item.thumbnailPath && (- <div className="flex justify-center">+ <div className="flex justify-center max-md:hidden"><imgsrc={getPrivateUrl(item.thumbnailPath)}alt={item.title}@@ -225,7 +236,7 @@ export function ItemCard({/></div>)}- <HStack className="justify-start space-x-2">+ <HStack className="justify-start space-x-2 max-md:col-span-2"><LuCirclePlay className="text-muted-foreground" /><span className="text-sm line-clamp-1">{isBatch && item.batchJobReadableIds?.length@@ -236,7 +247,7 @@ export function ItemCard({</HStack>{showDescription && item.description && (- <HStack className="justify-start space-x-2">+ <HStack className="justify-start space-x-2 max-md:col-span-2"><LuClipboardCheck className="text-muted-foreground" /><span className="text-sm line-clamp-1">{item.description}</span></HStack>@@ -248,12 +259,7 @@ export function ItemCard({</HStack>)}{showDuration && typeof item.duration === "number" && (- <HStack className="justify-start space-x-2">- <LuTimer className="text-muted-foreground" />- <span className="text-sm">- {formatDurationMilliseconds(item.duration)}- </span>- </HStack>+ <OperationDuration value={item.duration} />)}{showDueDate && item.deadlineType && (<HStack className="justify-start space-x-2">@@ -301,7 +307,7 @@ export function ItemCard({)}{Array.isArray(employeeIds) && employeeIds.length > 0 && (- <HStack className="justify-start space-x-2">+ <HStack className="justify-start space-x-2 max-md:order-1"><Avatar size="xs" name="Active Employee" /><span className="text-sm"><Trans>{employeeIds.length} Active</Trans>@@ -310,38 +316,32 @@ export function ItemCard({)}{showCustomer && item.customerId && (- <HStack className="justify-start space-x-2">- <LuSquareUser className="text-muted-foreground" />- <HStack className="truncate no-underline hover:no-underline">+ <HStack className="justify-start space-x-2 min-w-0">+ <LuSquareUser className="text-muted-foreground shrink-0" />+ <HStack className="min-w-0 truncate no-underline hover:no-underline"><Avatar size="xs" name={customer?.name ?? ""} />- <span>{customer?.name}</span>+ <span className="truncate">{customer?.name}</span></HStack></HStack>)}{Number(item.quantityScrapped) > 0 && (- <HStack className="justify-start space-x-2 text-red-500">+ <HStack className="justify-start space-x-2 text-red-500 max-md:order-1"><LuTrash className="w-4 h-4" /><span className="text-sm"><Trans>{item.quantityScrapped} Scrapped</Trans></span></HStack>)}+ {(item.assignee || (item.tags && item.tags.length > 0)) && (+ <div className="hidden flex-wrap items-center gap-1 text-xs max-md:order-2 max-md:col-span-2 max-md:flex">+ <AssigneeTags assignee={item.assignee} tags={item.tags} />+ </div>+ )}</CardContent>{(item.assignee || (item.tags && item.tags.length > 0)) && (- <CardFooter className="items-center justify-start space-2 text-xs flex-wrap">- {item.assignee && (- <EmployeeAvatar size="xs" employeeId={item.assignee} />- )}- {item.tags?.map((tag) => (- <Badge- key={tag}- variant="secondary"- className="border dark:border-none dark:shadow-button-base"- >- {tag}- </Badge>- ))}+ <CardFooter className="items-center justify-start space-2 text-xs flex-wrap max-md:hidden">+ <AssigneeTags assignee={item.assignee} tags={item.tags} /></CardFooter>)}</Card>diff --git a/apps/mes/app/components/MesAppBar.tsx b/apps/mes/app/components/MesAppBar.tsxnew file mode 100644index 0000000000..a08c28027d--- /dev/null+++ b/apps/mes/app/components/MesAppBar.tsx@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Button,+ cn,+ Heading,+ SidebarTrigger,+ useSidebar,+ useViewport+} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuChevronDown, LuChevronLeft } from "react-icons/lu";+import { Link } from "react-router";++type MesAppBarProps = {+ kind: "root" | "pushed";+ title: ReactNode;+ /** Pushed pages: the parent page name, under the title. */+ subtitle?: ReactNode;+ /** Pushed pages: where Back goes. */+ back?: { to: string };+ /** Phones: at most 2 icon actions, each 44×44. */+ actions?: ReactNode;+ /** The default md+ header's title when it differs from the phone one. */+ desktopTitle?: ReactNode;+ /**+ * The md+ header. Omit it for today's queue header (trigger + h4 title).+ * Pass `null` when the page renders its own md+ header, or none.+ */+ desktop?: ReactNode;+ /** Extra classes for the default md+ header. */+ desktopClassName?: string;+};++/**+ * The MES page header. Below md: one 52px bar with Back (pushed pages), a+ * 17px title and up to 2 actions; on root pages the title ▾ opens the queue+ * list, like the ERP's section switcher. From md: the header each page had+ * before.+ */+export function MesAppBar({+ kind,+ title,+ subtitle,+ back,+ actions,+ desktopTitle,+ desktop,+ desktopClassName+}: MesAppBarProps) {+ const { t } = useLingui();+ const { isPhone } = useViewport();+ const { openMobile, setOpenMobile } = useSidebar();++ const desktopHeader =+ desktop === undefined ? (+ <header+ className={cn(+ "sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card max-md:hidden",+ desktopClassName+ )}+ >+ <div className="flex items-center gap-2 px-2">+ <SidebarTrigger />+ <Heading size="h4">{desktopTitle ?? title}</Heading>+ </div>+ </header>+ ) : (+ desktop+ );++ // One header mounts at a time, so page actions (timers, menus) mount once.+ if (!isPhone) return <>{desktopHeader}</>;++ return (+ <>+ <header className="md:hidden sticky top-0 z-20 flex h-[calc(52px+env(safe-area-inset-top))] shrink-0 items-center gap-1 border-b border-border bg-card px-1 pt-safe">+ {kind === "pushed" && back ? (+ <Button+ asChild+ isIcon+ variant="ghost"+ size="lg"+ aria-label={t`Back`}+ className="shrink-0"+ >+ <Link to={back.to}>+ <LuChevronLeft className="size-6" />+ </Link>+ </Button>+ ) : (+ <span className="w-2 shrink-0" />+ )}+ {kind === "root" ? (+ <div className="flex min-w-0 flex-1 items-center">+ <button+ type="button"+ onClick={() => setOpenMobile(true)}+ aria-haspopup="dialog"+ aria-expanded={openMobile}+ className="flex min-h-11 min-w-0 items-center gap-1 rounded-lg px-1 text-foreground outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"+ >+ <span className="min-w-0 truncate text-[17px] font-semibold leading-tight">+ {title}+ </span>+ <LuChevronDown className="size-5 shrink-0 text-muted-foreground" />+ </button>+ </div>+ ) : (+ <div className="flex min-w-0 flex-1 flex-col justify-center">+ <span className="truncate text-[17px] font-semibold leading-tight text-foreground">+ {title}+ </span>+ {subtitle ? (+ <span className="truncate text-xs text-muted-foreground">+ {subtitle}+ </span>+ ) : null}+ </div>+ )}+ {actions ? (+ <div className="flex shrink-0 items-center self-stretch">+ {actions}+ </div>+ ) : null}+ </header>+ </>+ );+}diff --git a/apps/mes/app/components/MesBottomBar.tsx b/apps/mes/app/components/MesBottomBar.tsxnew file mode 100644index 0000000000..b25d350a21--- /dev/null+++ b/apps/mes/app/components/MesBottomBar.tsx@@ -0,0 +1,41 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useViewport } from "@carbon/react";+import { useEffect, useState } from "react";++/**+ * Phones: a page's bottom action bar. Give the returned ref to the bar (it+ * also carries `data-mes-bottom-bar`). The bar publishes how far its top edge+ * sits above the screen bottom as `--mes-bottom-bar-h` on <html>, so toasts+ * and the console pill clear it. The distance already includes the safe area+ * and anything under the bar (the tab bar under My Hours' Clock In bar).+ */+export function useMesBottomBar() {+ const { isPhone } = useViewport();+ const [element, setElement] = useState<HTMLElement | null>(null);++ useEffect(() => {+ if (!isPhone || !element) return;+ const root = document.documentElement;+ const write = () => {+ const top = element.getBoundingClientRect().top;+ root.style.setProperty(+ "--mes-bottom-bar-h",+ `${Math.max(0, window.innerHeight - top)}px`+ );+ };+ write();+ const observer = new ResizeObserver(write);+ observer.observe(element);+ window.addEventListener("resize", write);+ return () => {+ observer.disconnect();+ window.removeEventListener("resize", write);+ root.style.removeProperty("--mes-bottom-bar-h");+ };+ }, [isPhone, element]);++ return setElement;+}diff --git a/apps/mes/app/components/MesEmptyState.tsx b/apps/mes/app/components/MesEmptyState.tsxnew file mode 100644index 0000000000..1caaeb712c--- /dev/null+++ b/apps/mes/app/components/MesEmptyState.tsx@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn } from "@carbon/react";+import type { ReactNode } from "react";+import { LuInbox, LuTriangleAlert } from "react-icons/lu";++type MesEmptyStateProps = {+ title: ReactNode;+ action?: ReactNode;+ /** The page's container classes (height, padding). */+ className?: string;+};++/**+ * An empty list. From md up: today's dark round icon and mono caption.+ * Phones: a muted icon tile and a 17px title.+ */+export function MesEmptyState({+ title,+ action,+ className+}: MesEmptyStateProps) {+ return (+ <div+ className={cn(+ "flex flex-col items-center justify-center gap-4 max-md:h-auto max-md:gap-2 max-md:px-6 max-md:py-12 max-md:text-center",+ className+ )}+ >+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background max-md:rounded-xl max-md:bg-muted max-md:text-muted-foreground">+ <LuTriangleAlert className="h-6 w-6 max-md:hidden" />+ <LuInbox className="hidden h-6 w-6 max-md:block" />+ </div>+ <span className="text-xs font-mono font-light text-foreground uppercase max-md:mt-2 max-md:font-sans max-md:text-[17px] max-md:font-semibold max-md:normal-case">+ {title}+ </span>+ {action}+ </div>+ );+}diff --git a/apps/mes/app/components/MesTabBar.tsx b/apps/mes/app/components/MesTabBar.tsxnew file mode 100644index 0000000000..affd582e28--- /dev/null+++ b/apps/mes/app/components/MesTabBar.tsx@@ -0,0 +1,120 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn, isEditableTarget, TabBar, TabBarItem } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import { useEffect, useState } from "react";+import { LuMenu } from "react-icons/lu";+import { useLocation } from "react-router";+import { path } from "~/utils/path";+import type { QueueKey } from "./AppSidebar";+import { QUEUES, queuePath, useQueueTitles } from "./AppSidebar";++const TAB_KEYS: QueueKey[] = [+ "operations",+ "assigned",+ "active",+ "maintenance"+];++// Root pages that the More tab stands for.+const MORE_PATHS: string[] = [path.to.timeCardPage];++// Exact paths: `/x/picking/:id` shares the Picking prefix but is a pushed page.+const ROOT_PATHS = new Set([+ ...QUEUES.map((queue) => queuePath(queue.to)),+ path.to.timeCardPage+]);++const trimSlash = (pathname: string) => pathname.replace(/\/$/, "");++/** True on the root pages that show the tab bar. */+export function isTabBarPath(pathname: string) {+ return ROOT_PATHS.has(trimSlash(pathname));+}++const NON_TEXT_INPUTS = ["checkbox", "radio", "button", "submit", "reset"];++/**+ * Phones: Schedule · Assigned · Active · Maintenance · More, on root pages+ * only. More opens the More sheet (tools and the user menu); the other queues+ * are behind the app bar title. Hidden while a text field has focus.+ */+export function MesTabBar({+ activeEvents,+ activeMaintenanceCount,+ moreOpen,+ onMoreOpenChange+}: {+ activeEvents: number;+ activeMaintenanceCount: number;+ moreOpen: boolean;+ onMoreOpenChange: (open: boolean) => void;+}) {+ const { t } = useLingui();+ const titles = useQueueTitles();+ const { pathname } = useLocation();+ const [isTyping, setIsTyping] = useState(false);++ useEffect(() => {+ const onFocusIn = (event: FocusEvent) => {+ const target = event.target;+ setIsTyping(+ isEditableTarget(target) &&+ !(+ target instanceof HTMLInputElement &&+ NON_TEXT_INPUTS.includes(target.type)+ )+ );+ };+ const onFocusOut = () => setIsTyping(false);+ document.addEventListener("focusin", onFocusIn);+ document.addEventListener("focusout", onFocusOut);+ return () => {+ document.removeEventListener("focusin", onFocusIn);+ document.removeEventListener("focusout", onFocusOut);+ };+ }, []);++ if (!isTabBarPath(pathname)) return null;++ const current = trimSlash(pathname);+ const counts: Partial<Record<QueueKey, number>> = {+ active: activeEvents,+ maintenance: activeMaintenanceCount+ };++ return (+ <TabBar+ aria-label={t`Main`}+ data-mes-tab-bar=""+ data-visible={isTyping ? "false" : "true"}+ className={cn(+ "fixed inset-x-0 bottom-0 z-30 min-h-[calc(54px+env(safe-area-inset-bottom))]",+ isTyping && "hidden"+ )}+ >+ {QUEUES.filter((queue) => TAB_KEYS.includes(queue.key)).map((queue) => (+ <TabBarItem+ key={queue.key}+ to={queue.to}+ icon={<queue.icon />}+ label={titles[queue.key]}+ isActive={current === queuePath(queue.to)}+ count={counts[queue.key]}+ pill+ />+ ))}+ <TabBarItem+ icon={<LuMenu />}+ label={t`More`}+ isActive={MORE_PATHS.includes(current)}+ onClick={() => onMoreOpenChange(true)}+ aria-haspopup="dialog"+ aria-expanded={moreOpen}+ pill+ />+ </TabBar>+ );+}diff --git a/apps/mes/app/components/MoreSheet.tsx b/apps/mes/app/components/MoreSheet.tsxnew file mode 100644index 0000000000..211ade3dbd--- /dev/null+++ b/apps/mes/app/components/MoreSheet.tsx@@ -0,0 +1,468 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Company } from "@carbon/auth";+import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";+import {+ Avatar,+ BottomSheet,+ BottomSheetBack,+ BottomSheetBody,+ BottomSheetContent,+ BottomSheetHeader,+ BottomSheetTitle,+ cn,+ ItarDisclosure,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ NavRailItem,+ NavRailLink,+ Switch,+ useDisclosure+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { MouseEvent, ReactNode } from "react";+import { createContext, useContext, useEffect, useState } from "react";+import { createPortal } from "react-dom";+import {+ LuBuilding,+ LuCheck,+ LuChevronRight,+ LuLogOut,+ LuMapPin,+ LuMonitor,+ LuMoon,+ LuShieldCheck,+ LuSun,+ LuUser,+ LuUsers+} from "react-icons/lu";+import { Form, useLocation } from "react-router";+import type { Location } from "~/services/types";+import type { PinnedInUser } from "~/types";+import { path } from "~/utils/path";+import { useUserNav } from "./UserNav";++type Screen =+ | { id: "root" }+ | { id: "company" }+ | { id: "location" }+ /** A tool's own page, e.g. Add Inventory. */+ | { id: "tool"; tool: string; title: ReactNode };++type MorePageContextValue = {+ activeTool: string | null;+ slot: HTMLElement | null;+ open: (tool: string, title: ReactNode) => void;+ /** Back to the More list. */+ back: () => void;+ /** The tool's work is done: close the sheet. */+ done: () => void;+};++const MorePageContext = createContext<MorePageContextValue | null>(null);++/**+ * Set inside the phone More sheet: a tool opens its form as a page of the+ * sheet (‹ Back to the list) instead of a modal or popover of its own.+ */+export function useMorePage() {+ return useContext(MorePageContext);+}++/**+ * A tool's form surface: a page of the phone More sheet, or a modal+ * elsewhere. `open`, `close` (Cancel) and `done` (after success) work the same+ * for both, so a tool never checks where it is.+ */+export function useToolSurface(tool: string, title: string) {+ const page = useMorePage();+ const modal = useDisclosure();+ return {+ tool,+ title,+ inSheet: page !== null,+ isOpen: page ? page.activeTool === tool : modal.isOpen,+ open: () => (page ? page.open(tool, title) : modal.onOpen()),+ close: () => (page ? page.back() : modal.onClose()),+ done: () => (page ? page.done() : modal.onClose())+ };+}++/**+ * Renders a tool's form on its surface. `wrap` puts the whole form inside a+ * form element (ValidatedForm, fetcher.Form) so its footer can submit it.+ */+export function ToolSurface({+ surface,+ description,+ body,+ footer,+ wrap = (children) => children+}: {+ surface: ReturnType<typeof useToolSurface>;+ description?: ReactNode;+ body: ReactNode;+ footer: ReactNode;+ wrap?: (children: ReactNode) => ReactNode;+}) {+ if (surface.inSheet) {+ return (+ <MorePage tool={surface.tool}>+ {wrap(+ <div className="flex flex-col gap-4">+ {description ? (+ <p className="text-sm text-muted-foreground">{description}</p>+ ) : null}+ {body}+ <div className="flex gap-2 [&>*]:flex-1">{footer}</div>+ </div>+ )}+ </MorePage>+ );+ }+ if (!surface.isOpen) return null;+ return (+ <Modal open onOpenChange={(open) => !open && surface.close()}>+ <ModalContent>+ {wrap(+ <>+ <ModalHeader>+ <ModalTitle>{surface.title}</ModalTitle>+ {description ? (+ <ModalDescription>{description}</ModalDescription>+ ) : null}+ </ModalHeader>+ <ModalBody>{body}</ModalBody>+ <ModalFooter>{footer}</ModalFooter>+ </>+ )}+ </ModalContent>+ </Modal>+ );+}++/** A tool's page content; rendered into the sheet while its page shows. */+export function MorePage({+ tool,+ children+}: {+ tool: string;+ children: ReactNode;+}) {+ const page = useMorePage();+ if (!page?.slot || page.activeTool !== tool) return null;+ return createPortal(children, page.slot);+}++/**+ * Phones: the More tab's sheet. Everything the rail holds besides the queues+ * (those are behind the app bar title): the time card, inventory adjustments,+ * tools, and the user menu. Company, Location and each tool's form open as+ * pages in this sheet, with ‹ Back to the list.+ */+export function MoreSheet({+ open,+ onOpenChange,+ header,+ children,+ company,+ companies,+ consoleEnabled,+ consoleMode,+ location,+ locations,+ pinnedInUser+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Above everything, e.g. the company link back to the ERP. */+ header?: ReactNode;+ /** The rail's tools, as rail items. */+ children?: ReactNode;+ company: Company;+ companies: Company[];+ consoleEnabled?: boolean;+ consoleMode: boolean;+ location: string;+ locations: Location[];+ pinnedInUser: PinnedInUser | null;+}) {+ const { t } = useLingui();+ const { pathname } = useLocation();+ const [screen, setScreen] = useState<Screen>({ id: "root" });+ const [slot, setSlot] = useState<HTMLElement | null>(null);+ const toRoot = () => setScreen({ id: "root" });+ const user = useUserNav({ consoleMode, location, pinnedInUser });+ const { stationName } = user;++ useEffect(() => {+ if (!open) setScreen({ id: "root" });+ }, [open]);++ // Links, redirects and company switches all land here.+ // biome-ignore lint/correctness/useExhaustiveDependencies: runs per navigation+ useEffect(() => {+ onOpenChange(false);+ }, [pathname]);++ // A tap on a link closes the sheet, also on the current page.+ const closeOnLink = (event: MouseEvent<HTMLElement>) => {+ if ((event.target as Element).closest("a")) onOpenChange(false);+ };++ const modeOptions = [+ { value: "light", label: t`Light` },+ { value: "dark", label: t`Dark` },+ { value: "system", label: t`System` }+ ];++ const title =+ screen.id === "company" ? (+ <Trans>Company</Trans>+ ) : screen.id === "location" ? (+ <Trans>Location</Trans>+ ) : screen.id === "tool" ? (+ screen.title+ ) : (+ <Trans>More</Trans>+ );++ const page: MorePageContextValue = {+ activeTool: screen.id === "tool" ? screen.tool : null,+ slot,+ open: (tool, title) => setScreen({ id: "tool", tool, title }),+ back: toRoot,+ done: () => onOpenChange(false)+ };++ return (+ <>+ <BottomSheet open={open} onOpenChange={onOpenChange}>+ <BottomSheetContent>+ <BottomSheetHeader>+ {screen.id !== "root" && <BottomSheetBack onClick={toRoot} />}+ <BottomSheetTitle>{title}</BottomSheetTitle>+ </BottomSheetHeader>+ <BottomSheetBody className="max-md:px-2">+ {/* Rail items read their expanded layout from this group. */}+ <MorePageContext.Provider value={page}>+ <div+ data-state="expanded"+ onClick={closeOnLink}+ className="group flex flex-col gap-1"+ >+ {/* Kept mounted under a page, so a tool's form keeps its state+ and its fetcher while its page shows. */}+ <div+ className={cn(+ "flex flex-col gap-1",+ screen.id !== "root" && "hidden"+ )}+ >+ <div className="flex items-center gap-3 px-2 pb-2">+ <Avatar+ size="sm"+ src={user.displayAvatar ?? undefined}+ name={user.displayName}+ />+ <span className="min-w-0 truncate text-sm text-muted-foreground">+ {user.showingOperator ? (+ <Trans>Station: {stationName}</Trans>+ ) : (+ <Trans>Signed in as {stationName}</Trans>+ )}+ </span>+ </div>+ {header}+ {children}+ <Divider />+ {user.showingOperator ? (+ <NavRailItem+ icon={<LuUsers />}+ label={t`Switch Operator`}+ onClick={() => {+ user.switchOperator();+ onOpenChange(false);+ }}+ />+ ) : (+ <>+ <NavRailLink+ to={path.to.accountSettings}+ icon={<LuUser />}+ label={t`Account Settings`}+ />+ {companies.length > 1 && (+ <NavRailItem+ icon={<LuBuilding />}+ label={t`Company`}+ onClick={() => setScreen({ id: "company" })}+ trailing={<Drill detail={company.name} />}+ />+ )}+ {locations.length > 1 && (+ <NavRailItem+ icon={<LuMapPin />}+ label={t`Location`}+ onClick={() => setScreen({ id: "location" })}+ trailing={+ <Drill+ detail={+ locations.find(+ (l) => l.id === user.optimisticLocation+ )?.name+ }+ />+ }+ />+ )}+ </>+ )}+ <div className="flex h-10 items-center gap-4 px-2 text-sm text-foreground/70">+ <span className="flex size-6 shrink-0 items-center justify-center [&>svg]:size-4">+ {user.mode === "dark" ? <LuMoon /> : <LuSun />}+ </span>+ <span className="min-w-0 flex-1 truncate font-medium">+ <Trans>Appearance</Trans>+ </span>+ <div+ role="radiogroup"+ aria-label={t`Appearance`}+ className="flex shrink-0 rounded-lg bg-muted p-0.5"+ >+ {modeOptions.map((option) => {+ const selected = user.modePreference === option.value;+ return (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={selected}+ onClick={() => user.onModeChange(option.value)}+ className={cn(+ "hit-area flex h-8 min-w-11 items-center justify-center rounded-md px-2 text-sm text-muted-foreground",+ selected &&+ "bg-background text-foreground shadow-button-base"+ )}+ >+ {option.label}+ </button>+ );+ })}+ </div>+ </div>+ {!user.isOperatorPinnedIn && (+ <>+ {consoleEnabled && (+ <label className="flex h-10 items-center gap-4 px-2 text-sm text-foreground/70">+ <span className="flex size-6 shrink-0 items-center justify-center [&>svg]:size-4">+ <LuMonitor />+ </span>+ <span className="min-w-0 flex-1 truncate font-medium">+ <Trans>Console Mode</Trans>+ </span>+ <Switch+ checked={consoleMode}+ onCheckedChange={user.toggleConsoleMode}+ />+ </label>+ )}+ {CONTROLLED_ENVIRONMENT && (+ <NavRailItem+ icon={<LuShieldCheck />}+ label={t`About`}+ onClick={user.itarDisclosure.onOpen}+ />+ )}+ <Form method="post" action={path.to.logout}>+ <NavRailItem+ type="submit"+ icon={<LuLogOut />}+ label={t`Sign Out`}+ />+ </Form>+ </>+ )}+ </div>+ {screen.id === "tool" && (+ <div ref={setSlot} className="flex flex-col gap-4 px-2" />+ )}+ {screen.id === "company" &&+ companies.map((c) => {+ const logo =+ user.mode === "dark" ? c.logoDarkIcon : c.logoLightIcon;+ const isCurrent = c.companyId === company.companyId;+ return (+ <NavRailItem+ key={c.companyId}+ icon={+ <Avatar+ size="xs"+ name={c.name ?? undefined}+ src={logo ?? undefined}+ />+ }+ label={c.name ?? ""}+ isActive={isCurrent}+ onClick={() => {+ if (!isCurrent) user.switchCompany(c.companyId!);+ onOpenChange(false);+ }}+ trailing={isCurrent ? <Check /> : undefined}+ />+ );+ })}+ {screen.id === "location" &&+ locations.map((l) => {+ const isCurrent = l.id === user.optimisticLocation;+ return (+ <NavRailItem+ key={l.id}+ icon={<LuMapPin />}+ label={l.name}+ isActive={isCurrent}+ onClick={() => {+ if (!isCurrent) user.updateLocation(l.id);+ onOpenChange(false);+ }}+ trailing={isCurrent ? <Check /> : undefined}+ />+ );+ })}+ </div>+ </MorePageContext.Provider>+ </BottomSheetBody>+ </BottomSheetContent>+ </BottomSheet>+ {CONTROLLED_ENVIRONMENT && (+ <ItarDisclosure disclosure={user.itarDisclosure} />+ )}+ </>+ );+}++function Divider() {+ return <hr className="mx-2 my-1 h-px border-0 bg-border" />;+}++function Drill({ detail }: { detail?: ReactNode }) {+ return (+ <span className="flex min-w-0 items-center gap-1 text-muted-foreground">+ {detail ? (+ <span className="max-w-36 truncate text-sm">{detail}</span>+ ) : null}+ <LuChevronRight className="size-4 shrink-0" />+ </span>+ );+}++function Check() {+ return <LuCheck className="size-4 text-primary" />;+}diff --git a/apps/mes/app/components/OperationCardParts.tsx b/apps/mes/app/components/OperationCardParts.tsxnew file mode 100644index 0000000000..0ff7430cde--- /dev/null+++ b/apps/mes/app/components/OperationCardParts.tsx@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { Badge, Heading, HStack } from "@carbon/react";+import { formatDurationMilliseconds } from "@carbon/utils";+import { Trans } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuTimer } from "react-icons/lu";+import { getPrivateUrl } from "~/utils/path";+import EmployeeAvatar from "./EmployeeAvatar";++/*+ * Parts shared by the operation cards: the schedule board's ItemCard and the+ * Assigned / Active list's OperationsList.+ */++/** Phones: the item thumbnail at the start of the card header. */+export function PhoneThumbnail({ path, alt }: { path: string; alt: string }) {+ return (+ <img+ src={getPrivateUrl(path)}+ alt={alt}+ className="hidden max-md:block size-10 shrink-0 rounded-md object-cover"+ />+ );+}++/** The quantity at the header's end; phones caption it "Quantity". */+export function QuantityStat({+ children,+ className+}: {+ children: ReactNode;+ className?: string;+}) {+ return (+ <div className="flex flex-col items-end">+ <Heading size="h4" className={className}>+ {children}+ </Heading>+ <span className="text-xs text-muted-foreground md:hidden">+ <Trans>Quantity</Trans>+ </span>+ </div>+ );+}++/** The remaining time; phones use the short form ("2d 4h"). */+export function OperationDuration({ value }: { value: number }) {+ return (+ <HStack className="justify-start space-x-2">+ <LuTimer className="text-muted-foreground" />+ <span className="text-sm max-md:hidden">+ {formatDurationMilliseconds(value)}+ </span>+ <span className="text-sm md:hidden">+ {formatDurationMilliseconds(value, { style: "short" })}+ </span>+ </HStack>+ );+}++export function AssigneeTags({+ assignee,+ tags+}: {+ assignee?: string | null;+ tags?: string[] | null;+}) {+ return (+ <>+ {assignee && <EmployeeAvatar size="xs" employeeId={assignee} />}+ {tags?.map((tag) => (+ <Badge+ key={tag}+ variant="secondary"+ className="border dark:border-none dark:shadow-button-base"+ >+ {tag}+ </Badge>+ ))}+ </>+ );+}diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsxindex 5b6b868076..39c01eb20c 100644--- a/apps/mes/app/components/OperationsList.tsx+++ b/apps/mes/app/components/OperationsList.tsx@@ -3,37 +3,33 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import {- Badge,Card,CardContent,CardFooter,CardHeader,cn,- Heading,HStack,Tooltip,TooltipContent,TooltipTrigger} from "@carbon/react";-import {- convertDateStringToIsoString,- formatDurationMilliseconds-} from "@carbon/utils";+import { convertDateStringToIsoString } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import { cva } from "class-variance-authority";-import {- LuCalendarDays,- LuCirclePlay,- LuClipboardCheck,- LuTimer-} from "react-icons/lu";-import { Link } from "react-router";+import { LuCalendarDays, LuCirclePlay, LuClipboardCheck } from "react-icons/lu";+import { Link, useLocation } from "react-router";import { DateTime } from "~/components";-import EmployeeAvatar from "~/components/EmployeeAvatar";import { useDateFormatter } from "~/hooks";import type { Operation, OperationSettings } from "~/services/types";+import { withOrigin } from "~/utils/origin";import { getPrivateUrl, path } from "~/utils/path";import { DeadlineIcon, OperationStatusIcon } from "./Icons";+import {+ AssigneeTags,+ OperationDuration,+ PhoneThumbnail,+ QuantityStat+} from "./OperationCardParts";type OperationsListProps = {operations: Operation[];@@ -98,6 +94,7 @@ function OperationCard({}: OperationCardProps) {const { t } = useLingui();const { formatRelativeTime } = useDateFormatter();+ const location = useLocation();const isOverdue =operation.jobDeadlineType !== "No Deadline" && operation.jobDueDate? new Date(operation.jobDueDate) < new Date()@@ -113,29 +110,35 @@ function OperationCard({)}><Link- to={path.to.operation(operation.id)}+ to={withOrigin(path.to.operation(operation.id), location)}className="flex flex-col flex-1">- <CardHeader className="flex flex-col justify-between relative gap-2">+ <CardHeader className="flex flex-col justify-between relative gap-2 max-md:pb-1"><div className="flex w-full max-w-full justify-between items-start gap-2">- <div className="flex flex-col space-y-0 min-w-0">+ {showThumbnail && operation.thumbnailPath && (+ <PhoneThumbnail+ path={operation.thumbnailPath}+ alt={operation.jobReadableId ?? ""}+ />+ )}+ <div className="flex flex-col space-y-0 min-w-0 max-md:flex-1">{operation.itemReadableId && (<span className="text-xs text-muted-foreground line-clamp-1">{operation.itemReadableId}</span>)}- <span className="mr-auto font-semibold line-clamp-2 leading-tight">+ <span className="mr-auto font-semibold line-clamp-2 leading-tight max-md:text-foreground">{operation.itemDescription || operation.itemReadableId}</span></div>- <Heading size="h4" className="text-muted-foreground/70">+ <QuantityStat className="text-muted-foreground/70 max-md:text-foreground max-md:tabular-nums">{operation.targetQuantity ?? operation.operationQuantity ?? 0}- </Heading>+ </QuantityStat></div></CardHeader>- <CardContent className="gap-2 text-left whitespace-pre-wrap text-sm flex-grow">+ <CardContent className="gap-2 text-left whitespace-pre-wrap text-sm max-md:border-t-0 max-md:pt-1 flex-grow max-md:grid max-md:grid-cols-2 max-md:content-start max-md:gap-x-3 max-md:gap-y-1.5 max-md:[&>*]:min-w-0">{showThumbnail && operation.thumbnailPath && (- <div className="flex justify-center">+ <div className="flex justify-center max-md:hidden"><imgsrc={getPrivateUrl(operation.thumbnailPath)}alt={operation.jobReadableId}@@ -143,7 +146,7 @@ function OperationCard({/></div>)}- <HStack className="justify-start space-x-2">+ <HStack className="justify-start space-x-2 max-md:col-span-2"><LuCirclePlay className="text-muted-foreground" /><span className="text-sm line-clamp-1">{operation.jobReadableId}@@ -151,7 +154,7 @@ function OperationCard({</HStack>{showDescription && operation.description && (- <HStack className="justify-start space-x-2">+ <HStack className="justify-start space-x-2 max-md:col-span-2"><LuClipboardCheck className="text-muted-foreground" /><span className="text-sm line-clamp-1">{operation.description}@@ -165,12 +168,7 @@ function OperationCard({</HStack>)}{showDuration && typeof operation.duration === "number" && (- <HStack className="justify-start space-x-2">- <LuTimer className="text-muted-foreground" />- <span className="text-sm">- {formatDurationMilliseconds(operation.duration)}- </span>- </HStack>+ <OperationDuration value={operation.duration} />)}{showDueDate && operation.jobDeadlineType && (<>@@ -210,22 +208,20 @@ function OperationCard({)}</>)}+ {(operation.assignee ||+ (operation.tags && operation.tags.length > 0)) && (+ <div className="hidden flex-wrap items-center gap-1 text-xs max-md:col-span-2 max-md:flex">+ <AssigneeTags+ assignee={operation.assignee}+ tags={operation.tags}+ />+ </div>+ )}</CardContent>{(operation.assignee ||(operation.tags && operation.tags.length > 0)) && (- <CardFooter className="items-center justify-start text-xs flex-wrap mt-auto">- {operation.assignee && (- <EmployeeAvatar size="xs" employeeId={operation.assignee} />- )}- {operation.tags?.map((tag) => (- <Badge- key={tag}- variant="secondary"- className="border dark:border-none dark:shadow-button-base"- >- {tag}- </Badge>- ))}+ <CardFooter className="items-center justify-start text-xs flex-wrap mt-auto max-md:hidden">+ <AssigneeTags assignee={operation.assignee} tags={operation.tags} /></CardFooter>)}</Link>diff --git a/apps/mes/app/components/SearchFilter.tsx b/apps/mes/app/components/SearchFilter.tsxindex 28396d63cd..94dca117ae 100644--- a/apps/mes/app/components/SearchFilter.tsx+++ b/apps/mes/app/components/SearchFilter.tsx@@ -4,6 +4,7 @@import type { InputProps } from "@carbon/react";import {+ cn,Input,InputGroup,InputLeftElement,@@ -15,9 +16,17 @@ import { useUrlParams } from "~/hooks";type SearchFilterProps = InputProps & {param: string;+ /** Classes for the input group (the outer box). */+ groupClassName?: string;};-const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {+const SearchFilter = ({+ param,+ size,+ className,+ groupClassName,+ ...props+}: SearchFilterProps) => {const [params, setParams] = useUrlParams();const [query, setQuery] = useState(params.get(param) || "");const debounceQuery = useDebounce((q: string) => {@@ -25,7 +34,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {}, 500);return (- <InputGroup size={size}>+ <InputGroup size={size} className={groupClassName}><InputLeftElement><LuSearch className="text-muted-foreground w-3.5 h-3.5 mt-[-2px]" /></InputLeftElement>@@ -35,7 +44,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {setQuery(e.target.value);debounceQuery(e.target.value);}}- className="w-[100px] sm:w-[200px] text-sm"+ className={cn("w-[100px] sm:w-[200px] text-sm", className)}{...props}/></InputGroup>diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsxindex a68075b150..e91e4fa927 100644--- a/apps/mes/app/components/Suggestion.tsx+++ b/apps/mes/app/components/Suggestion.tsx@@ -38,6 +38,7 @@ import { useUser } from "~/hooks";import type { action } from "~/routes/x+/suggestion";import { suggestionValidator } from "~/services/models";import { path } from "~/utils/path";+import { MorePage, useMorePage } from "./MoreSheet";// Lazy, not a static import: @emoji-mart/react is CommonJS, so under SSR its// default import is `{ default: Picker }` and dev React warns "type is@@ -59,6 +60,10 @@ const Suggestion = () => {const fetcher = useFetcher<typeof action>();const location = useLocation();const popoverTriggerRef = useRef<HTMLButtonElement>(null);+ // Phones: the form is a page of the More sheet, not a popover.+ const morePage = useMorePage();+ const close = () =>+ morePage ? morePage.back() : popoverTriggerRef.current?.click();const [suggestion, setSuggestion] = useState("");const [emoji, setEmoji] = useState("💡");const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);@@ -75,6 +80,7 @@ const Suggestion = () => {const companyId = user.company.id;+ // biome-ignore lint/correctness/useExhaustiveDependencies: runs once per submission resultuseEffect(() => {if (fetcher.data?.success) {toast.success(fetcher.data.message);@@ -83,7 +89,8 @@ const Suggestion = () => {setAttachment(null);setAnonymous(true);setSendToCarbon(CARBON_SLACK_ENABLED);- popoverTriggerRef.current?.click();+ if (morePage) morePage.done();+ else popoverTriggerRef.current?.click();} else if (fetcher.data?.message) {toast.error(fetcher.data.message);}@@ -139,137 +146,150 @@ const Suggestion = () => {setEmojiPickerOpen(false);};- return (- <Popover>- <PopoverTrigger ref={popoverTriggerRef} asChild>- <NavRailItem icon={<LuMailbox />} label={t`Suggestion`} />- </PopoverTrigger>- <PopoverContent className="w-[380px] ">- <ValidatedForm- method="post"- action={path.to.suggestion}- validator={suggestionValidator}- fetcher={fetcher}- >- <Hidden name="path" value={location.pathname} />- <Hidden name="emoji" value={emoji} />- <Hidden name="attachmentPath" value={attachment?.path ?? ""} />- <Hidden name="userId" value={anonymous ? "" : user.id} />- <Hidden name="sendToCarbon" value={sendToCarbon ? "true" : ""} />- <VStack spacing={2}>- <VStack spacing={2} className="w-full">- <TextAreaControlled- name="suggestion"- label=""- value={suggestion}- onChange={(value) => setSuggestion(value)}- placeholder={t`Ideas, suggestions or problems?`}- />- {attachment && (- <Badge className="-mt-2 truncate" variant="secondary">- {attachment.name}- <BadgeCloseButton- type="button"- onClick={() => {- setAttachment(null);- }}- />- </Badge>- )}- </VStack>- <HStack className="w-full justify-between">- <VStack spacing={2}>- <HStack spacing={2}>- <Checkbox- isChecked={anonymous}- onCheckedChange={(checked) =>- setAnonymous(checked === true)- }- />- <span className="text-sm">- <Trans>Submit anonymously</Trans>- </span>- </HStack>- {CARBON_SLACK_ENABLED && (- <HStack spacing={2}>- <Checkbox- isChecked={sendToCarbon}- onCheckedChange={(checked) =>- setSendToCarbon(checked === true)- }- />- <span className="text-sm">- <Trans>Send to Carbon</Trans>- </span>- </HStack>- )}- </VStack>- <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>- <PopoverTrigger asChild>- <button- type="button"- className="inline-flex items-center justify-center rounded-md h-10 w-10 text-2xl hover:bg-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 shrink-0"- >- {emoji}- </button>- </PopoverTrigger>- <PopoverContent- className="w-auto p-0 border-0"- align="end"- sideOffset={8}- >- <Suspense>- <Picker- data={data}- onEmojiSelect={onEmojiSelect}- theme={pickerTheme}- previewPosition="none"- skinTonePosition="none"- navPosition="bottom"- perLine={8}- />- </Suspense>- </PopoverContent>- </Popover>- </HStack>- <HStack className="w-full justify-between">- <Button- variant="secondary"+ const form = (+ <ValidatedForm+ method="post"+ action={path.to.suggestion}+ validator={suggestionValidator}+ fetcher={fetcher}+ >+ <Hidden name="path" value={location.pathname} />+ <Hidden name="emoji" value={emoji} />+ <Hidden name="attachmentPath" value={attachment?.path ?? ""} />+ <Hidden name="userId" value={anonymous ? "" : user.id} />+ <Hidden name="sendToCarbon" value={sendToCarbon ? "true" : ""} />+ <VStack spacing={2}>+ <VStack spacing={2} className="w-full">+ <TextAreaControlled+ name="suggestion"+ label=""+ value={suggestion}+ onChange={(value) => setSuggestion(value)}+ placeholder={t`Ideas, suggestions or problems?`}+ />+ {attachment && (+ <Badge className="-mt-2 truncate" variant="secondary">+ {attachment.name}+ <BadgeCloseButton+ type="button"onClick={() => {- setSuggestion("");- setEmoji("💡");setAttachment(null);- popoverTriggerRef.current?.click();}}- >- <Trans>Cancel</Trans>- </Button>- <HStack spacing={1}>- <Button- isDisabled={suggestion.length === 0}- variant="secondary"- onClick={() => setSuggestion("")}- >- <Trans>Clear</Trans>- </Button>- <File- accept="image/*"- aria-label="Attach File"- className="px-2"- isDisabled={!!attachment}- variant="secondary"- onChange={uploadImage}- >- <LuImage />- </File>- <Submit isDisabled={suggestion.length < 3}>- <Trans>Send</Trans>- </Submit>- </HStack>+ />+ </Badge>+ )}+ </VStack>+ <HStack className="w-full justify-between">+ <VStack spacing={2}>+ <HStack spacing={2}>+ <Checkbox+ isChecked={anonymous}+ onCheckedChange={(checked) => setAnonymous(checked === true)}+ />+ <span className="text-sm">+ <Trans>Submit anonymously</Trans>+ </span></HStack>+ {CARBON_SLACK_ENABLED && (+ <HStack spacing={2}>+ <Checkbox+ isChecked={sendToCarbon}+ onCheckedChange={(checked) =>+ setSendToCarbon(checked === true)+ }+ />+ <span className="text-sm">+ <Trans>Send to Carbon</Trans>+ </span>+ </HStack>+ )}</VStack>- </ValidatedForm>- </PopoverContent>+ <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center justify-center rounded-md h-10 w-10 text-2xl hover:bg-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 shrink-0"+ >+ {emoji}+ </button>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto p-0 border-0"+ align="end"+ sideOffset={8}+ >+ <Suspense>+ <Picker+ data={data}+ onEmojiSelect={onEmojiSelect}+ theme={pickerTheme}+ previewPosition="none"+ skinTonePosition="none"+ navPosition="bottom"+ perLine={8}+ />+ </Suspense>+ </PopoverContent>+ </Popover>+ </HStack>+ <HStack className="w-full justify-between">+ <Button+ variant="secondary"+ onClick={() => {+ setSuggestion("");+ setEmoji("💡");+ setAttachment(null);+ close();+ }}+ >+ <Trans>Cancel</Trans>+ </Button>+ <HStack spacing={1}>+ <Button+ isDisabled={suggestion.length === 0}+ variant="secondary"+ onClick={() => setSuggestion("")}+ >+ <Trans>Clear</Trans>+ </Button>+ <File+ accept="image/*"+ aria-label="Attach File"+ className="px-2"+ isDisabled={!!attachment}+ variant="secondary"+ onChange={uploadImage}+ >+ <LuImage />+ </File>+ <Submit isDisabled={suggestion.length < 3}>+ <Trans>Send</Trans>+ </Submit>+ </HStack>+ </HStack>+ </VStack>+ </ValidatedForm>+ );++ if (morePage) {+ return (+ <>+ <NavRailItem+ icon={<LuMailbox />}+ label={t`Suggestion`}+ onClick={() => morePage.open("suggestion", t`Suggestion`)}+ />+ <MorePage tool="suggestion">{form}</MorePage>+ </>+ );+ }++ return (+ <Popover>+ <PopoverTrigger ref={popoverTriggerRef} asChild>+ <NavRailItem icon={<LuMailbox />} label={t`Suggestion`} />+ </PopoverTrigger>+ <PopoverContent className="w-[380px] ">{form}</PopoverContent></Popover>);};diff --git a/apps/mes/app/components/UserNav.tsx b/apps/mes/app/components/UserNav.tsxindex e759d5e350..f0dde0ef50 100644--- a/apps/mes/app/components/UserNav.tsx+++ b/apps/mes/app/components/UserNav.tsx@@ -30,7 +30,6 @@ import {} from "@carbon/react";import { modeValidator } from "@carbon/utils";import { Trans } from "@lingui/react/macro";-import { useRef } from "react";import {LuBuilding,LuChevronDown,@@ -51,15 +50,7 @@ import type { Location } from "~/services/types";import type { PinnedInUser } from "~/types";import { path } from "~/utils/path";-export function UserNav({- company,- companies,- consoleEnabled,- consoleMode,- location,- locations,- pinnedInUser-}: {+type UserNavProps = {company: Company;companies: Company[];consoleEnabled?: boolean;@@ -67,16 +58,20 @@ export function UserNav({location: string;locations: Location[];pinnedInUser: PinnedInUser | null;-}) {+};++/** The user menu's state and actions, shared by the rail menu and the phone More sheet. */+export function useUserNav({+ consoleMode,+ location,+ pinnedInUser+}: Pick<UserNavProps, "consoleMode" | "location" | "pinnedInUser">) {const user = useUser();const stationName = `${user.firstName} ${user.lastName}`;- const { isMobile } = useSidebar();const mode = useMode();const modePreference = useModePreference();- const consoleSubmitRef = useRef<HTMLButtonElement>(null);-const fetcher = useFetcher<typeof action>();const onModeChange = (value: string) => {@@ -94,6 +89,25 @@ export function UserNav({fetcher.submit(formData, { method: "POST", action: path.to.location });};+ const switchCompany = (companyId: string) => {+ const form = new FormData();+ form.append("companyId", companyId);+ fetcher.submit(form, {+ method: "post",+ action: path.to.switchCompany(companyId)+ });+ };++ const switchOperator = () => {+ fetcher.submit(null, { method: "POST", action: path.to.consolePinOut });+ };++ const toggleConsoleMode = () => {+ const formData = new FormData();+ formData.append("consoleMode", consoleMode ? "false" : "true");+ fetcher.submit(formData, { method: "post", action: path.to.consoleToggle });+ };+const optimisticLocation =(fetcher.formData?.get("location") as string | undefined) ?? location;@@ -104,17 +118,63 @@ export function UserNav({path.to.authenticatedRoot);const sessionUserId = routeData?.user?.id;- const isOperatorPinnedIn =+ const isOperatorPinnedIn = Boolean(consoleMode &&- pinnedInUser &&- sessionUserId &&- pinnedInUser.userId !== sessionUserId;- const showingOperator = consoleMode && pinnedInUser;- const displayName = showingOperator ? pinnedInUser.name : stationName;+ pinnedInUser &&+ sessionUserId &&+ pinnedInUser.userId !== sessionUserId+ );+ const showingOperator = consoleMode && pinnedInUser ? pinnedInUser : null;+ const displayName = showingOperator ? showingOperator.name : stationName;const displayAvatar = showingOperator- ? pinnedInUser.avatarUrl+ ? showingOperator.avatarUrl: user.avatarUrl;+ return {+ stationName,+ mode,+ modePreference,+ onModeChange,+ updateLocation,+ switchCompany,+ switchOperator,+ toggleConsoleMode,+ optimisticLocation,+ itarDisclosure,+ isOperatorPinnedIn,+ showingOperator,+ displayName,+ displayAvatar+ };+}++export function UserNav({+ company,+ companies,+ consoleEnabled,+ consoleMode,+ location,+ locations,+ pinnedInUser+}: UserNavProps) {+ const { isMobile } = useSidebar();+ const {+ stationName,+ mode,+ modePreference,+ onModeChange,+ updateLocation,+ switchCompany,+ switchOperator,+ toggleConsoleMode,+ optimisticLocation,+ itarDisclosure,+ isOperatorPinnedIn,+ showingOperator,+ displayName,+ displayAvatar+ } = useUserNav({ consoleMode, location, pinnedInUser });+return (<><DropdownMenu>@@ -140,16 +200,9 @@ export function UserNav({{/* Console mode with pinned-in operator: simplified menu */}{showingOperator ? (<>- <DropdownMenuLabel>{pinnedInUser.name}</DropdownMenuLabel>+ <DropdownMenuLabel>{showingOperator.name}</DropdownMenuLabel><DropdownMenuSeparator />- <DropdownMenuItem- onSelect={() => {- fetcher.submit(null, {- method: "POST",- action: path.to.consolePinOut- });- }}- >+ <DropdownMenuItem onSelect={switchOperator}><DropdownMenuIcon icon={<LuUsers />} /><Trans>Switch Operator</Trans></DropdownMenuItem>@@ -186,14 +239,7 @@ export function UserNav({<DropdownMenuRadioItemkey={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!)- });- }}+ onSelect={() => switchCompany(c.companyId!)}><HStack><Avatar@@ -283,30 +329,10 @@ export function UserNav({<DropdownMenuIcon icon={<LuMonitor />} /><Trans>Console Mode</Trans></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>+ <Switch+ checked={consoleMode}+ onCheckedChange={toggleConsoleMode}+ /></div></DropdownMenuItem>)}diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 877b401325..c29b574802 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -238,7 +238,10 @@ function Document({><head><meta charSet="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta+ name="viewport"+ content="width=device-width, initial-scale=1, viewport-fit=cover"+ />{/* Before any paint: records the OS color scheme for a `system` userand reloads once if the server rendered the wrong mode. */}<scriptdiff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 6df7486cbd..fc99b01ca9 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -32,6 +32,7 @@ import { RouteRealtime } from "@carbon/query";import { setClientCompanyId } from "@carbon/query/cache";import {Button,+ cn,Heading,ItarEntityPendingBlock,ItarUserCertification,@@ -52,7 +53,7 @@ import {import { Trans } from "@lingui/react/macro";import posthog from "posthog-js";import type { ReactNode } from "react";-import { Suspense, useEffect } from "react";+import { Suspense, useEffect, useState } from "react";import type {LoaderFunctionArgs,MiddlewareFunction,@@ -64,10 +65,12 @@ import {Form,Outlet,useLoaderData,+ useLocation,useNavigate} from "react-router";import { AppSidebar } from "~/components";import { ConsolePill } from "~/components/ConsolePill";+import { isTabBarPath, MesTabBar } from "~/components/MesTabBar";import { PinInOverlay } from "~/components/PinInOverlay";import RealtimeDataProvider from "~/components/RealtimeDataProvider";import SessionLockOverlay from "~/components/SessionLockOverlay";@@ -354,6 +357,9 @@ export default function AuthenticatedRoute() {}, [loaderData]);const navigate = useNavigate();+ const { pathname } = useLocation();+ const showTabBar = isTabBarPath(pathname);+ const [moreOpen, setMoreOpen] = useState(false);// Session lock (NIST 3.1.10) — client idle UX only; server enforces in// requireAuthSession. Inert unless CONTROLLED_ENVIRONMENT and non-console.@@ -526,13 +532,29 @@ export default function AuthenticatedRoute() {openClockEntry={openClockEntry}pinnedInUser={pinnedInUser}timeCardEnabled={timeCardEnabled}+ moreOpen={moreOpen}+ onMoreOpenChange={setMoreOpen}/>- <div className="flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border">+ {/* From lg the shell does not scroll, so the page area stops at the+ screen and each page's own scroller takes the overflow. */}+ <div+ className={cn(+ "flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border lg:max-h-[calc(100dvh-1rem)]",+ showTabBar &&+ "max-md:pb-[calc(54px+env(safe-area-inset-bottom))]"+ )}+ >{/* A company switch stays on the same page. Without the key the pagekeeps its state, so a form still held the previous company'svalues and saving wrote them to the new one. */}<Outlet key={companyId} /></div>+ <MesTabBar+ activeEvents={activeEvents}+ activeMaintenanceCount={activeMaintenanceCount}+ moreOpen={moreOpen}+ onMoreOpenChange={setMoreOpen}+ /><ShortcutHelp />{timeCardEnabled && (<Suspense fallback={null}>diff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsxindex b3d6fd7e7c..92e8400d61 100644--- a/apps/mes/app/routes/x+/active.tsx+++ b/apps/mes/app/routes/x+/active.tsx@@ -3,20 +3,16 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import {- Button,- Heading,- Input,- SidebarTrigger,- useViewport-} from "@carbon/react";+import { Button, Input, useViewport } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo, useRef, useState } from "react";-import { LuSearch, LuTriangleAlert } from "react-icons/lu";+import { LuSearch } from "react-icons/lu";import type { ImperativePanelHandle } from "react-resizable-panels";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import { OperationsList } from "~/components";+import { MesAppBar } from "~/components/MesAppBar";+import { MesEmptyState } from "~/components/MesEmptyState";import { getActiveJobOperationsByEmployee } from "~/services/operations.service";import { makeDurations } from "~/utils/durations";import type { Handle } from "~/utils/handle";@@ -70,18 +66,11 @@ export default function ActiveRoute() {}, [operations, searchTerm]);return (- <div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Active</Trans>- </Heading>- </div>- </header>+ <div className="flex flex-col flex-1 min-h-0">+ <MesAppBar kind="root" title={<Trans>Active</Trans>} /><main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent">- <div className="w-full p-4 h-[var(--header-height)]">+ <div className="w-full p-4 h-[var(--header-height)] max-md:h-auto max-md:pb-0"><div className="relative"><div className="flex justify-between gap-4"><div className="flex flex-grow">@@ -97,30 +86,24 @@ export default function ActiveRoute() {</div></div>{filteredOperations.length > 0 ? (- <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4">+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4 max-md:pt-3"><OperationsList key="active" operations={filteredOperations} /></div>) : searchTerm ? (- <div className="flex flex-col flex-1 w-full h-[calc(100%-var(--header-height)*2)] items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No results exist</Trans>- </span>- <Button onClick={() => setSearchTerm("")}>- <Trans>Clear Search</Trans>- </Button>- </div>+ <MesEmptyState+ className="flex-1 w-full h-[calc(100%-var(--header-height)*2)]"+ title={<Trans>No results exist</Trans>}+ action={+ <Button onClick={() => setSearchTerm("")}>+ <Trans>Clear Search</Trans>+ </Button>+ }+ />) : (- <div className="flex flex-col flex-1 w-full h-[calc(100%-var(--header-height)*2)] items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No active operations</Trans>- </span>- </div>+ <MesEmptyState+ className="flex-1 w-full h-[calc(100%-var(--header-height)*2)]"+ title={<Trans>No active operations</Trans>}+ />)}</main></div>diff --git a/apps/mes/app/routes/x+/assigned.tsx b/apps/mes/app/routes/x+/assigned.tsxindex 1988b23373..076979a50f 100644--- a/apps/mes/app/routes/x+/assigned.tsx+++ b/apps/mes/app/routes/x+/assigned.tsx@@ -9,13 +9,12 @@ import {Button,CarbonPulse,ClientOnly,- Heading,+ IconButton,Input,Popover,PopoverContent,PopoverTrigger,Separator,- SidebarTrigger,Switch,ToggleGroup,ToggleGroupItem,@@ -36,6 +35,7 @@ import { useLoaderData } from "react-router";import { OperationsList } from "~/components";import type { Column, DisplaySettings, Item } from "~/components/Kanban";import { Kanban } from "~/components/Kanban";+import { MesAppBar } from "~/components/MesAppBar";import { userContext } from "~/context";import {getJobOperationsAssignedToEmployee,@@ -235,22 +235,106 @@ export default function AssignedRoute() {!searchTerm &&columns.length > 0;+ const displayPopoverContent = (+ <PopoverContent className="w-56">+ <VStack>+ <span className="text-xs font-medium text-muted-foreground">+ <Trans>Columns</Trans>+ </span>+ {[+ {+ key: "emptyWorkCenters",+ label: t`Empty work centers`+ }+ ].map(({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={mergedDisplaySettings[key as keyof DisplaySettings]}+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...defaultDisplaySettings,+ ...prev,+ [key]: checked+ }))+ }+ />+ ))}+ <Separator />+ <span className="text-xs font-medium text-muted-foreground">+ <Trans>Cards</Trans>+ </span>+ {[+ { key: "showCustomer", label: t`Customer` },+ { key: "showDescription", label: t`Description` },+ { key: "showDueDate", label: t`Due Date` },+ { key: "showDuration", label: t`Duration` },+ { key: "showProgress", label: t`Progress` },+ { key: "showStatus", label: t`Status` },+ { key: "showSalesOrder", label: t`Sales Order` },+ { key: "showThumbnail", label: t`Thumbnail` }+ ].map(({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={mergedDisplaySettings[key as keyof DisplaySettings]}+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...defaultDisplaySettings,+ ...prev,+ [key]: checked+ }))+ }+ />+ ))}+ </VStack>+ </PopoverContent>+ );+return (- <div className="flex flex-col flex-1 min-w-0">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] overflow-y-scroll scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Assigned to Me</Trans>- </Heading>- </div>- </header>+ // Phones: the page takes the screen above the tab bar, so the list and+ // the board scroll inside it (see Schedule).+ <div className="flex flex-col flex-1 min-h-0 min-w-0 max-md:h-[calc(100dvh-54px-env(safe-area-inset-bottom))] max-md:flex-none">+ <MesAppBar+ kind="root"+ title={<Trans>Assigned</Trans>}+ desktopTitle={<Trans>Assigned to Me</Trans>}+ desktopClassName="overflow-y-scroll scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent"+ actions={+ <>+ {view === "board" && (+ <Popover>+ <PopoverTrigger asChild>+ <IconButton+ aria-label={t`Display`}+ variant="ghost"+ size="lg"+ icon={<LuSettings2 />}+ />+ </PopoverTrigger>+ {displayPopoverContent}+ </Popover>+ )}+ <IconButton+ aria-label={view === "board" ? t`List view` : t`Board view`}+ variant="ghost"+ size="lg"+ icon={view === "board" ? <LuList /> : <LuKanban />}+ onClick={() => setView(view === "board" ? "list" : "board")}+ />+ </>+ }+ />- <main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent">- <div className="w-full px-4 h-[var(--header-height)] flex items-center">+ {/* Phones: a column so the board fills what the toolbar leaves and+ each column scrolls under its header (see Schedule). */}+ <main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent max-md:flex max-md:flex-col">+ <div className="w-full px-4 h-[var(--header-height)] flex items-center max-md:h-auto max-md:pt-3"><div className="relative w-full"><div className="flex justify-between gap-4">- <div className="flex flex-grow">+ <div className="flex flex-grow min-w-0"><LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" /><Inputvalue={searchTerm}@@ -259,7 +343,7 @@ export default function AssignedRoute() {className="pl-8"/></div>- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 max-md:hidden">{view === "board" && (<Popover><PopoverTrigger asChild>@@ -271,69 +355,7 @@ export default function AssignedRoute() {<Trans>Display</Trans></Button></PopoverTrigger>- <PopoverContent className="w-56">- <VStack>- <span className="text-xs font-medium text-muted-foreground">- <Trans>Columns</Trans>- </span>- {[- {- key: "emptyWorkCenters",- label: t`Empty work centers`- }- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- mergedDisplaySettings[- key as keyof DisplaySettings- ]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...defaultDisplaySettings,- ...prev,- [key]: checked- }))- }- />- ))}- <Separator />- <span className="text-xs font-medium text-muted-foreground">- <Trans>Cards</Trans>- </span>- {[- { key: "showCustomer", label: t`Customer` },- { key: "showDescription", label: t`Description` },- { key: "showDueDate", label: t`Due Date` },- { key: "showDuration", label: t`Duration` },- { key: "showProgress", label: t`Progress` },- { key: "showStatus", label: t`Status` },- { key: "showSalesOrder", label: t`Sales Order` },- { key: "showThumbnail", label: t`Thumbnail` }- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- mergedDisplaySettings[- key as keyof DisplaySettings- ]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...defaultDisplaySettings,- ...prev,- [key]: checked- }))- }- />- ))}- </VStack>- </PopoverContent>+ {displayPopoverContent}</Popover>)}<ToggleGroup@@ -365,7 +387,7 @@ export default function AssignedRoute() {}>{() => (- <div className="flex flex-grow items-stretch overflow-hidden relative">+ <div className="flex flex-grow items-stretch overflow-hidden relative max-md:min-h-0"><div className="flex flex-1 min-h-full w-full relative"><Kanbancolumns={columns}diff --git a/apps/mes/app/routes/x+/batch.$batchId.tsx b/apps/mes/app/routes/x+/batch.$batchId.tsxindex c8283c64d7..a62c20a9db 100644--- a/apps/mes/app/routes/x+/batch.$batchId.tsx+++ b/apps/mes/app/routes/x+/batch.$batchId.tsx@@ -30,5 +30,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- throw redirect(path.to.operation(firstMember.id));+ throw redirect(+ path.to.operation(firstMember.id) + new URL(request.url).search+ );}diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsxindex 2532abd56d..90b2eab985 100644--- a/apps/mes/app/routes/x+/complete.tsx+++ b/apps/mes/app/routes/x+/complete.tsx@@ -20,6 +20,7 @@ import {finishJobOperation,insertProductionQuantity} from "~/services/operations.service";+import { readOrigin, withOrigin } from "~/utils/origin";import { path } from "~/utils/path";const log = getLogger("mes");@@ -103,6 +104,8 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}+ // The page the operation was opened from; finishing returns there.+ const origin = readOrigin(formData);const serviceRole = await getCarbonServiceRole();// Get current job operation and production quantities to check if operation will be finished@@ -234,7 +237,7 @@ export async function action({ request }: ActionFunctionArgs) {}return redirect(- path.to.operations,+ origin ?? path.to.operations,await flash(request, {...success("Operation finished successfully"),flash: "success"@@ -309,7 +312,7 @@ export async function action({ request }: ActionFunctionArgs) {}return redirect(- path.to.operations,+ origin ?? path.to.operations,await flash(request, {...success("Operation finished successfully"),flash: "success"@@ -317,7 +320,8 @@ export async function action({ request }: ActionFunctionArgs) {);}- return redirect(`${path.to.operation(validation.data.jobOperationId)}`);+ const operationPath = path.to.operation(validation.data.jobOperationId);+ return redirect(withOrigin(operationPath, origin));} else {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migrationconst { trackedEntityId, trackingType, ...d } = validation.data;@@ -380,7 +384,7 @@ export async function action({ request }: ActionFunctionArgs) {}return redirect(- path.to.operations,+ origin ?? path.to.operations,await flash(request, {...success("Operation finished successfully"),flash: "success"diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsxindex e1f34667e1..493b835957 100644--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx@@ -11,11 +11,21 @@ import {CardContent,CardHeader,CardTitle,+ ClientOnly,+ cn,generateHTML,Heading,HStack,IconButton,+ isRichTextEmpty,type JSONContent,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalTitle,SidebarTrigger,Status,useDisclosure,@@ -23,7 +33,7 @@ import {} from "@carbon/react";import { groupBy, isUnaffectedByNavigation } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { BsExclamationSquareFill } from "react-icons/bs";import { FaCheck, FaPause, FaPlay } from "react-icons/fa6";import { LuArrowLeft, LuCheck, LuCirclePlus, LuX } from "react-icons/lu";@@ -41,6 +51,7 @@ import EmployeeAvatar from "~/components/EmployeeAvatar";import { MaintenanceAddPartModal } from "~/components/MaintenanceDispatch";import MaintenanceOeeImpact from "~/components/MaintenanceOeeImpact";import MaintenanceSeverity from "~/components/MaintenanceSeverity";+import { MesAppBar } from "~/components/MesAppBar";import {getActiveMaintenanceEventByEmployee,getMaintenanceDispatch,@@ -213,6 +224,7 @@ export default function MaintenanceDetailRoute() {const fetcher = useFetcher();const deleteFetcher = useFetcher();const addPartModal = useDisclosure();+ const [confirmComplete, setConfirmComplete] = useState(false);const [allItems] = useItems();// Create item options for the combobox@@ -255,7 +267,14 @@ export default function MaintenanceDetailRoute() {return (<div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">+ <MesAppBar+ kind="pushed"+ title={dispatch.maintenanceDispatchId}+ subtitle={<Trans>Maintenance</Trans>}+ back={{ to: path.to.maintenance }}+ desktop={null}+ />+ <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card max-md:hidden"><div className="flex items-center gap-2 px-2 w-full justify-between"><HStack><SidebarTrigger />@@ -277,15 +296,24 @@ export default function MaintenanceDetailRoute() {<main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent p-4"><VStack spacing={4} className="max-w-2xl mx-auto">+ <div className="flex w-full items-center justify-between md:hidden">+ <MaintenanceStatus status={dispatch.status} />+ {getPriorityIcon(+ dispatch.priority as (typeof maintenanceDispatchPriority)[number]+ )}+ </div>{/* Work Center & OEE Impact */}<Card className="w-full">- <CardHeader>+ <CardHeader className="max-md:hidden"><CardTitle className="text-sm text-muted-foreground font-normal"><Trans>Work Center</Trans></CardTitle></CardHeader><CardContent><VStack spacing={2} className="items-start">+ <span className="hidden text-xs text-muted-foreground max-md:block">+ <Trans>Work Center</Trans>+ </span><span className="text-lg font-semibold">{dispatch.workCenter?.name ?? t`Unknown`}</span>@@ -304,21 +332,33 @@ export default function MaintenanceDetailRoute() {{/* Description */}{dispatch.content &&Object.keys(dispatch.content as object).length > 0 && (- <Card className="w-full">+ <Card+ className={cn(+ "w-full",+ isRichTextEmpty(dispatch.content as JSONContent) &&+ "max-md:hidden"+ )}+ ><CardHeader><CardTitle className="text-sm text-muted-foreground font-normal"><Trans>Description</Trans></CardTitle></CardHeader><CardContent>- <div- className="prose dark:prose-invert prose-sm max-w-none"- dangerouslySetInnerHTML={{- __html: generateHTML(- (dispatch.content ?? {}) as JSONContent- )- }}- />+ {/* generateHTML is empty on the server, and hydration keeps that+ empty markup, so the description renders on the client only. */}+ <ClientOnly fallback={null}>+ {() => (+ <div+ className="prose dark:prose-invert prose-sm max-w-none"+ dangerouslySetInnerHTML={{+ __html: generateHTML(+ (dispatch.content ?? {}) as JSONContent+ )+ }}+ />+ )}+ </ClientOnly></CardContent></Card>)}@@ -326,16 +366,22 @@ export default function MaintenanceDetailRoute() {{/* Time Tracking Controls */}{!isCompleted && (<Card className="w-full">- <CardHeader>+ <CardHeader className="max-md:hidden"><CardTitle><span className="text-sm text-muted-foreground"><Trans>Time Worked: {formatDuration(totalDuration)}</Trans></span></CardTitle></CardHeader>- <CardContent className="pt-6">+ <CardContent className="pt-6 max-md:pt-4">+ <p className="mb-3 text-xs text-muted-foreground md:hidden">+ <Trans>Time Worked: {formatDuration(totalDuration)}</Trans>+ </p><VStack spacing={4}>- <HStack spacing={4} className="justify-center w-full">+ <HStack+ spacing={4}+ className="justify-center w-full max-md:flex-col max-md:space-x-0 max-md:gap-3"+ ><ValidatedFormmethod="post"action={path.to.maintenanceEvent}@@ -375,6 +421,8 @@ export default function MaintenanceDetailRoute() {</button></ValidatedForm>+ {/* Desktop completes on click, as before; phones confirm+ first (the button below). */}<ValidatedFormmethod="post"action={path.to.maintenanceEvent}@@ -385,18 +433,30 @@ export default function MaintenanceDetailRoute() {dispatchId: dispatch.id,eventId: myActiveEvent?.id}}+ className="max-md:hidden"><Hidden name="dispatchId" value={dispatch.id} /><Hidden name="eventId" value={myActiveEvent?.id ?? ""} /><Hidden name="action" value="Complete" /><buttontype="submit"+ aria-label={t`Complete`}disabled={fetcher.state !== "idle"}className="group size-24 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:scale-105 transition-all text-accent-foreground text-3xl disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-30"><FaCheck className="group-hover:scale-110" /></button></ValidatedForm>+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuCheck />}+ isDisabled={fetcher.state !== "idle"}+ onClick={() => setConfirmComplete(true)}+ className="hidden w-full max-md:flex max-md:h-12"+ >+ <Trans>Complete</Trans>+ </Button></HStack></VStack></CardContent>@@ -459,6 +519,7 @@ export default function MaintenanceDetailRoute() {<Buttonvariant="secondary"leftIcon={<LuCirclePlus />}+ className="max-md:h-11"onClick={addPartModal.onOpen}><Trans>Add</Trans>@@ -492,6 +553,7 @@ export default function MaintenanceDetailRoute() {type="submit"aria-label={t`Remove part`}size="sm"+ className="max-md:size-11"variant="ghost"icon={<LuX className="h-4 w-4" />}isDisabled={deleteFetcher.state !== "idle"}@@ -553,15 +615,19 @@ export default function MaintenanceDetailRoute() {<span className="text-sm font-medium mb-2 block">{(dispatch.procedure as any)?.name}</span>- <div- className="prose dark:prose-invert prose-sm max-w-none"- dangerouslySetInnerHTML={{- __html: generateHTML(- ((dispatch.procedure as any).content ??- {}) as JSONContent- )- }}- />+ <ClientOnly fallback={null}>+ {() => (+ <div+ className="prose dark:prose-invert prose-sm max-w-none"+ dangerouslySetInnerHTML={{+ __html: generateHTML(+ ((dispatch.procedure as any).content ??+ {}) as JSONContent+ )+ }}+ />+ )}+ </ClientOnly></CardContent></Card>)}@@ -593,6 +659,48 @@ export default function MaintenanceDetailRoute() {onClose={addPartModal.onClose}/>)}+ {confirmComplete && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) setConfirmComplete(false);+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>{t`Complete ${dispatch.maintenanceDispatchId}?`}</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <Trans>This marks the dispatch as completed.</Trans>+ </ModalBody>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => setConfirmComplete(false)}+ >+ <Trans>Cancel</Trans>+ </Button>+ <Button+ isLoading={fetcher.state !== "idle"}+ onClick={() => {+ const formData = new FormData();+ formData.append("action", "Complete");+ formData.append("dispatchId", dispatch.id);+ formData.append("eventId", myActiveEvent?.id ?? "");+ fetcher.submit(formData, {+ method: "post",+ action: path.to.maintenanceEvent+ });+ setConfirmComplete(false);+ }}+ >+ <Trans>Complete</Trans>+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ )}</div>);}diff --git a/apps/mes/app/routes/x+/finish.tsx b/apps/mes/app/routes/x+/finish.tsxindex 8676212719..131a3fed0c 100644--- a/apps/mes/app/routes/x+/finish.tsx+++ b/apps/mes/app/routes/x+/finish.tsx@@ -13,6 +13,7 @@ import { data } from "react-router";import { getDatabaseClient } from "~/services/database.server";import { finishValidator } from "~/services/models";import { finishJobOperation } from "~/services/operations.service";+import { readOrigin } from "~/utils/origin";import { path } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -48,7 +49,7 @@ export async function action({ request }: ActionFunctionArgs) {}throw redirect(- path.to.operations,+ readOrigin(formData) ?? path.to.operations,await flash(request, success("Operation finished successfully")));}diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsxindex 74e692c653..b6aaf7640a 100644--- a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx@@ -18,6 +18,7 @@ import {postBulkCompletion,postSerialCompletions} from "~/services/quality.server";+import { readOrigin, withOrigin } from "~/utils/origin";import { path } from "~/utils/path";// Completions posted here insert productionQuantity rows, whose SQL interceptor@@ -68,7 +69,9 @@ export async function action({ request, params }: ActionFunctionArgs) {laborProductionEventId,machineProductionEventId};- const returnTo = path.to.inspection(operationId);+ // The page the inspection was opened from; Back keeps returning there.+ const origin = readOrigin(formData);+ const returnTo = withOrigin(path.to.inspection(operationId), origin);const fail = async (err: unknown, message: string): Promise<never> => {throw redirect(returnTo, await flash(request, error(err, message)));};diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsxindex b47a72e827..ccae62b944 100644--- a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx+++ b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx@@ -24,6 +24,7 @@ import {postBulkCompletion,postSerialCompletions} from "~/services/quality.server";+import { readOrigin, withOrigin } from "~/utils/origin";import { path } from "~/utils/path";// One decision surface: the quality verdict carries its physical outcome.@@ -63,7 +64,9 @@ export async function action({ request, params }: ActionFunctionArgs) {laborProductionEventId,machineProductionEventId};- const returnTo = path.to.inspection(operationId);+ // The page the inspection was opened from; Back keeps returning there.+ const origin = readOrigin(formData);+ const returnTo = withOrigin(path.to.inspection(operationId), origin);const fail = async (err: unknown, message: string): Promise<never> => {throw redirect(returnTo, await flash(request, error(err, message)));};@@ -391,7 +394,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (warnings.length > 0) {throw redirect(- willBeFinished ? path.to.operations : returnTo,+ willBeFinished ? (origin ?? path.to.operations) : returnTo,await flash(request,error(null, `${message}, but ${warnings.join("; ")}`)@@ -400,7 +403,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}throw redirect(- willBeFinished ? path.to.operations : returnTo,+ willBeFinished ? (origin ?? path.to.operations) : returnTo,await flash(request, success(message)));}diff --git a/apps/mes/app/routes/x+/job.$jobId.tsx b/apps/mes/app/routes/x+/job.$jobId.tsxindex 439c085462..c0f7b6bc8d 100644--- a/apps/mes/app/routes/x+/job.$jobId.tsx+++ b/apps/mes/app/routes/x+/job.$jobId.tsx@@ -7,10 +7,12 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";import { Heading, SidebarTrigger } from "@carbon/react";import { redirect } from "@carbon/utils";+import { Trans } from "@lingui/react/macro";import { LuArrowLeft } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { Link, useLoaderData } from "react-router";import { JobDag } from "~/components/JobDag";+import { MesAppBar } from "~/components/MesAppBar";import {getJobOperationDependencies,getJobOperations@@ -69,7 +71,14 @@ export default function JobDagRoute() {return (<div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">+ <MesAppBar+ kind="pushed"+ title={readableId}+ subtitle={<Trans>Jobs</Trans>}+ back={{ to: path.to.jobs }}+ desktop={null}+ />+ <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card max-md:hidden"><div className="flex items-center gap-2 px-2"><SidebarTrigger /><Linkdiff --git a/apps/mes/app/routes/x+/jobs.tsx b/apps/mes/app/routes/x+/jobs.tsxindex a87b5dc426..052903f10c 100644--- a/apps/mes/app/routes/x+/jobs.tsx+++ b/apps/mes/app/routes/x+/jobs.tsx@@ -7,9 +7,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";import {Button,- Heading,Input,- SidebarTrigger,Status,Table,Tbody,@@ -17,15 +15,18 @@ import {Th,Thead,Tr,+ useViewport,VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useMemo, useState } from "react";-import { LuSearch, LuTriangleAlert } from "react-icons/lu";+import { LuSearch } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { Link, useLoaderData } from "react-router";import { DateTime } from "~/components";import EmployeeAvatar from "~/components/EmployeeAvatar";+import { MesAppBar } from "~/components/MesAppBar";+import { MesEmptyState } from "~/components/MesEmptyState";import { userContext } from "~/context";import {getOpenJobs,@@ -105,6 +106,7 @@ function JobStatus({ status }: { status: string | null }) {}export default function JobsRoute() {+ const { isPhone } = useViewport();const { t } = useLingui();const { jobs, trackedEntities } = useLoaderData<typeof loader>();const [searchTerm, setSearchTerm] = useState("");@@ -121,15 +123,12 @@ export default function JobsRoute() {}, [jobs, searchTerm]);return (- <div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Open Jobs</Trans>- </Heading>- </div>- </header>+ <div className="flex flex-col flex-1 min-h-0">+ <MesAppBar+ kind="root"+ title={<Trans>Jobs</Trans>}+ desktopTitle={<Trans>Open Jobs</Trans>}+ /><main className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent"><div className="p-4">@@ -144,109 +143,166 @@ export default function JobsRoute() {</div>{filteredJobs.length > 0 ? (- <Table>- <Thead>- <Tr>- <Th>- <Trans>Job</Trans>- </Th>- <Th>- <Trans>Item</Trans>- </Th>- <Th>- <Trans>Quantity</Trans>- </Th>- <Th>- <Trans>Tracking</Trans>- </Th>- <Th>- <Trans>Assignee</Trans>- </Th>- <Th>- <Trans>Due Date</Trans>- </Th>- <Th>- <Trans>Deadline</Trans>- </Th>- <Th>- <Trans>Status</Trans>- </Th>- </Tr>- </Thead>- <Tbody>- {filteredJobs.map((job) => {- const trackingId = job.jobMakeMethodId- ? trackedEntities[job.jobMakeMethodId]- : null;-- return (- <Tr key={job.id}>- <Td>+ <>+ {isPhone ? (+ <ul className="flex flex-col -mx-4 border-y divide-y">+ {filteredJobs.map((job) => {+ const trackingId = job.jobMakeMethodId+ ? trackedEntities[job.jobMakeMethodId]+ : null;++ return (+ <li key={job.id}><Linkto={path.to.jobDag(job.id)}- className="font-medium text-foreground hover:underline"+ className="flex flex-col gap-1 px-4 py-3 min-h-11">- {job.jobId}- </Link>- </Td>- <Td>- <VStack spacing={0}>- <span>{job.itemReadableIdWithRevision ?? "—"}</span>- {job.name && (- <span className="text-xs text-muted-foreground">- {job.name}+ <div className="flex items-center justify-between gap-2">+ <span className="flex min-w-0 items-baseline gap-2">+ <span className="font-medium text-foreground">+ {job.jobId}+ </span>+ {trackingId && (+ <span className="truncate text-xs text-muted-foreground">+ {trackingId}+ </span>+ )}+ </span>+ <span className="flex shrink-0 items-center gap-2">+ <EmployeeAvatar employeeId={job.assignee} />+ <span className="text-sm text-foreground tabular-nums">+ {job.quantity ?? "—"}+ </span>+ </span>+ </div>+ <div className="flex min-w-0 gap-1 text-sm">+ <span className="shrink-0">+ {job.itemReadableIdWithRevision ?? "—"}</span>- )}- </VStack>- </Td>- <Td className="text-muted-foreground">- {job.quantity ?? "—"}- </Td>- <Td className="text-muted-foreground">- {trackingId ?? "—"}- </Td>- <Td>- <EmployeeAvatar employeeId={job.assignee} />- </Td>- <Td className="text-muted-foreground">- <DateTime- value={job.dueDate}- variant="date"- fallback="—"- />- </Td>- <Td className="text-muted-foreground">- {job.deadlineType ?? "—"}- </Td>- <Td>- <JobStatus status={job.status} />- </Td>- </Tr>- );- })}- </Tbody>- </Table>+ {job.name && (+ <span className="truncate text-muted-foreground">+ · {job.name}+ </span>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">+ <JobStatus status={job.status} />+ <span>{job.deadlineType ?? "—"}</span>+ <DateTime+ value={job.dueDate}+ variant="date"+ fallback="—"+ />+ </div>+ </Link>+ </li>+ );+ })}+ </ul>+ ) : (+ <div>+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Job</Trans>+ </Th>+ <Th>+ <Trans>Item</Trans>+ </Th>+ <Th>+ <Trans>Quantity</Trans>+ </Th>+ <Th>+ <Trans>Tracking</Trans>+ </Th>+ <Th>+ <Trans>Assignee</Trans>+ </Th>+ <Th>+ <Trans>Due Date</Trans>+ </Th>+ <Th>+ <Trans>Deadline</Trans>+ </Th>+ <Th>+ <Trans>Status</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {filteredJobs.map((job) => {+ const trackingId = job.jobMakeMethodId+ ? trackedEntities[job.jobMakeMethodId]+ : null;++ return (+ <Tr key={job.id}>+ <Td>+ <Link+ to={path.to.jobDag(job.id)}+ className="font-medium text-foreground hover:underline"+ >+ {job.jobId}+ </Link>+ </Td>+ <Td>+ <VStack spacing={0}>+ <span>+ {job.itemReadableIdWithRevision ?? "—"}+ </span>+ {job.name && (+ <span className="text-xs text-muted-foreground">+ {job.name}+ </span>+ )}+ </VStack>+ </Td>+ <Td className="text-muted-foreground">+ {job.quantity ?? "—"}+ </Td>+ <Td className="text-muted-foreground">+ {trackingId ?? "—"}+ </Td>+ <Td>+ <EmployeeAvatar employeeId={job.assignee} />+ </Td>+ <Td className="text-muted-foreground">+ <DateTime+ value={job.dueDate}+ variant="date"+ fallback="—"+ />+ </Td>+ <Td className="text-muted-foreground">+ {job.deadlineType ?? "—"}+ </Td>+ <Td>+ <JobStatus status={job.status} />+ </Td>+ </Tr>+ );+ })}+ </Tbody>+ </Table>+ </div>+ )}+ </>) : searchTerm ? (- <div className="flex flex-col items-center justify-center gap-4 py-16">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No results</Trans>- </span>- <Button onClick={() => setSearchTerm("")}>- <Trans>Clear Search</Trans>- </Button>- </div>+ <MesEmptyState+ className="py-16"+ title={<Trans>No results</Trans>}+ action={+ <Button onClick={() => setSearchTerm("")}>+ <Trans>Clear Search</Trans>+ </Button>+ }+ />) : (- <div className="flex flex-col items-center justify-center gap-4 py-16">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No open jobs</Trans>- </span>- </div>+ <MesEmptyState+ className="py-16"+ title={<Trans>No open jobs</Trans>}+ />)}</div></main>diff --git a/apps/mes/app/routes/x+/maintenance.tsx b/apps/mes/app/routes/x+/maintenance.tsxindex 02fc7f69b3..724bdd503e 100644--- a/apps/mes/app/routes/x+/maintenance.tsx+++ b/apps/mes/app/routes/x+/maintenance.tsx@@ -11,9 +11,7 @@ import {CardDescription,CardHeader,CardTitle,- Heading,HStack,- SidebarTrigger,Tabs,TabsContent,TabsList,@@ -21,9 +19,8 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { BsExclamationSquareFill } from "react-icons/bs";-import { LuTriangleAlert } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { Link, useLoaderData } from "react-router";import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";@@ -32,6 +29,8 @@ import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";import EmployeeAvatar from "~/components/EmployeeAvatar";import type { ColumnFilter } from "~/components/Filter";import { ActiveFilters, Filter, useFilters } from "~/components/Filter";+import { MesAppBar } from "~/components/MesAppBar";+import { MesEmptyState } from "~/components/MesEmptyState";import SearchFilter from "~/components/SearchFilter";import { userContext } from "~/context";import { useUrlParams } from "~/hooks";@@ -250,16 +249,30 @@ function MaintenanceCard({ dispatch }: { dispatch: MaintenanceDispatch }) {className={`h-2 w-2 rounded-full ${getStatusColor(dispatch.status)}`}/></HStack>- {getPriorityIcon(- dispatch.priority as (typeof maintenanceDispatchPriority)[number]- )}+ <HStack spacing={2}>+ <div className="hidden items-center gap-2 max-md:flex">+ <Badge+ variant={getOeeImpactColor(dispatch.oeeImpact ?? "No Impact")}+ >+ {dispatch.oeeImpact ?? t`No Impact`}+ </Badge>+ {dispatch.assignee && (+ <span className="text-xs">+ <EmployeeAvatar employeeId={dispatch.assignee} />+ </span>+ )}+ </div>+ {getPriorityIcon(+ dispatch.priority as (typeof maintenanceDispatchPriority)[number]+ )}+ </HStack></HStack><CardTitle className="text-base">{dispatch.workCenterName}</CardTitle><CardDescription className="text-xs">{dispatch.severity}</CardDescription></CardHeader>- <CardContent>+ <CardContent className="max-md:hidden"><HStack className="justify-between"><Badgevariant={getOeeImpactColor(dispatch.oeeImpact ?? "No Impact")}@@ -284,19 +297,17 @@ function EmptyState({onClear?: () => void;}) {return (- <div className="flex flex-col flex-1 w-full h-[calc(100dvh-var(--header-height)*2-40px)] items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- {message}- </span>- {onClear && (- <Button onClick={onClear}>- <Trans>Clear Search</Trans>- </Button>- )}- </div>+ <MesEmptyState+ className="flex-1 w-full h-[calc(100dvh-var(--header-height)*2-40px)]"+ title={message}+ action={+ onClear ? (+ <Button onClick={onClear}>+ <Trans>Clear Search</Trans>+ </Button>+ ) : undefined+ }+ />);}@@ -316,6 +327,14 @@ export default function MaintenanceRoute() {const { dispatches, assignedDispatches, workCenters } =useLoaderData<typeof loader>();const [activeTab, setActiveTab] = useState("all");+ // Phones: the tab row scrolls sideways; keep the active tab in view.+ const tabsListRef = useRef<HTMLDivElement>(null);+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run when the active tab changes+ useEffect(() => {+ tabsListRef.current+ ?.querySelector<HTMLElement>('[data-state="active"]')+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [activeTab]);const [params] = useUrlParams();const { hasFilters, clearFilters } = useFilters();const currentFilters = params.getAll("filter").filter(Boolean);@@ -405,23 +424,19 @@ export default function MaintenanceRoute() {const activeDispatches = getActiveDispatches();return (- <div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Maintenance</Trans>- </Heading>- </div>- </header>+ <div className="flex flex-col flex-1 min-h-0">+ <MesAppBar kind="root" title={<Trans>Maintenance</Trans>} /><main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent"><div className="w-full p-4"><VStack spacing={4}><div className="w-full"><Tabs value={activeTab} onValueChange={setActiveTab}>- <HStack className="justify-between w-full">- <TabsList>+ <HStack className="justify-between w-full max-md:flex-col max-md:items-stretch max-md:gap-2">+ <TabsList+ ref={tabsListRef}+ className="max-md:-mx-4 max-md:w-[calc(100%+2rem)] max-md:justify-start max-md:overflow-x-auto max-md:px-4 scrollbar-hide max-md:scroll-fade-x"+ ><TabsTrigger value="all"><Trans>All</Trans>{dispatches.length > 0 && (diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsxindex 0086af7701..4ecd2a691d 100644--- a/apps/mes/app/routes/x+/operations.tsx+++ b/apps/mes/app/routes/x+/operations.tsx@@ -12,14 +12,13 @@ import {Button,CarbonPulse,ClientOnly,- Heading,+ cn,HStack,IconButton,Popover,PopoverContent,PopoverTrigger,Separator,- SidebarTrigger,Switch,toast,useInterval,@@ -36,7 +35,7 @@ import {} from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useMemo, useState } from "react";-import { LuFactory, LuSettings2, LuTriangleAlert, LuX } from "react-icons/lu";+import { LuFactory, LuSettings2, LuX } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { data, useFetcher, useLoaderData } from "react-router";@@ -44,6 +43,8 @@ import type { ColumnFilter } from "~/components/Filter";import { ActiveFilters, Filter, useFilters } from "~/components/Filter";import type { Column, DisplaySettings, Item } from "~/components/Kanban";import { Kanban } from "~/components/Kanban";+import { MesAppBar } from "~/components/MesAppBar";+import { MesEmptyState } from "~/components/MesEmptyState";import SearchFilter from "~/components/SearchFilter";import { userContext } from "~/context";import { useUrlParams, useUser } from "~/hooks";@@ -432,7 +433,7 @@ export default function ScheduleRoute() {return (<ClientOnlyfallback={- <div className="flex h-dvh w-[calc(100dvw-var(--sidebar-width-icon))] items-center justify-center">+ <div className="flex w-full flex-1 items-center justify-center"><CarbonPulse /></div>}@@ -566,47 +567,123 @@ function KanbanSchedule() {];}, [processes, workCenters, availableTags, people, t]);+ const showStationChip =+ !!peopleStation &&+ !currentFilters.some((filter) => filter.startsWith("workCenterId:"));++ const renderStationChip = (className?: string) =>+ showStationChip && peopleStation ? (+ <HStack+ spacing={0}+ className={cn("rounded-md border border-border bg-card", className)}+ >+ <span className="flex items-center gap-1.5 px-2 py-1 text-sm whitespace-nowrap">+ <LuFactory className="flex-shrink-0" />+ <Trans>Your station: {peopleStation.name}</Trans>+ </span>+ <IconButton+ aria-label={t`Clear station default`}+ icon={<LuX />}+ variant="ghost"+ size="sm"+ onClick={() =>+ peopleOverrideFetcher.submit(+ { date: peopleDate ?? "" },+ { method: "post", action: path.to.peopleOverride }+ )+ }+ />+ </HStack>+ ) : null;++ const displayPopoverContent = (+ <PopoverContent className="w-56">+ <VStack>+ <span className="text-xs font-medium text-muted-foreground">+ <Trans>Columns</Trans>+ </span>+ {[{ key: "emptyWorkCenters", label: t`Empty work centers` }].map(+ ({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={mergedDisplaySettings[key as keyof DisplaySettings]}+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...defaultDisplaySettings,+ ...prev,+ [key]: checked+ }))+ }+ />+ )+ )}+ <Separator />+ <span className="text-xs font-medium text-muted-foreground">+ <Trans>Cards</Trans>+ </span>+ {[+ { key: "showCustomer", label: t`Customer` },+ { key: "showDescription", label: t`Description` },+ { key: "showDueDate", label: t`Due Date` },+ { key: "showDuration", label: t`Duration` },+ { key: "showProgress", label: t`Progress` },+ { key: "showStatus", label: t`Status` },+ { key: "showSalesOrder", label: t`Sales Order` },+ { key: "showThumbnail", label: t`Thumbnail` }+ ].map(({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={mergedDisplaySettings[key as keyof DisplaySettings]}+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...defaultDisplaySettings,+ ...prev,+ [key]: checked+ }))+ }+ />+ ))}+ </VStack>+ </PopoverContent>+ );+return (- <div className="flex flex-col flex-1 min-h-0 w-full">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Schedule</Trans>- </Heading>- </div>- </header>+ // Phones: the shell grows with its content, so the page takes the screen+ // above the tab bar itself; each column then scrolls under its header.+ <div className="flex flex-col flex-1 min-h-0 w-full max-md:h-[calc(100dvh-54px-env(safe-area-inset-bottom))] max-md:flex-none">+ <MesAppBar+ kind="root"+ title={<Trans>Schedule</Trans>}+ actions={+ <Popover>+ <PopoverTrigger asChild>+ <IconButton+ aria-label={t`Display`}+ variant="ghost"+ size="lg"+ icon={<LuSettings2 />}+ />+ </PopoverTrigger>+ {displayPopoverContent}+ </Popover>+ }+ /><div className="flex flex-col flex-1 min-h-0 overflow-auto relative">- <HStack className="px-4 py-2 justify-between bg-card border-b border-border">- <HStack>- <SearchFilter param="search" size="sm" placeholder={t`Search`} />+ <HStack className="px-4 py-2 justify-between bg-card border-b border-border max-md:gap-2 max-md:space-x-0 max-md:pt-3">+ <HStack className="max-md:min-w-0 max-md:flex-1 max-md:space-x-0 max-md:gap-2">+ <SearchFilter+ param="search"+ size="sm"+ placeholder={t`Search`}+ groupClassName="max-md:min-w-0 max-md:flex-1"+ className="max-md:w-full"+ /><Filter filters={filters} />- {peopleStation &&- !currentFilters.some((filter) =>- filter.startsWith("workCenterId:")- ) && (- <HStack- spacing={0}- className="rounded-md border border-border bg-card"- >- <span className="flex items-center gap-1.5 px-2 py-1 text-sm whitespace-nowrap">- <LuFactory className="flex-shrink-0" />- <Trans>Your station: {peopleStation.name}</Trans>- </span>- <IconButton- aria-label={t`Clear station default`}- icon={<LuX />}- variant="ghost"- size="sm"- onClick={() =>- peopleOverrideFetcher.submit(- { date: peopleDate ?? "" },- { method: "post", action: path.to.peopleOverride }- )- }- />- </HStack>- )}+ {renderStationChip("max-md:hidden")}</HStack><Popover>@@ -614,71 +691,22 @@ function KanbanSchedule() {<ButtonleftIcon={<LuSettings2 />}variant="secondary"- className="border-dashed border-border"+ className="border-dashed border-border max-md:hidden"><Trans>Display</Trans></Button></PopoverTrigger>- <PopoverContent className="w-56">- <VStack>- <span className="text-xs font-medium text-muted-foreground">- <Trans>Columns</Trans>- </span>- {[- { key: "emptyWorkCenters", label: t`Empty work centers` }- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- mergedDisplaySettings[key as keyof DisplaySettings]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...defaultDisplaySettings,- ...prev,- [key]: checked- }))- }- />- ))}- <Separator />- <span className="text-xs font-medium text-muted-foreground">- <Trans>Cards</Trans>- </span>- {[- { key: "showCustomer", label: t`Customer` },- { key: "showDescription", label: t`Description` },- { key: "showDueDate", label: t`Due Date` },- { key: "showDuration", label: t`Duration` },- { key: "showProgress", label: t`Progress` },- { key: "showStatus", label: t`Status` },- { key: "showSalesOrder", label: t`Sales Order` },- { key: "showThumbnail", label: t`Thumbnail` }- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- mergedDisplaySettings[key as keyof DisplaySettings]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...defaultDisplaySettings,- ...prev,- [key]: checked- }))- }- />- ))}- </VStack>- </PopoverContent>+ {displayPopoverContent}</Popover></HStack>+ {(showStationChip || currentFilters.length > 0) && (+ <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide scroll-fade-x border-b border-border bg-card px-4 py-1.5 md:hidden [&>*]:shrink-0">+ {renderStationChip()}+ {currentFilters.length > 0 && <ActiveFilters filters={filters} />}+ </div>+ )}{currentFilters.length > 0 && (- <HStack className="px-4 py-1.5 justify-between bg-card border-b border-border w-full">+ <HStack className="px-4 py-1.5 justify-between bg-card border-b border-border w-full max-md:hidden"><HStack><ActiveFilters filters={filters} /></HStack>@@ -695,26 +723,20 @@ function KanbanSchedule() {progressByItemId={progressByOperation}/>) : hasFilters ? (- <div className="flex flex-col w-full h-full items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No results</Trans>- </span>- <Button onClick={clearFilters}>- <Trans>Clear Filters</Trans>- </Button>- </div>+ <MesEmptyState+ className="w-full h-full"+ title={<Trans>No results</Trans>}+ action={+ <Button onClick={clearFilters}>+ <Trans>Clear Filters</Trans>+ </Button>+ }+ />) : (- <div className="flex flex-col w-full h-full items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No work centers exist</Trans>- </span>- </div>+ <MesEmptyState+ className="w-full h-full"+ title={<Trans>No work centers exist</Trans>}+ />)}</div></div>diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.tsxindex 89ca43de69..1178c7d5de 100644--- a/apps/mes/app/routes/x+/picking.$pickingListId.tsx+++ b/apps/mes/app/routes/x+/picking.$pickingListId.tsx@@ -43,7 +43,13 @@ import {} from "@carbon/react";import { isUnaffectedByNavigation } from "@carbon/utils";import { Trans } from "@lingui/react/macro";-import { Suspense, useEffect, useMemo, useState } from "react";+import {+ type ComponentProps,+ Suspense,+ useEffect,+ useMemo,+ useState+} from "react";import {LuCheck,LuChevronDown,@@ -60,6 +66,8 @@ import type {import { Await, useFetcher, useLoaderData } from "react-router";import { Enumerable } from "~/components/Enumerable";import ItemThumbnail from "~/components/ItemThumbnail";+import { MesAppBar } from "~/components/MesAppBar";+import { useMesBottomBar } from "~/components/MesBottomBar";import { PickingListStatus } from "~/components/PickingListStatus";import { ShortPickModal } from "~/components/ShortPickModal";import type { PickingListRecommendation } from "~/services/inventory.service";@@ -125,6 +133,7 @@ type RecommendationsPromise = Promise<>;export default function PickingExecutionRoute() {+ const bottomBarRef = useMesBottomBar();const { pickingList, recommendations } = useLoaderData<typeof loader>();const lines = pickingList.lines ?? [];@@ -160,14 +169,21 @@ export default function PickingExecutionRoute() {return (<div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center justify-between gap-2 border-b bg-card">+ <MesAppBar+ kind="pushed"+ title={pickingList.pickingListId}+ subtitle={<Trans>Picking</Trans>}+ back={{ to: path.to.picking }}+ desktop={null}+ />+ <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center justify-between gap-2 border-b bg-card max-md:hidden"><div className="flex items-center gap-2 px-2"><SidebarTrigger /><Heading size="h4">{pickingList.pickingListId}</Heading><PickingListStatus status={pickingList.status} /></div><div className="flex items-center gap-3 px-3">- <span className="text-sm text-muted-foreground tabular-nums">+ <span className="text-sm text-muted-foreground tabular-nums whitespace-nowrap">{completedCount}/{lines.length} <Trans>lines</Trans></span><PickingListControls@@ -177,13 +193,14 @@ export default function PickingExecutionRoute() {</div></header>- <main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent p-4">+ <main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent p-4 max-md:pb-28"><div className="w-full max-w-5xl mx-auto pb-16"><VStack spacing={4} className="w-full">- {kits.map((kit) => (+ {kits.map((kit, index) => (<PickingKitCardkey={kit.key}kit={kit}+ status={index === 0 ? pickingList.status : undefined}pickingListId={pickingList.id}isLocked={isLocked}recommendations={recommendations}@@ -192,6 +209,22 @@ export default function PickingExecutionRoute() {</VStack></div></main>+ <div+ ref={bottomBarRef}+ data-mes-bottom-bar+ className="fixed inset-x-0 bottom-0 z-20 flex items-center gap-3 border-t border-border bg-card px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] md:hidden"+ >+ <span className="shrink-0 whitespace-nowrap text-sm text-muted-foreground tabular-nums">+ {completedCount}/{lines.length} <Trans>lines</Trans>+ </span>+ <PickingListControls+ pickingListId={pickingList.id}+ status={pickingList.status}+ size="lg"+ finishVariant="primary"+ className="min-w-0 flex-1 [&_button]:w-full [&_button]:h-12"+ />+ </div></div>);}@@ -206,10 +239,16 @@ type FinishStatusResponse = {function PickingListControls({pickingListId,- status+ status,+ size = "md",+ finishVariant = "secondary",+ className}: {pickingListId: string;status: string;+ size?: "md" | "lg";+ finishVariant?: "primary" | "secondary";+ className?: string;}) {const fetcher = useFetcher<FinishStatusResponse>();const isSubmitting = fetcher.state !== "idle";@@ -256,10 +295,10 @@ function PickingListControls({return (<>- <HStack spacing={2}>+ <HStack spacing={2} className={className}>{status === "Draft" && (<Button- size="md"+ size={size}leftIcon={<LuPlay />}isLoading={isSubmitting}isDisabled={isSubmitting}@@ -270,8 +309,8 @@ function PickingListControls({)}{status === "In Progress" && (<Button- size="md"- variant="secondary"+ size={size}+ variant={finishVariant}leftIcon={<LuCheck />}isLoading={isSubmitting}isDisabled={isSubmitting}@@ -379,11 +418,14 @@ function isLineResolved(line: Line) {function PickingKitCard({kit,+ status,pickingListId,isLocked,recommendations}: {kit: Kit;+ /** Phones: the list status, shown in the first kit's header row. */+ status?: ComponentProps<typeof PickingListStatus>["status"];pickingListId: string;isLocked: boolean;recommendations: RecommendationsPromise;@@ -403,10 +445,17 @@ function PickingKitCard({return (<Card><CardHeader>- <CardTitle>- {kit.jobReadableId ?? "Unknown Job"}- {kit.operationName ? ` · ${kit.operationName}` : ""}- </CardTitle>+ <div className="max-md:flex max-md:items-start max-md:justify-between max-md:gap-2">+ <CardTitle>+ {kit.jobReadableId ?? "Unknown Job"}+ {kit.operationName ? ` · ${kit.operationName}` : ""}+ </CardTitle>+ {status ? (+ <span className="shrink-0 md:hidden">+ <PickingListStatus status={status} />+ </span>+ ) : null}+ </div>{kit.workCenterName && (<CardDescription><Enumerable value={kit.workCenterName} />@@ -415,7 +464,7 @@ function PickingKitCard({</CardHeader><CardContent><BarProgress progress={progress} className="mb-4" />- <div className="border rounded-lg">+ <div className="border rounded-lg max-md:-mx-4 max-md:rounded-none max-md:border-x-0 max-md:border-b-0">{kit.lines.map((line, index) => (<PickLineItemkey={line.id}@@ -588,7 +637,7 @@ function PickLineItem({? "bg-emerald-600": quantityPicked > 0? "bg-orange-500"- : "bg-red-600"+ : "bg-red-600 max-md:bg-muted max-md:text-foreground")}>{quantityPicked}/{quantityToPick}@@ -602,7 +651,7 @@ function PickLineItem({? "bg-emerald-600": isShort? "bg-orange-500"- : "bg-red-600"+ : "bg-red-600 max-md:bg-muted max-md:text-foreground")}>{isShort ? quantityPicked : quantityToPick}@@ -621,15 +670,19 @@ function PickLineItem({>{/* Identity — item, part number, suggested lots, and (mobile) the count */}<div className="flex items-start justify-between gap-4 min-w-0 sm:flex-1">- <HStack spacing={4} className="min-w-0">- <ItemThumbnail- size="xl"- thumbnailPath={null}- type={(item?.type as "Part") ?? "Part"}- />+ <HStack spacing={4} className="min-w-0 flex-1 max-md:space-x-3">+ <div className="shrink-0 max-md:[&>*]:size-11 max-md:[&_svg]:size-7">+ <ItemThumbnail+ size="xl"+ thumbnailPath={null}+ type={(item?.type as "Part") ?? "Part"}+ />+ </div><VStack spacing={1} className="min-w-0">- <p className="truncate text-base font-medium">{itemName}</p>- <p className="truncate font-mono text-sm text-muted-foreground">+ <p className="w-full text-base font-medium md:truncate max-md:line-clamp-2">+ {itemName}+ </p>+ <p className="w-full truncate font-mono text-sm text-muted-foreground">{item?.readableIdWithRevision ?? lineItem?.readableId}</p>{substitutedFrom && (@@ -783,7 +836,7 @@ function PickLineItem({variant="secondary"onClick={() => setShortOpen(true)}isDisabled={isSubmitting}- className="flex-1 sm:flex-none"+ className="flex-1 sm:flex-none max-md:h-12"><Trans>Short</Trans></Button>@@ -793,7 +846,7 @@ function PickLineItem({onClick={() => pick(quantityToPick)}isLoading={isSubmitting}isDisabled={isSubmitting}- className="flex-1 sm:flex-none"+ className="flex-1 sm:flex-none max-md:h-12"><Trans>Pick</Trans></Button>diff --git a/apps/mes/app/routes/x+/picking._index.tsx b/apps/mes/app/routes/x+/picking._index.tsxindex 6d1ed711bb..aa5fbe67b6 100644--- a/apps/mes/app/routes/x+/picking._index.tsx+++ b/apps/mes/app/routes/x+/picking._index.tsx@@ -8,16 +8,15 @@ import {CardContent,CardHeader,CardTitle,- Heading,HStack,- SidebarTrigger,VStack} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { LuTriangleAlert } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { Link, useLoaderData } from "react-router";import { DateTime } from "~/components";+import { MesAppBar } from "~/components/MesAppBar";+import { MesEmptyState } from "~/components/MesEmptyState";import { PickingListStatus } from "~/components/PickingListStatus";import { userContext } from "~/context";import { getAssignedPickingLists } from "~/services/picking.service";@@ -43,15 +42,8 @@ export default function PickingIndexRoute() {const { pickingLists } = useLoaderData<typeof loader>();return (- <div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Picking</Trans>- </Heading>- </div>- </header>+ <div className="flex flex-col flex-1 min-h-0">+ <MesAppBar kind="root" title={<Trans>Picking</Trans>} /><main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent">{pickingLists.length > 0 ? (@@ -81,14 +73,14 @@ export default function PickingIndexRoute() {</CardHeader><CardContent><VStack className="gap-1">- <HStack className="justify-between text-sm">+ <HStack className="justify-between text-sm max-md:w-full"><span className="text-muted-foreground"><Trans>Location</Trans></span><span>{pl.locationName}</span></HStack>{pl.dueDate && (- <HStack className="justify-between text-sm">+ <HStack className="justify-between text-sm max-md:w-full"><span className="text-muted-foreground"><Trans>Due Date</Trans></span>@@ -97,7 +89,7 @@ export default function PickingIndexRoute() {</span></HStack>)}- <HStack className="justify-between text-sm">+ <HStack className="justify-between text-sm max-md:w-full"><span className="text-muted-foreground"><Trans>Progress</Trans></span>@@ -113,14 +105,10 @@ export default function PickingIndexRoute() {})}</div>) : (- <div className="flex flex-col flex-1 w-full h-[calc(100%-var(--header-height))] items-center justify-center gap-4">- <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">- <LuTriangleAlert className="h-6 w-6" />- </div>- <span className="text-xs font-mono font-light text-foreground uppercase">- <Trans>No picking lists assigned</Trans>- </span>- </div>+ <MesEmptyState+ className="flex-1 w-full h-[calc(100%-var(--header-height))]"+ title={<Trans>No picking lists assigned</Trans>}+ />)}</main></div>diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsxindex 3366de3e7f..0f826bcc94 100644--- a/apps/mes/app/routes/x+/recent.tsx+++ b/apps/mes/app/routes/x+/recent.tsx@@ -3,13 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import {- Button,- Heading,- Input,- SidebarTrigger,- useViewport-} from "@carbon/react";+import { Button, Input, useViewport } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo, useRef, useState } from "react";import { LuSearch, LuTriangleAlert } from "react-icons/lu";@@ -17,6 +11,7 @@ import type { ImperativePanelHandle } from "react-resizable-panels";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import { OperationsList } from "~/components";+import { MesAppBar } from "~/components/MesAppBar";import { getRecentJobOperationsByEmployee } from "~/services/operations.service";import { makeDurations } from "~/utils/durations";import type { Handle } from "~/utils/handle";@@ -70,18 +65,11 @@ export default function ActiveRoute() {}, [operations, searchTerm]);return (- <div className="flex flex-col flex-1">- <header className="sticky top-0 z-10 flex h-[var(--header-height)] shrink-0 items-center gap-2 border-b bg-card">- <div className="flex items-center gap-2 px-2">- <SidebarTrigger />- <Heading size="h4">- <Trans>Recent</Trans>- </Heading>- </div>- </header>+ <div className="flex flex-col flex-1 min-h-0">+ <MesAppBar kind="root" title={<Trans>Recent</Trans>} /><main className="flex-1 min-h-0 w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent">- <div className="w-full p-4 h-[var(--header-height)]">+ <div className="w-full p-4 h-[var(--header-height)] max-md:h-auto max-md:pb-0"><div className="relative"><div className="flex justify-between gap-4"><div className="flex flex-grow">@@ -97,7 +85,7 @@ export default function ActiveRoute() {</div></div>{filteredOperations.length > 0 ? (- <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4">+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4 max-md:pt-3"><OperationsList key="active" operations={filteredOperations} /></div>) : searchTerm ? (diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex a8628220f4..89815b3a16 100644--- a/apps/mes/app/routes/x+/timecard.tsx+++ b/apps/mes/app/routes/x+/timecard.tsx@@ -12,6 +12,7 @@ import {CardContent,CardHeader,CardTitle,+ cn,DropdownMenu,DropdownMenuContent,DropdownMenuIcon,@@ -33,7 +34,8 @@ import {Td,Th,Thead,- Tr+ Tr,+ useViewport} from "@carbon/react";import { datetime } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";@@ -50,6 +52,8 @@ import {import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { Link, useLoaderData } from "react-router";import { DateTime } from "~/components";+import { MesAppBar } from "~/components/MesAppBar";+import { useMesBottomBar } from "~/components/MesBottomBar";import {clockIn,clockOut,@@ -184,6 +188,8 @@ export async function action({ request }: ActionFunctionArgs) {}export default function MESTimecardPage() {+ const bottomBarRef = useMesBottomBar();+ const { isPhone } = useViewport();const { entries, openEntry, weekOffset, weekStart, weekEnd } =useLoaderData<typeof loader>();const fetcher = useAction<typeof action>({@@ -221,311 +227,444 @@ export default function MESTimecardPage() {setEditClockOut(entry.clockOut ? toLocalDatetimeInput(entry.clockOut) : "");}+ const renderClockForm = (size: "md" | "lg", className?: string) =>+ openEntry ? (+ <fetcher.Form method="post" className={className}>+ <input type="hidden" name="intent" value="clockOut" />+ <Button+ variant="destructive"+ type="submit"+ size={size}+ className={className}+ disabled={fetcher.state !== "idle"}+ >+ <Trans>Clock Out</Trans>+ </Button>+ </fetcher.Form>+ ) : (+ <fetcher.Form method="post" className={className}>+ <input type="hidden" name="intent" value="clockIn" />+ <Button+ leftIcon={<LuPlay />}+ type="submit"+ size={size}+ className={className}+ disabled={fetcher.state !== "idle"}+ >+ <Trans>Clock In</Trans>+ </Button>+ </fetcher.Form>+ );++ const renderSaveForm = (entryId: string) => (+ <fetcher.Form method="post">+ <input type="hidden" name="intent" value="updateEntry" />+ <input type="hidden" name="entryId" value={entryId} />+ <input+ type="hidden"+ name="clockIn"+ value={+ isNaN(new Date(editClockIn).getTime())+ ? ""+ : new Date(editClockIn).toISOString()+ }+ />+ {editClockOut && !isNaN(new Date(editClockOut).getTime()) && (+ <input+ type="hidden"+ name="clockOut"+ value={new Date(editClockOut).toISOString()}+ />+ )}+ <Button+ isLoading={fetcher.state !== "idle"}+ variant="secondary"+ type="submit"+ disabled={isNaN(new Date(editClockIn).getTime())}+ >+ <Trans>Save</Trans>+ </Button>+ </fetcher.Form>+ );++ const renderEntryMenu = (+ entry: { id: string; clockIn: string; clockOut: string | null },+ size: "md" | "lg"+ ) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`More options`}+ variant="ghost"+ size={size}+ icon={<LuEllipsisVertical />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.edit}+ onClick={() => startEdit(entry)}+ >+ <DropdownMenuIcon icon={<LuPencil />} />+ <Trans>Edit</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.delete}+ onClick={() =>+ setDeletingEntry({+ id: entry.id,+ clockIn: entry.clockIn+ })+ }+ className="text-destructive"+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+return (- <div className="flex flex-col h-full w-full overflow-y-auto p-4 md:p-6">- <div className="max-w-[60rem] mx-auto w-full">- <Card className="overflow-hidden">- <CardHeader>- <HStack className="justify-between items-center">- <CardTitle>- <Trans>My Hours</Trans>- </CardTitle>- <HStack className="gap-1">- {openEntry ? (- <fetcher.Form method="post">- <input type="hidden" name="intent" value="clockOut" />- <Button- variant="destructive"- type="submit"- disabled={fetcher.state !== "idle"}- >- <Trans>Clock Out</Trans>- </Button>- </fetcher.Form>- ) : (- <fetcher.Form method="post">- <input type="hidden" name="intent" value="clockIn" />- <Button- leftIcon={<LuPlay />}- type="submit"- disabled={fetcher.state !== "idle"}- >- <Trans>Clock In</Trans>- </Button>- </fetcher.Form>- )}+ <>+ <MesAppBar kind="root" title={<Trans>My Hours</Trans>} desktop={null} />+ <div className="flex flex-col h-full w-full overflow-y-auto p-4 md:p-6 max-md:h-auto max-md:overflow-visible max-md:pb-24">+ <div className="max-w-[60rem] mx-auto w-full">+ <Card className="overflow-hidden">+ <CardHeader className={cn(!openEntry && "max-md:hidden")}>+ <HStack className="justify-between items-center">+ <CardTitle className="max-md:hidden">+ <Trans>My Hours</Trans>+ </CardTitle>+ <HStack className="gap-1 max-md:hidden">+ {renderClockForm("md")}+ </HStack></HStack>- </HStack>- {openEntry && (- <Badge variant="green" className="w-fit">- <Trans>- Clocked in since{" "}- <DateTime value={openEntry.clockIn} variant="time" />- </Trans>- </Badge>- )}- </CardHeader>- <CardContent>- <HStack className="justify-between items-center mb-4">- <Button variant="outline" asChild leftIcon={<LuChevronLeft />}>- <Link to={`${path.to.timeCardPage}?week=${weekOffset - 1}`}>- <Trans>Prev</Trans>- </Link>- </Button>- <span className="text-sm text-muted-foreground">- <DateTime- value={weekStart}- variant="date"- dateOptions={{ dateStyle: "medium" }}- />{" "}- —{" "}- <DateTime- value={weekEnd}- variant="date"- dateOptions={{ dateStyle: "medium" }}- />- </span>- <Button- variant="outline"- disabled={isCurrentWeek}- asChild={!isCurrentWeek}- rightIcon={<LuChevronRight />}- >- {isCurrentWeek ? (- <span>- <Trans>Next</Trans>- </span>- ) : (- <Link to={`${path.to.timeCardPage}?week=${weekOffset + 1}`}>- <Trans>Next</Trans>+ {openEntry && (+ <Badge variant="green" className="w-fit">+ <Trans>+ Clocked in since{" "}+ <DateTime value={openEntry.clockIn} variant="time" />+ </Trans>+ </Badge>+ )}+ </CardHeader>+ <CardContent>+ <HStack className="justify-between items-center mb-4">+ <Button+ variant="outline"+ asChild+ leftIcon={<LuChevronLeft className="max-md:mr-0" />}+ className="max-md:size-11 max-md:px-0"+ >+ <Link to={`${path.to.timeCardPage}?week=${weekOffset - 1}`}>+ <span className="max-md:sr-only">+ <Trans>Prev</Trans>+ </span></Link>- )}- </Button>- </HStack>+ </Button>+ <span className="text-sm text-muted-foreground max-md:whitespace-nowrap">+ <DateTime+ value={weekStart}+ variant="date"+ dateOptions={{ dateStyle: "medium" }}+ />{" "}+ —{" "}+ <DateTime+ value={weekEnd}+ variant="date"+ dateOptions={{ dateStyle: "medium" }}+ />+ </span>+ <Button+ variant="outline"+ disabled={isCurrentWeek}+ asChild={!isCurrentWeek}+ rightIcon={<LuChevronRight className="max-md:ml-0" />}+ className="max-md:size-11 max-md:px-0"+ >+ {isCurrentWeek ? (+ <span className="max-md:sr-only">+ <Trans>Next</Trans>+ </span>+ ) : (+ <Link to={`${path.to.timeCardPage}?week=${weekOffset + 1}`}>+ <span className="max-md:sr-only">+ <Trans>Next</Trans>+ </span>+ </Link>+ )}+ </Button>+ </HStack>- <TableBase className="table-fixed w-full">- <colgroup>- <col className="w-[16%]" />- <col className="w-[28%]" />- <col className="w-[28%]" />- <col className="w-[12%]" />- <col className="w-[16%]" />- </colgroup>- <Thead>- <Tr>- <Th className="whitespace-nowrap">- <Trans>Date</Trans>- </Th>- <Th>- <Trans>Clock In</Trans>- </Th>- <Th>- <Trans>Clock Out</Trans>- </Th>- <Th className="text-center">- <Trans>Duration</Trans>- </Th>- <Th />- </Tr>- </Thead>- <Tbody>- {entries.length === 0 ? (- <Tr>- <Td- colSpan={5}- className="text-center text-muted-foreground py-8"- >+ {/* One layout mounts: the edit row (its inputs and Save form)+ must not exist twice. */}+ {isPhone ? (+ <>+ {entries.length === 0 ? (+ <p className="py-8 text-center text-sm text-muted-foreground"><Trans>No time entries for this week</Trans>- </Td>- </Tr>- ) : (- entries.map((entry) =>- editingId === entry.id ? (- <Tr key={entry.id}>- <Td className="whitespace-nowrap">- {formatDay(entry.clockIn, locale)}- </Td>- <Td>- <Input- type="datetime-local"- value={editClockIn}- onChange={(e) => setEditClockIn(e.target.value)}- className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"- />- </Td>- <Td>- <Input- type="datetime-local"- value={editClockOut}- onChange={(e) => setEditClockOut(e.target.value)}- className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"- />- </Td>- <Td className="text-muted-foreground text-center">—</Td>- <Td className="text-center">- <HStack className="justify-center">- <fetcher.Form method="post">- <input- type="hidden"- name="intent"- value="updateEntry"- />- <input- type="hidden"- name="entryId"- value={entry.id}- />- <input- type="hidden"- name="clockIn"- value={- isNaN(new Date(editClockIn).getTime())- ? ""- : new Date(editClockIn).toISOString()- }- />- {editClockOut &&- !isNaN(new Date(editClockOut).getTime()) && (- <input- type="hidden"- name="clockOut"- value={new Date(editClockOut).toISOString()}- />- )}+ </p>+ ) : (+ <ul className="-mx-4 divide-y divide-border border-y border-border">+ {entries.map((entry) =>+ editingId === entry.id ? (+ <li+ key={entry.id}+ className="flex flex-col gap-2 px-4 py-3"+ >+ <span className="text-sm font-medium">+ {formatDay(entry.clockIn, locale)}+ </span>+ <Input+ type="datetime-local"+ aria-label={t`Clock In`}+ value={editClockIn}+ onChange={(e) => setEditClockIn(e.target.value)}+ className="w-full"+ />+ <Input+ type="datetime-local"+ aria-label={t`Clock Out`}+ value={editClockOut}+ onChange={(e) => setEditClockOut(e.target.value)}+ className="w-full"+ />+ <HStack className="justify-end">+ {renderSaveForm(entry.id)}<Button- isLoading={fetcher.state !== "idle"}- variant="secondary"- type="submit"- disabled={isNaN(- new Date(editClockIn).getTime()- )}+ variant="ghost"+ onClick={() => setEditingId(null)}>- <Trans>Save</Trans>+ <Trans>Cancel</Trans></Button>- </fetcher.Form>- <Button- variant="ghost"- onClick={() => setEditingId(null)}- >- <Trans>Cancel</Trans>- </Button>- </HStack>- </Td>+ </HStack>+ </li>+ ) : (+ <li+ key={entry.id}+ className="flex items-center gap-2 py-2 pl-4 pr-1"+ >+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <div className="flex items-baseline justify-between gap-2">+ <span className="text-sm font-medium">+ {formatDay(entry.clockIn, locale)}+ </span>+ <span className="text-sm tabular-nums">+ {formatDuration(+ entry.clockIn,+ entry.clockOut+ )}+ </span>+ </div>+ <span className="flex items-center gap-1 text-xs text-muted-foreground">+ <DateTime+ value={entry.clockIn}+ variant="time"+ />+ <span aria-hidden>–</span>+ {entry.clockOut ? (+ <DateTime+ value={entry.clockOut}+ variant="time"+ />+ ) : (+ <Badge variant="green">+ <Trans>Active</Trans>+ </Badge>+ )}+ </span>+ </div>+ {renderEntryMenu(entry, "lg")}+ </li>+ )+ )}+ </ul>+ )}+ </>+ ) : (+ <div>+ <TableBase className="table-fixed w-full">+ <colgroup>+ <col className="w-[16%]" />+ <col className="w-[28%]" />+ <col className="w-[28%]" />+ <col className="w-[12%]" />+ <col className="w-[16%]" />+ </colgroup>+ <Thead>+ <Tr>+ <Th className="whitespace-nowrap">+ <Trans>Date</Trans>+ </Th>+ <Th>+ <Trans>Clock In</Trans>+ </Th>+ <Th>+ <Trans>Clock Out</Trans>+ </Th>+ <Th className="text-center">+ <Trans>Duration</Trans>+ </Th>+ <Th /></Tr>- ) : (- <Tr key={entry.id}>- <Td className="whitespace-nowrap">- {formatDay(entry.clockIn, locale)}- </Td>- <Td>- <DateTime value={entry.clockIn} variant="time" />- </Td>- <Td>- {entry.clockOut ? (- <DateTime value={entry.clockOut} variant="time" />+ </Thead>+ <Tbody>+ {entries.length === 0 ? (+ <Tr>+ <Td+ colSpan={5}+ className="text-center text-muted-foreground py-8"+ >+ <Trans>No time entries for this week</Trans>+ </Td>+ </Tr>+ ) : (+ entries.map((entry) =>+ editingId === entry.id ? (+ <Tr key={entry.id}>+ <Td className="whitespace-nowrap">+ {formatDay(entry.clockIn, locale)}+ </Td>+ <Td>+ <Input+ type="datetime-local"+ value={editClockIn}+ onChange={(e) =>+ setEditClockIn(e.target.value)+ }+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"+ />+ </Td>+ <Td>+ <Input+ type="datetime-local"+ value={editClockOut}+ onChange={(e) =>+ setEditClockOut(e.target.value)+ }+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"+ />+ </Td>+ <Td className="text-muted-foreground text-center">+ —+ </Td>+ <Td className="text-center">+ <HStack className="justify-center">+ {renderSaveForm(entry.id)}+ <Button+ variant="ghost"+ onClick={() => setEditingId(null)}+ >+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </Td>+ </Tr>) : (- <Badge variant="green">- <Trans>Active</Trans>- </Badge>- )}- </Td>- <Td className="text-center">- {formatDuration(entry.clockIn, entry.clockOut)}- </Td>- <Td className="text-right">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label={t`More options`}- variant="ghost"- icon={<LuEllipsisVertical />}- />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- shortcut={MENU_ITEM_SHORTCUTS.edit}- onClick={() => startEdit(entry)}- >- <DropdownMenuIcon icon={<LuPencil />} />- <Trans>Edit</Trans>- </DropdownMenuItem>- <DropdownMenuItem- shortcut={MENU_ITEM_SHORTCUTS.delete}- onClick={() =>- setDeletingEntry({- id: entry.id,- clockIn: entry.clockIn- })- }- className="text-destructive"- >- <DropdownMenuIcon icon={<LuTrash />} />- <Trans>Delete</Trans>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </Td>- </Tr>- )- )- )}- </Tbody>- </TableBase>+ <Tr key={entry.id}>+ <Td className="whitespace-nowrap">+ {formatDay(entry.clockIn, locale)}+ </Td>+ <Td>+ <DateTime+ value={entry.clockIn}+ variant="time"+ />+ </Td>+ <Td>+ {entry.clockOut ? (+ <DateTime+ value={entry.clockOut}+ variant="time"+ />+ ) : (+ <Badge variant="green">+ <Trans>Active</Trans>+ </Badge>+ )}+ </Td>+ <Td className="text-center">+ {formatDuration(entry.clockIn, entry.clockOut)}+ </Td>+ <Td className="text-right">+ {renderEntryMenu(entry, "md")}+ </Td>+ </Tr>+ )+ )+ )}+ </Tbody>+ </TableBase>+ </div>+ )}- {entries.length > 0 && (- <div className="mt-4 text-right text-sm font-medium">- <Trans>Total: {formatTotalHours(entries)}</Trans>- </div>- )}- </CardContent>- </Card>- </div>- {deletingEntry && (- <Modal- open- onOpenChange={(open) => {- if (!open) setDeletingEntry(null);- }}- >- <ModalOverlay />- <ModalContent>- <ModalHeader>- <ModalTitle>+ {entries.length > 0 && (+ <div className="mt-4 text-right text-sm font-medium">+ <Trans>Total: {formatTotalHours(entries)}</Trans>+ </div>+ )}+ </CardContent>+ </Card>+ </div>+ {deletingEntry && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) setDeletingEntry(null);+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ <Trans>+ Delete Timecard (+ <DateTime+ value={deletingEntry.clockIn}+ variant="absolute"+ />+ )+ </Trans>+ </ModalTitle>+ </ModalHeader>+ <ModalBody><Trans>- Delete Timecard (- <DateTime value={deletingEntry.clockIn} variant="absolute" />)+ Are you sure you want to delete this timecard? This cannot be+ undone.</Trans>- </ModalTitle>- </ModalHeader>- <ModalBody>- <Trans>- Are you sure you want to delete this timecard? This cannot be- undone.- </Trans>- </ModalBody>- <ModalFooter>- <Button- variant="secondary"- onClick={() => setDeletingEntry(null)}- >- <Trans>Cancel</Trans>- </Button>- <Button- variant="destructive"- onClick={() => {- const formData = new FormData();- formData.append("intent", "deleteEntry");- formData.append("entryId", deletingEntry.id);- fetcher.submit(formData, { method: "post" });- setDeletingEntry(null);- }}- >- <Trans>Delete</Trans>- </Button>- </ModalFooter>- </ModalContent>- </Modal>- )}- </div>+ </ModalBody>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => setDeletingEntry(null)}+ >+ <Trans>Cancel</Trans>+ </Button>+ <Button+ variant="destructive"+ onClick={() => {+ const formData = new FormData();+ formData.append("intent", "deleteEntry");+ formData.append("entryId", deletingEntry.id);+ fetcher.submit(formData, { method: "post" });+ setDeletingEntry(null);+ }}+ >+ <Trans>Delete</Trans>+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ )}+ </div>+ <div+ ref={bottomBarRef}+ data-mes-bottom-bar+ className="fixed inset-x-0 bottom-[calc(54px+env(safe-area-inset-bottom))] z-20 border-t border-border bg-card px-4 py-3 md:hidden"+ >+ {renderClockForm("lg", "w-full h-12")}+ </div>+ </>);}diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.cssindex 2e63a80394..6e1dcc4778 100644--- a/apps/mes/app/styles/tailwind.css+++ b/apps/mes/app/styles/tailwind.css@@ -157,3 +157,24 @@ p.is-editor-empty:first-child:before {.animate-spinner {animation: spinner-fade 1.2s linear infinite;}++/*+ * Phones (< 768px): toasts sit above the MES tab bar while it shows, or above+ * a page's bottom action bar. Sonner's own mobileOffset only applies up to 600px.+ * A bottom bar carries `data-mes-bottom-bar`; `useMesBottomBar` publishes+ * `--mes-bottom-bar-h` on <html>: its top edge from the screen bottom, safe+ * area included.+ */+@media (width < 48rem) {+ body:has([data-mes-tab-bar][data-visible="true"]):not(+ :has([data-mes-bottom-bar])+ )+ [data-sonner-toaster][data-y-position="bottom"] {+ bottom: calc(54px + env(safe-area-inset-bottom) + 16px);+ }++ body:has([data-mes-bottom-bar])+ [data-sonner-toaster][data-y-position="bottom"] {+ bottom: calc(var(--mes-bottom-bar-h, 64px) + 16px);+ }+}diff --git a/apps/mes/app/utils/origin.tsx b/apps/mes/app/utils/origin.tsxnew file mode 100644index 0000000000..b66cbd52e4--- /dev/null+++ b/apps/mes/app/utils/origin.tsx@@ -0,0 +1,66 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useLingui } from "@lingui/react/macro";+import { useSearchParams } from "react-router";+import {+ queueKeyForPath,+ queuePath,+ useQueueTitles+} from "~/components/AppSidebar";+import { path } from "~/utils/path";++/** The query parameter that carries the page an operation was opened from. */+export const ORIGIN_PARAM = "from";++/**+ * `to` plus `?from=<the current page>`, so Back can return to that page.+ * Without an origin it is `to` unchanged.+ */+export function withOrigin(+ to: string,+ from: string | { pathname: string; search: string } | null+): string {+ if (from === null) return to;+ const separator = to.includes("?") ? "&" : "?";+ const value = encodeURIComponent(+ typeof from === "string" ? from : `${from.pathname}${from.search}`+ );+ return `${to}${separator}${ORIGIN_PARAM}=${value}`;+}++/**+ * The origin page, or null. Only MES paths (`/x/…`) count. Reads the URL's+ * search params, or a form that posts the origin as a hidden `from` field.+ */+export function readOrigin(+ params: Pick<URLSearchParams, "get"> | Pick<FormData, "get">+): string | null {+ const from = params.get(ORIGIN_PARAM);+ return typeof from === "string" && from.startsWith("/x/") ? from : null;+}++/** A form's hidden `from` field, so the action's redirect keeps the origin. */+export function OriginInput() {+ const [searchParams] = useSearchParams();+ const origin = readOrigin(searchParams);+ return origin ? (+ <input type="hidden" name={ORIGIN_PARAM} value={origin} />+ ) : null;+}++/** Back on Operation, Assembly and Inspection: the `from` page, else Schedule. */+export function useOrigin(): { to: string; label: string } {+ const { t } = useLingui();+ const [searchParams] = useSearchParams();+ const titles = useQueueTitles();+ const from = readOrigin(searchParams);+ if (!from) return { to: path.to.operations, label: titles.operations };+ // Back from a job graph returns to that job, not to the Jobs list.+ if (queuePath(from).startsWith(`${path.to.jobDag("")}/`)) {+ return { to: from, label: t`Job` };+ }+ const key = queueKeyForPath(queuePath(from));+ return { to: from, label: key ? titles[key] : titles.operations };+}