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(skills): add carbon-design skill encoding Carbon's design language and a design-review gate
aashu9cef81a43fdb
diff --git a/.claude/skills/README.md b/.claude/skills/README.mdindex ffa3f24ac1..c30cadcc5a 100644--- a/.claude/skills/README.md+++ b/.claude/skills/README.md@@ -71,6 +71,7 @@ in root-cause, BLOCKED in fix) always surface to the human.| `writing-skills` | House guide for authoring skills | skills || `pr-explainer` | Self-contained HTML review aid for a PR | `.pr-review/*.html` || `pr-splitter` | Split a large PR into reviewable stacked PRs | branches + split notes |+| `carbon-design` | Carbon's design language: principles, page archetypes, components, states, copy, anti-patterns + mandatory design review for any ERP/MES UI | design brief + reviewed UI || `ui` | Remote-managed UI exploration shim (uidotsh) | — || `agent-browser` | External: browser CLI reference (pinned in `skills-lock.json`) | — || `make-interfaces-feel-better` | External: UI polish principles (pinned in `skills-lock.json`) | — |diff --git a/.claude/skills/carbon-design/SKILL.md b/.claude/skills/carbon-design/SKILL.mdnew file mode 100644index 0000000000..c992eb010a--- /dev/null+++ b/.claude/skills/carbon-design/SKILL.md@@ -0,0 +1,187 @@+---+name: carbon-design+description: >-+ Carbon's design language — the principles, page archetypes, components, states, copy rules+ and anti-patterns that make UI look and behave like the rest of Carbon (ERP + MES). Use+ whenever designing, building, restyling or reviewing any user-facing UI in apps/erp, apps/mes,+ packages/react or packages/form: a new page, module, feature, component, table, form, drawer+ or modal, dashboard, settings screen, empty/loading/error state, status, or shop-floor screen+ — and whenever someone says a screen "doesn't feel like Carbon", looks off, is inconsistent,+ or needs a design pass or UI review. Trigger even when the request is framed as a feature+ ("add X to Y") that will need new UI. Prefer this over generic UI/design/frontend skills in+ this repo. Not for the docs site (use carbon-docs) or backend-only work.+---++# carbon-design — the design DNA of Carbon++Carbon has a consistent, largely unwritten design language. Features built without it+"work" but feel generic. This skill encodes that language so anything you design — including+things Carbon has never had — looks and behaves as if the same team made it.++**Announce at start:** "Using the carbon-design skill — designing {feature} in Carbon's language."++It is **not** a component catalog. Components are one part. The skill teaches *why* Carbon+makes each choice, so you can make the right choice where no component or precedent exists:++> Reuse existing patterns when they fit. Extend the design system when necessary.+> Never force an existing component into a use case where it doesn't belong.++## The Carbon feel in one paragraph++A calm, dense, monochrome working tool for manufacturers who live in it all day. Color is spent+only on meaning (status, type, overdue/negative, charts). Every record is identified by a+readable ID that is visible, copyable and linked. Records are state machines: the status pill+sits next to the ID and the next step is the one primary button. Documents open into a fixed+workspace — header strip, structure on the left, work in the middle, metadata on the right.+State lives in the URL. Secondary things hide in known places (⋯ menu, Properties panel,+hidden columns, row menus), never behind modes. Permissions and locks disable in place.+Everything is keyboard-reachable, translated, and honest about its state. On the shop floor+the same language gets bigger, simpler and touch-first.++## The 12 laws (short form — the reasoning is in `references/principles.md`)++1. **Quiet chrome, loud data.** Tokens only; hue only for meaning; ink primary; no colored prose.+2. **Identity first.** Readable IDs / thumbnails / avatars — visible, copyable, linked. No raw ids.+3. **Lifecycle drives the UI.** `Status` next to the ID; exactly one primary = the next step; status locks in place.+4. **Structure left, work center, metadata right.** The 3-pane document workspace.+5. **The URL is the state.** Route tabs, route drawers, search-param filters.+6. **One component per concept.** Same thing, same look, everywhere (status maps, DateTime, Enumerable, icon vocabulary).+7. **Match the nearest sibling** before inventing anything.+8. **Hide in known places, never in modes.** ⋯ menu, Properties, hidden columns, row menu.+9. **Disable, don't hide** for permissions and locks.+10. **Dense, not cramped.** `text-sm` body, `text-xs` muted labels, h-8 buttons, 4/8/16 spacing, `font-medium`.+11. **Primitives own the surface.** `Card > CardContent`, no double edges, `rounded-lg` inner boxes, no big shadows.+12. **Honest, grounded, translated, keyboard-first.** Real states only; real APIs and domain rules (verified in source); every string in Lingui; named shortcuts.++## Workflow++Follow these steps for any UI work. Steps 1–4 happen **before** writing code.++### Step 1 — Classify the work+Identify every surface the feature touches and read the matching references. Always read+`references/principles.md` and `references/anti-patterns.md` once per task.++| The feature involves… | Read |+|---|---|+| A new page, module, record type, or navigation entry | `references/page-archetypes.md` |+| Any styling decision (color, type, spacing, radius, icons, dark mode) | `references/foundations.md` |+| Choosing or building components | `references/components.md` |+| A list, table, line items, tree, board | `references/tables-and-lists.md` |+| A form, input, settings, save behaviour | `references/forms.md` |+| Buttons, menus, modals, drawers, destructive actions, shortcuts | `references/actions-and-overlays.md` |+| Statuses, progress, toasts, alerts, loading, empty, error, locked states | `references/status-and-feedback.md` |+| Keyboard, drag & drop, motion, accessibility, responsive | `references/interaction-motion-a11y.md` |+| Anything operators use on the shop floor (`apps/mes`) | `references/shop-floor-mes.md` |+| Any user-facing words | `references/content-and-copy.md` |+| Unsure how far to reuse vs invent | `references/worked-examples.md` |++### Step 2 — Find the sibling and read it+Pick the archetype (`page-archetypes.md` §15) and open its exemplar files. Also find the+closest existing screen *in the same module*. Read their actual code — the exemplar is the+spec. Canonical starting points:++| Need | Exemplar (paths from `apps/erp/app/`) |+|---|---|+| Module list | `routes/x+/sales+/rmas.tsx`, `modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx`, `modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx` |+| Document workspace | `routes/x+/sales-return-order+/$id.tsx` + `modules/sales/ui/SalesReturnOrders/SalesReturnOrder{Header,Explorer,Properties}.tsx`; richer: `modules/sales/ui/Quotes/QuoteHeader.tsx` |+| Config row CRUD | `routes/x+/sales+/customer-types.tsx` (+ `.new`, `.$customerTypeId`, `.delete.$customerTypeId`), `modules/sales/ui/CustomerTypes/CustomerTypeForm.tsx` |+| Record form | `modules/sales/ui/Customer/CustomerForm.tsx` |+| Line form | `modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx` |+| Properties panel | `modules/quality/ui/Issue/IssueProperties.tsx` |+| Settings | `routes/x+/settings+/sales.tsx`, `routes/x+/settings+/items.tsx` |+| Status wrapper | `modules/sales/ui/Quotes/QuoteStatus.tsx` + `packages/utils/src/status-colors.ts` |+| Confirm / transition modal | `components/Modals/ConfirmDelete/ConfirmDelete.tsx`, `modules/inventory/ui/Receipts/ReceiptPostModal.tsx` |+| MES operator screen | `apps/mes/app/components/JobOperation/JobOperation.tsx`, `apps/mes/app/components/OperationsList.tsx` |++### Step 3 — Decide reuse / extend / create+For each piece of UI, decide and record which:+- **Reuse** — an existing component or pattern whose *job* matches.+- **Extend** — the job matches but a recurring need is missing (new variant/prop). Prefer this+ over a near-duplicate component.+- **Create** — the job is genuinely new. Build it from tokens and primitives following+ `components.md` §7 so it is native to the system.+- **Never force-fit** — if using an existing component would bend its meaning (Status for a+ category, Table for three config items, Alert for routine info), create instead.++### Step 4 — Write a short design brief (before code)+Keep it to ~15 lines. It is what you'll review against in Step 6.++```+Design brief — <feature>+- Users & context: <who, desk or floor, how often>+- Archetype(s): <A–I / MES> — exemplar: <path(s)>+- Layout & hierarchy: <what is identity, primary action, work, metadata; where each lives>+- Actions: <primary per surface; secondary; what goes in ⋯ / row menu; destructive flow>+- Create/edit: <where it opens; container; save model>+- Data display: <list shape; renderers per value type; statuses + colors by lifecycle position>+- States: <empty / loading / error / locked / no-permission — incl. every overlay that fetches>+- Data cases: <nulls and special values the domain already models (e.g. deadline types, locked+ rows, mixed selections, multi-currency) and how each renders — reuse the domain's own+ predicates (e.g. `deadlineRequiresDueDate`) instead of approximating>+- Copy: <titles, buttons, toasts, empty text — in Carbon patterns>+- Reuse / extend / create: <list, with the reason for each extend/create and what was rejected>+```+If the user asked only for a design (no code), the brief plus annotated ASCII wireframes and+component choices is the deliverable.++### Step 5 — Build+Follow the brief and the exemplar.++**Verify before you use — every time.** The most common way a Carbon-looking design breaks is+an invented API. Before writing any of these, open the source and confirm it:+- each import path and export (e.g. `NumberControlled` lives in `~/components/Form`, not+ `@carbon/react`; form fields need a `ValidatedForm`),+- each prop and its type (read the component's props type — e.g. `DatePicker` takes a+ `CalendarDate`, `Button` has no `success` variant),+- each `path.to.*` helper (grep `apps/erp/app/utils/path.ts`),+- each schema column or view you rely on (grep `packages/database/src/types.ts`; tables vs+ views differ),+- each helper or hook name (`formatDurationMilliseconds`, not a guess).+If you say "same as X" or "copied from X", import X's export or quote it exactly — never+re-type values from memory. If you can't verify something, say so in the brief as an open+question instead of stating it.++Make it mechanical: before finishing, write a **props audit** in your review summary — one+line per component you rendered, listing the props you passed and the `file:line` of the+props type you checked them against (e.g. `RadioGroupButton value,children — packages/react/src/Radio.tsx:54`).+Any prop you can't point to gets removed or replaced. Invented props (`size` on a component+that has none, `options` on a compound `Select`, `defaultSort` on `Table`, `isDisabled` on+`Checkbox` when it takes `disabled`) are the single most common defect in Carbon sketches.++Also obey the mechanics rules:+`.claude/rules/conventions-ui.md`, `.claude/rules/conventions-forms.md`,+`.claude/rules/i18n-lingui-system.md`, `.claude/rules/date-handling.md`,+`.claude/rules/numeric-precision.md`, `.claude/rules/table-csv-export.md`, `packages/react/AGENTS.md`.+Where those files disagree with the code (e.g. Card radius), the code wins — note it.++### Step 6 — Design-language review (mandatory)+Run `references/design-review.md`: the seven questions, the checklist, the grep for red flags,+and the state walk-through. **Fix every FIX and re-run** until clean. Work is not done until the+review summary is written. If something can't be made to fit without a system change (a new+shared component, a new token), stop and ask rather than improvising a one-off.++## When Carbon itself is inconsistent++Carbon has drift (listed in `references/anti-patterns.md` §3). Decide in this order:+1. the majority pattern in the code,+2. the newest canonical module (Sales Return Orders, Sept 2026),+3. the written rule.+Never copy a legacy pattern (`anti-patterns.md` §2) just because a sibling still has it, and+mention any drift you touched in your summary.++## Relationship to other guidance++- `.claude/rules/conventions-ui.md`, `.ai/ds-rules.md`, `packages/react/AGENTS.md` — component+ mechanics and hard rules; this skill builds on them and explains the *why*.+- `make-interfaces-feel-better` skill — generic polish; Carbon applies its motion, tabular-nums+ and text-wrap rules, but **not** image outlines or 40px ERP hit areas. This skill wins where+ they differ.+- `translate` skill — filling `.po` catalogs after you add strings.+- `test` / `agent-browser` skills — to look at the real rendered screen during review.++## Done when++- [ ] Design brief written (Step 4) and followed+- [ ] Every reuse/extend/create decision recorded with its reason+- [ ] `references/design-review.md` checklist all PASS or justified N/A; red-flag grep clean or justified+- [ ] Review summary written in the final message, including open questions about driftdiff --git a/.claude/skills/carbon-design/references/actions-and-overlays.md b/.claude/skills/carbon-design/references/actions-and-overlays.mdnew file mode 100644index 0000000000..44ec40fbb9--- /dev/null+++ b/.claude/skills/carbon-design/references/actions-and-overlays.md@@ -0,0 +1,170 @@+# Actions and overlays — hierarchy, placement, modals, destructive flows++## Contents+1. Action hierarchy — how prominent an action should be+2. Where actions live, per surface+3. Overlay decision table+4. Overlay anatomy and button order+5. Destructive actions+6. Keyboard bindings for actions+7. Action microcopy++---++## 1. Action hierarchy++Carbon's budget: **one primary per surface**. Secondary is the default look (46% of buttons).++| Level | Treatment | When |+|---|---|---|+| Primary | `Button` default/primary, or `Submit`, or `New` | the next step on this surface: Save, the next lifecycle transition, "Add X" on a list |+| Secondary | `Button variant="secondary"` | every other visible action, dropdown triggers (`rightIcon={<LuChevronDown/>}`), Cancel in modals |+| Quiet | `ghost` / `IconButton ghost` / `link` | inline, toolbar, panel actions, panel toggles |+| Hidden-in-place | ⋯ `DropdownMenu`, `renderContextMenu`, hover-revealed row icons | rare, administrative and destructive actions |+| Destructive | `destructive` variant / `MenuItem destructive` | irreversible or data-removing; always confirmed |++Rules:+- **Status-driven primary** in record headers: the button for the next valid step is primary,+ the rest secondary (`variant={status === "Draft" ? "primary" : "secondary"}`). Never two+ primaries.+- A header shows roughly **3–6 visible actions** besides panel toggles. More → move rare ones+ into ⋯, group related documents into one "Shipments ▾" dropdown, or use `SplitButton`.+- Text + icon (`leftIcon`) for actions that need a word; `IconButton` + tooltip only for+ universal icons (⋮, copy, link, close, toggles, chevrons, drag).+- Transitions not valid in the current status: the newest headers (Sales Return Order) render+ only valid ones; older headers render all and disable the invalid. Pick one approach per+ header; the next valid step must always be visible.+- Permission-gated actions are **disabled**, not hidden.++## 2. Where actions live++| Surface | Primary | Secondary / others | Rare & destructive |+|---|---|---|---|+| List page | `New` "Add X" in the Table title bar (`primaryAction`) | toolbar (search, filter, sort, columns, views, export); ⋮ "Bulk Import" next to Add; bulk menu `renderActions` when rows selected | row menu `renderContextMenu`: Edit first → domain verbs → Delete last |+| Document header | next lifecycle step (right side) | Preview/PDF ▾, related-doc ▾, other transitions | ⋯ next to the ID: audit log, copy/revision, Reopen, separator, Delete |+| Explorer | — | footer "Add Line Item" (secondary, full width, ⌘⇧L) | row ⋮ (hover-revealed): Delete Line |+| Card on a detail page | `CardAction` top-right (often `New`) or `CardFooter` Save bottom-left | — | — |+| Drawer form | Save (footer, left) | Cancel `solid` (right of Save) | — |+| Modal | primary action (footer, right) | Cancel `secondary` (left of primary) | — |+| Properties panel | none (autosave) | tiny ghost copy-link / copy-id icon buttons at top | — |+| Settings card | Save in `CardFooter` (or instant Switch) | — | — |+| MES operation | giant Start/Pause in the dock | full-width `lg` buttons in the dock, "More actions" sheet | confirm modal |++A card's section title is left, its action right:+`<HStack className="justify-between items-start"><CardHeader>…</CardHeader><CardAction><New to="new" /></CardAction></HStack>`+(exemplar `modules/sales/ui/Customer/CustomerContacts.tsx`).++## 3. Overlay decision table++| Situation | Component | Size |+|---|---|---|+| Create/edit a config row from its list | `ModalDrawer` (drawer) via nested route | `md` (1/3); `lg` (1/2) for rule builders / many sections |+| Create an entity from inside a selector | the entity's form with `type="modal"` | Modal `medium` |+| Record / line form: page card vs inline create | `ModalCard` | `xlarge`; lines `xxlarge` |+| Read-only drill-down beside a list (ledger, audit log, run detail) | `Drawer` | `lg`/`xl`/`full` |+| Multi-step wizard, side-by-side comparison | `Drawer` | `xl`/`full` |+| Lifecycle transition needing confirmation or a few inputs (Post, Void, Finalize, Release, Approve, Send, Cancel order) | `Modal` | `medium`; `large`/`xxlarge` when listing lines |+| Destructive confirmation | `ConfirmDelete` / `Confirm` | medium |+| Non-committing pick or explanation (assignee, color, "why this price", filter, sort) | `Popover` | content |+| Rich hover preview | `HoverCard` | — |+| Explain an icon / truncated text | `Tooltip` | — |+| Overflow actions | `DropdownMenu` | — |+| MES action list | `BottomSheet` | `max-w-md` |+| A decision the user must make before continuing | `Modal` with two explicit choices — **not** a warning banner (`8ee90a4252`) | medium |++Don't: open a drawer from a drawer; put a top-level document create in a drawer; use a+full page for a 3-field lookup row; use a Modal for read-only reading material longer than a+screen (use a Drawer or route); use `window.confirm`.++Mount header-launched modals only when open (`{modal.isOpen && <XModal />}`); keep a drawer+mounted (`isOpen` prop) only when it must keep state between openings.++Any popover-based dropdown with an internal scroll list inside a Drawer/Modal must stop+`onWheel`/`onTouchMove` propagation on `PopoverContent` (`.claude/rules/conventions-ui.md`).++## 4. Overlay anatomy and button order++- Header → Title (+ optional Description). Titles `text-base font-medium`; Modal descriptions+ are common, Drawer descriptions rare.+- Body: Modal `px-6`; Drawer body is an inner white rounded card that scrolls.+- Footer: Modal footer is a tinted bar (`border-t bg-muted/40`), right-aligned; Drawer footer+ right-aligned; `CardFooter` left-aligned.+- Close ✕ is built into Modal/Drawer content — don't add another.++**Button order depends on the container:**++| Container | Order | Cancel variant |+|---|---|---|+| `ModalFooter` (confirm / action modal) | `[Cancel] [Primary]` — primary rightmost | `secondary` |+| `ModalDrawerFooter` / `DrawerFooter` (form drawer) | `<HStack>[Save] [Cancel]</HStack>` — Save leftmost | `solid` |+| `CardFooter` / `ModalCardFooter` (page form) | `[Save]` only | — |++When the primary action itself means "cancel", rename the dismiss button: "Back",+"Don't Cancel" + destructive "Cancel Job", "Keep editing" + destructive "Discard import".++**Submitting from an overlay:**+- One user action = **one** submission. Don't loop several `fetcher.submit` calls on one fetcher+ (each aborts the previous); send `ids[]` + parameters to one route and do the batching on the+ server (bulk routes switch on `field`/`intent`, e.g. `routes/x+/job+/update.tsx`).+- Keep the overlay open while submitting (`isLoading` on the primary, `isDisabled` on Cancel);+ close it when the fetcher returns success (a `useEffect` on `fetcher.state`/`fetcher.data`, as+ `CustomerTypeForm` does in modal mode) and show the toast then. On error keep it open with the+ message.+- Simple yes/no confirms: use `Confirm` (`confirmVariant`, `confirmText`) — it binds ⌘↵ via+ `SHORTCUTS.confirm` like `ConfirmDelete`.++Exemplars: `apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx`,+`modules/inventory/ui/Receipts/ReceiptPostModal.tsx`,+`modules/sales/ui/SalesOrder/CancelSalesOrderModal.tsx`.++## 5. Destructive actions++1. **Entry:** never a visible one-click button on a list or header. A `MenuItem destructive`+ (red) with `LuTrash`, **last** in the row menu; in header ⋯ menus after a+ `DropdownMenuSeparator`. Disabled when locked or without permission.+2. **Label:** "Delete" on document lists, "Delete <Entity>" on settings lists and headers+ ("Delete Line", "Delete Rule").+3. **Confirm:** `ConfirmDelete` — title "Delete {name}", body+ `t\`Are you sure you want to delete ${name}? This cannot be undone.\``, footer+ `[Cancel secondary] [Delete destructive ⌘↵]`. State consequences when they exist ("Any+ assignments referencing this printer will be cleared."). Override the verb with `deleteText`+ (Void, Remove, Reverse Entry).+4. **Wiring:** route-driven (`{collection}.delete.$id.tsx` renders ConfirmDelete; action deletes+ and redirects with `success("…")`) — exemplar+ `apps/erp/app/routes/x+/resources+/abilities.delete.$id.tsx`; or disclosure-driven in+ headers/tables (`{deleteModal.isOpen && <ConfirmDelete … />}`).+5. **No undo.** Reversibility is modelled as soft delete ("Deactivate", "Move to Trash").+6. Other destructive commits (Void, Reject, Cancel Job, Revoke) use `variant="destructive"`+ inside a confirm `Modal` that shows what will be affected.++## 6. Keyboard bindings for actions++- Combos are **named constants**: shared `SHORTCUTS` (`packages/react/src/shortcuts.ts`), ERP+ (`apps/erp/app/shortcuts.ts`), MES (`apps/mes/app/shortcuts.ts`). Never a string literal at+ the call site. Add new ones to the registry and to the app's `ShortcutHelp.tsx`.+- Bind via `Button shortcut={…}` (renders a keycap badge, inert when disabled, scoped to the+ topmost dialog), `useShortcutKeys`, `useShortcutKeyMap`; two-key sequences+ `useShortcutSequence`. Never a hand-rolled `keydown` listener.+- `Submit` binds ⌘/Ctrl+Enter automatically; confirms bind `SHORTCUTS.confirm`.+- **Enter** only on one-obvious-action screens (choice screens, single input); **⌘Enter** for+ real forms. Hide the keycap (`hideShortcutKey`) on trivial screens.+- MES: no bare letters (barcode scanners type); use `alt+digit`, space, enter, arrows.++## 7. Action microcopy++| Context | Pattern |+|---|---|+| Form submit | "Save" (create and edit) |+| Form dismiss | "Cancel" |+| List create | "Add <Entity>" (via `New label={t\`Entity\`}`) |+| Create from selector | "Create <typed text>" |+| New related doc in a menu | "New Shipment", "New Invoice" |+| Overlay title | "New <Entity>" / "Edit <Entity>" |+| Lifecycle modal title | "<Verb> <Entity>" ("Post Receipt", "Cancel Sales Order") |+| Lifecycle modal body | "Are you sure you want to post this receipt?" + consequences |+| Menu items | Title Case verb (+ noun): "Edit", "Delete Line", "Export Lines to CSV", "Reopen" |+| ⋮ aria-label | "More options" |++Buttons and menu items are **Title Case**. Some features added Aug–Sep 2026 use sentence-case+buttons ("Create new rule") — that's drift; use Title Case unless the neighbouring screens in+the same module are consistently sentence case.diff --git a/.claude/skills/carbon-design/references/anti-patterns.md b/.claude/skills/carbon-design/references/anti-patterns.mdnew file mode 100644index 0000000000..8bc66012a8--- /dev/null+++ b/.claude/skills/carbon-design/references/anti-patterns.md@@ -0,0 +1,134 @@+# Anti-patterns — what Carbon intentionally does not do++Three kinds:+1. **Generic SaaS reflexes** — technically fine, but they make a screen feel un-Carbon.+2. **Legacy patterns** — Carbon used to do these and deliberately moved away. Some still exist+ in the code; don't copy them.+3. **Carbon's own drift** — places where the codebase is inconsistent today, and what to do.++---++## 1. Generic SaaS reflexes++### Layout and hierarchy+- A hero/page header (title + subtitle + illustration + big CTA) above a list. → The `Table`+ `title` *is* the page title; one "Add X".+- Stacked tables or many widgets on one list page. → One table per list route; dashboards only+ on module landing pages.+- Client-side tabs for record sections. → Route tabs (`DetailsTopbar`) / Explorer / header view+ switcher.+- A detail page as one long form. → Header strip + Explorer | content cards | Properties.+- Metadata mixed into the main form or displayed as a big key/value table in the content. →+ Properties panel.+- Line items as a big editable spreadsheet in the content pane. → Explorer + Summary.+- Wide-screen layouts that stretch forever. → capped `max-w-*`.+- Nested scroll regions inside cards. → the page scrolls.+- Center-aligned content blocks / marketing-style sections in app pages.++### Visual+- Brand-colored primary buttons, colored headings, colored section backgrounds.+- Green/amber/yellow sentences to signal status. → muted text + `Lu*` icon; status chips.+- Big drop shadows, `rounded-2xl`/`3xl` on app boxes, gradients on panels, glassmorphism.+- Borders on top of primitive shadow edges (double lines); hand-rolled cards.+- Bold (`font-bold`/`semibold`) body text for emphasis; `text-lg`+ for card titles.+- Arbitrary sizes (`text-[13px]`, `h-[37px]`), raw grays (`text-gray-500`), hex colors.+- Icons from other sets, colored decorative icons, icon-only buttons for actions that need a word.+- Illustrations or large emoji in empty states; confetti; "🎉" toasts.+- Right-aligned numeric columns in list tables; bold totals.++### Interaction+- "Edit" button → edit mode → Save/Cancel for a document. → always editable, locked by status;+ Properties autosave.+- Autosave on create forms or multi-field edits. → explicit Save.+- Multiple primary buttons; a primary Cancel; a destructive action as a visible one-click button.+- Undo snackbars instead of confirmation. → `ConfirmDelete`; soft delete where reversible.+- `window.confirm`, hand-rolled confirm dialogs.+- Hiding controls a user lacks permission for. → disable.+- Warning banners for decisions. → Modal with explicit choices.+- Separate "View" / "Edit" / "Delete" buttons on every row. → `renderContextMenu`.+- Floating "+" action buttons on desk screens. → "Add X" in the title bar (FAB is MES-only).+- Hover-scale animations, bouncy springs, page transitions, `transition-all`.+- A spinner covering the page for data loads. → skeleton / NProgress / `isLoading` button.+- Toast for validation errors. → inline field errors.+- Required-field asterisks. → "Optional" tag.+- Custom "?" tooltips on labels. → `termId` glossary help.+- Hand-rolled `keydown` listeners, combo string literals at call sites.+- Drawer opening another drawer; modal for long read-only content.+- Holding view state in `useState` that should survive refresh (tab, filter, selected record).+- Records listed as `div` stacks with fixed-width columns inside drawers/modals. → `TableBase`+ primitives with Hyperlink IDs and the entity's Status.+- A drawer/popover that opens before its data and shows the empty message or the previous+ selection's rows while loading. → skeleton, then data or empty.+- Several submits looped on one fetcher; closing the modal immediately after submit. → one+ server-side bulk submission; close on success.+- Trend arrows in green/red text; colored numbers inside sentences. → `Badge green|red`.+- Continuous rainbow/graded heat ramps. → discrete bands, number in every cell.+- Comparison matrices with criteria as rows when users need to pick the best row. → items as+ rows, sortable criteria as columns.+- Native `title=` tooltips. → `Tooltip`.+- Designing against invented APIs (props, route helpers, columns) or restating a sibling's+ constants from memory. → open the source; import the constant.++### Copy+- "Oops!", "Successfully saved! 🎉", exclamation marks, marketing voice.+- Sentence-case buttons/headers in ERP; Title Case toasts.+- English literals "for now"; concatenated translated fragments; "(s)" plurals.+- Data-model words where users have their own ("Procedure" for operators, "entity", "record").+- Showing raw UUIDs, raw enum values, or ISO timestamps.++## 2. Legacy patterns — don't copy even if you see them++| Legacy | Use instead | Moved in |+|---|---|---|+| `hover:scale-95` on buttons, `transition-all` | `active:scale-[0.96]`, scoped transitions | `6ac029e9d3`, `099ff087c2` |+| `shadow-sm` on inputs/selects | flat bordered fields | `fb5a23f67c` |+| Card with `border` + dark gradient; hand-rolled `rounded-lg border bg-card` cards | `Card > CardHeader + CardContent` | `4d7500407a`, `c238af5f5a` |+| Modal as a gray tray with an inset white body; Modal on `bg-background` | single `bg-card` modal + muted footer bar | `3afa609c17`, `920b207e92` |+| Edge-attached drawer | floating drawer (primitive) | `30fd547b16` |+| `bg-muted` app-shell/entity layouts | `bg-card` content on `bg-background` chrome | `8aa53b0439`, `3237d6a639` |+| Ad-hoc uppercase eyebrow labels (`text-xxs uppercase tracking-wide …`) | `Subheading` | `6409f4bc4e` |+| Raw `<h1 className="text-xl font-semibold">` titles; `font-headline` on card/modal titles | `Heading`; sans titles | `2fffd20eab` |+| Amber/green status text | `Badge`/`Status`, or muted text + icon | `c10513d5c9` |+| Loud `Alert variant="warning"` for context | calm Card with one accent icon / `Alert info` | `b15cb4e9f2` |+| Solid colored Badges for flags | outline Badge / dot + label | `e984069683` |+| Plain Badge for lookup values; non-wrapping chip rows | `Enumerable` / `EnumerableGroup` +N | `fb87a5ac41`, `4634b460f0` |+| Local status color maps; Status without icon | `status-colors.ts` + `Status` | `771e6b5069`, `ba3a286b5c` |+| `toLocaleString`, `new Date()` display | `DateTime`, formatter hooks | `c0f5783516` |+| `LoadingBars` | `CarbonPulse` | `2fffd20eab` |+| `useKeyboardShortcuts`, `usePrettifyShortcut` | `Button shortcut`, `useShortcutKeyMap` | `c1d997d77e` |+| `Progress` | `BarProgress` | `fe93c3c0b1` |+| Pill (`rounded-full`) tabs | `Tabs` primitive | `409850aab5` |+| Capped `max-h` + inner scroll on card lists | natural height | `a277baeadd` |+| Hard-coded `h-[50px]` headers; `100dvh` calcs without the inset | `h-[var(--header-height)]`, subtract `--content-inset` | `7f5f1d2145`, `6409f4bc4e` |+| Auth screens inside a bordered card | form directly on background | `c249b2fe76` |+| Selection ring on read-only cells | ring only on editable cells | `6ea9142601` |+| "No results / Remove Filters" for pre-filtered tables | `emptyState` neutral sentence | `678cf28e16` |+| Combobox "Add X" button empty state | inline sentence link (`useEmptyState`) | `ce5aa7d0d8` |+| Tables for small rich config sets | cards + drawer | `ad9e436003` |+| Posting-group-style N×M config matrices | flat defaults + per-entity override | `.ai/lessons.md` |+| Collapsed line-item forms when editing | expanded by default | `540abad96d` |+| Emoji in CTAs/confirmations | plain copy | `1640fdd35e` |+| `Spinner className="h-8 w-8"` | `Spinner size={32}` | — |+| Non-Lucide icons (`BsThreeDotsVertical`, `IoMdAdd`, `RxCheck`, `FaTrash`) | `LuEllipsisVertical`, `LuPlus`, `LuCheck`, `LuTrash` | — |++## 3. Carbon's own drift — what to do today++| Where Carbon is inconsistent | Do this |+|---|---|+| Detail content pane background: `6409f4bc4e` moved it to `bg-card`, the Returns PR `9b26ab2dc1` put `bg-muted dark:bg-card` back; all 23 3-pane routes use the latter today | Copy the sibling route shell verbatim for consistency; mention it in your summary as an open question — don't introduce a third value |+| Card radius: docs say `rounded-2xl`/`rounded-lg`, code is `rounded-xl` | Trust the primitive; never override Card radius |+| "Shadows over borders" (conventions-ui) vs borders dominant in app code | Shadows belong to primitives; app inner boxes use `border rounded-lg` |+| Header transitions: show-all-disabled (Quote) vs show-only-valid (RMA) | Either, consistently within the header; next step always visible and primary |+| Button/menu casing drift to sentence case in Aug–Sep 2026 features | Title Case, unless the same module is consistently sentence case |+| Status word colors (`Closed`, `Pending`, `In Progress`) | Choose by lifecycle position; follow the entity family's existing map |+| Success toast grammar mixed | "Updated X" / "X created" / "X deleted" |+| Arbitrary micro text sizes (~170 uses) | `text-xs`, or `text-xxs` if you must |+| `text-amber-*` (~50 uses) | amber only as an icon/dot accent |+| Raw status enums in ~26 wrappers | translate in the wrapper |+| Hover reveals without focus reveals | add `focus-visible`/`group-focus-within` |+| Ellipsis aria-labels vary | "More options" |+| Focus ring: Button blue halo vs fields `ring-ring` | reuse the primitive; for new field-like elements use the `ring-ring/50` recipe |+| `.claude/rules/conventions-ui.md` / `packages/react/AGENTS.md` claims that disagree with code | code wins; note the discrepancy in your summary |++Rule of thumb from `principles.md` §4: majority in code → newest canonical module (Sales Return+Orders) → written rule — and never copy anything in section 2.diff --git a/.claude/skills/carbon-design/references/components.md b/.claude/skills/carbon-design/references/components.mdnew file mode 100644index 0000000000..379420283f--- /dev/null+++ b/.claude/skills/carbon-design/references/components.md@@ -0,0 +1,260 @@+# Components — what exists, when to use it, how to extend++Primitives: `@carbon/react` (`packages/react/src/`, flat files, barrel `index.tsx`, subpath+exports `@carbon/react/{Chart,Editor,ErrorBoundary,…}`). Form fields: `~/components/Form`+(`apps/erp/app/components/Form/index.ts` — `@carbon/form` fields + ~60 domain selectors).+App-level: `~/components` (`apps/erp/app/components/index.ts`) and `apps/mes/app/components`.++Status legend: **canonical** = default choice · **niche** = right for one job · **don't** =+dead, legacy or buggy.++## Contents+1. The reuse / extend / create rule+2. Catalog by job+3. Choosing between overlapping components+4. Variant semantics (Button, IconButton, Badge, others)+5. Do-not-use list+6. Gaps — patterns that are hand-rolled today+7. Building a new component the Carbon way++---++## 1. Reuse → extend → create++1. **Reuse** an existing component when its *job* matches (not just its look). Grep+ `packages/react/src/` and `apps/erp/app/components/` first.+2. **Extend** it (a new variant, prop or slot) when the job matches but a real, recurring need+ is missing — and the extension would make sense for other call sites.+3. **Create** a new component only when the job is genuinely new. Build it from tokens and+ primitives (§7) so it still looks native.+4. **Never force** a component into a job it wasn't made for (a `Status` pill for a category,+ a `Table` for 3 config rows, a `Card` as a list row, `Badge` as a button, `Alert` for+ routine info). A forced fit reads as "almost Carbon", which is worse than a clean new piece.++## 2. Catalog by job++### Actions+| Component | Job | Status |+|---|---|---|+| `Button` | every text button. Variants `primary secondary solid active destructive ghost outline link`, sizes `sm md lg`, `leftIcon/rightIcon`, `isLoading`, `isDisabled`, `asChild` (Link as button), `shortcut` | canonical |+| `IconButton` | icon-only button; **requires** `aria-label`; always set `variant` explicitly | canonical |+| `New` (ERP) | list "Add X" primary link-button with `LuCirclePlus`, binds `n` when sole | canonical |+| `Submit` (form) | form submit: loading, disabled, ⌘↵, unsaved-changes blocker | canonical |+| `SplitButton` | one main action + alternates (Job Release ▾ Mark as Planned) | niche |+| `DropdownMenu` + `IconButton LuEllipsisVertical` | "More options" overflow | canonical |+| `Menu`/`MenuItem`/`MenuIcon` | row actions via `Table renderContextMenu` (renders both right-click and ⋮) | canonical |+| `Menubar`/`MenubarItem` | strip of tool actions above a section; stage flow bars | niche |+| `Copy` | copy-to-clipboard icon button (check for 1.5s) | canonical |+| `File` | "Upload" button opening a file picker | canonical |+| `ActionBar`, standalone `Toggle` | — | **don't** (dead) |++### Surfaces and overlays+| Component | Job | Status |+|---|---|---|+| `Card` + `CardHeader/Title/Description/Content/Footer/Action` | a section on a page; `isCollapsible` | canonical |+| `CardAttributes/CardAttribute*` | label/value strip in a header card | niche (under-used) |+| `ModalDrawer` (+ `ModalDrawerProvider type`) | config-row create/edit: drawer on its route, modal when opened from a picker | canonical |+| `ModalCard` (+ `ModalCardProvider type`) | record/line form: card on the page, modal when creating | canonical |+| `Modal` | confirm, lifecycle transition, short focused task, inline create | canonical |+| `Drawer` | read-only drill-down, large editor, wizard, comparison (`size lg/xl/full`) | canonical |+| `ConfirmDelete`, `Confirm` (`~/components/Modals`) | destructive / generic confirm | canonical — never hand-roll |+| `Popover` | click-to-open, non-committing pick or explanation | canonical |+| `HoverCard` | rich preview on hover (documents, glossary) | niche |+| `Tooltip` | one short line explaining an icon or truncated text | canonical |+| `TruncatedTooltipText` | text that shows a tooltip only when clipped | canonical |+| `BottomSheet` | MES touch action sheet | niche (MES) |+| `ScrollArea`, `Resizable*`, `Separator`, `Collapsible`, `Accordion` | plumbing | canonical / niche |++### Data display+| Component | Job | Status |+|---|---|---|+| `Table` (ERP `~/components`) | every record list | canonical |+| `Table/Thead/Tr/Td` (`@carbon/react`) | small static tables inside cards | canonical primitive |+| `Grid` (ERP) | small editable child lists on master data | niche |+| `TreeView` (ERP) | hierarchies (BoM, CoA, lines with methods) | canonical |+| `SortableList` / `LineReorder` | ordered, individually edited children | canonical |+| `Status` (via `*Status.tsx`) | workflow state | canonical |+| `Badge` | tags, identifiers, ad-hoc semantic facts | canonical |+| `Enumerable` / `EnumerableGroup` (ERP) | user-defined lookup values (hash color, `+N` overflow) | canonical |+| `Count` | number next to a label/tab ("99+") | canonical |+| `Avatar`, `EmployeeAvatar`, `CustomerAvatar`, `SupplierAvatar`, `*AvatarGroup` | people and partners | canonical |+| `ItemThumbnail` | item image/placeholder | canonical |+| `Hyperlink` (ERP) | link to a record in a cell, hover "Open" | canonical |+| `DateTime` (ERP wrapper) | every displayed date/time (company timezone popover) | canonical |+| `BarProgress` | progress / x-of-y meter | canonical |+| `MetricCard` | KPI tile | canonical |+| `Activity` | history/activity row | niche |+| `Heading`, `Subheading`, `SettingsSectionHeader` | titles, eyebrows | canonical |+| `Chart` (subpath: `ChartContainer`, `ChartTooltip`, `ChartLegend`) | charts, with theme vars `hsl(var(--chart-N))`; pair with `DateSelect`/`PeriodSelector` for the period and `CSVLink` for export — exemplar `apps/erp/app/modules/items/ui/Item/ItemCostHistoryChart.tsx` (Card + Tabs chart/table) | canonical |+| `Paragraph`, `Kbd`, `Progress`, `TextShimmer`, `TVColorBars`, `Brackets`, `AutodeskViewer` | — | **don't** |++### Feedback and state+`Alert` (in-page banner; destructive/warning/info/success), `toast` (client), `flash()`+(server), `Spinner` (inline, size via `size={n}` prop), `Loading` (region), `Skeleton`+(known shape), `CarbonPulse` (full-screen brand wait), `PulsingDot` ("live"), `Empty` (ERP+in-panel empty), `UpgradeOverlay` (plan gating). Details in `status-and-feedback.md`.++### Inputs (raw `@carbon/react` outside forms; `~/components/Form` inside `ValidatedForm`)+`Input`/`InputGroup`, `NumberField`, `Textarea`, `Checkbox`, `Switch`, `RadioGroup`,+`RadioGroupButton`, `ChoiceCardGroup`, `ChoiceSelect`, `Select`, `Combobox`,+`CreatableCombobox`, `MultiSelect`, `CreatableMultiSelect`, `DatePicker`/`DateRangePicker`/+`DateTimePicker`/`TimePicker`, `Slider`, `InputOTP`, `Label`, `LabelWithHelp`,+`TrackedEntityPicker`, `ToggleGroup`, `Tabs`, `Editor` (rich text).++## 3. Choosing between overlapping components++### Overlays+| Need | Use |+|---|---|+| Confirm a destructive action | `ConfirmDelete` (or `Confirm` with `confirmVariant`) |+| Lifecycle transition needing confirmation or a few inputs (Post, Void, Release, Finalize) | `Modal` (`medium`; `large`/`xxlarge` if it lists lines) |+| Create/edit a config row from its list | `ModalDrawer` (default drawer `md`; `lg` if complex) |+| Create any entity from inside a selector | that entity's form with `type="modal"` |+| Record or line form that lives on the page | `ModalCard` (`xxlarge` modal for lines) |+| Read-only detail / drill-down beside a list, wizard, comparison | `Drawer` `lg`/`xl`/`full` |+| Pick a value / explain a number without committing | `Popover` |+| MES action list | `BottomSheet` |++### Menus+| Need | Use |+|---|---|+| Row actions in a list | `Table renderContextMenu` → `MenuItem` + `MenuIcon` |+| Record overflow | `DropdownMenu` + `IconButton variant="secondary" size="sm"` ⋮ |+| Button that opens choices (Preview ▾, Ship ▾) | `DropdownMenu` + `Button rightIcon={<LuChevronDown/>}` |+| Main action with alternates | `SplitButton` |+| Tool strip | `Menubar` |++### Selects+| Situation | Use |+|---|---|+| Short fixed enum (≤ ~10), no search | `Select` |+| Long / DB-backed list | `Combobox` or a domain selector (`Customer`, `Item`, `Employee`, `Location`…) |+| User may add the value | `CreatableCombobox` (domain selectors already open the entity form as a modal) |+| Many values | `MultiSelect` / `CreatableMultiSelect` |+| 2–5 modes that each need a sentence of explanation, with room | `ChoiceCardGroup` |+| Same, compact (toolbar/filter row) | `ChoiceSelect` |+| Keyboard choice screen with button-looking options | `RadioGroup` + `RadioGroupButton` |+| Boolean in a form | `Boolean` (Switch; `bordered` = toggle card with description) |+| Boolean in a table cell / row selection | read-only `Checkbox` |+| Switch a *view/mode* of the same content (date range, list/kanban) | `ToggleGroup` |+| Switch between content panels inside a card/panel | `Tabs` |+| Toolbar on/off state | `Button`/`IconButton variant={on ? "active" : "ghost"}` |++### Chips+| Meaning | Use |+|---|---|+| Workflow state of a record | `Status` via `{Entity}Status.tsx` |+| User-defined lookup value (type, group, location, UoM) | `Enumerable` |+| Neutral tag / typed metadata (with domain icon) | `Badge variant="secondary"` |+| Identifier / version / code ("V3", "JSON") | `Badge variant="outline"` |+| Ad-hoc positive/negative fact ("Expired", "+12%", "Error") | `Badge variant="green"|"red"|"yellow"|"blue"` |+| Count | `Count` |++### Loading+`Button isLoading` (actions) · `Skeleton` blocks (known shape) · `Loading` (unknown shape+region) · `Spinner` (inline) · `CarbonPulse` (full-screen brand) · `PulsingDot` (live, not+loading).++### Titles+Page title → `Heading` (serif sizes) / `Table title`; record ID → `Heading size="h4"`;+card title → `CardTitle`; eyebrow → `Subheading`; settings group → `SettingsSectionHeader`.++## 4. Variant semantics++### Button (1,300 call sites)+| Variant | Meaning | Typical labels |+|---|---|---|+| `primary` (default) | the **single** forward action on this surface | Save, Confirm, Release, Post, Send, Add X |+| `secondary` | every other real button (46% of all) | Cancel in **Modals**, Close, Preview ▾, Add Line Item, Download |+| `solid` | Cancel/Close in **Drawer** footers; buttons on already-tinted surfaces | Cancel |+| `ghost` | low-emphasis inline/toolbar actions, icon-as-child buttons in panels | copy, link, panel actions |+| `destructive` | irreversible or data-removing commit | Delete, Void, Reject, Deactivate, Cancel Job |+| `active` | pressed state of a toolbar toggle | `{isActive ? "active" : "ghost"}` |+| `link` | text links styled as buttons | Edit Shipping |+| `outline` | rare; MES week nav, topbar utility buttons | — |++Status-driven primary: `variant={status === "Draft" ? "primary" : "secondary"}`.+Sizes: `md` default in ERP, `sm` in dense rows/panels, `lg` in MES.++### IconButton+Always set `variant`: `ghost` for icons sitting on a surface or row (panel toggles, chevrons,+close, drag handle, row ⋮); `secondary` for standalone controls that must look like buttons+(header ⋮, Copy, pagination, refresh); `solid` on tinted surfaces (⋮ in explorer trees).+Header ⋮ is `size="sm"`. aria-label for ⋮: "More options".++### Badge+`secondary` neutral tags · `outline` identifiers/versions · color names for ad-hoc semantic+facts. Prefer color names (`red`) over `destructive`; `default` (primary-filled) is almost+unused.++### Others+- `Alert`: `destructive` (blocking error), `warning` (needs attention), `info` (context).+ Use inside modals/forms for conditions, not for action results (those are toasts).+- `Heading` sizes: `h3` screens/sections, `h4` record header, `h2` via Table.+- `Subheading`: `heavy` reports, `light` Properties/sidebars.+- `ModalContent size`: default `medium`; `small` confirm-ish; `large/xlarge/xxlarge` when+ listing lines. `DrawerContent size`: default `md` (1/3), `lg` (1/2), `xl`, `full`.+- `Switch`: `small` in dense lists, default elsewhere.+- `DateTime variant`: `date` (default for business dates), `absolute`, `relative`, `time`.++## 5. Do-not-use list++| Don't | Use instead |+|---|---|+| `ActionBar`, `Toggle` (standalone), `TVColorBars`, `Brackets`, `TextShimmer`, `AutodeskViewer` | — (dead) |+| `Progress` | `BarProgress` |+| `Paragraph` | `text-sm text-muted-foreground` |+| `Kbd` for shortcuts | Button `shortcut` / `ShortcutKey` |+| `TabsTrigger variant` | (prop is ignored) |+| `useKeyboardShortcuts`, `usePrettifyShortcut`, `LoadingBars` | deleted — `shortcut`/`useShortcutKeyMap`; `CarbonPulse` |+| `Spinner className="size-8"` | `Spinner size={32}` (inline style wins over classes) |+| `IconButton` without `variant` | explicit variant |+| Raw `<button>` styled by hand | `Button`/`IconButton` (a bare `<button>` is OK only as an unstyled full-row hit target, e.g. a tree row, with focus-visible styles) |+| Hand-rolled delete confirm, `window.confirm` | `ConfirmDelete` |+| Hand-rolled `animate-spin` icons | `Spinner` / `isLoading` |+| `Badge` for lifecycle status | `Status` |+| `FormLabel`/`FormError` outside `FormControl` (throws → 500) | plain `<label>` / heading |++## 6. Gaps — patterns that are hand-rolled today++Carbon has no shared component yet for these; match the existing hand-rolled shape exactly+(copy from the named exemplar) rather than inventing a variant:+- **Record header strip** — ~38 copies of the same container (exemplar+ `modules/sales/ui/SalesReturnOrders/SalesReturnOrderHeader.tsx`). `DocumentHeader` exists+ but is a Card-header used by posting docs.+- **Properties panel** — 24 copies (`modules/quality/ui/Issue/IssueProperties.tsx`).+- **`*Status.tsx` wrappers** — one per entity (`modules/sales/ui/Quotes/QuoteStatus.tsx`).+- **Hover-revealed row action** and **dashed "add" row** — raw buttons in trees/lists.+- **Label/value lists** in panels (CardAttributes exists but is rarely used).++If your feature would create the *third* copy of a gap pattern, consider proposing the shared+component — but ask first (`packages/react/AGENTS.md` "Ask First" covers changing the barrel or+widely used APIs).++## 7. Building a new component the Carbon way++Checklist for anything new:+1. **Place it right.** Generic, domain-free → `packages/react/src/{Name}.tsx` (flat, exported+ from the barrel — ask first). Knows about Carbon data (items, people, storage, company TZ)+ → `apps/erp/app/components/` (or the module's `ui/`). MES-only → `apps/mes/app/components/`.+2. **Compose primitives** (Radix-based parts, `Button`, `Popover`, `Badge`, `Card`) — don't+ re-implement focus, portals, keyboard handling or loading.+3. **Variants via `cva`** with *semantic* names (`secondary`, `destructive`, `heavy`) — not+ `blue`, `big`. Merge classes with `cn()`. `forwardRef` + `displayName`; `asChild` where a+ Link may need to be the element. Compound parts (`XHeader/XBody`) over config objects,+ unless the content is data-driven.+4. **Tokens only.** Colors from §1 of `foundations.md`; radius `rounded-md` (controls) or+ `rounded-lg` (boxes); sizes on the control scale (h-6/8/10/11/12); spacing 1/2/4.+5. **States:** hover `bg-accent` or `bg-muted`; selected `bg-accent/60`; focus+ `focus-visible:` ring (reuse `focus-visible:border-ring focus-visible:ring-[3px]+ focus-visible:ring-ring/50` for fields/cards); disabled `opacity-50` ++ `cursor-not-allowed`/`pointer-events-none`; loading via `isLoading`; invalid+ `border-destructive`. Pair every hover-reveal with `focus-visible`/`group-focus-within`.+6. **Motion:** property-scoped transition 150–200ms ease-out; press `active:scale-[0.96]`;+ `motion-reduce:` fallback; `AnimatePresence initial={false}`.+7. **Copy:** all strings via Lingui; aria-labels translated.+8. **Dark mode + a non-zinc theme** checked.+9. **MES variant?** If operators will use it, give it a touch size (`lg`, ≥44px) rather than a+ separate component.+10. **One concept, one component:** if it replaces ad-hoc markup elsewhere, say so in your+ summary and offer to sweep the call sites (don't do it unasked).diff --git a/.claude/skills/carbon-design/references/content-and-copy.md b/.claude/skills/carbon-design/references/content-and-copy.mdnew file mode 100644index 0000000000..584a1cf7d4--- /dev/null+++ b/.claude/skills/carbon-design/references/content-and-copy.md@@ -0,0 +1,124 @@+# Content and microcopy++## Contents+1. Casing+2. Tone+3. Copy patterns by surface+4. Lingui — every string translatable+5. Terminology and glossary+6. Formatting numbers, money, dates++---++## 1. Casing — Title Case names things, sentence case says things++| Title Case | Sentence case |+|---|---|+| column headers ("Start Date", "Unit of Measure") | toasts ("Updated quote line") |+| form labels ("Tax Amount") | empty states ("No lines yet") |+| buttons ("Add Note", "Mark Short") | descriptions, helper text |+| menu items ("Delete Line", "Export Lines to CSV") | confirmation bodies |+| page, table, card, modal and drawer titles ("Sales Orders", "New Payment Term") | placeholders ("e.g. Acme Manufacturing") |+| breadcrumbs, sub-nav entries | aria-labels ("Remove slide") |+| | modal titles phrased as questions ("Discard this import?") |++Minor words stay lower in Title Case ("Unit of Measure", "Copy Link to Sales Order"). Domain+nouns keep capitals inside sentences only when they're proper Carbon objects in context — be+consistent within a screen (don't mix "Copy link to issue" and "Copy link to Sales Order").++## 2. Tone++- **Terse and system-voiced for outcomes:** "Failed to update quote", "Supplier part deleted".+- **Consequence-first for risk:** "Are you sure you want to delete SO-0012? This cannot be+ undone." State side effects: "Any assignments referencing this printer will be cleared."+- **Plain questions on the shop floor:** "How many were actually picked?"+- **Definitional on create:** "A customer is a business or person who buys your parts or+ services." (one sentence, create mode only)+- **Toggle labels state the current state + consequence:** "Materials are included" /+ "Materials are not included", with one explanatory line.+- **Warmth only at the edges:** "Looks empty here 👀", "Search across your workspace...". No+ exclamation marks, no emoji in CTAs or confirmations, no "Oops!", no marketing voice.+- **Honest:** never claim a state you haven't confirmed ("pending" must mean pending).+- **Numbers carry context:** "12 of 40", "3d late", "Expires in 12d".++## 3. Copy patterns by surface++| Surface | Pattern |+|---|---|+| List title | plural noun: "Sales Orders" |+| List create | "Add <Entity>" |+| Overlay title | "New <Entity>" / "Edit <Entity>" (one `<Trans>` per title) |+| Record card title (edit) | "<Entity>" or "<Entity> Overview" |+| Submit | "Save"; a domain verb only if the submit is a domain action ("Post", "Register") |+| Lifecycle modal | title "<Verb> <Entity>"; body "Are you sure you want to <verb> this <entity>?" + consequences |+| Delete confirm | title "Delete {name}"; body "Are you sure you want to delete {name}? This cannot be undone." |+| Validation | "<Field> is required" |+| Success toast | "Updated <noun>" / "<Noun> created" / "<Noun> deleted" |+| Error toast | "Failed to <verb> <noun>" |+| Empty (lifecycle) | "No <things> yet" |+| Empty (search) | "No <things> found" / "No results found" |+| Empty selector | "No <plural> yet" + "Add your first <noun> so you can assign it here." |+| Access | "Access Denied" (toast) |+| Unsaved | "Unsaved changes" / "Stay on this page" / "Leave this page" |+| Loading | "Loading..." / "Loading <noun>..." |+| Placeholder | "Select", "Search...", "e.g. …" |++## 4. Lingui — every string translatable, as a whole++Rule (project memory + `.claude/rules/i18n-lingui-system.md`): **all new user-facing copy is+translatable from day one** — labels, buttons, titles, headers, menu items, toasts, empty+states, aria-labels, tooltips, placeholders, descriptions.++- Components: `const { t } = useLingui()` → `t\`…\``; JSX: `<Trans>…</Trans>`; static+ descriptors (breadcrumbs, module lists, glossary): `msg\`…\`` translated at render.+- **One message per sentence/title.** Never concatenate fragments (`<Trans>Edit</Trans>{" "}+ <Trans>Customer Type</Trans>`, `${t\`Add\`} ${label}`) — word order differs by language.+- **Plurals with `<Plural>`**, not "(s)" (`modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx`+ shows the right way).+- **Status labels are translated** in their wrapper (older wrappers render the raw enum).+- **Labels in constants and config objects** (period options, chart `ChartConfig` labels,+ select options, column-group names) are `msg\`…\`` descriptors rendered with+ `i18n._(descriptor)` (from `useLingui()`), or built inside the component with `t`. A plain+ string passed to `t(variable)` is never extracted. Placeholder values like "N/A" are+ translated too (or use an em dash "—").+- Menu labels in bulk menus and row menus are `<Trans>` even when the surrounding sketch+ is "just a diff" — they're user-facing.+- Interpolate values into the message: `t\`Are you sure you want to delete ${name}?\``.+- After adding strings, the locale catalogs need extraction; see the `translate` skill for+ filling `.po` files.++Known gaps you must not copy: English defaults in `ConfirmDelete`/`Confirm`, `Copy`,+`ActionMenu`; raw status enums; English server flash strings; "(s)" plurals.++## 5. Terminology and glossary++- Carbon vocabulary: a **Method** = BoM + BoP; "Change Notice" (not ECO); method types "Make to+ Order | Purchase to Order | Pull from Inventory"; "Readable ID"/"Number" for human IDs.+ Check `packages/glossary/src/terms.ts` before naming a concept.+- Fields whose label is domain jargon get `termId` (→ `LabelWithHelp`). New terms: `msg` term ++ one-sentence definition + docs anchor, in `packages/glossary` (ask first).+- Name by the user's mental model, not the table name (`019fcf0a46`: "Procedure" →+ "Instructions" for operators). Order choices by likely use.++## 6. Formatting numbers, money, dates++| Kind | Use |+|---|---|+| Money | `useCurrencyFormatter()` (kinds: default, `rate`, `compact`, `wholeUnits`, `currency`); per-row currency `formatMoney` from `@carbon/utils` |+| Quantity | `useQuantityFormatter` |+| Number | `useNumberFormatter` (`@react-aria/i18n`) |+| Percent | `usePercentFormatter` |+| Duration | `formatDurationMilliseconds` |+| Date / time display | `<DateTime variant="date|absolute|relative|time">` (ERP wrapper adds company TZ) |+| Date in strings | `useDateFormatter()` from `~/hooks` (not the react-aria one) |++Dates in **labels and headers** (week columns, "Due Mar 4", period names) are formatted too —+`useDateFormatter().formatDate(value, options)` with `@internationalized/date` values, never+hand-built "Mar 4" strings or month-name arrays. Business "today" comes from the company or+location timezone passed down from the loader (`datetime.today(tz)` server-side,+`getLocationTimeZone`/`getCompanyTimeZone`), not the browser's zone, whenever it decides+which week/day a value falls in.++Never `toFixed`, `toLocaleString`, `new Date(...).toLocale…`, or `Date` arithmetic in UI+(`.claude/rules/date-handling.md`, `.claude/rules/numeric-precision.md`). Always+`tabular-nums` on displayed numbers.diff --git a/.claude/skills/carbon-design/references/design-review.md b/.claude/skills/carbon-design/references/design-review.mdnew file mode 100644index 0000000000..54f3e4e75f--- /dev/null+++ b/.claude/skills/carbon-design/references/design-review.md@@ -0,0 +1,134 @@+# Design-language review — run before calling any UI work done++This review is **mandatory** for every piece of UI designed or built with this skill. It is a+self-critique loop, not a formality: find the gaps, fix them, re-run until clean.++## How to run it++1. **Re-read the design brief** you wrote at the start (archetype, sibling exemplar, reuse /+ extend / create decisions).+2. **Open the sibling exemplar again** and compare side by side — structure, header, actions,+ states, copy. Differences must be intentional and justified.+3. **Walk the checklist below.** For every item answer PASS / FIX / N/A. Every FIX gets changed+ now, not listed as a follow-up.+4. **Grep your diff** for the mechanical red flags (§3).+5. **Render the states** mentally (or in the browser via the `test` / `agent-browser` skills if+ the app is running): empty, loading, one row, many rows, long text, locked, no permission,+ error, dark mode, mobile (ERP < 768px) or tablet (MES).+6. Repeat 3–5 until everything is PASS or a justified N/A. Then write the review summary (§4).++## 1. The seven questions (answer in one line each)++1. **Does this feel like Carbon?** Put it next to the sibling screen: would a user notice a+ different hand?+2. **Is the information hierarchy consistent?** Identity first; one primary; metadata recedes;+ structure / work / metadata in their zones.+3. **Did we introduce a new pattern unnecessarily?** For each new component or layout: which+ existing one was rejected, and why?+4. **Could an existing Carbon pattern solve this better?** (archetype, overlay, list shape,+ Status, Enumerable, Empty, BarProgress, ConfirmDelete…)+5. **Are spacing, typography, icons, controls and states consistent?**+6. **Does the interaction behave the way a Carbon user expects?** URL state, keyboard, where+ create opens, where actions live, save model, destructive flow.+7. **Did any generic SaaS reflex slip in?** Check `anti-patterns.md` §1 line by line.++## 2. Checklist++### Structure+- [ ] Correct archetype (`page-archetypes.md`) and matches its exemplar's shape+- [ ] Identity (readable ID / thumbnail / avatar) visible, copyable where the sibling allows, linked+- [ ] Meaningful view state lives in the URL (route or search params)+- [ ] Create opens where the rule says (full page / route drawer / modal / no form)+- [ ] Secondary things are hidden only in standard places (⋯, Properties, hidden columns, row menu)+- [ ] Breadcrumbs via route `handle`; paths via `path.to.*`; module registered in submodules / search / Create menu when applicable++### Actions+- [ ] Exactly one primary per surface; in headers it's the next lifecycle step+- [ ] Destructive actions are last in a menu, `destructive`, confirmed with `ConfirmDelete`/`Confirm`+- [ ] Permission-gated controls disabled, not hidden; locked states disable in place+- [ ] Footer button order matches the container (modal `[Cancel][Primary]`, drawer `[Save][Cancel solid]`, card `[Save]`)+- [ ] Icon-only actions are `IconButton` with explicit `variant` and translated `aria-label` (+ Tooltip)+- [ ] Shortcuts use named constants; ⌘↵ saves; no bare letters in MES++### Visual+- [ ] Tokens only — no raw grays, no hex, no arbitrary sizes; hue only for meaning+- [ ] Type roles right: serif only for page titles; `text-sm` body; `text-xs` muted labels; `font-medium` emphasis+- [ ] Spacing on the 4/8/16 rhythm; content widths capped like siblings+- [ ] Primitives own shadows/radius; app boxes `rounded-lg border`; no double edges; `Card > CardContent`+- [ ] Icons are `Lu*`, sized by context, colored only when meaningful; reuse the shared icon vocabulary+- [ ] Works in dark mode and a non-zinc theme++### Grounding+- [ ] Every import, prop, `path.to.*` helper, hook and schema column used was opened and confirmed in source+- [ ] Every "same as / copied from X" claim is an import of X or an exact quote of it+- [ ] Domain special cases are handled with the domain's own predicates (deadline types, lock helpers, nullable dates, multi-currency), and each has a designed rendering++### Data+- [ ] Lists use the shared `Table` with icons on every column, Title Case translated headers, identity column pinned+- [ ] Record lists inside drawers/modals/cards are tables (`TableBase` primitives or compact `Table`), not div stacks — with Hyperlink IDs and the entity's Status wrapper+- [ ] Comparison tables put the things being chosen in rows and the criteria in sortable columns+- [ ] Trends/deltas are `Badge green|red`; numbers inside sentences are not colored; magnitude grids use discrete bands (sibling's exact bands if one exists)+- [ ] Every value uses its semantic renderer (Status, Enumerable, EmployeeAvatar, DateTime, currency formatter, BarProgress)+- [ ] Numbers `tabular-nums`, left-aligned in lists, with context ("x of y")+- [ ] Status colors from `status-colors.ts`, chosen by lifecycle position; wrapper translates labels++### States+- [ ] Empty (lifecycle vs no results), loading (skeleton of real shape / `isLoading`), error (toast / inline), locked, no permission, plan-gated — each designed and honest+- [ ] Nothing can be mistaken for another state (empty vs failed, editable vs read-only, pending vs done)+- [ ] Every overlay/panel that fetches on open has loading (skeleton), error, and empty states — and never shows stale rows from a previous selection+- [ ] One user action = one submission; overlays stay open while submitting and close on success+- [ ] Hover reveals also reveal on focus; focus visible everywhere++### Forms+- [ ] Right container for the record's rank; one form component with swappable shell+- [ ] Layout: drawer single column; card grid 2→3 cols; custom fields last; long text below+- [ ] Optional tag (no asterisks), `termId` for jargon, helperText for constraints+- [ ] Explicit Save vs autosave per the rule++### Copy+- [ ] Title Case names things; sentence case says things+- [ ] Patterns match `content-and-copy.md` (Add X, New/Edit X, Failed to…, No X yet, This cannot be undone.)+- [ ] Every string (incl. aria-labels, toasts, tooltips, placeholders) through Lingui, whole sentences, `<Plural>` for plurals+- [ ] User's words, not table names++### Motion & a11y+- [ ] Property-scoped transitions 150–200ms, press not hover, `initial={false}`, `motion-reduce` fallback+- [ ] Keyboard path through the main flow; drag & drop has a keyboard sensor+- [ ] MES: ≥44px targets, nothing hover-only, one dominant action++## 3. Mechanical red flags (grep your changed files)++```bash+# run from the repo root; replace FILES with your changed .tsx files+FILES=$(git diff --name-only --diff-filter=AM -- '*.tsx')+grep -nE 'text-(gray|slate|zinc|neutral)-[0-9]|text-\[[0-9]+px\]|#[0-9a-fA-F]{3,6}\b' $FILES+grep -nE 'text-(green|emerald|amber|yellow)-[0-9]+' $FILES # ok on icons/dots only, never on prose+grep -nE 'transition-all|hover:scale|shadow-(lg|xl|2xl)|rounded-(2xl|3xl)' $FILES+grep -nE 'from "react-icons/(?!lu)|<svg' $FILES+grep -nE 'window\.confirm|addEventListener\("keydown"|toLocale(Date)?String|toFixed\(' $FILES+grep -nE '<IconButton' $FILES | grep -v 'variant=' # every IconButton sets a variant+grep -nE 'aria-label="[A-Za-z]' $FILES # literal aria-labels → t``+grep -nE '>\s*[A-Z][a-z]+( [A-Za-z]+)*\s*<' $FILES # bare JSX text → <Trans>+grep -nE '\(s\)' $FILES # plurals → <Plural>+grep -nE ' title=\{?["`t]' $FILES # native title= → Tooltip+grep -nE 'size="sm"' $FILES # MES files: every operator action is lg+grep -nE '<div[^>]*(divide-y|grid-cols-\[)' $FILES # record list as divs? → TableBase+grep -nE 'font-headline|size="h[123]"' $FILES # serif only for the page title+```+(`grep -P` may be needed for the lookahead on some systems; if unavailable, grep+`react-icons/` and inspect.) Every hit is either fixed or justified in the summary.++## 4. Review summary (write this at the end)++```+Design-language review+- Archetype: <A–I or MES> — exemplar: <path>+- Reused: <components/patterns>+- Extended: <what + why> (or none)+- New: <component/pattern + why no existing one fits + how it follows Carbon's language> (or none)+- Deviations from the exemplar: <each with a reason> (or none)+- States covered: empty / loading / error / locked / no-permission / dark / mobile|tablet+- Open questions for the team: <e.g. drift items touched> (or none)+- Props audit: <Component — props used — file:line of its props type> (one line each)+- Checklist: all PASS (N/A: …)+```diff --git a/.claude/skills/carbon-design/references/forms.md b/.claude/skills/carbon-design/references/forms.mdnew file mode 100644index 0000000000..6c48ce3c38--- /dev/null+++ b/.claude/skills/carbon-design/references/forms.md@@ -0,0 +1,235 @@+# Forms and inputs++Read with `.claude/rules/conventions-forms.md` (mechanics: `ValidatedForm`, zod validator,+route action). This file covers the **design** of forms: containers, layout, labels, save+model, copy.++## Contents+1. Principles+2. Which container a form lives in+3. Canonical skeletons (drawer, record card, settings card)+4. Field layout+5. Labels, optional, help, placeholders, validation+6. New vs edit+7. Save model — explicit submit vs autosave+8. Disabled, read-only, locked+9. Inputs — which field component++---++## 1. Principles++- **One form component, swappable shell.** The same `XForm` renders as a card on a page, a+ drawer over a list, or a modal from a picker; the provider (`ModalDrawerProvider` /+ `ModalCardProvider`) picks the shell and `<Hidden name="type" value={type} />` tells the+ action which one submitted.+- **Rank decides the container**, not taste (§2).+- **Save is explicit on forms; autosave only on property surfaces** (§7).+- **Mark optional, never required.** No asterisks anywhere.+- **Help lives in the label via the glossary** (`termId`), not in custom tooltips.+- **Flat forms.** Sections inside a form are rare; long text and uploads go below the grid.+- **Every selector can create what's missing** in place (domain selectors open the entity form+ as a modal, pre-filled with what was typed).++## 2. Which container++| Record rank | Container | Opened by |+|---|---|---|+| Primary record (customer, supplier, part…) and document **lines** | `ModalCard` — Card on the page; Modal (`xlarge`, lines `xxlarge`) when created inline | `/new` page, Explorer "Add Line Item" |+| Lookup / config record (types, reasons, terms, work centers) | `ModalDrawer` — Drawer (`md`, `lg` if complex) via nested route; Modal (`medium`) from a picker | list `Outlet`, selector "Create …" |+| Document header sections (payment, shipping, planning) and top-level new-document forms | plain `Card` with `CardFooter` Save | detail content pane, `new.tsx` |+| Company preference group | settings `Card`, one `intent` per card | settings page |+| A lifecycle transition that needs inputs | `Modal` form (see `actions-and-overlays.md`) | header button |++## 3. Canonical skeletons++### Drawer form (config row) — exemplar `modules/sales/ui/CustomerTypes/CustomerTypeForm.tsx`, `modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx`++```tsx+<ModalDrawerProvider type={type}>+ <ModalDrawer open={open} onOpenChange={(open) => { if (!open) onClose?.(); }}>+ <ModalDrawerContent>+ <ValidatedForm validator={xValidator} method="post"+ action={isEditing ? path.to.x(initialValues.id!) : path.to.newX}+ defaultValues={initialValues} fetcher={fetcher} className="flex flex-col h-full">+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing ? <Trans>Edit Payment Term</Trans> : <Trans>New Payment Term</Trans>}+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <Hidden name="type" value={type} />+ <VStack spacing={4}>+ <Input name="name" label={t`Name`} />+ {/* … */}+ <CustomFormFields table="x" />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}><Trans>Save</Trans></Submit>+ <Button size="md" variant="solid" onClick={() => onClose()}><Trans>Cancel</Trans></Button>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+</ModalDrawerProvider>+```+In modal mode the form closes itself and toasts on success via a `useEffect` on+`fetcher.state`/`fetcher.data` (see CustomerTypeForm). Route: `onClose={() => navigate(-1)}`;+the URL is the drawer's open state. Trivial one-field drawers add `hideShortcutKey` to Submit.++### Record form (card ↔ modal) — exemplar `modules/sales/ui/Customer/CustomerForm.tsx` (mirror `modules/purchasing/ui/Supplier/SupplierForm.tsx`)++```tsx+<ModalCardProvider type={type}>+ <ModalCard onClose={onClose}>+ <ModalCardContent size="medium">+ <ValidatedForm …>+ <ModalCardHeader>+ <ModalCardTitle>{isEditing ? <Trans>Customer Overview</Trans> : <Trans>New Customer</Trans>}</ModalCardTitle>+ {!isEditing && <ModalCardDescription><Trans>A customer is a business or person who buys your parts or services.</Trans></ModalCardDescription>}+ </ModalCardHeader>+ <ModalCardBody>+ <Hidden name="id" /><Hidden name="type" value={type} />+ <div className={cn("grid w-full gap-x-8 gap-y-4",+ type === "modal" ? "grid-cols-1" : isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-1 md:grid-cols-2")}>+ {/* fields … */}+ <CustomFormFields table="customer" />+ </div>+ </ModalCardBody>+ <ModalCardFooter>+ <HStack><Submit isDisabled={isDisabled}><Trans>Save</Trans></Submit></HStack>+ </ModalCardFooter>+ </ValidatedForm>+ </ModalCardContent>+ </ModalCard>+</ModalCardProvider>+```+Card forms have **no Cancel** (navigation is the cancel). Line forms: exemplar+`modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx` (`xxlarge`, locked by status).++### Settings card — exemplar `routes/x+/settings+/inventory.tsx`++```tsx+<SettingsSectionHeader><Trans>Kanban</Trans></SettingsSectionHeader>+<Card>+ <ValidatedForm method="post" validator={v} defaultValues={…} fetcher={fetcher}>+ <CardHeader>+ <CardTitle><Trans>Kanban Output</Trans></CardTitle>+ <CardDescription><Trans>Style of kanban output to show in the Kanban table</Trans></CardDescription>+ </CardHeader>+ <CardContent>+ <Hidden name="intent" value="kanbanOutput" />+ <div className="flex flex-col gap-8 max-w-[400px]">{/* fields */}</div>+ </CardContent>+ <CardFooter><Submit><Trans>Save</Trans></Submit></CardFooter>+ </ValidatedForm>+</Card>+```+A single boolean setting is a toggle card that saves on change (no footer) — exemplar+`routes/x+/settings+/items.tsx`.++## 4. Field layout++1. **Drawers:** single column, `VStack spacing={4}`. A small group of related numbers may sit in+ a `grid sm:grid-cols-3 gap-4` row (WorkCenterForm rates).+2. **Cards:** `grid w-full gap-x-8 gap-y-4`; create = `grid-cols-1 md:grid-cols-2`, edit =+ `grid-cols-1 lg:grid-cols-3`, modal = `grid-cols-1`.+3. **Order:** identity (ID, name) → classification (type, status) → relationships (customer,+ item, employee) → quantities / money → dates → location → `<CustomFormFields table=…/>`+ last in the grid. Long text (`TextArea`) and uploads **below** the grid, full width.+4. **Hidden fields first** in the body (`id`, `type`, FK context).+5. **Sections** (`Subheading variant="heavy"` between groups) only for genuinely long forms+ (WorkCenterForm: Basic Information / Costing / Scheduling). Prefer flat.+6. **Custom fields** — include `<CustomFormFields table="…"/>` on any entity that supports them.+7. **Boolean** in a form: `Boolean` (Switch). With `bordered` + `description` it becomes a toggle+ card: label + description left, switch right.+8. No field is wider than it needs to be in settings (`max-w-[400px]`).++## 5. Labels, optional, help, placeholders, validation++| Element | Rule | Example |+|---|---|---|+| Label | Title Case, translated `label={t\`…\`}`, rendered `text-xs font-medium text-muted-foreground` | "Customer Status", "Unit of Measure" |+| Optional | automatic "Optional" tag inferred from the zod schema; override with `isOptional` | — |+| Required marker | **none** — no asterisks | — |+| Help (domain term) | `termId="<entity>-<field>"` → `LabelWithHelp` info + HoverCard + "Learn more" | `termId="customer-status"` |+| Help (constraint/consequence) | `helperText` sentence under the field | "Customer ID cannot be changed after creation" |+| Placeholder | rare; "Select" for selectors, `e.g. …` for free text | `e.g. Acme Manufacturing` |+| Validation message | from zod: **"<Field> is required"**, sentence case | "Name is required" |+| Field error | below field, `text-destructive text-xs`; input `border-destructive`; first invalid field focused | automatic |+| Server failure | toast/flash "Failed to <verb> <noun>" — not inline | "Failed to create customer type" |+| Description on create | one definitional sentence "A <entity> is …" in the header, create mode only | CustomerForm |++New glossary terms: add to `packages/glossary` (`msg` term + one-sentence definition + docs+anchor) — ask first per `packages/glossary/AGENTS.md`.++## 6. New vs edit++| Aspect | New | Edit |+|---|---|---|+| Title | "New X" | "Edit X" (drawers) / "X" or "X Overview" (cards) — one `<Trans>` per title |+| Description | definitional sentence | usually omitted |+| ID field | `SequenceOrCustomId` | read-only `Input isReadOnly` (+ helperText) |+| Grid | 2 cols | 3 cols |+| Focus | `autoFocus={!isEditing}` on first field | none |+| Fields needing an id (contacts, jobs) | hidden | shown |+| Permission | `can("create")` | `can("update")` |+| Submit label | **Save** | **Save** |++Use a domain verb instead of "Save" only when the submit performs a domain action ("Submit+Inspection", "Register", "Post", "Dispose").++## 7. Save model++| Surface | Save model | Trigger | Feedback |+|---|---|---|---|+| Card / drawer / modal form | explicit `<Submit>` "Save" | click or ⌘↵ | page: flash via redirect; modal: toast |+| Properties panel field | autosave per field | `onChange` (select, date) / `onBlur` (text) → `fetcher.submit({ ids, field, value })` to a bulk-update route | toast on **error only** |+| Editable table/grid cell | autosave, optimistic | blur (Enter/Tab blur first) | revert + error |+| Single on/off setting | autosave | `Switch onCheckedChange` → `fetcher.submit({ intent, enabled })` | success toast |+| Multi-field setting group | explicit Save per Card | click | flash/toast |+| Canvas editors (workflow builder) | debounced autosave (~1s) | change | — |++**Rule:** autosave only when the change is a single reversible field on an existing record,+on a property/grid/toggle surface, with no cross-field validation. Anything that creates a+record, changes several fields together, or triggers a lifecycle event has an explicit button.+`Submit` guards unsaved changes by default ("Unsaved changes" / "Stay on this page" / "Leave+this page"); opt out with `withBlocker={false}` only inside tabs/modals where it misfires.++Properties panel fields still wrap each inline field in its own tiny `ValidatedForm` so field+components work; import those fields from `@carbon/form` directly (they use the `inline` mode).+Exemplar: `modules/quality/ui/Issue/IssueProperties.tsx`.++## 8. Disabled, read-only, locked++- **Read-only by nature** (IDs after creation, derived values): `isReadOnly`.+- **No permission:** `Submit isDisabled`; `isDisabled = isEditing ? !can("update", m) :+ !can("create", m)`. Menu items `disabled`, not hidden.+- **Document locked by status:** `ValidatedForm isDisabled={isEditing && isLocked}` with+ `isLocked = is{Entity}Locked(status)` from `{module}.models.ts`; server enforces with+ `requireUnlocked` (`apps/erp/app/utils/lockedGuard.server.ts`). Exit is "Reopen" in the ⋯ menu.+ No "locked" banner.++## 9. Inputs — which field component++**`~/components/Form` / `@carbon/form` fields only work inside a `ValidatedForm`** — they+call `useField`, which throws outside a form context. A control that lives outside a form+(a filter bar, a preview modal's parameters, a toolbar) uses the raw `@carbon/react` input+instead (`NumberField`, `DatePicker` with a `CalendarDate` value, `Select`, `Combobox`,+`ToggleGroup`), or the whole control group is wrapped in a `ValidatedForm` with a validator.++Inside forms import from `~/components/Form`: `Input`, `Number` (currency-aware in ERP),+`Select`, `Combobox`, `CreatableCombobox`, `MultiSelect`, `DatePicker`, `DateTimePicker`,+`Boolean`, `TextArea`, `Hidden`, `Submit`, `CustomFormFields`, `SequenceOrCustomId`, and domain+selectors (`Customer`, `Supplier`, `Item`, `Employee`, `Location`, `UnitOfMeasure`, `Currency`,+`Account`, … — check `apps/erp/app/components/Form/index.ts` before building a new one).+For a foreign key **always** use (or add) a domain selector; never a raw id input. A new domain+selector copies `apps/erp/app/components/Form/Customer.tsx` (creatable, opens the entity form as+a modal, permission-aware empty state via `useEmptyState` in+`apps/erp/app/components/Form/emptyStates.tsx`).++Selection widgets: see the Selects table in `components.md` §3.diff --git a/.claude/skills/carbon-design/references/foundations.md b/.claude/skills/carbon-design/references/foundations.mdnew file mode 100644index 0000000000..ef3ea72549--- /dev/null+++ b/.claude/skills/carbon-design/references/foundations.md@@ -0,0 +1,254 @@+# Visual foundations — color, surfaces, type, spacing, radius, icons++Read this when you set any class that affects color, size, spacing, radius, border, shadow,+font or icon. Values here were read from source on 2026-09-28; if a primitive changed since,+the primitive wins — re-read it.++## Contents+1. Color tokens and what each is for+2. Semantic color usage (the rules)+3. Surfaces and elevation+4. Typography+5. Spacing and density+6. Radius, borders, shadows+7. Icons+8. Dark mode and themes++---++## 1. Color tokens++Tokens are CSS variables injected on `<html>` per user theme (8 themes in+`packages/utils/src/themes.ts`, default `zinc`/"Modern"), mapped to Tailwind in+`packages/config/tailwind/theme.css`. **Never assume the primary is blue** — themes change it.++| Token (Tailwind) | Light (zinc) | Role |+|---|---|---|+| `bg-background` | gray 95% | app chrome: nav rail, page canvas, secondary-button fill, Properties panel (`bg-background/30`) |+| `bg-card` | white | the content you work in: content panel, `CardContent`, Modal, table, drawer body |+| `bg-popover` | white | dropdowns, popovers, tooltips (primitives set it) |+| `bg-muted` / `/50` `/40` `/30` | gray 93% | trays (Tabs list), row hover/selected, subtle fills, Modal footer bar (`bg-muted/40`) |+| `bg-accent` / `/60` `/30` | gray 96% | `Card` shell tray, dropdown focus, hover fill, selected explorer row (`bg-accent/60`) |+| `bg-active` + `text-active-foreground` | gray 85% | Button `active` variant, selected nav item |+| `text-foreground` | near-black | primary text |+| `text-muted-foreground` | gray 46% | secondary text, labels, metadata, decorative icons |+| `bg-primary` / `text-primary` | ink (theme-dependent) | primary button, count bubbles, links in places, selection tint `bg-primary/10` |+| `destructive` | red | destructive button, form errors, invalid border (`border-destructive`) |+| `border` / `input` | gray 90% | all borders (global `* { border-border }` — plain `border` is enough) |+| `ring` | ink | input focus ring (`focus-visible:ring-ring/50`) |+| `success` | green | **defined but ~unused** — don't build on it; use `Status color="green"` or `text-emerald-500` icons |++There is **no `warning` or `info` token**. Warnings use `Status`/`Badge` yellow/orange,+`Alert variant="warning"|"info"`, or an amber *icon*.++`secondary` (`bg-secondary`) is effectively unused. Don't introduce it.++## 2. Semantic color — the rules++1. **Neutral text:** `text-foreground` or `text-muted-foreground`. Never `text-gray-*`,+ `text-zinc-*`, `text-slate-*`. For slightly-muted in-between, `text-foreground/70-80`.+2. **Status:** only through `<Status color>` or Badge color variants (see+ `status-and-feedback.md`). Seven names: `gray yellow blue orange green red purple`.+3. **Categorical kind (type/entity):** hue identifies *kind* — domain icon maps in+ `apps/erp/app/components/Icons.tsx`, search entity chips; user-defined values via+ `Enumerable` (hash-colored, meaningless by design).+4. **Signed / threshold data:** `text-red-500` for negative, overdue, failed values in cells+ (e.g. overdue due date). Positive is usually just neutral; `text-emerald-500` only when+ "on time/good" genuinely needs affirming next to a red counterpart.+5. **Prose is never colored for status.** No `text-green-*`, `text-emerald-*`,+ `text-amber-*`, `text-yellow-*` sentences ("Planned automatically", "Low confidence").+ Use `text-muted-foreground` + a `Lu*` icon (`LuCircleCheck`, `LuTriangleAlert`) and let the+ words carry the meaning (`.ai/ds-rules.md`). Chips, dots, and severity icons may carry hue.+6. **Charts:** `hsl(var(--chart-1..6))` and theme vars, never hex.+7. **Hue recipe when you truly need a tinted chip or cell** (match `Badge`): light+ `bg-{hue}-100 text-{hue}-800 border-{hue}-500/20`, dark `dark:bg-{hue}-500/15+ dark:text-{hue}-400`. Green is **emerald**, purple is **violet**. A bare 500-level hue+ (`text-red-500`, `bg-emerald-500` dot) reads in both modes without a `dark:` pair.+8. **Trends and deltas** ("+12% vs last month", "3 fewer late receipts"): a `Badge+ variant="green"|"red"` next to the value, as the purchasing dashboard does+ (`apps/erp/app/routes/x+/purchasing+/_index.tsx`) — not colored text, not colored arrows.+9. **Numbers inside sentences are never colored** ("82% loaded · 40h of 48h"): keep the+ sentence muted; if the value is a problem, put a red `Badge` or a `LuTriangleAlert` icon+ beside it.+10. **Magnitude encodings (heatmaps, load grids, density):** use **a few discrete bands, never+ a continuous multi-hue ramp** or graded opacity steps, and show the number in every cell+ (`tabular-nums`) so color is never the only signal.+ - If a sibling view already encodes the same measure, **reuse its exact bands** — same+ thresholds, same classes, ideally the same exported function/constants — so two views+ never disagree. Work-center load today: `loadCellClass` in+ `apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsx` (> 120% red,+ > 100% amber, else emerald, all as `bg-{hue}-500/15 text-{hue}-700 dark:text-{hue}-400`).+ If it isn't exported, propose exporting it rather than copying the numbers.+ - With no sibling, healthy values stay **neutral** and hue appears only at problem+ thresholds (near → yellow/amber tint, over → red tint).+11. **Accent for "the thing that is selected/focused":** `bg-accent/60`, `bg-muted`,+ `bg-primary/10`, `border-primary ring-2 ring-primary/20` for selected cards/choices — never+ a saturated fill.++## 3. Surfaces and elevation++```+body / nav rail .......................... bg-background (gray)+ └ content panel (md+: inset, rounded-2xl) bg-card (white)+ ├ Card shell ......................... bg-accent + shadow-button-base + rounded-xl (the tray)+ │ ├ CardHeader ...................... transparent, px-6 py-4, text-muted-foreground+ │ └ CardContent ..................... bg-card + border + rounded-xl + p-6 (the paper)+ ├ Tabs list .......................... bg-muted tray; active tab bg-background + shadow+ ├ Table .............................. bg-card; row hover bg-muted+ └ inner boxes ........................ rounded-lg border p-3|p-4 (bg-card or bg-muted/40)+overlays: Modal bg-card rounded-2xl, footer bar border-t bg-muted/40+ Drawer floats inset p-3, shell bg-accent > DrawerBody bg-card rounded-xl+ Popover / Dropdown / Tooltip bg-popover rounded-md border shadow-md+Properties panel ......................... bg-background/30 border-l, w-96+```++Rules:+- **Compose `Card > CardHeader + CardContent`.** Content placed directly in `<Card>` reads gray.+ Never hand-roll a top-level card from `rounded-lg border bg-card`.+- **One edge per surface.** Don't put a border on something whose primitive already draws a+ shadow edge (a bordered `CardContent` under a `CardHeader` → `CardContent className="border-0"`+ with `CardHeader className="border-b border-border"`, per `.ai/lessons.md` "The design-system+ `Card` is a gray tray").+- **Tinting a Card shell** requires the `dark:` twin (`bg-emerald-500/5 dark:bg-emerald-500/5`)+ or the base `dark:bg-card` silently wins in dark mode.+- **Detail content area:** copy the background class of the sibling 3-pane route verbatim+ (currently `bg-muted dark:bg-card` on all 23 of them — see `anti-patterns.md` §Carbon's own+ drift). Don't invent a third option.+- **Scroll:** the page (or the content pane) is the only scroll surface. No `max-h` ++ `overflow-y-auto` regions inside cards (`.ai/lessons.md` "Card lists never get their own+ scroll region").+- **Full-height calcs** inside the content panel subtract `var(--topbar-height)`,+ `var(--header-height)` and `var(--content-inset)`; prefer `h-full` inheritance for new pages.++## 4. Typography++Fonts: Geist (sans, everything), Geist Mono (`font-mono`, ids/codes/system text), Hedvig+Letters Serif (`font-headline`, **page titles only via `Heading` display/h1/h2/h3**).++| Role | Use | Resulting style |+|---|---|---|+| Public / onboarding / greeting title | `Heading size="display"` or `"h1"` | serif |+| List page title | `Table title=…` (renders `Heading h2`) | serif `md:text-2xl` |+| Settings page / section title / DocumentHeader | `Heading size="h3"` | serif `md:text-xl` |+| Record header ID (SO-000123) | `Heading size="h4"` | **sans** `md:text-base text-sm font-medium` |+| Card / Modal / Drawer title | `CardTitle` / `ModalTitle` / `DrawerTitle` | sans `text-base font-medium tracking-tight` |+| Card / Modal description | `CardDescription` / `ModalDescription` | `text-xs` / `text-sm` muted |+| Eyebrow / group label | `Subheading variant="heavy"` (reports) or `"light"` (Properties, sidebars); `as="h3"` when it's a real heading | uppercase, tracked, small |+| Settings group label | `SettingsSectionHeader` | wraps `Subheading light` |+| Body / cells / inputs / menu items | — | `text-sm` |+| Labels, metadata, helper, errors | — | `text-xs` (labels `font-medium text-muted-foreground`) |+| Micro meta | `text-xxs` (10.8px token) | only when `text-xs` truly won't fit |+| IDs, codes, JSON, serials | `font-mono text-xs` (often `text-muted-foreground`) | |+| Any number that changes or aligns | `tabular-nums` | |+| KPI value | `MetricCard` (`text-4xl tabular-nums`) | |++Rules:+- Weight: `font-medium` is the emphasis weight (71%). `font-semibold` for totals rows and KPI+ numbers. `font-bold` only inside Badge and document-summary line totals. Never+ `font-extrabold`/`font-black`.+- **No arbitrary sizes** (`text-[11px]`, `text-[13px]`) in new code even though ~170 exist.+- **Uppercase is component-owned** (Badge/Status, `Subheading`, the mono empty-state label).+ Don't hand-write `uppercase tracking-wide` labels — use `Subheading`.+- Never a raw `<h1 className="text-xl font-semibold">` page title — use `Heading`.+- Wrapping: `text-balance` on titles, `text-pretty` on body (Tailwind v4 names), `truncate` /+ `line-clamp-1` in dense rows; `min-w-0` on flex children that must truncate. `truncate` is+ inert on `Heading` (it sets `text-balance`) — wrap it or use `noOfLines`.+- Page-level serif is a **brand moment**; never use `font-headline` on card, drawer, modal or+ record-header titles. A component rendered *inside* a page (a view, a panel, a section)+ never renders `Heading` h1–h3 — it titles itself with `CardTitle`, `Subheading`, or the+ host page's existing title (e.g. the `Table` title).+- Hover detail uses `Tooltip`, never the native `title=` attribute.++## 5. Spacing and density++Scale is 4px-based and dominated by **4 / 8 / 16**, with 6px for icon-text pairs.++| Use | Value |+|---|---|+| Icon + text in a chip/meta row | `gap-1` / `gap-1.5` |+| Default gap between siblings | `gap-2` (most used utility) |+| Between blocks / cards on a page | `gap-4`, `VStack spacing={4}` |+| Form grid | `grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4` (edit), `md:grid-cols-2` (create) |+| Drawer form fields | `VStack spacing={4}` single column |+| Detail content pane | `VStack spacing={4} className="p-4"` |+| Card internals | `CardHeader px-6 py-4`, `CardContent p-6` (from the primitive — don't override) |+| Inner bordered box | `p-3` or `p-4` |+| Page-level / empty-state breathing | `py-8`–`py-16`, settings page `py-12 px-4` |++Controls (heights): Button `sm h-6 · md h-8 (default) · lg h-11`; IconButton 24/32/44;+Input/Select `sm h-8 · md h-10 (default) · lg h-12`; table rows 44px. **Same-row buttons share a+size.** ERP uses md/sm; MES uses lg (see `shop-floor-mes.md`).++`VStack`/`HStack` take `spacing` (VStack 0,1,2,3,4,8; HStack 0,1,2,3,4,6,8), are+`space-y/x-*` based and `VStack` is `w-full`. Prefer `gap-*` when a child may inject siblings at+runtime (e.g. `Hyperlink` prefetch links) — `space-*` then adds a phantom margin+(`.ai/lessons.md` "`space-x-*` gives a phantom margin"). A flex child that fills the rest of a+row is `flex-1 min-w-0`, never `w-full`; fixed siblings get `shrink-0`.++Content widths are capped: full-page create `max-w-4xl`, posting documents `max-w-5xl`,+settings `max-w-[60rem]`, party records `max-w-[80rem]`. `2xl:` is never used; `xl:` rarely.++## 6. Radius, borders, shadows++`--radius` = 7px. `rounded-sm` 3 · `rounded-md` 5 · `rounded-lg` 7 · `rounded-xl` 11 ·+`rounded-2xl` 15 · `rounded-full` pills/avatars/dots.++| Element | Radius |+|---|---|+| App content panel, Modal | `rounded-2xl` (primitive) |+| Card shell, CardContent, Drawer body | `rounded-xl` (primitive) |+| Buttons, inputs, badges, popovers, dropdowns, tooltips | `rounded-md` (primitive) |+| **App-built inner boxes, list items, tiles** | `rounded-lg` |+| Dropdown items, small buttons | `rounded-sm` |++App code uses `rounded-lg`/`rounded-md`; `xl`/`2xl` belong to primitive shells. No `rounded-3xl`.++Borders: 1px `border` (color is global). Dividers `border-b` / `divide-y`, faded+`border-border/60`. Drop zones and "add" placeholders `border-dashed`. Inputs are **flat+bordered fields with no shadow** (`fb5a23f67c`).++Shadows: recipe shadows (`shadow-button-base`, dark inset stacks) live in primitives. App code+uses at most `shadow-sm` for small floating chips/drag previews; overlays get theirs from the+primitive. No `shadow-2xl`. Don't use the defined-but-dead tokens `shadow-popover`,+`shadow-dropdown-item`, `shadow-select-item`, `shadow-button-danger`.++## 7. Icons++- **Library: Lucide via `react-icons/lu` only** (`Lu*`, ~96% of icons). No other react-icons+ sets, no `lucide-react`, no inline `<svg>` for new work. A missing glyph is added the way+ `apps/erp/app/assets/icons/BanknoteArrows.tsx` does it (GenIcon with Lucide path data, stroke 2).+- **Sizing:** bare `<LuX />` renders at 1em and inherits size from text; `Button leftIcon` /+ `rightIcon` and `IconButton` size icons themselves (don't add classes). Explicit sizes:+ `size-4` (16px) standard, `size-3.5`/`size-3` in dense meta rows and chips, `size-6`/`size-8`+ only for empty-state or hero icons. Prefer `size-*` over `h-4 w-4` in new code.+- **Color:** inherit, or `text-muted-foreground`. Hue only when the icon *is* the status or+ type signal (`LuTriangleAlert text-red-500` for overdue, domain type icons).+- **Icon + text vs icon-only:** actions with a visible label use `leftIcon`. Icon-only is for+ universally understood, repeated, space-constrained actions (⋮, copy, link, close, panel+ toggles, drag handle, chevrons) and must be an `IconButton` with a translated `aria-label`,+ usually wrapped in a `Tooltip`. If the action needs a word to be understood, it gets a word.+- **Shared icon vocabulary** — reuse, don't re-pick:++| Meaning | Icon |+|---|---|+| Record ID column | `LuBookMarked` |+| Status column | `LuStar` |+| Dates (created, due, order) | `LuCalendar` |+| Person (created by, assignee) | `LuUser`; customer `LuSquareUser`; supplier `LuContainer` |+| Quantity / number | `LuHash` |+| Location | `LuMapPin`; tags `LuTag`; item group `LuGroup`; email `LuMail` |+| Edit / Delete | `LuPencil` / `LuTrash` |+| Add | `LuCirclePlus` (buttons), `LuPlus` (compact) |+| More options | `LuEllipsisVertical` (never horizontal) |+| Explorer / Properties toggles | `LuPanelLeft` / `LuPanelRight` |+| Warning / error inline | `LuTriangleAlert`; confirmed `LuCircleCheck`; copy `LuCopy`; link `LuLink` |+| Domain types | `MethodIcon`, `MethodItemTypeIcon`, `TrackingTypeIcon`, `TimeTypeIcon`, `OperationStatusIcon` from `apps/erp/app/components/Icons.tsx` |+| Module icons | `apps/erp/app/hooks/useModules.tsx` |++## 8. Dark mode and themes++`.dark` class on `<html>` swaps every variable, so **token-only UI needs no `dark:` classes**.+You need `dark:` only when you use a raw palette hue (then use the Badge recipe in §2) or tint+a primitive shell. In dark mode `card` is *darker* than `background` — never assume "card is+lighter". Test both modes and at least one non-zinc theme (e.g. `blue`) when you introduce any+color.diff --git a/.claude/skills/carbon-design/references/interaction-motion-a11y.md b/.claude/skills/carbon-design/references/interaction-motion-a11y.mdnew file mode 100644index 0000000000..c39bed46c1--- /dev/null+++ b/.claude/skills/carbon-design/references/interaction-motion-a11y.md@@ -0,0 +1,81 @@+# Interaction, motion and accessibility++## Contents+1. Interaction patterns+2. Motion+3. Accessibility+4. Responsive (ERP) — summary++---++## 1. Interaction patterns++| Pattern | Carbon way | Exemplar |+|---|---|---|+| Keyboard shortcuts | named constants + `Button shortcut` / `useShortcutKeys` / `useShortcutKeyMap`; listed in `ShortcutHelp.tsx` (see `actions-and-overlays.md` §6) | `packages/react/src/shortcuts.ts`, `apps/erp/app/shortcuts.ts` |+| Global search / go-to | ⌘K palette; register sub-pages via `use{Module}Submodules`; `g` + letter module go-to | `apps/erp/app/components/Layout/Topbar/Search.tsx` |+| Drag & drop | dnd-kit with **`KeyboardSensor` always**, pointer `activationConstraint: { distance: 8 }`, `TouchSensor` on touch boards, translated screen-reader announcements, `dropAnimation={null}` | `apps/erp/app/components/LineReorder/ReorderableLineList.tsx`, `apps/mes/app/components/Kanban/Kanban.tsx` |+| Reorder document lines | explicit edit mode: draft order, Save/Cancel bar, Esc cancels, Save disabled until dirty | `apps/erp/app/components/LineReorder/` |+| Reorder BoM/BoP | live reorder + throttled (~1s) save | `apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx` |+| Hover-revealed actions (ERP only) | `opacity-0 group-hover:opacity-100` **plus** `focus-visible:opacity-100` / `group-focus-within:opacity-100`; named groups (`group/row`) | `apps/erp/app/components/Hyperlink.tsx` |+| Context menus | same items as the ⋮ menu, via `Menu`/`MenuItem` (`Table renderContextMenu`) | `packages/react/src/Menu.tsx` |+| Optimistic UI | read pending `fetcher.formData` and render it as truth; no React `useOptimistic` | `apps/erp/app/components/Assignee.tsx` |+| Autosave | only on property/grid/toggle surfaces (`forms.md` §7) | `apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx` |+| Unsaved changes | `Submit` blocker (default on) | `packages/form/src/components/Submit.tsx` |+| Realtime | `RealtimeDataProvider` keeps picker caches fresh; screens revalidate on change but **not while a fetcher is submitting** | `apps/mes/app/hooks/useRealtime.tsx` |+| Bulk | `withSelectableRows` + `renderActions` (ERP tables only) | `apps/erp/app/modules/items/ui/Parts/PartsTable.tsx` |+| Barcode scanning | `useKeyboardWedge` buffers scans; a scanned Carbon URL navigates there; MES avoids bare-letter shortcuts | `packages/react/src/hooks/useKeyboardWedge.ts` |+| Copy identity | `Copy` next to IDs; "Copy link to X" / "Copy X number" icon buttons in Properties | `packages/react/src/Copy.tsx` |+| Audit | "audit log" item in the header ⋯ menu opens `AuditLogDrawer` (`useAuditLog`) | `apps/erp/app/components/AuditLog/` |+| Whole-row hit targets | a checkbox/choice row is a full-row `<label>` (`px-4 py-3 rounded-lg border hover:bg-accent`) | (`6e99e39b48`) |++No undo system exists — confirm destructive actions instead. No global "edit mode" for a record.++## 2. Motion++Motion is sparse and functional (framer-motion in ~43 files; no page transitions).++- **Durations:** 150–200ms default (`duration-150`, `duration-200`); 75ms for press; ≤300ms for+ panels. Nothing slow.+- **Easing:** `ease-out`; sidebar/panels ease-out-quint `cubic-bezier(0.23,1,0.32,1)`.+- **Transitions are property-scoped:** `transition-colors`, `transition-transform`,+ `transition-opacity`, `transition-[background-color,color,transform,box-shadow]`. Never+ `transition-all` in new code.+- **Press, not hover:** `active:scale-[0.96]` (Button has it). No `hover:scale-*`.+- **Enter/exit:** overlays animate via primitives (`animate-in fade-in zoom-in-95`) — don't add+ your own. `AnimatePresence initial={false}` so nothing animates on page load.+- **Icon swaps:** scale 0.25 → 1, opacity 0 → 1, blur 4px → 0, spring `bounce: 0`,+ `duration: 0.3`, `AnimatePresence mode="wait" initial={false}`+ (`apps/mes/app/components/JobOperation/components/Controls.tsx`).+- **Height changes:** animate height (shared panel) rather than a geometry jump (BoM/BoP expand).+- **Reduced motion:** every new motion gets a `motion-reduce:` fallback (`motion-reduce:transform-none`,+ `motion-reduce:transition-none`) or `useReducedMotion`.+- **Stagger** only for small groups revealed together (~60ms in, ~30ms out).+- Brand motion (CarbonPulse sweep, NProgress shine, VOID//SYS glitch) is for loading/error edges+ only.++## 3. Accessibility++- **Icon-only = `IconButton` with a translated `aria-label`** (type-required); wrap in `Tooltip`+ when not obvious. Never a bare `<button>` with only an icon.+- **Focus always visible** via `focus-visible:` (reuse primitive rings). Any hover-revealed+ control must also reveal on focus.+- **Status never color-only** — `Status` has icon + text; overdue gets text *and* an icon.+- **Semantics from primitives** (Radix, Base UI Tooltip, react-aria dates) — don't rebuild+ dialogs, menus, selects, or tooltips.+- **Headings:** `Subheading as="h3"` when it's a real section heading; `sr-only` labels for+ icon-only table columns ("Actions", "Expand").+- **Drag & drop:** keyboard sensor + translated announcements.+- **Field help:** `LabelWithHelp` (HoverCard + `sr-only` definition).+- **Hit areas:** ERP default buttons are 32px; for small custom targets extend the hit area with+ a pseudo-element (`before:-inset-2`) rather than growing the visual. MES targets ≥44px.+- **Clickable non-buttons:** avoid `onClick` on `div`/`tr`; use `Button`, `Link` or a `<label>`.+- **Known gaps to not copy:** untranslated aria-labels (esp. MES), hover-only reveals,+ `transition-all` + `hover:scale-105` on MES buttons without reduced-motion.++## 4. Responsive (ERP) — summary++Desktop-first, one JS breakpoint (768px). Panels collapse to drawers on mobile, Properties+collapses under 1024px, grids collapse to one column, headers scroll horizontally, content+widths are capped. `lg:` is the main layout breakpoint; `2xl:` is never used. Details in+`page-archetypes.md` §14; MES in `shop-floor-mes.md`.diff --git a/.claude/skills/carbon-design/references/page-archetypes.md b/.claude/skills/carbon-design/references/page-archetypes.mdnew file mode 100644index 0000000000..0416d6e088--- /dev/null+++ b/.claude/skills/carbon-design/references/page-archetypes.md@@ -0,0 +1,251 @@+# Page archetypes, layout and navigation++Every Carbon screen is one of a small number of archetypes. **Identify the archetype first**,+then open its exemplar and match the shape. Paths below are relative to `apps/erp/app/`+unless they start with `apps/` or `packages/`.++## Contents+1. App shell+2. Two navigation contexts: module mode vs document mode+3. Archetype A — Module list page+4. Archetype B — Document workspace (3-pane)+5. Archetype C — Item master (route tabs)+6. Archetype D — Party / master record (Customer, Supplier, Person)+7. Archetype E — Posting document (single column)+8. Archetype F — Settings preference page+9. Archetype G — Config collection (table + drawer)+10. Archetype H — Module dashboard+11. Archetype I — Split list/detail lookup+12. Where "create" opens — decision rule+13. Navigation: sub-nav, breadcrumbs, handles, command palette+14. Responsive behaviour+15. Choosing an archetype for something new++---++## 1. App shell (don't rebuild — plug into it)++```+┌──────┬──────────────────────────────────────────────────────────────────┐+│ RAIL │ ╭ content panel: bg-card, md:inset + rounded-2xl + border ───────╮ │+│ w-14 │ │ TOPBAR 49px Company ▾ / Module / List / ID ✎ 🔔 Avatar │ │+│ ⌕ │ ├────────────────────────────────────────────────────────────────┤ │+│ mods │ │ <main> module layout (sub-nav + Outlet) or document workspace │ │+│ ⚙ │ ╰────────────────────────────────────────────────────────────────╯ │+└──────┴──────────────────────────────────────────────────────────────────┘+```+- Shell: `routes/x+/_layout.tsx`. Rail: `components/Layout/Navigation/PrimaryNavigation.tsx`+ (icon rail, hover-expands, pushes content). Modules are registered in `hooks/useModules.tsx`+ (`{ key, permission, name, to, icon }`, Lucide icons, Settings pinned bottom).+- Topbar: breadcrumbs (from route `handle`), global ✎ Create menu+ (`components/Layout/Topbar/CreateMenu.tsx`), notifications, avatar.+- ⌘K command palette (`components/Layout/Topbar/Search.tsx`) indexes every module's+ `use{Module}Submodules` hook, so new sub-pages become searchable by registering them there.+- Layout CSS vars: `--topbar-height` 49px, `--header-height` 50px, `--content-inset`.++## 2. Two navigation contexts++| Context | Route folder | Chrome | Purpose |+|---|---|---|---|+| **Module mode** | plural: `routes/x+/sales+/…` | `GroupedContentSidebar` sub-nav (240px) + `<Outlet/>` | browse collections |+| **Document mode** | singular: `routes/x+/quote+/$quoteId…` | no sub-nav; full-width workspace | work on one record |++Both set `handle.module` so the rail stays highlighted. A detail route nested under a module+folder hides the sub-nav with `handle.hideModuleSidebar` (`utils/handle.ts`).++## 3. Archetype A — Module list page++```+┌ sub-nav ─────┬──────────────────────────────────────────────────────────────┐+│ ─ MANAGE ─ │ [◧] Quotes (serif h2) [⊕ Add Quote n] [⋮] │+│ ◉ Customers │ [✓3▾] [🔍 Search] [Filter] [Sort][Columns][◇View][⇩][‹›] │+│ ◉ Quotes ▾ │ (active filter chips — only when filters set) │+│ · My view │ ┌──────────┬─────────┬────────┬─────────┬────┐ │+│ ─ CONFIGURE ─│ │Q-00012 📌│Customer │ STATUS │ Expires │ ⋮ │ ← ID pinned │+│ ◉ Price Lists│ └──────────┴─────────┴────────┴─────────┴────┘ (drawer Outlet)│+└──────────────┴──────────────────────────────────────────────────────────────┘+```+- Route: `<VStack spacing={0} className="h-full"><XTable data count /><Outlet /></VStack>`;+ loader uses `getGenericQueryFilters(searchParams)` (`utils/query.ts`) → service →+ `{ data, count }`. Exemplar: `routes/x+/sales+/rmas.tsx` ++ `modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx`.+- **The `Table` `title` prop is the page title.** No bespoke header above a table.+- Everything else (columns, filters, row menu, empty state) → `tables-and-lists.md`.+- Sub-nav entries come from `modules/{module}/ui/use{Module}Submodules.tsx`. Group naming:+ first group = the module's main work ("Manage" or a domain name), middle groups =+ sub-domains, **last group = "Configure"** for lookup tables (often `role: "employee"`-gated).++## 4. Archetype B — Document workspace (3-pane)++For transactional/lifecycle records with lines or rich sub-content: Quote, Sales Order, PO,+RFQs, invoices, RMA, Job, Issue, Change Notice, Maintenance, Procedure, Training.++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ [◧] SO-000123 ⧉ [⋮] (TO SHIP) [Preview▾] [Ship] [Invoice▾] [RMAs▾] [◨] │ 50px+├──────────────┬──────────────────────────────────────────┬───────────────────┤+│ EXPLORER │ CONTENT p-4, VStack spacing 4, scrolls │ PROPERTIES w-96 │+│ resizable │ ┌ Summary card (lines, totals) ─────────┐ │ PROPERTIES 🔗 # ⧉│+│ ▸ Line 1 ⋮ │ ┌ Notes card ───────────────────────────┐ │ Customer ▸ │+│ ▸ Line 2 │ ┌ Documents card ───────────────────────┐ │ Assignee ▸ │+│ │ ┌ Payment / Shipping card forms ────────┐ │ Dates, custom… │+│ [⊕ Add Line ⌘⇧L]│ (selecting a line routes to it here) │ Tags │+└──────────────┴──────────────────────────────────────────┴───────────────────┘+```+- Route shell: `PanelProvider` → header component → `ResizablePanels explorer content+ properties` (`components/Layout/Panels.tsx`). Exemplar (newest, cleanest):+ `routes/x+/sales-return-order+/$id.tsx`, `$id.details.tsx`, `$id.$lineId.details.tsx` with+ `modules/sales/ui/SalesReturnOrders/SalesReturnOrder{Header,Explorer,Properties,LineForm}.tsx`.+ Richer: `modules/sales/ui/Quotes/QuoteHeader.tsx`,+ `modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx` (downstream-doc dropdowns),+ `modules/production/ui/Jobs/JobHeader.tsx` (derived badges, view switcher),+ `modules/quality/ui/Issue/IssueProperties.tsx` (autosave properties).+- `$id._index.tsx` redirects to `$id.details`. Parent loader loads the record + lines; children+ read them via `useRouteData(path.to.x(id))`.++**Header grammar** (container: `flex flex-shrink-0 items-center justify-between gap-x-4 p-2+bg-card border-b h-[var(--header-height)] overflow-x-auto scrollbar-hide` — it never wraps):++| Left = identity, in order | Right = lifecycle, in order |+|---|---|+| 1. ghost `IconButton` `LuPanelLeft` "Toggle Explorer" | 1. cross-links to related docs (secondary) |+| 2. `<Link>` → `Heading size="h4"` readable ID (+ `RevisionSuffix`) | 2. outputs: `Preview ▾` / `PDF` / `Reports ▾` |+| 3. `<Copy text={readableId} />` | 3. view switcher (only if the record has sub-views) |+| 4. ⋯ `DropdownMenu`: `IconButton variant="secondary" size="sm" icon={<LuEllipsisVertical/>}` — audit log, copy/revision, Reopen, separator, destructive Delete last | 4. lifecycle transitions — **next step is the only `primary`** |+| 5. `<EntityStatus />` + derived badges (Overdue, "3d late") | 5. downstream docs: plain button before any exist, `Receipts ▾` dropdown after |+| | 6. ghost `IconButton` `LuPanelRight` "Toggle Properties" |++Modals launched from the header are rendered after the header div and mounted only when open.++**Explorer:** full-height list, rows = thumbnail + `font-semibold` ID + muted description,+hover `bg-accent/30`, selected `bg-accent/60`, hover-revealed chevron + ⋮; pinned footer+`border-t p-4` with a full-width secondary "Add Line Item" (`EXPLORER_SHORTCUTS.addLine`, ⌘⇧L);+`Empty` + the same button when there are no lines. Hierarchical lines use `TreeView`.+Reorder is an explicit edit mode (`components/LineReorder/`).++**Properties:** `w-96 bg-background/30 h-full overflow-y-auto border-l border-border px-4 py-2+text-sm` (`w-[450px]` for rich documents). Top: `Subheading variant="light" as="h3"` "Properties"++ small copy-link / copy-id icon buttons; then readable ID and inline-editable name; then+labelled inline fields, each saving on change/blur to a bulk-update route; assignee, custom+fields, tags. Read-only when locked.++**Content:** a vertical stack of Cards. Documents show a `…Summary` card (line rows with+96px thumbnail, heading ID, line total, badges; totals block with muted Subtotal/Tax/Shipping+and `text-xl font-semibold` Total, all `justify-between`) — see+`modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx`. Line items are **never** a+list `Table` in the content pane.++## 5. Archetype C — Item master (Part, Material, Tool, Consumable, Service)++Header with identity left and `DetailsTopbar` (segmented route links with ⌘⇧letter shortcuts,+tabs disabled when irrelevant) right; explorer with client `Tabs` (Manufacturing / Used In) ++search; Properties shows the selected BoM node. Exemplar: `routes/x+/part+/$itemId.tsx`,+`modules/items/ui/Parts/PartHeader.tsx`, `modules/items/ui/Parts/usePartNavigation.tsx`,+`components/Layout/Navigation/DetailsTopbar.tsx`.++## 6. Archetype D — Party / master record (Customer, Supplier, Person)++Centered `max-w-[80rem] p-4`: header Card (name + ⋮ + `CardAttributes` strip of key facts) over+a `md:grid-cols-[1fr_4fr]` of `DetailSidebar` (sections with `Count` badges) and routed content.+Exemplar: `routes/x+/customer+/$customerId.tsx`, `modules/sales/ui/Customer/CustomerHeader.tsx`,+`components/Layout/Navigation/DetailSidebar.tsx`. Use for long-lived records with many+sub-collections (contacts, locations, terms) and no line-based lifecycle.++## 7. Archetype E — Posting document (Receipt, Shipment, Journal Entry, Fixed Asset)++Centered `max-w-5xl mx-auto p-4` stack of cards, no explorer/properties; header via+`components/DocumentHeader.tsx` inside a Card or a `*Header` strip. Lines are a card-row list+with inline inputs (`.claude/rules/shipments-receipts-ui-patterns.md`). Use for short-lived,+often system-generated documents that are filled in then posted.++## 8. Archetype F — Settings preference page++```+ScrollArea → VStack py-12 px-4 max-w-[60rem] mx-auto gap-4+ Heading h3 "Sales"+ SettingsSectionHeader "Documents"+ Card [ CardHeader(Title + Description) | CardContent(max-w-[400px] fields) | CardFooter(Save) ]+ Card [ CardHeader(Title + Description) … Switch on the right → saves instantly + toast ]+```+One Card = one independently saved concern (one `intent` each in the route action). A single+on/off is a `Switch` / `Boolean bordered` toggle card that autosaves; multi-field groups have+a Save footer. Exemplars: `routes/x+/settings+/sales.tsx`, `routes/x+/settings+/inventory.tsx`,+`routes/x+/settings+/items.tsx` (toggles), `components/SettingsSectionHeader.tsx`. A toggle's+label states the current state plus a one-line consequence (`dd560505c1`).++Company-wide preferences go in Settings (`modules/settings/ui/useSettingsSubmodules.tsx`).+Module lookup tables (types, reasons, statuses) go in the module's **Configure** sub-nav group,+not in Settings.++## 9. Archetype G — Config collection (table + drawer)++Lookup/config rows (customer types, scrap reasons, payment terms, API keys): list `Table`+whose first column is `Hyperlink → Enumerable value={name}` (relative link) and a drawer form+rendered via nested routes `{collection}.new.tsx`, `{collection}.$id.tsx`,+`{collection}.delete.$id.tsx`. Exemplar: `routes/x+/sales+/customer-types.tsx` (+ `.new`,+`.$customerTypeId`, `.delete.$customerTypeId`) and+`modules/sales/ui/CustomerTypes/CustomerTypeForm.tsx`. Small **rich** config sets (approval+rules, assignments) use cards + drawer instead of a table (`ad9e436003`).++## 10. Archetype H — Module dashboard++Module `_index.tsx` is either a redirect to the main list or a dashboard of `MetricCard`s ++a chart (`routes/x+/sales+/_index.tsx`). Dashboards are the only multi-widget pages. Charts via+`@carbon/react/Chart` with theme vars.++## 11. Archetype I — Split list/detail lookup++For rapid lookup loops across many rows (inventory quantities): the table stays in a+`ResizablePanel`, the detail renders beside it via `<Outlet/>`, close ✕ returns with params+preserved. Exemplar: `routes/x+/inventory+/quantities.tsx`.++## 12. Where "create" opens — decision rule++| What is created | Opens as | Shape |+|---|---|---|+| A record that gets its own detail workspace (document, job, part, customer) | **full page** `routes/x+/{entity}+/new.tsx`, centered `max-w-4xl`, the record form in a Card; on save redirect to the detail page | `routes/x+/quote+/new.tsx` + `QuoteForm.tsx` |+| A flat lookup/config row (≤ ~5 fields, no children) | **right drawer** over the list via nested route; form written with `ModalDrawer` | CustomerTypeForm |+| The same row created from inside a picker | same form, `type="modal"` (ModalDrawer switches to Modal) | `components/Form/Customer.tsx` |+| A child line of an open document | **modal** from the Explorer "Add Line Item"; then edited as a Card in the content pane (`ModalCard`) | SalesReturnOrderLineForm |+| A downstream document derived from another (receipt from PO) | **no form**: action-only route creates it, redirects to it | `.claude/rules/shipments-receipts-ui-patterns.md` |+| Delete | `ConfirmDelete` modal, often its own `delete.$id` route | |++Top-level creates have two entry points by design: the list's "Add X" and the global ✎ Create+menu (add new document types to `CreateMenu.tsx`). Both link to the same `path.to.newX`.++## 13. Navigation++- **Breadcrumbs** come only from route `handle.breadcrumb` (Lingui `msg`). Detail routes use+ `detailBreadcrumb({ breadcrumb: msg\`Quotes\`, to: path.to.quotes }, data => data?.quote?.quoteId)`+ so crumbs end with the readable ID (`utils/handle.ts`). Never render breadcrumbs by hand.+- **Recently viewed** is automatic for any route whose handle has a detail breadcrumb and a module.+- **In-record navigation:** `DetailsTopbar` (item masters), `DetailSidebar` (party records),+ Explorer rows (document lines), a header view dropdown (Job).+- **Paths** always via `path.to.*` (`utils/path.ts`); never string-built URLs.++## 14. Responsive++One JS breakpoint: `useIsMobile` = `< 768px`. ERP is desktop-first:+- < md: rail hidden → hamburger drawer; module sub-nav → "Submodules" drawer; Explorer and+ Properties become overlay drawers that close on navigation; breadcrumbs hidden.+- 768–1023px: Properties starts collapsed.+- Form grids collapse to one column (`grid-cols-1 md:grid-cols-2 lg:grid-cols-3`).+- Headers never wrap — they scroll horizontally.+- Table gutters `px-0 md:px-4 lg:px-6`.++MES is tablet-first with `lg` as the pivot — see `shop-floor-mes.md`.++## 15. Choosing an archetype for something new++Ask in order:+1. Is it a collection users search, filter and open? → **A** (and **G** for its config rows).+2. Does one record have a lifecycle (statuses, next steps) and lines or rich sub-content? → **B**.+3. Is it a master record with many sub-collections and no lifecycle? → **D**.+4. Is it a short-lived document that is filled in and posted? → **E**.+5. Is it a company-wide preference? → **F**.+6. Is it a rapid lookup loop across many rows? → **I**.+7. Is it an item-like record with several facets (planning, costing, inventory)? → **C**.+8. Operator on the shop floor? → MES (`shop-floor-mes.md`).++If none fits, compose from these shells (header strip, 3-pane, card stack, table) before+inventing a new layout, and state in your design brief why no archetype fits.diff --git a/.claude/skills/carbon-design/references/principles.md b/.claude/skills/carbon-design/references/principles.mdnew file mode 100644index 0000000000..77459a3587--- /dev/null+++ b/.claude/skills/carbon-design/references/principles.md@@ -0,0 +1,265 @@+# Carbon design principles — how a Carbon designer thinks++This is the core of the skill. Everything else (tokens, components, page shapes) is these+principles applied. When you face a situation no reference covers, reason from here.++Each principle has: the rule, **why** Carbon does it, how it shows up, and a **test question**+you can ask of your own design.++## Contents+1. Who Carbon is for (the premise)+2. The 19 principles+3. Carbon vs generic SaaS — the contrast table+4. How to decide when principles pull in different directions++---++## 1. The premise++Carbon is an ERP + MES for manufacturers. Its users are planners, buyers, accountants,+quality engineers, and machine operators. They are in the tool **all day**, doing repetitive+work on many records, often under time pressure, often with a customer or a machine waiting.++So Carbon is a **working tool, not a showcase**. It optimises for:+- scanning many records quickly (dense, calm, consistent),+- knowing exactly where a record is in its lifecycle and what to do next,+- never losing your place (URL state, panels, back button),+- trusting what the screen says (honest states, one color meaning per color),+- doing it with the keyboard on a desk, or with gloves on a tablet on the floor.++The named aesthetic reference in commits and rules is **"Vercel/Geist"**: neutral base,+monochrome chrome, thin edges, sparse semantic color, quick motion. On top of that Carbon has+its own voice only at the edges: serif page titles, the animated Carbon mark loader, the+"VOID//SYS" error screen, "Looks empty here 👀".++---++## 2. The principles++### P1. Quiet chrome, loud data — color is spent only on meaning+The UI frame is monochrome (tokens: `background`, `card`, `muted`, `accent`, `foreground`,+`muted-foreground`). The primary button is **ink** (near-black in light, white in dark in the+default `zinc` theme), not a brand color. Saturated color appears in only four places:+status chips, categorical type/entity icons, signed or threshold data (negative, overdue,+failed), and charts.+- **Why:** a dense ERP screen already carries a lot of information. Color works as a signal+ only while it is rare. The team has repeatedly *removed* color: amber text became a red badge+ only when late (`c10513d5c9`), a loud amber Alert became a calm Card with one amber icon+ (`b15cb4e9f2`), solid badges became dot + label pills (`e984069683`).+- **Shows up as:** `text-muted-foreground` (≈2,500 uses) vs `text-gray-*` (8); no green or amber+ *prose* (`.ai/ds-rules.md` Color Rules); success toasts are blue, not green.+- **Test:** *If I removed every hue from this screen, would anything lose meaning? If not, the+ hue is decoration — remove it. If yes, is each hue the one Carbon uses for that meaning?*++### P2. The record's identity comes first+Every record has a human **readable ID** (`SO-000123`, `J-0042`, `P-1001.A`). It is the+headline of the detail page (`Heading size="h4"` in the header, linkable, with `<Copy>`), the+first column of every list (a `Hyperlink`, pinned left, `LuBookMarked` header icon), the last+breadcrumb, and the thing people say out loud. Items are identified by thumbnail + ID over a+muted name; people by avatar + name; customers/suppliers by their avatar components.+- **Why:** users find, discuss and cross-reference records by ID. Making it prominent,+ copyable and clickable everywhere is what makes navigation fast.+- **Test:** *Can the user see, copy and click the identity of every record on this screen?+ Is anything shown as a raw UUID or raw foreign-key id?*++### P3. Lifecycle drives the UI+Most Carbon records are state machines (Draft → Released → Completed…). The UI makes the+current state and the next step obvious:+- status is a `Status` pill right next to the identity;+- the button for the **next valid step is the only primary** on the header+ (`variant={status === "Draft" ? "primary" : "secondary"}`); everything else is secondary;+- a status that forbids editing **locks the record in place** (`is{Entity}Locked(status)` →+ `isDisabled`, server-enforced by `requireUnlocked`), and the way back is a "Reopen" item in+ the ⋯ menu — no banner.+- **Why:** the most common question is "where is this and what do I do now?". A single primary+ answers the second half; the status pill answers the first.+- **Test:** *Is there exactly one primary action, and is it the next step for this status?+ What happens to editing when the status moves on?*++### P4. Structure left, work center, metadata right+A document workspace is always: fixed 50px header strip (identity left, lifecycle right) →+**Explorer** (lines/tree, resizable, left) | **content** (cards stacked, center) |+**Properties** (inline-autosaving fields, fixed width, right). The code calls it the+"Standard 3-pane detail workspace". Secondary metadata lives in Properties, never mixed into+the main form.+- **Why:** the structure you navigate, the thing you work on, and the facts about it have+ different reading patterns. Fixed places mean users never hunt.+- **Test:** *For each piece of information: is it structure, work, or metadata — and is it in+ that zone?*++### P5. The URL is the state+Tabs on detail pages are routes. Drawers are nested routes rendered through the list's+`<Outlet/>`. Filters, sort, search, pagination and saved views are search params. Opening a+drawer preserves the list's query string.+- **Why:** deep links, back button, refresh and sharing all just work; loaders fetch on the+ server; nothing is lost when a user is interrupted.+- **Test:** *If the user refreshes or pastes this URL to a colleague, do they see the same+ thing? Is any meaningful view state held only in `useState`?*++### P6. One shared component per concept — then everyone uses it+When a concept appears twice, Carbon makes one component or one map and sweeps the call sites:+status colors (`packages/utils/src/status-colors.ts`), dates (`DateTime`), eyebrow labels+(`Subheading`), empty selector states (`useEmptyState`), shortcuts (`SHORTCUTS`), lookup chips+(`Enumerable`). Similar things must *look and behave* the same everywhere: the same status word+has one color; the same header column has the same icon; the same value has the same+Enumerable color (hash of the string).+- **Why:** consistency is what makes a 50-module product learnable. Every divergence is a+ thing users must relearn.+- **Test:** *Does this concept already have a component, map or constant? Am I creating a+ second way to show the same thing?*++### P7. Reuse the sibling's shape before inventing+Before designing a screen, find the nearest existing screen of the same **kind** and match its+shape exactly. Counterpart entities are mirrored (CustomerForm and SupplierForm differ only in+nouns). New modules copy the canonical list + 3-pane pattern (the newest, RMAs, copies it+exactly). Review feedback on the Returns PR asked for "house UI patterns": an attribute card is+"a master-data pattern", documents get a `…Summary`.+- **Why:** Carbon's consistency is not in a style guide — it is in its siblings.+- **Test:** *Which existing screen is this most like? What would a user expect, having used+ that screen?*++### P8. Progressive disclosure through fixed places, not modes+Carbon hides secondary things in **known places**: rare/destructive record actions in the ⋯+menu next to the ID; metadata in the collapsible Properties panel; audit columns hidden by+default in tables (not removed); row actions in right-click + ⋮; line details behind a chevron+in the Explorer; related documents behind one "Shipments ▾" button. There is no global+"edit mode" toggle for a document — editing is always on until status locks it.+- **Why:** hiding in a predictable place keeps screens calm without making things undiscoverable.+- **Test:** *Is every hidden thing in one of Carbon's standard hiding places? Could the user+ guess where it is?*++### P9. Disable, don't hide — for permissions and locks+Without permission or when locked, controls render **disabled**, not removed (menu items use+`disabled={!permissions.can(...)}`; forms get `isDisabled`). Exceptions: empty-state CTAs are+hidden without permission, and the newest headers render only the lifecycle transitions valid+for the current status (the next step always remains visible).+- **Why:** users learn the layout once; a disabled control explains that the action exists and+ is currently unavailable.+- **Test:** *For a read-only user, does the screen keep its shape?*++### P10. Dense, not cramped — ERP is a desk tool+Body text is `text-sm` (14px), labels and metadata `text-xs` (12px), default button `h-8`,+inputs `h-10`, table rows 44px, spacing mostly 4/8/16px. Weight is `font-medium` for emphasis,+never bold for UI text. Whitespace grows only at page and empty-state level, and detail pages+use `p-4` with `spacing={4}` between cards (`8aa53b0439`).+- **Why:** users scan many rows; a roomy marketing layout would push data below the fold.+- **Test:** *Would a planner looking at 50 of these rows see them without scrolling past+ decoration? Is anything bigger or bolder than its importance?*++### P11. Hierarchy by size, weight and tone — not by boxes and color+Hierarchy comes from: serif `Heading` for page titles only; `text-base font-medium` for+card/modal/drawer titles; `text-sm` content; `text-xs text-muted-foreground` for labels and+secondary metadata; `Subheading` for eyebrow labels. Secondary metadata is visually+subordinate to the entity and never competes with the main action.+- **Why:** calm, editorial hierarchy survives density; boxes-in-boxes and colored headings+ do not.+- **Test:** *Squint: is the most important thing the most prominent, and does metadata recede?*++### P12. Surfaces are layered by tone; the primitive owns the edge+Gray chrome (`bg-background`), white content (`bg-card`), `Card` = gray tray with a white+`CardContent`. Depth comes from tone plus a hairline edge, not big shadows. Shadow recipes+(`shadow-button-base`) live inside primitives; app code uses a 1px `border` and `rounded-lg`+for inner boxes, and never stacks a border on top of a primitive's shadow edge.+- **Why:** flat calm surfaces for long sessions; one edge per surface avoids "blurry double+ lines".+- **Test:** *Am I adding a shadow, radius or border that a primitive already provides?*++### P13. Quiet by default, honest always+Empty states are small and calm ("invitation, not an error"). Loading shows a skeleton of the+real shape, delayed ~300ms so fast loads don't flash. The team treats a misleading state as a+bug: "pending no longer lies" (`daaddf5a85`), read-only cells don't show an edit ring+(`6ea9142601`), stale timestamps removed (`1824cbfe7c`), a failed load must not read as+"no data".+- **Test:** *Could any state on this screen be mistaken for a different state? (Empty vs+ failed, loading vs nothing, editable vs read-only, saved vs pending.)*++### P14. Status is color + icon + words, from one map+`<Status color>` = tinted uppercase pill + a fixed icon per color + tooltip. Colors come from+`packages/utils/src/status-colors.ts`; choose by lifecycle *position* (not started gray,+waiting yellow, released/with another party blue, being worked orange, done green, dead/failed+red, special purple).+- **Test:** *Is status readable in grayscale? Is its color the one its lifecycle position gets+ everywhere else?*++### P15. Keyboard-first, but deliberate+⌘/Ctrl+Enter saves forms (`Submit` does it), `n` creates on a list with one Add button, ⌘K+searches, `g` + letter goes to a module, ⌘⇧L adds a line. Every combo is a named constant.+Enter is the shortcut only on one-obvious-action screens; keycap badges are hidden on trivial+screens.+- **Test:** *Can a power user complete the main flow without the mouse? Did I add a combo+ literal instead of a constant?*++### P16. Words are the user's words, translated from day one+Name things by the user's mental model ("Instructions" not "Procedure" for operators,+`019fcf0a46`). Title Case names things (headers, labels, buttons, menu items, titles); sentence+case says things (toasts, empty states, descriptions, confirmations). Terse,+consequence-first copy ("Failed to update quote", "This cannot be undone."). Every string goes+through Lingui (`t`, `<Trans>`, `msg`), including aria-labels and toasts. Domain jargon gets a+glossary `termId`.+- **Test:** *Would an operator or buyer use these words? Is every string translatable as a+ whole sentence?*++### P17. Desk and floor are different contexts of the same language+MES (shop floor) uses the same tokens, primitives, status colors and copy rules, but changes+the *ergonomics*: `size="lg"` controls, hero Start/Pause, actions always visible (no hover+reveal, no context menus, no bulk), no bare-letter shortcuts (barcode scanners type), task+queues instead of modules, cards instead of wide tables.+- **Test:** *Who is holding the device and what are their hands doing?*++### P18. Build on what's there; remove what misleads+Improve an existing design rather than stripping it down ("BatchItemCard was a stripped-down+card… It now carries them forward", `7775cd66bd`). Remove things users don't need or that+mislead (banners, stale data, duplicate breadcrumbs, extra buttons).+- **Test:** *Did I add anything a user doesn't need to finish the task? Did I drop anything+ the sibling screen gives users?*++### P19. Grounded in the real model — never a plausible-looking API+A Carbon screen is built on Carbon's actual components, props, routes and schema, and on the+domain's own rules (deadline types, lock predicates, OEE impact, multi-currency). A design that+*looks* right but calls a prop that doesn't exist, links to a route helper that doesn't exist,+or treats "no deadline" jobs like dated ones is not Carbon — it's a mock-up. Carbon extends+existing domain machinery (an existing record type, status map, bulk-update route or lock+helper) rather than building a parallel system that answers the same question differently.+- **Test:** *Did I open the source for every component, prop, path helper and column I used?+ Does every special value the domain models have a designed rendering?*++---++## 3. Carbon vs generic SaaS++Use this table when a design "works" but feels generic.++| Generic SaaS reflex | What Carbon does instead |+|---|---|+| Brand-colored primary buttons, colorful icons everywhere | Ink primary; icons inherit text color or `text-muted-foreground`; hue only for meaning |+| Big hero header with title, subtitle, illustration | List pages: `Table` title (serif h2) + one "Add X" button. Detail: 50px header strip |+| Cards with big shadows, `rounded-2xl`/`3xl`, gradients | `Card` primitive (tray + white content), inner boxes `rounded-lg border` |+| Green "Success!" text, amber warning paragraphs | Status pills / red badge only when late; muted text + `Lu*` icon for inline notes |+| Page-level client tabs | Route tabs (`DetailsTopbar`) or Explorer sections |+| Edit button → edit mode → Save | Always-editable; Properties autosave per field; locked by status |+| Separate "Actions" buttons per row | `renderContextMenu` → right-click + ⋮ column, Edit first, Delete last |+| Modal for everything | Route drawer for config rows, full page for documents, modal for confirms/transitions and inline create |+| Toast "Saved successfully! 🎉" | "Updated quote", "Customer created", "Failed to update quote" |+| "Are you sure?" with OK/Cancel | `ConfirmDelete`: "Delete {name}", "Are you sure you want to delete {name}? This cannot be undone." Cancel left, destructive right, ⌘↵ |+| Required-field asterisks | "Optional" tag inferred from the zod schema |+| Custom tooltips explaining fields | Glossary `termId` → `LabelWithHelp` |+| Friendly illustrations for empty states | Small dashed-circle icon, `text-xs` muted line, at most one secondary "Add X" |+| Spinner in the middle of the page | Skeleton of the real shape, NProgress bar for navigation, `Button isLoading` for actions |+| Numbers right-aligned with bold totals | Left-aligned list cells with `tabular-nums`; right alignment only in label→amount summaries; totals `font-semibold` |+| Undo snackbars | Confirm first; soft delete where reversible ("Deactivate", "Move to Trash") |+| Floating "+" action button | "Add X" primary in the table title bar (desk); FAB only in MES operation dock |+| Hover-scale animations, bouncy springs | Press `active:scale-[0.96]`, 150–200ms ease-out, property-scoped transitions |+| Wide-screen dashboards with many widgets | Content capped (`max-w-4xl` create, `max-w-5xl` posting docs, `max-w-[60rem]` settings); dashboards only on module landing pages |++---++## 4. When principles conflict++1. **Consistency with the nearest sibling beats local optimisation** (P6, P7). If the sibling+ screen does X, do X, even if Y is marginally nicer — then raise Y as a system-wide proposal.+2. **Honesty beats calm** (P13 over P1). A real problem gets a red badge or Alert.+3. **The operator's hands beat density** in MES (P17 over P10).+4. **Translation beats convenience** (P16): never ship an English literal "for now".+5. **When Carbon itself is inconsistent**, follow in this order: the majority pattern in the+ code → the newest canonical module (Sales Return Orders, 2026-09-10) → the written rule.+ Never copy a pattern listed in `anti-patterns.md` just because a sibling has it.diff --git a/.claude/skills/carbon-design/references/shop-floor-mes.md b/.claude/skills/carbon-design/references/shop-floor-mes.mdnew file mode 100644index 0000000000..8f4e94f00e--- /dev/null+++ b/.claude/skills/carbon-design/references/shop-floor-mes.md@@ -0,0 +1,72 @@+# Shop floor (MES) — same language, different ergonomics++Read this for anything in `apps/mes/` or any screen an operator uses at a machine, terminal,+wall display, or on a tablet. Also read `.claude/rules/mes-job-operation-ui.md` for the+operation screen's structure.++## Who and why++Operators work standing, often gloved, often one-handed, on shared tablets and terminals with+barcode scanners that *type into the page*. Attention is on the machine; mistakes cost scrap+and time. So MES keeps Carbon's tokens, primitives, status colors, copy rules and Lingui — and+changes the ergonomics.++## What changes++| Dimension | ERP (desk) | MES (floor) |+|---|---|---|+| Control size | `sm`/`md` (24/32px buttons) | **`size="lg"` default** (44–48px); hero Start/Pause 56 → 96 → 128px |+| Text | `text-xs`/`text-sm` | `text-sm`/`text-base`; big numbers for counts |+| Navigation | module rail + sub-nav + breadcrumbs + ⌘K | touch `Sidebar` of **task queues** (Schedule, Assigned, Active, Jobs, Maintenance, Picking) with live counts; per-page sticky header with title or "‹ Back" |+| Detail tabs | routes | client `Tabs` (Details / Model / Instructions / Chat) |+| Actions | header strip, menus | **dock**: right column at `lg`, bottom bar below `lg` (safe-area padding); one color-coded primary; "More actions" sheet |+| Secondary actions | ⋯ menus, context menus | `BottomSheet` / FAB sheet of big round icon buttons |+| Hover-reveal | common | **none** — everything visible |+| Context menus / bulk | yes | **none** |+| Lists | feature-rich Table | cards in `grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))]`, simple tables with one search, Kanban |+| Keyboard | bare letters OK (`n`, `g`) | **no bare letters** — `alt+1..7`, space (start/stop), enter, arrows; yield Enter to scans |+| Input | typing | barcode wedge; scanning a Carbon URL navigates |+| Identity | per-user login | shared terminal "console mode": PIN-in, Switch Operator, idle lock |+| Toasts | bottom-right | bottom-left (dock lives bottom-right) |+| Overlays | Drawer, ModalDrawer, Modal | **Modal + BottomSheet only** |+| Money | yes | no — quantities and durations |+| Glossary help | `termId` | none |+| Breakpoints | desktop-first, `md`/`lg` | tablet-first, **`lg` pivot**, ~7× more responsive classes; `tall:` variant for tall screens |+| Wall displays | — | dark, `clamp()`/viewport-scaled type, no interaction, "last updated" stamp |++## Rules for MES screens++1. **One dominant action**, visible, big, color-coded by meaning (Start emerald, Pause red),+ with a 3D press (`border-b-4 active:translate-y-1`) — plus a `motion-reduce:` fallback.+2. **Confirmations** use the same `Modal` layout as ERP (Cancel secondary left, action right),+ both `size="lg"`, and show what will be affected (EndShift lists each operation).+3. **Plain human questions** are fine on the floor: "How many were actually picked?",+ "Forgot to Clock Out?" / "I'm Still Working".+4. **Operator words** over data-model words ("Instructions", not "Procedure").+5. **Numbers with context:** "12 of 40", time elapsed, due status with an icon.+6. **Cards show the fields an operator scans:** item ID + description, big quantity, job ID,+ status (icon + text), due; optional fields controlled by display settings.+7. Status colors come from the shared maps — don't keep a local MES color map.+7a. **Every operator action is touch-sized** — including the "secondary" ones living in a pill,+ an indicator, or a banner (e.g. "Mark Machine Up"): `size="lg"` or the dock's icon-button+ sizes, never `sm`. If it's time-critical, it belongs in the dock.+7b. **Sheet/list rows** (More Actions, reason pickers) use muted icons+ (`stroke-muted-foreground`); color only for the one action whose meaning is the color.+7c. **Tap-to-submit choices are the last step.** If a choice submits on tap, optional inputs+ (a note) must come *before* it or in a follow-up step — never below buttons that already+ submitted.+7d. **Operator actions never navigate the operator away** from the operation screen (no+ redirects to ERP-style lists); they toast and stay.+7e. Reason pickers and other short lists loaded on open follow the loading rules in+ `status-and-feedback.md` §6 (skeleton while loading, empty only when truly empty).+8. Translate aria-labels (MES has many English literals — don't add more).+9. Where MES and ERP share a concept, **share the component** (`OperationStatusIcon`,+ `KANBAN_CARD_SHELL`, `DateTime`); MES is converging on ERP's visual language.++## Exemplars++`apps/mes/app/components/JobOperation/JobOperation.tsx` (shell),+`apps/mes/app/components/JobOperation/components/Controls.tsx` (dock, hero buttons, FAB),+`apps/mes/app/components/OperationsList.tsx` (cards), `apps/mes/app/components/AppSidebar.tsx`,+`apps/mes/app/components/ShortPickModal.tsx`, `apps/mes/app/components/EndShift.tsx`,+`apps/mes/app/components/Display/DisplayFrame.tsx`, `apps/mes/app/shortcuts.ts`.diff --git a/.claude/skills/carbon-design/references/status-and-feedback.md b/.claude/skills/carbon-design/references/status-and-feedback.mdnew file mode 100644index 0000000000..99499c8386--- /dev/null+++ b/.claude/skills/carbon-design/references/status-and-feedback.md@@ -0,0 +1,194 @@+# Status, feedback and system states++## Contents+1. Status — color semantics+2. Status components and placement+3. Progress+4. Toasts and flash+5. Alerts (in-page)+6. Loading+7. Empty states+8. Errors, not-found, access denied+9. Disabled, read-only, locked, plan-gated+10. Interactive state classes++---++## 1. Status — color semantics++Single source of truth: `packages/utils/src/status-colors.ts` (`*_STATUS_COLOR_MAP` per+entity + registry). Rendered by `<Status color>` (`packages/react/src/Status.tsx`): uppercase+12px tinted pill + a **fixed icon per color** + tooltip. Color is never the only signal.++**Choose the color by lifecycle position, not by the word:**++| Position | Color | Icon | Typical values |+|---|---|---|---|+| Not started / draft / queued | `gray` | dashed circle | Draft (100% consistent), Todo, Open, Registered, Queued |+| Scheduled / waiting on someone / needs approval | `yellow` | clock | Planned, Needs Approval, To Review, Waiting, Invited |+| Released / in motion / with another party | `blue` | loader | Ready ("Released"), Sent, Confirmed, To Invoice, Submitted, generic In Progress |+| Being worked / partial / needs attention | `orange` | alert circle | Job & operation In Progress/Paused, To Ship, To Receive, Pending, Partial, Due Today |+| Terminal success | `green` | check | Completed, Done, Posted, Paid, Active, Passed, Closed (issue/period) |+| Terminal failure / cancelled / dead | `red` | slash | Cancelled, Voided, Rejected, Expired, Failed, Overdue, Archived, Closed (orders/RFQs) |+| Special | `purple` | star | Skipped (only) |++Known splits (follow the majority unless you're extending that exact entity family):+`In Progress` blue for generic docs, **orange for production** (deliberate); `Closed` red for+orders; `Pending` orange; `Overdue` red; `Archived` red; `Inactive` gray.++A new status: add a map to `status-colors.ts` and a `{Entity}Status.tsx` wrapper. Never an+inline color map in a component.++## 2. Status components and placement++Wrapper (one per entity, `modules/{module}/ui/{Entity}/{Entity}Status.tsx`), exemplar+`modules/sales/ui/Quotes/QuoteStatus.tsx` — returns `null` for missing/unknown values, owns+display aliasing ("Ready" shown as "Released", raw value in tooltip) and derived statuses+(`ShipmentStatus` → "Invoiced"). **Translate the label** (older wrappers render the raw enum —+don't copy that).++Where status appears:+1. **Record header**, right after the ⋯ menu, followed by derived badges ("Overdue", "3d late"+ with a projected-date tooltip, "Due Today").+2. **List Status column** — the wrapper is the cell *and* the filter option label; `LuStar`+ icon; `pluralHeader: t\`Statuses\``.+3. **Cross-entity summaries** — related documents show each other's status (receipts inside a+ PO header dropdown, job status on SO lines).+4. **Properties panel** only when status is edited there. Normally status changes via header+ transitions.+5. **Icon-only status** in dense rows: `OperationStatusIcon` + tooltip.+6. **Stage flow** for multi-document journeys (RFQ → Quote → Order; change notice stages): a+ `Menubar` strip — current stage `font-semibold` with emerald icon, done stages+ `text-foreground/70` + `LuCheck`, future `text-muted-foreground` + `LuCircle`+ (`modules/items/ui/ChangeNotice/ChangeNoticeStatusFlow.tsx`).++Status vs other chips: `Status` = lifecycle; `Enumerable` = user-defined values (color+meaningless); `Badge` color = ad-hoc facts. `PulsingDot` = "live / active now", not status.++## 3. Progress++`BarProgress` is the house meter (segmented 2px bars; default emerald fill; `gradient`+red → green; `invertGradient` when lower is better; `label`/`value` header; accessible+`role="progressbar"`). Table cell: `value={\`${done}/${total}\`}`. Numbers always get their+denominator ("12 of 40", `4e795c4f0c`). Don't use `Progress`. Time-relative progress uses+badges: "3d late" (red) / "2d early" (green) with a tooltip.++## 4. Toasts and flash++- **Results of actions are toasts.** Server actions: `flash(request, success("…"))` /+ `error(err, "…")` then `redirect` (`.claude/rules/flash-system.md`); client: `toast.success`+ / `toast.error`. Don't restyle — success toasts are **solid blue**, errors solid red+ (`packages/react/src/Toast.tsx`); ERP bottom-right, MES bottom-left.+- Validation errors are inline, never toasts.+- Properties autosave toasts on error only.++Wording (sentence case, no trailing period, no exclamation):++| Outcome | Pattern | Example |+|---|---|---|+| Update | verb-first past tense | "Updated quote line" |+| Create | noun-first | "Customer type created" |+| Delete | "<Noun> deleted" (preferred) or "Successfully deleted <noun>" (legacy majority) | "Supplier part deleted" |+| Domain action | noun + past participle | "Journal entry posted" |+| Failure | **"Failed to <verb> <noun>"** (82%) + `: ${message}` in client toasts | "Failed to update quote" |+| Recoverable | "… Please try again." | |+| Load failure | redirect to the list with "Failed to load <noun>" | |++Wrap client toast strings in `t`. (Server flash strings are English today — a known gap; if you+add new ones, keep them short and in this grammar.)++## 5. Alerts (in-page)++`Alert` variants `destructive | warning | info | success | default`, anatomy+`<Alert variant><LuIcon/><AlertTitle/><AlertDescription/></Alert>`, short title phrase.+Use for a **condition** the user must see while doing something (inside a modal or form):+"Lines need prices or lead times". Not for action results (toasts) and not for routine+context — a loud warning for information becomes a calm `Card` with one accent icon or+`Alert variant="info"` (`b15cb4e9f2`). A decision is a Modal with explicit choices, not a+banner.++## 6. Loading++| Situation | Pattern |+|---|---|+| Route navigation | global NProgress bar — nothing to add |+| Table reload | built-in skeleton after 300ms |+| Action button | `Button isLoading={fetcher.state !== "idle"}` / `Submit` does it |+| Confirm modal acting via navigation | `isDisabled={navigation.state !== "idle"}` |+| Deferred loader data | `<Suspense fallback={<XSkeleton/>}><Await>` with a skeleton of the real shape (`components/Skeletons.tsx`), or `null` if the area can pop in |+| Region with unknown shape | `<Loading isLoading>` |+| Inline small wait | `<Spinner size={16} />` |+| Full-screen brand wait | `CarbonPulse` |+| Status change / assignment | **optimistic**: render pending `fetcher.formData` as truth (`components/Assignee.tsx` `useOptimisticAssignment`) |+| Loading copy | "Loading..." or "Loading <noun>..." |++Never flash an empty state before data arrives — show a skeleton (`7f5f1d2145`).++**Surfaces that fetch when opened** (a drill-down drawer, a preview modal, a popover, an MES+sheet loading reasons) have three explicit states, keyed on the fetcher/loader:+1. `fetcher.state !== "idle"` or no data yet → `Skeleton` rows of the real shape (or+ `Loading`). Never show the previous selection's rows, and never show the empty message.+2. Error → `toast.error(t\`Failed to load …\`)` or an inline `Alert variant="destructive"`+ in the overlay, with the overlay still usable (close/retry).+3. Loaded and empty → the empty pattern below. Only now.+Reset or key the fetcher per selection (e.g. `fetcher.load(url)` on open, render from+`fetcher.data` only when it matches the selected key).++## 7. Empty states++| Context | Pattern |+|---|---|+| Table | built in: "No data exists" + Add; "No results found" + Remove Filters; `emptyState` override for pre-filtered tables |+| Panel / explorer / card list | `<Empty>` (`components/Empty.tsx`): `LuCircleDashed` muted, `text-xs` "Looks empty here 👀", optional children = **one** secondary `Button leftIcon={<LuCirclePlus/>}` "Add …", shown only with permission and not locked |+| Selector / combobox | `useEmptyState` → "No <plural> yet" + inline link "Add your first <noun> so you can assign it here." (permission-aware; without permission "Ask an admin with <module> permission…") |+| Specific text | "No <things> yet" (lifecycle hasn't produced data) vs "No <things> found" (search/filter miss); sentence case |+| Feature not set up / preview unavailable | an invitation: soft icon, short title, one-line hint, one action — never an error look (`daaddf5a85`) |++No illustrations. No emoji except the single generic `Empty` line.++## 8. Errors, not-found, access denied++- One root `ErrorBoundary` per app (`RootErrorBoundary`, the "VOID//SYS" screen). Don't add+ per-route boundaries.+- Loader not found: `throw notFound("…")`. Load failure: `throw redirect(listPath, await+ flash(request, error(err, "Failed to load X")))`.+- No permission: `requirePermissions` redirects home with an "Access Denied" toast. Don't+ build 403 pages.+- Inline: field errors, `Alert variant="destructive"` in modals, table cell `ring-red-500`.+- A failed load must never render as "empty" (`e59a9e26e2`).++## 9. Disabled, read-only, locked, plan-gated++- **Locked:** `is{Entity}Locked(status)` in `{module}.models.ts` → `isDisabled`; server+ `requireUnlocked` (`apps/erp/app/utils/lockedGuard.server.ts`); exit via "Reopen" in ⋯. Fields+ render disabled, nothing hidden, no banner. Released revisions may add `LuLock` inside the+ status badge.+- **No permission:** disabled controls, not hidden (exception: empty-state CTAs hide).+- **Visuals:** `opacity-50` + `cursor-not-allowed` (Button/Input), `pointer-events-none` while+ loading; menu items `data-[disabled]:opacity-50`.+- **Plan gating:** `UpgradeOverlay` (`components/UpgradeOverlay/UpgradeOverlay.tsx`) — the real+ UI rendered blurred and inert with a centered upgrade card. Variants Section/Inline/+ StickyGradient/Dialog. Don't hide gated features.++## 10. Interactive state classes++| State | Class |+|---|---|+| Focus (fields, badges, tabs, checkbox, cards) | `focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50` |+| Focus (Button) | built in (blue offset halo) — reuse Button |+| Focus-within (groups) | `focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50` |+| Menu keyboard highlight | `focus:bg-accent focus:text-accent-foreground` (primitives) |+| Open trigger | `data-[state=open]:bg-accent` |+| Hover (neutral) | `hover:bg-accent` or `hover:bg-muted`; table rows `group-hover:bg-muted` (built in) |+| Hover (ghost button) | built in `hover:bg-primary/10` |+| Press | `active:scale-[0.96]` (Button) |+| Selected row (explorer/list) | base `hover:bg-accent/30`, selected `bg-accent/60 hover:bg-accent/50` |+| Selected table row | `data-[state=selected]:bg-muted` |+| Selected card / choice | `border-primary ring-2 ring-primary/20` |+| Selected tab | segmented: `bg-background` + shadow on a `bg-muted` tray (Tabs primitive) |+| Selected nav | `bg-active` / `variant="active"` |+| Invalid | `border-destructive`, `aria-invalid` |+| Disabled | `disabled:opacity-50 disabled:cursor-not-allowed` |++Selected state is a **tinted background**, never a saturated fill or a colored left border.+Always `focus-visible:`, never bare `focus:` rings.diff --git a/.claude/skills/carbon-design/references/tables-and-lists.md b/.claude/skills/carbon-design/references/tables-and-lists.mdnew file mode 100644index 0000000000..4bad7d755d--- /dev/null+++ b/.claude/skills/carbon-design/references/tables-and-lists.md@@ -0,0 +1,250 @@+# Tables, lists and data-heavy UI++Paths relative to `apps/erp/app/` unless they start with `apps/` or `packages/`.++## Contents+1. Principles+2. Which list shape — table, explorer, tree, grid, kanban, cards, feed+3. The Table: capabilities you get for free+4. Column conventions + canonical skeleton+5. Cell rendering by data type+6. Filters, search, sort, views, bulk+7. Row actions+8. Line items and editable grids+9. Numbers, money, dates, units+10. Empty, loading, no-results+11. When a table legitimately differs++---++## 1. Principles++1. **One `Table` for every record list** (`components/Table/Table.tsx`, 143 of 145 lists).+ Never hand-roll a list table — you'd lose search, filters, views, export, pagination,+ keyboard nav and the empty/loading states.+2. **List route = table + `<Outlet/>`; state lives in the URL** (`?search`, `?filter=col:eq:v`,+ `?sort=col:asc`, `?view=`).+3. **First column = identity**: `Hyperlink` to the record, pinned left, `LuBookMarked` icon.+ Items add a thumbnail and stack ID over a muted name.+4. **Every column has an icon and a translated Title Case header.**+5. **Values render through semantic cell components, never raw ids or raw enums.**+6. **Filters are declared on the column** (`meta.filter`).+7. **Row actions are one `renderContextMenu`** → right-click + pinned ⋮ column.+8. **One create affordance**: `primaryAction` = `<New>`, permission-gated.+9. **Hide audit/secondary columns by default, don't omit them.**+10. **Dense single-line rows** (44px, `text-sm`, truncate, `max-w-[30dvw]`).+11. **Left-aligned, tabular numbers** in list tables.+12. **Line items inside documents are not the list table.**++## 2. Which list shape++| Shape | Use when | Exemplar |+|---|---|---|+| **Table** | a collection users search, filter, sort, export; one record per row; rows open a page or drawer | `modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx` |+| **Compact Table** | an operational sub-collection inside a record (job operations/materials, count lines) | `modules/production/ui/Jobs/JobOperationsTable.tsx` |+| **Explorer list** | the lines of the document you're inside; selecting routes to the line | `modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx` |+| **TreeView** | hierarchies: BoM, lines with methods, chart of accounts | `components/TreeView/TreeView.tsx` |+| **SortableList** | ordered children each edited inline (BoM/BoP) | `components/SortableList.tsx` |+| **Grid** | small editable child lists on master data (supplier parts, price overrides) | `components/Grid/Grid.tsx` |+| **Card-row list** | lines the user fills in before posting (receipts, shipments) | `modules/inventory/ui/Shipments/ShipmentLines.tsx` |+| **Kanban** | work moved between states or work centers by dragging | `apps/mes/app/components/Kanban/`, `modules/production/ui/Schedule/Kanban/Kanban.tsx` |+| **Card grid** | operator (MES) lists read at a glance on touch | `apps/mes/app/components/OperationsList.tsx` |+| **Activity feed** | history / audit narrative for one record | `components/Activity.tsx` |+| **Cards + drawer** | a *small, rich* config set (approval rules, assignments) | — (`ad9e436003`) |++Rule of thumb: find many records → Table; work inside one document's lines → Explorer ++Summary; parent/child → TreeView; move work between states → Kanban; operator on the floor →+cards; 2–6 rich config items → cards.++### Record lists inside drawers, modals, popovers and cards++A list of *records* is a table wherever it appears — a drill-down drawer, a preview modal,+a card on a detail page. **Never render records as a stack of `div`s with fixed-width+columns.** Use the `@carbon/react` table primitives (`Table as TableBase` with `full`,+`Thead`, `Tbody`, `Tr`, `Th`, `Td`) for small embedded lists, or the ERP `Table` with+`compact` when users need search/filter/export. Each row still follows the list rules:+identity as `Hyperlink` (readable ID), the entity's own `{Entity}Status` wrapper (e.g.+`JobStatus`), `DateTime`, formatter hooks, `tabular-nums`. Size the overlay for the table+(`DrawerContent size="lg"`, `ModalContent size="large"|"xlarge"`).+Exemplar: `modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx` (TableBase in an+lg Drawer with `JobStatus`).++### Orient decision tables for the decision++When users compare things to choose one (suppliers for a PO, quotes, work centers), the+**things being chosen are rows and the criteria are columns**, so each criterion is sortable+and filterable. Transposed matrices (criteria as rows) are only for side-by-side reading of 2–4+items where sorting doesn't matter (`modules/purchasing/ui/SupplierQuote/SupplierQuoteCompareDrawer.tsx`).++## 3. The Table — capabilities you get for free++Key props (`components/Table/Table.tsx`): `columns`, `data`, `count`, `title` (the page+title), `primaryAction`, `headerActions`, `table` + `withSavedView` (top-level lists),+`withSearch` (default on), `withPagination` (on), `withColumnOrdering` (on), `withCsvExport`+(on), `withSelectableRows` + `renderActions` (bulk), `renderContextMenu`,+`renderExpandedRow`, `defaultColumnVisibility`, `defaultColumnPinning`, `compact` (embedded),+`emptyState`, `importCSV`, `getRowClassName`, `withInlineEditing` + `editableComponents`.++Column `meta` (`components/Table/types.ts`): `icon`, `filter` (`static | fetcher | custom`,+`isArray`), `filterHeader`, `pluralHeader`, `renderTotal` + `formatter` (footer aggregate),+`exportValue`, `exportOnly`, `sortBy`. CSV rules: `.claude/rules/table-csv-export.md`+(export = what the user sees; no `_` in accessorKey).++## 4. Column conventions + skeleton++1. Component is `memo(...)` with `displayName`; columns in `useMemo` (deps include `t`);+ `renderContextMenu` in `useCallback`.+2. Append `useCustomColumns("table")` last.+3. **Order:** identity → partner/owner → Status → progress → references → dates → money →+ people → enumerables → booleans → audit (Created/Updated By/At).+4. `accessorKey` for real fields (sortable); `id:` for derived columns (+ `exportValue`,+ `filterHeader`).+5. Id-resolved columns get `meta.exportValue` so CSV shows the name.+6. `title` = plural noun; `defaultColumnPinning={{ left: [idColumn] }}`;+ `defaultColumnVisibility` hides `createdBy/createdAt/updatedBy/updatedAt` and low-signal columns.+7. Drawer links on config lists keep the query string: ``navigate(`${path.to.x(id)}?${params}`)``.++Skeleton (distilled from `modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx` and+`PurchaseOrdersTable.tsx`):++```tsx+const WidgetsTable = memo(({ data, count }: Props) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const customColumns = useCustomColumns<Widget>("widget");+ const columns = useMemo<ColumnDef<Widget>[]>(() => [+ { accessorKey: "widgetId", header: t`Widget Number`,+ cell: ({ row }) => <Hyperlink to={path.to.widgetDetails(row.original.id!)}>{row.original.widgetId}</Hyperlink>,+ meta: { icon: <LuBookMarked /> } },+ { accessorKey: "status", header: t`Status`,+ cell: ({ row }) => <WidgetStatus status={row.original.status} />,+ meta: { icon: <LuStar />, pluralHeader: t`Statuses`,+ filter: { type: "static", options: widgetStatusType.map((s) => ({ value: s, label: <WidgetStatus status={s} /> })) } } },+ { accessorKey: "dueDate", header: t`Due Date`,+ cell: (item) => <DateTime value={item.getValue<string>()} variant="date" />,+ meta: { icon: <LuCalendar /> } },+ { accessorKey: "assignee", header: t`Assignee`,+ cell: ({ row }) => <EmployeeAvatar employeeId={row.original.assignee} />,+ meta: { icon: <LuUser />, filter: { type: "static", options: people.map((p) => ({ value: p.id, label: p.name })) },+ exportValue: (row) => people.find((p) => p.id === row.assignee)?.name ?? row.assignee } },+ { accessorKey: "createdAt", header: t`Created At`,+ cell: (item) => <DateTime value={item.getValue<string>()} variant="date" />, meta: { icon: <LuCalendar /> } },+ ...customColumns,+ ], [t, people, customColumns]);++ const renderContextMenu = useCallback((row: Widget) => (+ <>+ <MenuItem disabled={!permissions.can("update", "sales")} onClick={() => navigate(path.to.widgetDetails(row.id!))}>+ <MenuIcon icon={<LuPencil />} /><Trans>Edit</Trans>+ </MenuItem>+ <MenuItem destructive disabled={!permissions.can("delete", "sales")} onClick={() => onDelete(row)}>+ <MenuIcon icon={<LuTrash />} /><Trans>Delete</Trans>+ </MenuItem>+ </>+ ), [permissions]);++ return (+ <Table<Widget> count={count} columns={columns} data={data} title={t`Widgets`}+ table="widget" withSavedView+ defaultColumnPinning={{ left: ["widgetId"] }}+ defaultColumnVisibility={{ createdAt: false }}+ primaryAction={permissions.can("create", "sales") && <New label={t`Widget`} to={path.to.newWidget} />}+ renderContextMenu={renderContextMenu} />+ );+});+```++## 5. Cell rendering by data type++| Type | Render with | Header icon |+|---|---|---|+| Record identity | `Hyperlink` → readable ID (+ `RevisionSuffix`) | `LuBookMarked` |+| Item | `HStack` `ItemThumbnail size="sm"` + Hyperlink over `VStack` (ID, then `text-xs text-muted-foreground` name) | `LuBookMarked` |+| Named config row | `Hyperlink` → `Enumerable value={name}` | — |+| Status | module `{Entity}Status` (never a raw string or plain Badge) | `LuStar` |+| Person | `EmployeeAvatar employeeId` | `LuUser` |+| Customer / supplier | `CustomerAvatar` / `SupplierAvatar` (groups for many) | `LuSquareUser` / `LuContainer` |+| User-defined enum (type, group, location, UoM) | `Enumerable value` (`EnumerableGroup` for many) | domain |+| Fixed typed enum with meaning (method, tracking) | `Badge variant="secondary"` + domain icon + translated label | domain |+| Tags | `HStack gap-1` of `Badge variant="secondary"`; filter `isArray: true` | `LuTag` |+| Boolean | read-only `Checkbox isChecked` | `LuToggleLeft` |+| Date | `DateTime value variant="date"` | `LuCalendar` |+| Late / on-time date | `DateTime` wrapped in `text-red-500` when late (muted otherwise) | `LuCalendar` |+| Money | `useCurrencyFormatter().format(v)` in `tabular-nums`; `meta.renderTotal` for footer sums | `LuDollarSign` |+| Per-row currency | `formatMoney` from `@carbon/utils`; no cross-currency total | |+| Progress x/y | `BarProgress progress={pct} value={\`${done}/${total}\`}` | |+| Count / quantity | `<span className="tabular-nums">`; `useQuantityFormatter` where decimals matter | `LuHash` |+| Long text | `max-w-[320px] truncate`, usually hidden by default | |+| Custom fields | automatic via `useCustomColumns` (`hooks/useCustomColumns.tsx` is the most compact type → renderer map) | |++## 6. Filters, search, sort, views, bulk++- **Search:** built in (`?search=`, debounced); server-side matching.+- **Filters:** per column `meta.filter` — `static` options (label may be the cell component,+ e.g. the Status pill), `fetcher` (endpoint), `custom`. Active filters show as chips under the+ toolbar. `pluralHeader` for the chip label.+- **Sort:** header click menu; `?sort=`; `meta.sortBy` to redirect.+- **Views:** `withSavedView` + `table="…"` on every top-level module list; views appear in the+ module sub-nav under the matching submodule (same `table` key).+- **Bulk:** `withSelectableRows` + `renderActions(rows)` → a `DropdownMenuContent` with+ `DropdownMenuLabel` "Update", `DropdownMenuSub` per field, destructive delete disabled when+ any row is ineligible; submits `ids[]` + `field` + `value` to one bulk route (exemplar+ `modules/items/ui/Parts/PartsTable.tsx`).+- **Import:** `importCSV={[{ table, label }]}` → ⋮ "Bulk Import" next to Add.++## 7. Row actions++`renderContextMenu` returns `MenuItem`s: **Edit** (`LuPencil`) first → domain verbs (Duplicate,+Receive, Create Change Notice, sub-menus via `MenuSub`) → **Delete** (`LuTrash`,+`destructive`) last. "Edit"/"Delete" on document lists, "Edit {Noun}"/"Delete {Noun}" on+config lists. Gate with `disabled`, never omit. Status-gated items are disabled+(`!["Draft"].includes(row.status)`). Row click does nothing (navigation is the Hyperlink or the+menu) unless the row is expandable. Report/workbench tables with no openable records omit+`renderContextMenu` and the Hyperlink column.++## 8. Line items and editable grids++| Surface | Pattern |+|---|---|+| Document lines (quote, SO, PO, invoice, return) | Explorer (left) + `…Summary` card (center) — never a list Table in the content pane |+| Operational sub-table in a record | `Table compact title=… primaryAction=…`; editable → `withInlineEditing` + `editableComponents` (`EditableNumber(mutation)`), `forceEditMode` for Draft docs |+| Small editable child list | `Grid` in a Card with `onNewRow` "New" row and an `<Outlet/>` for the form |+| BoM / BoP | `SortableList` with expandable inline forms, live reorder + throttled save |+| Receiving / shipping lines | card-row list with inline `NumberField` + selectors, per-line persistence |++Inline-edit cells: only editable cells show the selection ring and hover pencil; read-only+cells go `bg-muted/50` in edit mode; container owns arrow/Tab/Enter in the capture phase+(`.ai/lessons.md` "Inline-editable table cells commit on blur").++## 9. Numbers, money, dates, units++- Money: `useCurrencyFormatter({ rate?, compact?, wholeUnits?, currency? })` — pick a *kind*,+ never a digit count (`.claude/rules/numeric-precision.md`).+- Quantities: `useQuantityFormatter`; plain numbers `useNumberFormatter`; percent+ `usePercentFormatter`.+- Dates: `<DateTime variant="date">` for anything read as a calendar date; never+ `new Date().toLocale…` (`.claude/rules/date-handling.md`).+- `tabular-nums` on every numeric span. Left-aligned in list tables (the Table has no+ alignment API); right-aligned only in label → amount summaries.+- Units: beside the value (`12 EA`) or an Enumerable "Unit of Measure" column.+- Totals: list footer aggregate (`renderTotal`), document Summary totals block+ (`font-semibold`, not bold). Multi-currency lists show no total.++## 10. Empty, loading, no-results (built in — don't reimplement)++- Loading: skeleton grid after 300ms (`useSpinDelay`).+- Truly empty: toolbar and pagination hide; black circle + `LuTriangleAlert` + mono uppercase+ "No data exists" + the `primaryAction`.+- Filtered to nothing: "No results found" + secondary "Remove Filters".+- Pre-filtered sub-table with nothing yet: pass `emptyState` with a neutral sentence ("No+ production events recorded for this operation yet") — don't show "Remove Filters" to a user+ who never filtered (`678cf28e16`).+- Non-table lists: `Empty` (see `status-and-feedback.md`).++## 11. When a table legitimately differs++Reports/workbenches/matrices (trial balance, planning, capacity) have no Hyperlink column and+no row menu; system-created records (inspections, workflow runs, synced card transactions)+have no `primaryAction`; embedded wizard tables turn chrome off (`withSearch={false}`,+`withCsvExport={false}`, `sort={null}`, `withSidebarTrigger={false}`). The People list's identity+column is avatar + name. State the reason in your design brief when you deviate.diff --git a/.claude/skills/carbon-design/references/worked-examples.md b/.claude/skills/carbon-design/references/worked-examples.mdnew file mode 100644index 0000000000..482ec1b740--- /dev/null+++ b/.claude/skills/carbon-design/references/worked-examples.md@@ -0,0 +1,101 @@+# Worked examples — reasoning like a Carbon designer++These show the *reasoning*, not code to copy. Each walks the workflow from `SKILL.md`:+classify → find the sibling → reuse / extend / create → brief → review. Use them to calibrate+how much of Carbon's existing language a new feature should inherit.++---++## Example 1 — A new lookup: "Hold Reasons" for sales orders++**Request:** planners want to put a sales order on hold with a reason from a company-defined+list.++**Classify.** Two things: a *lookup collection* (hold reasons) and a *state change on a+document* (hold/release a sales order).++**Siblings.** Lookup: Customer Types / Return Reasons (archetype G). State change: Cancel+Sales Order (`CancelSalesOrderModal.tsx`) and the SO header.++**Decisions.**+- Hold reasons live in the Sales sub-nav **Configure** group (not Settings): table whose first+ column is `Hyperlink → Enumerable`, drawer via `hold-reasons.new.tsx` / `$id.tsx` /+ `delete.$id.tsx`, `HoldReasonForm` written with `ModalDrawer` so the selector can create one+ inline (`type="modal"`). A `HoldReason` domain selector copied from `components/Form/Customer.tsx`.+- "On Hold" is a lifecycle position → add it to `SALES_STATUS_COLOR_MAP`. Held = waiting on+ someone → **yellow** (clock). Not orange (not being worked) and not red (not dead).+- "Put on Hold" is a rare, reversible transition → it goes in the header ⋯ menu, not as a+ visible button. It opens a `Modal` ("Hold Sales Order", reason selector + optional note,+ `[Cancel][Hold]`). While held, the next-step primary (Ship/Invoice) is disabled, and "Release+ Hold" becomes the header's primary.+- Held orders are locked like other statuses (`isSalesOrderLocked`) — fields disabled in place,+ no banner. The reason shows in Properties as a read-only field and in the status tooltip.+- List: status filter already covers it; add a "Hold Reason" column hidden by default.++**Rejected:** a red "ON HOLD" banner across the page (loud, and duplicates the status pill); a+toggle switch in Properties (a lifecycle event must be explicit, with a reason).++---++## Example 2 — A novel component: lot genealogy timeline++**Request:** on a tracked lot, show where it came from and where it went (received → split →+consumed into a job → shipped), in order.++**Classify.** New visualization inside an existing record page (tracked entity). No existing+component shows an ordered, branching history. `Activity` is close (a feed) but has no notion+of quantity flow; the traceability graph is a full-screen canvas.++**Decision: create, in Carbon's language.** A `LotTimeline` component in the module's `ui/`+(domain-aware → not `packages/react`), rendered inside a `Card` titled "Genealogy" in the+content pane.+- Each event row mirrors `Activity`'s grammar: small leading icon (`Lu*`, muted; hue only for+ a failed/scrapped event), **readable IDs as `Hyperlink`s** (receipt, job, shipment), quantity+ with unit and `tabular-nums` ("40 EA of 120"), the actor as `EmployeeAvatar`, time as+ `DateTime variant="relative"`.+- Connectors are 1px `border-border` lines, not colored arrows. Branches indent with the+ `TreeView` `LevelLine` spacing so it rhymes with BoM trees.+- Statuses of linked documents use their existing `*Status` wrappers.+- Empty: `Empty` with "No movements yet". Loading: skeleton rows of the same height.+- Long histories: render at natural height (no inner scroll); collapse sub-branches behind a+ chevron.++**Rejected:** a colorful horizontal stepper with big circles (generic SaaS, low density, can't+branch); a new color per event type (hue without meaning).++---++## Example 3 — Surfacing a blocking condition: customer credit hold++**Request:** when a customer is over their credit limit, confirming a new sales order should be+blocked unless a manager overrides.++**Classify.** A fact about a party record + a guard on a document transition.++**Siblings.** Party record header (`CustomerHeader.tsx` `CardAttributes`), SO header+transitions, `QuoteFinalizeModal` (Alert inside a modal for a blocking condition).++**Decisions.**+- On the customer: credit limit and current exposure are *metadata* → `CardAttributes` in the+ customer header card; exposure over limit shows a `Badge variant="red"` "Over Limit" next to+ the value (hue only because it means something). No banner on the customer page.+- On the SO: the Confirm button stays the primary (it *is* the next step). Clicking it opens+ the usual confirm modal, which shows `Alert variant="destructive"` "Customer over credit+ limit" with the numbers (currency formatter) and, for users with the override permission, a+ destructive-styled "Confirm Anyway". Without permission the confirm button is disabled with a+ tooltip explaining why.+- The server enforces the same rule (flash "Customer is over their credit limit" on violation).+- Copy is consequence-first and exact: "Exposure $12,400 of $10,000 limit."++**Rejected:** hiding the Confirm button (breaks the header shape, P9); a toast after the fact+(the user needs to decide *before* acting); amber text on the SO header (P1).++---++## Calibration notes++- Most of each design came from **existing parts** (archetypes, overlays, Status, Enumerable,+ Hyperlink, DateTime). New surface area was small and justified.+- Each new element was checked against a *reason*: lifecycle position for colors, record rank+ for containers, frequency for action prominence.+- Each example says what was **rejected** and why — include that in your own briefs.