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
fix: docs skill (#1606)
Sid78239f8bf8a1
diff --git a/.claude/rules/agent-knowledge-base.md b/.claude/rules/agent-knowledge-base.mdindex 9aaf22cc6d..e88634e7cd 100644--- a/.claude/rules/agent-knowledge-base.md+++ b/.claude/rules/agent-knowledge-base.md@@ -3,7 +3,7 @@ description: The in-app agent's read-only doc corpus (kb/) is generated from docpaths:- "apps/erp/app/modules/agent/**"- "docs/content/**"- - "scripts/generate-agent-kb.ts"+ - "docs/scripts/generate-agent-kb.ts"---# Agent Knowledge Base (docs → agent)@@ -16,7 +16,7 @@ the erp Docker image copies `apps/**` but **not** `docs/**`). The corpus lives a- `apps/erp/app/modules/agent/kb/manifest.json` — the keyword index `search_docs` scans- `apps/erp/app/modules/agent/kb/README.md` — auto-written "do not edit" notice-All of it is **generated by `scripts/generate-agent-kb.ts`** from `docs/content/**` and is+All of it is **generated by `docs/scripts/generate-agent-kb.ts`** from `docs/content/**` and is**committed** (tracked in git), the same way the Lingui `.po` catalogs are committed.## The contract: regenerate before committing docs changes@@ -33,7 +33,7 @@ pnpm run generate:agent-kb # reads docs/content, writes apps/erp/app/modules/aWhen to run it:- You edited anything under `docs/content/**` (added, changed, or removed a doc).-- You changed `scripts/generate-agent-kb.ts` itself.+- You changed `docs/scripts/generate-agent-kb.ts` itself.Then stage the regenerated `apps/erp/app/modules/agent/kb/**` alongside your docs edit.diff --git a/.claude/skills/carbon-docs/SKILL.md b/.claude/skills/carbon-docs/SKILL.mdindex 8ad84b67f1..0df47b75dd 100644--- a/.claude/skills/carbon-docs/SKILL.md+++ b/.claude/skills/carbon-docs/SKILL.md@@ -18,6 +18,35 @@ or change docs **in that system, in its house style, grounded in real Carbon cod**Announce at start:** "Using the carbon-docs skill — authoring docs for {topic}."+## First: ask which kind of page this is++Not all doc pages are equal — a settings toggle does not get the treatment a production flow gets, and+the single biggest quality failure so far has been writing every page in the long narrative register.+**Before any research or writing, ask the user to pick the page type** (AskUserQuestion, one question,+your recommended type first — infer it from the topic). Skip the question only when the user already+named the type in their request, or you're editing an existing page without changing its shape (keep+its current type). Several pages in one request → one question covering them.++| Type | Reader's question | Shape | Budget |+|---|---|---|---|+| **Flow / tour** (Guide) | "walk me through it" | Narrative chapter in a flow: sequenced, illustrated, second-person storytelling, prior stages set up | length serves the story |+| **System / entity** (Reference) | "how does it work — fields, statuses, rules?" | 1–2 lead sentences → `<StatusFlow entity=…>` lifecycle → rule/gotcha Callouts → `<FieldTable>` → `<Cards>` onward | ~800–1,500 words |+| **Settings / how-to** (Reference) | "how do I turn it on / use it?" | 1–2 lead sentences → `<Steps>` → one gotcha Callout → where-it-lives | ~300–600 words; steps, not story |+| **Concept / overview** (Reference) | "what is this area?" | Short intro + `<Cards>` linking to the owning pages | ~150–300 words |++A page can mix types **by section** (an entity page that ends with a short settings section) — pick the+dominant type for the page, then hold each section to its own shape. Troubleshooting/FAQ content never+gets a reader-visible section: it goes in `<AgentContext>` (see Reference components).++**No page ends cold.** Every page closes pointing onward: entity and concept pages with a small+`<Cards>` Related row, settings pages with where-it-lives links, guide chapters get "read next" for+free. A page that just stops is an IA bug, not a style choice.++The house voice below scales with this choice: full narrative register belongs to Guides; entity pages+dial it down to scannable-with-gotchas; settings/how-to pages drop it entirely. On a settings page the+reader wants the steps, not an essay — two-factor auth is a 500-word how-to, not an 1,800-word+meditation on passwords.+> The single biggest mistake is writing plausible ERP-generic prose. Carbon's behavior is specific and> often counterintuitive (WIP is a GL balance not a table; a payment is a posted entity applied via> settlements; overhead IS absorbed into WIP per production event; fixed-asset disposal is@@ -44,9 +73,12 @@ The **holy source of truth is the actual source code + the LATEST database migrasubsystem the cache still describes the old way.- **Document only real, ACTIVE features.** Omit placeholders / inactive / not-yet-shipped things (e.g.integration registry entries with `active: false` like QuickBooks/Sage). Don't surface them.+- **Deliberately undocumented:** the **Implementation Hub** (`/x/get-started`, `packages/onboarding`+ content) stays out of the docs by the user's decision — don't document it, and don't link to it.- **When code and cache disagree, code wins** — and note the drift.-- **Method:** dispatch a research subagent per feature → return verified facts with `file:line` refs →- then write. This is how every flow in the Guide was built. Don't skip it for anything non-trivial.+- **Method:** one research subagent per feature → a structured **fact sheet** with `file:line` refs+ (contract in Authoring workflow step 1) → then write from it. This is how every flow in the Guide was+ built. Don't skip it for anything non-trivial.## Three surfaces (know which you're touching)@@ -61,10 +93,29 @@ Guide for the story. (Guide chapters were given 12 cross-flow links — interlin## Authoring workflow (every change)-1. **Research (grounded).** Subagent verifies the feature vs source + newest migrations. Get exact- table/column/enum/transition names + `file:line`. Flag what a generic description would get wrong.-2. **Pick the surface + placement.** Guide flow + frontmatter, or Reference folder + `meta.json` order.+1. **Research (grounded) → a fact sheet.** Dispatch a research subagent per feature. It must return a+ structured **fact sheet**, not prose: entities/tables/columns; exact status strings and which entity+ owns each; transitions with the action that drives them (service fn / route / edge function) as+ `file:line`; gates and settings (`companySettings.*`, plan features); the real UI labels for every+ where-to-click; the gotchas a generic description would get wrong; and an explicit "could not verify"+ list — a gap on that list is more research work, never a writing improvisation. The writer then works+ ONLY from the fact sheet + the page-type template, and writing stays in the main loop on the main+ model — no model downgrades for prose; the fact sheet is the handoff, not a license for a weaker+ writer.+2. **Pick the surface + placement** (the page *type* was chosen up front). Guide flow + frontmatter, or+ Reference folder + `meta.json` + `REFERENCE_GROUPS` — run the placement checklist below before+ creating any new page.3. **Write in the house voice** with the surface's real components (below). Lead with a concrete example.+ **Decide media placement yourself as you write — don't wait to be asked.** Drop a `<Screenshot>` slot+ wherever the reader needs to see the actual UI, with a label naming the real screen + state (the fact+ sheet's UI labels are the source); use `<Figure>` only when a registry key genuinely fits. Typical+ density by page type: settings/how-to 1 (the screen with the switch/steps), entity 1–2 (the list or+ detail view, or the lifecycle UI), guide chapters one per major beat, concept stubs none. **Boy Scout+ rule:** editing an existing Reference page that has no `<Screenshot>`? Add the one slot its type calls+ for while you're there — the Reference surface shipped with almost none, and it goes on the media+ manifest like any new slot. Reuse existing slots on a rewrite; never drop or re-label one that a real+ capture may already exist for. Slot `label`s double as the image's alt text once a capture lands, so+ write them as a description of what's *shown* (screen + state), never as a caption or a filename.4. **Verify — against the user's running dev server, read-only.** They usually have `pnpm --filter docs dev`up. **Never** `pkill`/restart it, run `next build`, or `rm .next` under it — verify by fetching pages:```bash@@ -127,11 +178,23 @@ Each `##` heading becomes a sidebar rail entry — so structure chapters as 3–## Reference — entity pages-- Frontmatter: `title` + `description` only.-- **Nav = `meta.json` `pages` arrays** (ordered). Folders: `content/docs/{reference,platform,integrate}/`.- Root order in `content/docs/meta.json`; a folder's order + sidebar title in its own `meta.json`- (`{ "title": "Product reference", "defaultOpen": true, "pages": [...] }`). Add a page → add its slug to- the folder's `pages`. **Don't list `index` in `pages`** — fumadocs treats `index.mdx` as the folder index+- Frontmatter: `title` + `description` (+ `plan` for a paid-feature gate).+- **Placement checklist — run it BEFORE creating any page.** (1) Does an existing page already own this+ topic? Grep `content/docs` for the feature name; if a page covers it, **extend that page** with a+ section instead of creating a parallel one — a bucket page that re-documents features owned elsewhere+ is scattering, not architecture. (2) One noun per page. (3) If genuinely new: which sidebar group does+ it belong to (`REFERENCE_GROUPS`, next bullet)? If none fits, propose a group to the user rather than+ letting the page dangle ungrouped. (4) **Sub-folders are exceptional** — one entity = one page;+ `change-orders/` is the only folder today, and splitting a feature across a new folder needs the+ user's sign-off first.+- **Nav is TWO layers — miss the second and your page dangles at the bottom of the sidebar.** Folders:+ `content/docs/{reference,platform,building,integrations}/`. A folder's `meta.json` `pages` array is+ authoritative for membership AND order (top-level section order is the root `meta.json`) — and the flat+ Product-reference list is additionally nested into sidebar groups by the hardcoded `REFERENCE_GROUPS`+ slug map in `app/docs/layout.tsx`, whose group order and within-group slug order are what the reader+ sees. A reference page missing from that map is appended **ungrouped** after the groups. So adding a+ reference page = slug into `reference/meta.json` **and** into the right `REFERENCE_GROUPS` group.+ **Don't list `index` in `pages`** — fumadocs treats `index.mdx` as the folder indexand the nav renders it as **"Overview"**; listing it duplicates the title as a sibling. Integrations aretheir own top-level section (`content/docs/integrations/`) grouped by category — document only `active`integrations (omit `active: false` placeholders + commented-out ones).@@ -149,13 +212,24 @@ Each `##` heading becomes a sidebar rail entry — so structure chapters as 3–(omit when the table has no type column); `required` only when the source marks it so; the child is thedescription as **MDX** (so inline `` `code` ``, *italics*, `<Term>` render — that's why it's children, not a`type={{}}` prop). Registered in **both** `mdx.tsx` and `editorial/mdx.tsx`.- - `<StatusFlow><Status name accent? branch? terminal?>meaning</Status></StatusFlow>`+ - `<StatusFlow entity="job"><Status name accent? branch? terminal?>meaning</Status></StatusFlow>`(`components/editorial/status-flow.tsx`) — an **interactive** lifecycle widget (selectable pills → a detail`Callout` showing the meaning) that replaces a linear `| Status | Meaning |` table. Children in source(lifecycle) order; meanings are MDX. Flags: `accent` = the single pivotal milestone (≤1, optional);`branch` = a temporary returnable hold (Paused, On Hold, Needs Approval); `terminal` = an off-path exit- (Cancelled, Voided, Lost, Expired). Use it ONLY for a **linear** lifecycle — a 2-axis comparison matrix+ (Cancelled, Voided, Lost, Expired). **`entity` is REQUIRED in practice**: it resolves each status's+ real ERP badge color from `@carbon/utils/status-colors` (`statusColorMaps`); omit it and every pill+ silently renders gray — that is a bug, not a style. If the entity has no map yet, add one to+ `packages/utils/src/status-colors.ts`, **derived from the module's `*Status.tsx` component in the+ ERP** (never guessed), then pass it. Use it ONLY for a **linear** lifecycle — a 2-axis comparison matrix(e.g. invoices sales-vs-purchase) or a small enum list stays a markdown table.+ - `<AgentContext>…</AgentContext>` — renders **nothing** on the site; its content ships only to the+ in-app agent's knowledge base (`pnpm run generate:agent-kb` → `apps/erp/app/modules/agent/kb/`,+ regenerated automatically by check-and-commit). Put troubleshooting/FAQ, exact error strings, and+ internal mechanics (table names, routes, enum internals) here — reader-facing prose stays free of+ them. Never write a reader-visible "Troubleshooting" section. About half the Reference pages still+ have no `<AgentContext>`: when your fact sheet surfaced exact error strings for a page you're+ editing, seed or extend its block while you're there.- `<PlanBadge plan="Business" />` — flags a paid feature. Whole-page gate → set `plan: Business` infrontmatter; renders a small **"Paid"** pill inline with the page title (label is fixed to "Paid"; the`plan` value only feeds the hover tooltip + the banner copy). Section gate → drop `<PlanBadge>` in-body.@@ -187,6 +261,20 @@ Each `##` heading becomes a sidebar rail entry — so structure chapters as 3–## House voice+Calibrated by the page type chosen up front: Guides get the full register below; entity pages keep the+grounding and the gotchas but stay scannable; settings/how-to pages take only "quote real names exactly"+and "ground every where-to-click" — no narrative, no rhetorical asides, no answering questions nobody+asked. Cutting to budget beats compressing: drop whole asides, don't shorten every sentence.++- **Active voice, second person, one term per concept.** Never alternate synonyms for the same thing+ ("API key" one paragraph, "API token" the next) — the glossary term is the term, everywhere. No+ colloquialisms or idioms; the catalogs are translated and idioms don't survive it.+- **Never state the obvious.** "Click Save to save" documents nothing. A step earns its place by+ carrying something the button label doesn't already say.+- **Every page stands alone.** A reader (or an AI retriever) lands cold from search: state the context+ and prerequisites in place rather than leaning on the previous page. How-to/settings pages name their+ prerequisites explicitly before the steps ("needs `settings` update permission", "requires the Slack+ integration connected").- **Second person, concrete, narrative.** Anchor in the running example (the 90-unit humanoid-robot order)."Open the sales order dashboard." / "You don't build 90 robots as one monolithic job."- **Quote real status names exactly**, in quotes: `**"To Ship and Invoice"**`, `**"Posted"**`, `**"Open"**`.@@ -195,10 +283,13 @@ Each `##` heading becomes a sidebar rail entry — so structure chapters as 3–`Ordered/In Progress/Completed`) before you attribute it, and state the transition fully (an order at`"To Ship and Invoice"` flips to `"To Invoice"` once everything has shipped but isn't billed — don't implyit sits at one value until fully closed).-- **Go easy on em-dashes.** Stacked, they read as a tic — at most one per paragraph, and never a dash-pair- parenthetical in an opening sentence. Default to a period or comma; reach for the dash only when it truly- beats both. ("Too many em-dashes" is the single most common copy note from review.) Applies to `caption=`- and `title=` strings too, not just body prose.+- **Em-dashes are rationed — count them.** Hard budget: at most 1 per ~150 words of body prose (a 600-word+ page gets 4, total), never two in one paragraph, never a dash-pair parenthetical in an opening sentence,+ and none in `title=`, `caption=`, or frontmatter strings. Default to a period, comma, or colon; most+ dashes read better as two sentences. Do NOT mimic the dash-heavy style of this skill file or of older+ pages — "too many em-dashes" is the single most common copy note this project gets. Before declaring a+ page done, count (`grep -o '—' <page>.mdx | wc -l`) and cut to budget; when delegating prose to a+ subagent, put the budget in its prompt verbatim.- **Keep the running example's nouns and numbers exact.** It's the *sales order* (don't drift to a bare"order" when instructing the reader) and it's *90 units* (not "a robot"). Once you name the entity and thequantity, stay consistent every time — drift is what makes a tour feel sloppy.@@ -286,6 +377,10 @@ to raise the whole site's connectivity.- **Regen `.source` before typecheck** after any frontmatter/schema change (the schema is baked into`.source/` at generate time).- **Figure keys must exist** — see the list above; a typo renders nothing, silently.+- **Inline code chips are for identifiers, never statements.** A full command, SQL statement, or long+ path in an inline `` `…` `` span renders as one unbroken chip that can overflow its container —+ anything that reads as a *line of code* goes in a fenced block (fences are fine inside Callouts),+ and inline stays for short tokens (`companyId`, `crbn_…`, `Settings → X` labels stay plain bold).- **Bare `{…}` in MDX is a JS expression.** A token in prose like `{item.id}` (e.g. inside an example rulemessage) fails the build with `item is not defined`. Wrap any literal braces/tokens in backticks: `` `{item.id}` ``.- **`Write` blocks on existing files** — natural collision protection when a parallel session co-writes the@@ -308,8 +403,32 @@ to raise the whole site's connectivity.## Verification bar-Never declare docs done without: the new content rendering (in the user's running dev server, or a clean-`pnpm --filter docs build`), every internal link resolving, any new `<Term>` glossary entries grounded in-source + their popovers rendering, names matching real code, **no generic repeated-headings**, and a re-read that confirms each page says what matters / names the mistake / points onward. Then+**Mechanical gate — run on every touched page BEFORE the re-read; each must come back clean.** These are+deterministic, so there is no judgment call to get lazy on:++Measure READER-VISIBLE content only — raw `wc -w` counts frontmatter and the invisible `<AgentContext>`+block too, overstating a page by up to 40% and making budgets meaningless:++```bash+awk '/<AgentContext>/{s=1} !s{print} /<\/AgentContext>/{s=0}' <page>.mdx | wc -w # words vs the type's budget+awk '/<AgentContext>/{s=1} !s{print} /<\/AgentContext>/{s=0}' <page>.mdx | grep -o '—' | wc -l # em-dashes ≤ 1 per ~150 words+grep -n '<StatusFlow>' <page>.mdx # bare = gray pills; must carry entity="…"+grep -nE '^(title|description): [^"]*: ' <page>.mdx # unquoted colon-space = YAML, 500s the site+grep -m1 '^description:' <page>.mdx | wc -c # ≤ ~170 raw (the SEO meta: 150–160 chars of text)+```++Plus two eyeball checks no grep covers: a `## Troubleshooting` heading may exist only inside+`<AgentContext>`, and every `<Figure illustration=…>` key is in the registry list.++Never declare docs done without: the mechanical gate passing, the new content rendering (in the user's+running dev server, or a clean `pnpm --filter docs build`), every internal link resolving, any new+`<Term>` glossary entries grounded in source + their popovers rendering, names matching real code,+**no generic repeated headings**, and a re-read that confirms each page says what matters / names the+mistake / points onward.++**Close with a media manifest.** The final report to the user MUST end with the list of images/media the+work needs captured — every unfilled `<Screenshot>` slot on a page you created or touched, one line each:+`page path — slot label (ratio) — what to capture (screen + state)`. Build it with+`grep -n '<Screenshot' <touched pages>`. That list is the user's capture worklist; a slot you don't+report is a slot that never gets filled. No new slots → say "no new media needed" explicitly. Thenrecord progress (the `.ai/plans/` plan file if one exists, + memory). **Don't kill or rebuild under the user's running dev server.**diff --git a/.claude/skills/carbon-docs/references/information-architecture.md b/.claude/skills/carbon-docs/references/information-architecture.mdindex fefdfeff45..228dbb604c 100644--- a/.claude/skills/carbon-docs/references/information-architecture.md+++ b/.claude/skills/carbon-docs/references/information-architecture.md@@ -36,27 +36,33 @@ The original 5 chapters carry no flow fields and fall into `make-to-order` (flowKeep a flow to ~2–5 chapters; a chapter to 3–5 `##` sections. If a chapter sprawls, split it.-## Reference — folder tree + meta.json `pages` arrays+## Reference — meta.json membership + `REFERENCE_GROUPS` placement`content/docs/**` → `/docs`, rendered through a **custom `DocsNav`** (`components/api/docs-nav.tsx`), not-the stock Fumadocs sidebar. Nav order comes from `meta.json` `pages` arrays.--Folders today: `reference/` (the entity pages — "Product reference"), `platform/` (architecture/deployment/-env), `integrate/` (app-connections, webhooks).--```jsonc-// content/docs/meta.json (root order)-{ "pages": ["index", "platform", "reference", "integrate"] }-```-```jsonc-// content/docs/reference/meta.json (folder title + page order)-{ "title": "Product reference", "defaultOpen": true,- "pages": ["items", "methods", "routings", "work-centers", "jobs", "...", "traceability"] }-```--**To add a Reference page:** create `content/docs/<folder>/<slug>.mdx` (frontmatter = `title` + `description`),-then add `<slug>` to that folder's `meta.json` `pages` array in the right reading position. Omitted pages get-appended — prefer explicit ordering.+the stock Fumadocs sidebar.++Folders today, in sidebar order (the root `meta.json`): `reference/` ("Product reference"), `building/`+(API keys, webhooks, local development, architecture), `integrations/` (by category), `platform/`+(self-hosting, backups, demo data, licensing), then the glossary. Product reference leads because users+and admins are the largest audience; platform/ops content sits low.++The nav is built by `app/docs/layout.tsx`, and it is TWO layers:++1. **Membership + order** — a folder's `meta.json` `pages` array is authoritative for both. `toNav()`+ preserves tree order (it no longer alphabetizes), so curating a section = editing its meta.json.+2. **Grouping** — the flat Product-reference list is nested into sidebar groups ("Getting started",+ "Sales", "Items & engineering", … "Administration") by the hardcoded `REFERENCE_GROUPS` slug map in+ the same `layout.tsx`, ordered by the business flow (sell → engineer → plan → buy → make → stock →+ ship → inspect → bill → account, then people/automation/admin). Group order and within-group order+ follow that map. A reference slug missing from the map is appended **ungrouped after all the+ groups** — visible, but dangling at the bottom of the rail.++**To add a Reference page:** create `content/docs/<folder>/<slug>.mdx` (frontmatter = `title` ++`description`, + `plan` if paid-gated), add `<slug>` to the folder's `meta.json` `pages`, **and** — for+`reference/` — add it to the right `REFERENCE_GROUPS` group in `app/docs/layout.tsx`. No fitting group+means proposing one, not skipping the step. Moving a page between folders changes its URL: add a+redirect in `next.config.mjs` and update inbound links (URLs are a contract). Note the site root `/`+is a rewrite serving `/docs/building/architecture` — keep it pointed at wherever that page lives.One page **per entity/concept** (one-noun-per-page). Slugs: short, kebab-case, stable (URLs are a contract).@@ -70,12 +76,14 @@ the swagger schema.Decide a page's type up front; mixing them is what makes docs confusing.-| Type | Surface | Answers | Shape |-|---|---|---|---|-| Guide chapter | Guide | "walk me through ___" | narrated, sequenced, illustrated, opinionated |-| Concept | Reference | "what is ___, why?" | explanation + links |-| Reference | Reference | "exact fields / statuses / options?" | tables, `<EnvVars>`, scannable |-| Overview | either | "what's here?" | short intro + `<Cards>` |+The four types (and their ask-the-user-first rule) live in SKILL.md — this is the same taxonomy:++| Type | Surface | Answers | Shape | Budget |+|---|---|---|---|---|+| Flow / tour | Guide | "walk me through ___" | narrated, sequenced, illustrated, opinionated | length serves the story |+| System / entity | Reference | "how does ___ work — fields, statuses, rules?" | lead → `<StatusFlow entity=…>` → Callouts → `<FieldTable>` → `<Cards>` | ~800–1,500 words |+| Settings / how-to | Reference | "how do I turn ___ on / use it?" | lead → `<Steps>` → one gotcha Callout → where-it-lives | ~300–600 words |+| Concept / overview | either | "what is this area?" | short intro + `<Cards>` | ~150–300 words |Don't put exhaustive field tables in a narrative chapter — link out to the Reference page. Don't putmotivational narration in a field table — link back to the Guide.diff --git a/.claude/skills/check-and-commit/SKILL.md b/.claude/skills/check-and-commit/SKILL.mdindex 1820114154..9352358af8 100644--- a/.claude/skills/check-and-commit/SKILL.md+++ b/.claude/skills/check-and-commit/SKILL.md@@ -28,7 +28,7 @@ paths, derive:- `SCHEMA_CHANGED` — any file under `packages/database/supabase/migrations/`- `AGENT_KB_RELEVANT` — the diff touches `docs/content/**` or- `scripts/generate-agent-kb.ts`. When true, Gate 1b regenerates the agent's doc+ `docs/scripts/generate-agent-kb.ts`. When true, Gate 1b regenerates the agent's doccorpus (`apps/erp/app/modules/agent/kb/`) so the generated copy ships in this samecommit instead of drifting behind the docs (same model as the `.po` files —see `.ai/rules/agent-knowledge-base.md`).diff --git a/apps/erp/app/modules/agent/kb/README.md b/apps/erp/app/modules/agent/kb/README.mdindex fd1e04a46a..a150801bed 100644--- a/apps/erp/app/modules/agent/kb/README.md+++ b/apps/erp/app/modules/agent/kb/README.md@@ -1,7 +1,7 @@# Agent knowledge base (auto-generated — do not edit)Every file in this folder is generated from the docs site (`docs/content/**`) by-`scripts/generate-agent-kb.ts`. It is the read-only corpus the in-app agent searches+`docs/scripts/generate-agent-kb.ts`. It is the read-only corpus the in-app agent searches(`search_docs`) and reads (`read_doc`), bundled into the erp image so it ships with the app.**Do not edit these files by hand — your changes will be overwritten.**diff --git a/apps/erp/app/modules/agent/kb/docs/building/api-keys.md b/apps/erp/app/modules/agent/kb/docs/building/api-keys.mdindex 5885bfc961..879e011fdf 100644--- a/apps/erp/app/modules/agent/kb/docs/building/api-keys.md+++ b/apps/erp/app/modules/agent/kb/docs/building/api-keys.md@@ -2,23 +2,19 @@> A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions.-An API key is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more.+An API key is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their session's permissions, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more. Manage keys under **Settings → API Keys**.-Create and manage keys under **Settings → API Keys**. Every key you see is listed by **Name**, a masked **Key** preview (only the last five characters, e.g. `crbn_•••abcde`), its **Scopes**, **Rate Limit**, who created it, and when it expires.+Claude.ai, Claude Desktop, and ChatGPT connect over **OAuth**: add the server URL, approve in the browser, and the connection inherits the role and company of whoever authorized it. A key is for everything that can't do that browser dance: Claude Code, Cursor, VS Code, Codex, headless scripts, and CI (stdio-only clients bridge through `mcp-remote`). The [authentication reference](/api/authentication) covers both flows.## Creating a key-Click **New API Key** and give it a **Name** (unique within your company). Optionally set **Expires At** — a future date after which the key stops working; leave it blank and the key never expires. Then grant scopes with the permission matrix (covered below) and save.+Click **New API Key**, give it a **Name** (unique within your company), optionally set **Expires At** (blank means never), grant scopes in the permission matrix, and save. Carbon shows the full key exactly once, in a dialog headed "You can only see this key once. Store it safely." — copy it right then. Only a SHA-256 hash and a five-character preview are kept, so a lost key means delete and recreate. The same dialog hands you a ready-to-paste MCP command that wires the key into an AI assistant.-Carbon shows the full key exactly once, in a dialog headed "You can only see this key once. Store it safely." Copy it right then. Carbon never stores the raw key: it keeps only a SHA-256 hash for lookup and the five-character preview for display. There is no way to reveal a key again later, so if you lose it, delete the key and create a new one.+Anyone holding the key can act as it, within its scopes. Store it in a secret manager, never commit it, and rotate (delete and recreate) if it leaks.-Anyone holding the key can act as it, within its scopes. Treat it like a password: store it in a secret manager, never commit it to source control, and rotate it (delete and recreate) if it leaks.+## Authenticating a request-The full format is `crbn_` followed by a random token. The same dialog also hands you a ready-to-paste MCP command that wires the key into an AI assistant — see [The MCP endpoint](#the-mcp-endpoint) below.--## How a key authenticates a request--Send the key as a bearer token on every request. The hosted Data API lives at `rest.carbon.ms`:+Send the key as a bearer token; the hosted Data API lives at `rest.carbon.ms`:```httpGET /salesOrder?select=id,salesOrderId,status@@ -26,79 +22,49 @@ Host: rest.carbon.msAuthorization: Bearer crbn_your_key_here```-Carbon hashes the incoming key, looks up the matching record, and checks two things before it lets the request through:--- **Expiry.** If the key has an `expiresAt` in the past, the request is rejected.-- **Rate limit.** The request is counted against the key's window; if the window is full, the request is rejected.--There is no separate login step and no token to refresh. The header is the whole handshake.--`rest.carbon.ms` takes the key as `Authorization: Bearer crbn_…` and forwards it internally as the `carbon-key` header that the database reads. If you run Carbon yourself and call PostgREST directly, send `carbon-key: crbn_…` against `/rest/v1/<table>` instead. The MCP endpoint that fronts the Carbon API takes the same `Bearer` token either way.--## Permission scoping--A key does **not** inherit the permissions of the person who created it. It acts with exactly the scopes stored on the key, and only for the company it belongs to. A brand-new key with no scopes granted can authenticate but can read and write nothing.--You grant scopes in the permission matrix when you create or edit the key. Each cell is a `module_action` pair — the same shape Carbon uses for a user's permissions. So a key scoped to view sales and create inventory can read `salesOrder` rows and insert inventory records, but a call that needs, say, `purchasing_update` is refused with "API key lacks required permissions" unless you granted that exact scope.-- - **Scopes**: The set of permissions the key carries, e.g. `sales_view`, `inventory_create`. Empty means no access. Edit them anytime from the key's form.- - **Company**: A key is bound to the single company it was created under. It can never reach another company's data, even one you also belong to.+There is no login step and no token to refresh. Carbon hashes the incoming key, looks it up, and checks expiry and the rate limit before letting the request through.-Because scopes are checked on every request against the key's own record, tightening a key's scopes (or deleting the key) takes effect immediately — there is no cached session to wait out.+`rest.carbon.ms` takes `Authorization: Bearer crbn_…` and forwards it internally as the `carbon-key` header. Calling PostgREST directly on a self-hosted install, send `carbon-key: crbn_…` against `/rest/v1/<table>` instead. The MCP endpoint takes the same Bearer token either way.-## Rate limiting+## Scopes and rate limit-Every key allows **60 requests per minute**. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.+A key does **not** inherit its creator's permissions: it acts with exactly the `module_action` scopes stored on it (`sales_view`, `inventory_create`, …), and only within its company. A key with no scopes can authenticate but read and write nothing. Scopes are checked on every request against the key's own record, so tightening them, or deleting the key, takes effect immediately. On Carbon Cloud, API access is a **Business-tier feature**: a company on the Starter plan gets `403` on every call regardless of the key's scopes; see `docs/platform/licensing`.-The limit is platform-controlled, not something you set: the key's form has no rate-limit field, and `insertApiKey`/`updateApiKey` strip the columns from whatever is submitted (`apps/erp/app/modules/settings/settings.service.ts:1282`). The **Rate Limit** column in the key list reports the limit in force; it is not an input.--The limit is counted per key, not per company, so one integration burning its allowance does not throttle another.--A rejected request comes back `429` with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `Retry-After` (`packages/auth/src/services/auth.server.ts:255`). Read `Retry-After` and wait it out rather than hammering through the rejection.+Every key allows **60 requests per minute**, counted per key, so one integration burning its allowance doesn't throttle another. The limit is platform-controlled: the form has no rate-limit field, and the list's **Rate Limit** column is a report, not an input. A rejected request comes back `429` with `Retry-After` and `X-RateLimit-*` headers; wait it out rather than hammering through.## What the key unlocks-One key unlocks two surfaces. Reach for the Carbon API first; drop to the Data API only when you need raw table access.--### The Carbon API--The [Carbon API](/api) is Carbon's service layer — the safe way to read and write, running the same validation, recalculation, and permission checks the app itself uses. Reach it over plain HTTP at `POST /api/v1/{module}/{operation}` — the key goes in an `Authorization: Bearer` header, and the full operation catalogue is described by [`/api/v1/openapi.json`](/api). The same surface is also exposed over MCP: the creation dialog hands you a ready-to-paste command that registers the key with an AI assistant, which then operates strictly within the key's scopes. See [Connect over MCP](/api/mcp).--### The Data API+One key unlocks two surfaces. Reach for the **[Carbon API](/api)** first: the service layer, the same code the app runs when you click a button, with every call validating its input, recalculating what depends on it, and enforcing your permissions. Every operation is reachable two ways with the same arguments, plain HTTP at `POST /api/v1/{module}/{operation}` or a tool over [MCP](/api/mcp), and each carries a `READ` / `WRITE` / `DESTRUCTIVE` classification so a client can filter or gate by risk. Each operation has its own reference page with copyable samples in six languages, and the published OpenAPI spec means a typed client in your language is one generator command away — see [Client SDKs](/api/sdks).-The same key also unlocks the [Data API](/api/data) — direct REST access to every table and view, hosted at `rest.carbon.ms` (the full endpoint catalogue is generated in the [reference](/api/data)). The same row-level security that governs the app governs these calls: the key is scoped to its company and permissions by the database itself, not just the application layer, so it can only ever touch data its scopes allow.+The **[Data API](/api/data)** is direct REST access to every table and view, governed by the same row-level security as the app.-The Data API writes straight to tables, so Carbon does not recalculate the derived values — totals, statuses, ledger entries — that it maintains when you write through the Carbon API. It's the escape hatch: reach for the Carbon API first, and use the Data API when it doesn't cover what you need and you know exactly what the table touches.--The full endpoint catalogue, with request and response shapes per resource, lives in the generated [Data API reference](/api/data).+It writes straight to tables, so Carbon does not recalculate the derived values (totals, statuses, ledger entries) it maintains when you write through the Carbon API. Use it when the Carbon API doesn't cover what you need and you know exactly what the table touches.## Keys versus webhooks-API keys and `docs/building/webhooks` are two halves of an integration, pulling in opposite directions:--- An **API key** lets *you* call *Carbon* — poll for data, create records, run reports on demand.-- A **webhook** lets *Carbon* call *you* — an HTTP callback the moment a subscribed record changes.--They are independent: a webhook is not authenticated with an API key (Carbon does not sign webhook payloads at all), and an API key does not subscribe to anything. The common pattern is to use both together: let a webhook tell you *that* a record changed, then use your API key to fetch the full, current record from the REST API.+An **API key** lets *you* call *Carbon*; a **`docs/building/webhooks`** lets *Carbon* call *you* when a subscribed record changes. They're independent — webhook payloads aren't signed with a key — and the common pattern is both together: the webhook tells you *that* a record changed, your key fetches the full, current record.- Webhooks Get an HTTP callback when a Carbon record changes, then pull the detail with your key.- Data API The generated endpoint catalogue for every table and view.-## Troubleshooting+## Internals and troubleshooting-The exact rejections an API key can return, and the one-time-secret gotcha.+Key format is `crbn_` + random token; storage is SHA-256 hash + last-five preview. `insertApiKey`/`updateApiKey` strip rate-limit columns from any submission (`settings.service.ts:1282`). The 429 response headers come from `packages/auth/src/services/auth.server.ts:255`.### "API key lacks required permissions"-The call needs a `module_action` scope the key doesn't carry. Scopes are checked per request against the key's own record (`packages/database/supabase/functions/lib/supabase.ts:315`), not the creator's permissions — a key with no scopes can authenticate but read and write nothing. Add the exact `module_action` (e.g. `purchasing_update`) to the key in the permission matrix under **Settings → API Keys**. It takes effect immediately, no session to wait out.+The call needs a `module_action` scope the key doesn't carry — checked per request against the key's record (`functions/lib/supabase.ts:315`), never the creator's permissions. Add the exact scope in the permission matrix; it applies immediately.++### 403 on every call despite correct scopes+On Carbon Cloud, API access is Business-tier: the key path blocks Starter-plan companies outright (`packages/auth/src/services/auth.server.ts:312-330`). Upgrade the plan; the key itself is fine. A 403 on a single operation is the scope problem above instead. Connectors (OAuth) hit the same plan gate through the identity they inherit.### "Rate limit exceeded"-The key exceeded its allowance for the current window (`supabase.ts:304`). Every key allows 60 requests per minute, and the limit is platform-controlled — there is no field to raise it, and the API-key service strips the columns from any submitted value. The `429` carries `Retry-After` and `X-RateLimit-*` headers; wait out `Retry-After` rather than retrying immediately. If 60/minute is genuinely too tight for your integration, batch your reads (PostgREST `in.(...)` filters and embedded relations fetch in one call) or talk to us.+Over the key's 60/minute window (`supabase.ts:304`). Platform-controlled, no field to raise it. Honor `Retry-After`; if the ceiling is genuinely too tight, batch reads (PostgREST `in.(...)` filters, embedded relations) or talk to us.### "API key has expired"-The key's `expiresAt` is in the past, so it's rejected before any work (`supabase.ts:293`). Create a new key (optionally with a later **Expires At**, or leave it blank to never expire) and swap it in — expiry can't be extended on a used key.+`expiresAt` is in the past (`supabase.ts:293`). Expiry can't be extended on a used key — create a new one and swap it in.### "API key not found"-The `carbon-key` (or Bearer token) didn't hash to a key for this company (`supabase.ts:287`). Usually a mistyped/truncated key, a key from a different company, or one that was deleted. Carbon stores only a SHA-256 hash and the five-character preview, so verify the full key value.+The token didn't hash to a key for this company (`supabase.ts:287`): mistyped/truncated, a different company's key, or a deleted one. Verify the full value.-### I lost the key / can't find where to see it again-There's no way to reveal a key after creation. Carbon shows the full key exactly once, in the "You can only see this key once. Store it safely." dialog, and keeps only a hash afterward. If you lost it, delete the key and create a new one.+### I lost the key / can't see it again+Not possible by design — the full key is shown once at creation and only a hash is kept. Delete and recreate.diff --git a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md b/apps/erp/app/modules/agent/kb/docs/building/architecture.mdsimilarity index 99%rename from apps/erp/app/modules/agent/kb/docs/platform/architecture.mdrename to apps/erp/app/modules/agent/kb/docs/building/architecture.mdindex 6a891d97b7..64e05705b1 100644--- a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md+++ b/apps/erp/app/modules/agent/kb/docs/building/architecture.md@@ -646,7 +646,7 @@ refuses to start without it.| `logger` | Structured logging, with request-id correlation. || `notifications` | The notification event taxonomy (enums only). || `printing` | Printer registry, label queue, physical print delivery. |-| `onboarding` | New-company setup, the "Implementation Hub". |+| `onboarding` | New-company setup content. || `kv` | Redis client plus rate limiting. || `stripe` | Billing. Cloud edition only. || `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |diff --git a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.mdindex 75ffa619f0..afb544f977 100644--- a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md+++ b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md@@ -13,7 +13,7 @@ Platform-wide behavior and edition.One of `community`, `cloud`, `enterprise`, or `test`. Gates edition-specific features.Enables ITAR / controlled-environment restrictions: the US-Person certification gate, ITAR hostnames and branding, Slack and analytics disabled, and mandatory `docs/reference/two-factor` that a company admin cannot turn off.-Allowed sign-in methods: `email`, `google`, `azure`, `passkey`, `sso` (`docs/platform/single-sign-on`, Enterprise edition only).+Allowed sign-in methods: `email`, `google`, `azure`, `passkey`, `sso` (`docs/reference/single-sign-on`, Enterprise edition only).Base domain the apps are served from.Public URL of the ERP app.Public URL of the MES app.@@ -39,7 +39,7 @@ Azure OAuth client id, when `azure` is enabled.Azure OAuth client secret.Local only. Sign in as this email without a magic link.-Enterprise `docs/platform/single-sign-on` adds two more:+Enterprise `docs/reference/single-sign-on` adds two more:Turns on the SAML engine in the auth service.SAML signing key — base64-encoded PKCS#1 DER RSA, minimum 2048-bit; the generation command is in `.env.example`.diff --git a/apps/erp/app/modules/agent/kb/docs/platform/single-sign-on.md b/apps/erp/app/modules/agent/kb/docs/platform/single-sign-on.mddeleted file mode 100644index c24d8bee3f..0000000000--- a/apps/erp/app/modules/agent/kb/docs/platform/single-sign-on.md+++ /dev/null@@ -1,93 +0,0 @@-# Single sign-on--> Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.--Single sign-on hands control of Carbon sign-in to your own identity provider — Okta, Entra ID, Google Workspace, or any SAML 2.0 IdP. You register your email domains once — proving you own each one with a DNS record — and from then on your IT team grants and revokes access centrally: everyone on those domains signs in to both ERP and MES with their normal work email — Carbon recognizes the domain and routes them to your IdP automatically, with no SSO button to find. Registering alone doesn't take anything away — the magic link and other methods keep working until you turn on [Require SSO](#requiring-sso).--## Requirements--SSO is an Enterprise feature. Automatic SSO routing on the login page and the settings section are active only when the instance runs the **Enterprise** edition (`CARBON_EDITION=enterprise`), which requires a `docs/platform/licensing`. It is a capability of your own `docs/platform/self-hosting` deployment — Carbon Cloud sign-in is unaffected.--Enable it through `docs/platform/self-hosting/environment-variables`:--Add `sso` to the comma-separated list of sign-in methods. Without it, the button never renders.-Turns on the SAML engine in the auth service (GoTrue).-The SAML signing key — a base64-encoded PKCS#1 DER RSA key, minimum 2048-bit. The exact `openssl` generation command is in `.env.example`.--Carbon registers providers directly against the auth service with its service-role key — no Supabase account or plan is involved.--## Connect your identity provider--The whole exchange lives on one screen: **Settings** → **Security**, under the **"Single Sign-On"** heading. Viewing it requires the `settings` view permission; saving requires `settings` update.--**Copy Carbon's service provider details.** The **"Service Provider Details"** card shows the **"ACS URL"** and **"SP Metadata URL"** with copy buttons. Copy them from the screen rather than constructing them by hand.--**Register Carbon in your IdP.** In Okta, Entra ID, or Google Workspace, create a SAML application using those two URLs. The assertion must include an **email attribute** — the email is how Carbon matches each sign-in to a person and a company.--**Paste the IdP metadata back into Carbon.** In the **"Identity Provider"** card, provide either the **"IdP Metadata URL"** or the raw **"IdP Metadata XML"** — exactly one of the two — then **"Save"**. After saving, the card gains a **"Require SSO"** switch and a **"Deactivate"** button — the sign that the connection is active.--**Verify your email domains.** The **"Email Domains"** card appears once the connection exists. Add each domain your people sign in with, publish the DNS record it shows you, and click **"Verify"** — see [Verifying a domain](#verifying-a-domain). Only verified domains route SSO sign-ins.--- **IdP Metadata URL**: The SAML metadata URL published by your identity provider. Provide this *or* the XML, never both — the form rejects the submission with **"Provide either a metadata URL or metadata XML (exactly one)"**.-- **IdP Metadata XML**: The raw metadata document, for IdPs that don't publish a metadata URL.-- **Add a domain**: One domain at a time, e.g. `example.com`. Domains are lowercased and must be bare hostnames — no `@`, no spaces; enter internationalized domains in punycode (`xn--`) form. Public email providers (`gmail.com`, `outlook.com`, …) are refused. Several companies may hold a **pending** claim on the same domain at once — a claim on its own blocks nobody. Exclusivity kicks in at verification: only one company can ever hold a domain **verified**, and only DNS control gets you there. Adding a domain your own company already has fails with **"This domain has already been added"**.--## Verifying a domain--A domain routes SSO sign-ins only after you prove your company controls it. Each added domain starts **Pending** with a DNS challenge — a unique TXT record shown right on the card:--| Record | Value |-| --- | --- |-| **Host** | `_carbon-challenge.example.com` |-| **Type** | `TXT` |-| **Value** | `carbon-domain-verification=<your unique token>` |--Add the record at your DNS host (copy both fields from the card — the token is unique to your company and this domain), then click **"Verify"**. Many DNS providers auto-append your domain to the record's name field: in Cloudflare, for example, enter only `_carbon-challenge` (plus any subdomain) and check the preview under the field shows the host once, not twice. Carbon looks the record up and, on a match, flips the domain to **Verified** — from then on it participates in sign-in routing and [Require SSO](#requiring-sso) enforcement. Verification is one-time: the domain stays verified until you remove it, and the TXT record may be deleted afterwards if you prefer a tidy zone.--If verification fails, the message tells you why: the record isn't visible yet (DNS changes can take a few minutes to propagate — wait and retry), the record's value doesn't match the token (re-copy it exactly), or the DNS lookup itself failed (the server couldn't reach the public resolvers; check its outbound DNS access). A **Pending** domain has no effect anywhere: it can't capture sign-ins, and it never triggers Require SSO — so adding a domain is always safe.--Only one company can hold a domain verified — first to prove DNS control wins. A **"Verify"** attempt on a domain another company already verified fails with a deliberately generic message, so the button can't be used to probe which domains are registered where. Verification is also permanent: the holder keeps the domain even if DNS control later changes hands (a domain sale, a rebrand). The clean handover is for the holding company to **Remove** the domain from its list, which frees it for the new owner to verify. Failing that, operators of a self-hosted deployment can delete the claim directly (`DELETE FROM "ssoDomain" WHERE "domain" = 'example.com';`) — note the previous holder's provider registration keeps routing the domain until its connection is re-saved, though sign-ins on it are rejected either way once the row is gone.--To turn SSO off, use the **"Deactivate"** button in the Identity Provider card. It opens a **"Deactivate Single Sign-On"** confirmation warning that "Users on your registered domains will no longer be able to sign in through your identity provider. This cannot be undone." — the provider registration is deleted outright and the domain claims are released, so re-enabling means saving the connection again and re-verifying your domains.--## How sign-in works--The login page is email-first, and the SSO fork is invisible. The user types their email and presses **"Continue"** — there is no separate SSO button to choose. Carbon checks whether the email's domain has an active connection (a rate-limited check that reveals nothing beyond yes or no); if it does, the browser redirects to your IdP, the user authenticates there, and lands back in Carbon signed in to the connection's company. If it doesn't, the same button falls through to the ordinary magic-link (or sign-up) flow. Users never have to know whether their company uses SSO.--Before any session is created, Carbon enforces the connection's boundaries itself: the asserted email's domain must be one of the connection's **verified** email domains. An assertion outside them is rejected with **"SSO sign-in rejected: this email domain is not registered for your company's SSO connection."** — even a misconfigured or hostile IdP can't sign someone into another company.--Provisioning is **invite-first** — there is no self-serve signup through SSO. Three outcomes:--- **Already a member** of the connection's company: signed straight in.-- **Has a pending invite**: the first SSO sign-in accepts it — the person lands in the company with exactly the invite's role and permissions.-- **Neither**: rejected with **"SSO sign-in succeeded but no invite exists for `[email protected]`. Contact your administrator."** (the message names the address). Nothing is provisioned, so creating the invite and retrying just works.--Invites cooperate with this automatically: when you invite someone whose email domain has an active SSO connection, the invite email links to the login page with their address prefilled instead of carrying a magic-link code — the IdP is never bypassed, even on day one.--MES uses the same email-first sign-in and enforces the same domain rules, but it doesn't run first-time provisioning. A brand-new SSO user who starts at MES sees **"Complete your first SSO sign-in in Carbon ERP, then return here."** — after that one ERP sign-in, MES works normally.--## Existing accounts--People who already sign in with a magic link or OAuth don't lose anything when SSO arrives.--The first SSO sign-in quietly attaches the SAML identity to the existing account. Nothing changes for the user: it's the same account, the magic link keeps working, and no invite is needed, because an existing member is already authorized.--Coverage follows the registered domains: every existing member whose email domain is registered with the connection signs in with SSO automatically on their next login, no re-invite needed. People not yet in the company still need an invite from the `docs/reference/people`; invite emails for these domains route to SSO automatically.--## Requiring SSO--Once the connection works, you can make it the only way in. The **"Identity Provider"** card carries a **"Require SSO"** switch: while it's on, anyone whose email domain is **verified** on the active connection can sign in **only** through your identity provider (a pending domain enforces nothing). Every other method is refused server-side — the magic-link form, Google and Outlook sign-in, and passkeys all answer with **"Your organization requires single sign-on. Sign in with your work email to continue."** and no session is created.--The ordering protects you from locking yourself out: the switch exists only on an active connection, so the path is always *set up SSO, prove a sign-in works, enforce last*. Turning the switch off — or deactivating the connection — immediately restores the other sign-in methods for those domains.--If enforcement is on and your identity provider is unreachable, nobody on the covered domains can sign in to turn it off. Operators of a self-hosted deployment can lift the requirement directly in the database:--```sql-UPDATE "ssoConnection" SET "requireSso" = false WHERE "companyId" = '<id>';-```--Magic-link sign-in works again on the next attempt; re-enable the switch once the IdP is healthy.--## Two-factor authentication--SSO sessions skip Carbon's `docs/reference/two-factor` and the company-wide two-factor requirement in every environment, including controlled (ITAR) deployments. Your identity provider already enforced its own MFA policy during sign-in, and challenging twice is friction without security — MFA attestation for SSO sign-ins belongs to the IdP policy. Magic-link logins still go through Carbon's own two-factor challenge.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/account.md b/apps/erp/app/modules/agent/kb/docs/reference/account.mdindex 076a99b12b..73ca3b745e 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/account.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/account.md@@ -1,125 +1,52 @@# Your account-> Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language, kept separate from the company-wide settings an admin controls.+> Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language — separate from company-wide settings.-Everything on the **Account** screen is yours alone. Your name and photo, the passkeys you sign in with,-which topics reach you by email, the theme you look at all day: these are personal preferences, scoped to-your user, and changing them touches nothing for anyone else on the team. That's the line to keep in mind.-Company-wide switches (locations, integrations, defaults, who can do what) live under **Settings** and are-gated by admin permissions. Your account settings need no special permission at all.--Open it from your avatar in the top bar. The sidebar has two sections, **Profile** and **Notifications**-(`apps/erp/app/modules/account/ui/useAccountSubmodules.tsx:9`); landing on `/x/account` redirects you-straight to Profile (`apps/erp/app/routes/x+/account+/_index.tsx:4`).+Everything on the **Account** screen is yours alone: your name and photo, the passkeys you sign in with, which topics reach you by email, the theme you look at all day. Changing them touches nothing for anyone else. Company-wide switches live under **Settings** and are gated by admin permissions; your account settings need no special permission at all. Open it from your avatar in the top bar.## Profile-Profile is the one card everyone shares. The description on it says it plainly: *"This information will be-visible to all users, so be careful what you share."* (`.../ui/Profile/ProfileForm.tsx:44`).-- - **First name / Last name**: Your display name across Carbon. Both are required.- - **Phone**: Optional. A phone-formatted field, blank by default.- - **About**: A short bio, capped at 160 characters (`ProfileForm.tsx:62`).- - **Photo**: Your avatar. Uploading routes the image through Carbon's `image-resizer` before it's saved (`.../ui/Profile/ProfilePhotoForm.tsx`); you can also remove it and fall back to your initials.- - **Email**: Shown, but **read-only** — the field is disabled (`ProfileForm.tsx:53`). You can't change your sign-in email from here.--Saving writes only to your own `user` row (`updatePublicAccount`, `.../account.service.ts:161`), so the-edit is always self-scoped.--Your email is how you sign in and how Carbon addresses notifications to you, so it isn't editable as a-casual profile field. Changing it is an identity change handled outside these self-service settings.--## Signing in — passkeys and two-factor--Carbon supports several sign-in methods, and which ones are available is a deployment-wide choice, not a-per-user one. The `AUTH_PROVIDERS` environment variable turns them on and off; the default set is-`email,google,azure` (`packages/env/src/index.ts:114`). That covers a **magic link** to your email, and-**Google** and **Microsoft (Azure)** OAuth. There's no password field on this screen — Carbon signs you in-by magic link or OAuth, not by a stored password you type each time.+Profile is the one card everyone shares; the form itself warns *"This information will be visible to all users, so be careful what you share."*-The same screen is where you add an authenticator app for two-factor codes — see-`docs/reference/two-factor` for setup, company-wide enforcement, and recovery.+ - **First name / Last name**: Your display name across Carbon.+ - **Phone**: Optional.+ - **About**: A short bio, capped at 160 characters.+ - **Photo**: Your avatar; remove it to fall back to your initials.+ - **Email**: Shown but **read-only**. Your email is your sign-in identity, so changing it is handled outside these self-service settings.-The codebase carries a password-change form, but it isn't wired into any account route today — the Account-sidebar exposes Profile, Security, and Notifications. Password management isn't a live self-service control here.-Sign-in is magic link, OAuth, or a passkey.+## Signing in-The sign-in controls you manage yourself live on **Account → Security**, not on Profile. The passkey card-only appears when the `passkey` provider is enabled (`isAuthProviderEnabled("passkey")`,-`.../account+/security.tsx`). A passkey lets you-sign in with biometrics — Face ID, Touch ID, or your device PIN — instead of waiting on a magic-link email.-From the Profile page you can:+Sign-in is a magic link, Google or Microsoft OAuth, or a passkey — there is no password. Which methods exist is a deployment-wide choice, not a per-user one.- - **Add a passkey**: Registers a new credential through your browser's WebAuthn prompt (`onAddPasskey`, `security.tsx`). You can hold more than one — a laptop and a phone, say.- - **Rename a passkey**: Give a credential a recognizable name (up to 100 characters) so you can tell your devices apart.- - **Remove a passkey**: Deletes it; that device can no longer sign you in. Each row shows when it was added, when it was last used, and whether it's synced across your devices.+**Account → Security** is where you manage your own credentials. Add a passkey through your browser's WebAuthn prompt to sign in with Face ID, Touch ID, or your device PIN; rename each one so you can tell devices apart; remove one to revoke that device. Each row shows when it was added and last used. The same screen holds the authenticator-app card — see `docs/reference/two-factor` for setup, enforcement, and recovery.-A passkey is tied to a device. If you register only one and lose that device, fall back to the magic-link-email or your OAuth provider to get back in — then add a fresh passkey. Registering a second passkey up-front saves the round trip.+A passkey is tied to a device. Register a second one up front, or you'll be falling back to the magic-link email when the first device goes missing.## Notification preferences-Which alerts reach you, and on which channel, is set on the **Notifications** page — and it's per-user.-In-app notifications (the bell in the top bar) are **always delivered**; the toggles only govern the extra-channels, **email** and, when your company has connected Slack, **Slack** (`.../account+/notifications.tsx`).-Each row is a topic — Approvals, Jobs, Inventory, Purchasing, Quality, and so on — with a switch per channel.--The default is *on*: an absent preference row counts as enabled (`notifications.tsx:130`), so you're opting-**out** of a channel for a topic, not opting in. Two things gate what you see:--- The **Slack** column appears only if an admin connected the Slack integration for the company- (`slackActive`, `notifications.tsx:47`).-- **Email** notifications depend on your company's plan. If the `EMAIL_NOTIFICATIONS` feature isn't in the- plan, Carbon tells you so, and your email preferences are stored but only take effect once it's enabled- (`notifications.tsx:49`, `:175`).--For the full picture of what raises a notification and how Carbon fans it out across channels, see the-`docs/reference/notifications`. This page is where you tune it for yourself.--## Theme and language--Carbon lets you pick a color theme; the choice is stored in a cookie on your browser, not in the database-(`.../account+/theme.tsx`), so it follows you per-device and applies to nobody else. That's the personal-end of theming. Company-wide branding — the logo, the default look a new user starts with — is an admin-setting elsewhere, not something you set from your account.--Carbon ships a translated interface across many locales, and a per-user language preference is part of the-account model. In the current build the language picker isn't surfaced on the Account sidebar — the-interface follows the app's resolved locale. Treat language as a preference Carbon carries for you rather-than a live toggle on this screen.+**Account → Notifications** is your personal grid of topic × channel switches: in-app is always delivered, and the toggles govern email and (when connected) Slack. The default is on; a switch off is an opt-out for that one topic and channel. What raises each notification and how channels are gated is the `docs/reference/notifications` — this page is where you tune it for yourself.-## Personal attributes+## Theme, language, and attributes-Beyond the shared profile, your company can define **user attributes** — structured fields like a-certification date, a shirt size, or a shift preference — grouped into categories. Whether a given-attribute lands on your public profile or stays admin-only depends on its category being public, and whether-*you* can edit your own value depends on it being marked self-managed.-When it is, you can set the value yourself; when it isn't, only an admin can-(`.../account+/$userId.attribute.tsx:48`). Attribute types range from text and numbers to dates, booleans,-and pick-lists.+Your color theme is stored in a browser cookie, so it follows you per device and applies to nobody else; company-wide branding is an admin setting. Language is a preference Carbon carries for you rather than a live toggle on this screen. Your company can also define **user attributes** (a certification date, a shift preference) grouped into categories: whether one shows on your public profile depends on its category being public, and you can edit your own value only when the attribute is marked self-managed.-Your account is the small surface you own on a shared system: a profile the team can see, the keys you sign-in with, the alerts you let through, and the theme you stare at. None of it reaches past you. For the-switches that do — the ones that shape how the whole company works — see the company settings under-**Settings**, and read the `docs/reference/notifications` for how alerts are-raised in the first place.+For the switches that shape the whole company, see `docs/reference/company-settings` and `docs/reference/people`.-## Troubleshooting+## Internals and troubleshooting-Why some sign-in controls aren't editable here — these are preconditions, not error messages.+Sidebar sections come from `useAccountSubmodules.tsx:9`; `/x/account` redirects to Profile (`routes/x+/account+/_index.tsx:4`). Profile saves via `updatePublicAccount` (`account.service.ts:161`), self-scoped to the user's own `user` row. Photo uploads route through the `image-resizer` function. The passkey card renders only when `isAuthProviderEnabled("passkey")` (`security.tsx`); passkey names cap at 100 characters. Notification preferences: absent row = enabled (`notifications.tsx:130`); Slack column gated by `slackActive` (`notifications.tsx:47`); email gated by the `EMAIL_NOTIFICATIONS` plan feature (`notifications.tsx:49, :175`). Theme is a cookie (`theme.tsx`). Attribute self-editing is gated by the self-managed flag (`$userId.attribute.tsx:48`).### Can't change your email from the Account screen-The Email field on Profile is shown but **read-only** (disabled). Your email is your sign-in identity and how Carbon addresses your notifications, so it isn't editable as a profile field. Changing it is an identity change handled outside these self-service settings, not something you do here.+The field is deliberately read-only. Email is the sign-in identity and the notification address; changing it is an identity change handled outside self-service.### There's no password to change-Carbon signs you in by magic link, OAuth, or a passkey — there's no stored password you type each time. A password-change form exists in the codebase but isn't wired into any account route, so password management is not a live control on this screen.+Sign-in is magic link, OAuth, or passkey. A password-change form exists in the codebase but isn't wired into any account route, so password management is not a live control here.### The passkey card isn't showing-Passkeys appear only when the `passkey` sign-in provider is enabled for the deployment. Which sign-in methods exist is a deployment-wide choice set by the `AUTH_PROVIDERS` environment variable (default `email,google,azure`), not a per-user setting. If passkey isn't in that set, the card won't render — sign in by magic link or OAuth instead.+The `passkey` provider isn't enabled for the deployment. `AUTH_PROVIDERS` (default `email,google,azure`) decides which sign-in methods exist; it's deployment-wide, not per-user.### There's no language picker-A per-user language preference is part of the account model, but in the current build the picker isn't surfaced on the Account sidebar — the interface follows the app's resolved locale. Treat language as a preference Carbon carries for you, not a live toggle here.+The per-user language preference exists in the account model, but the picker isn't surfaced on the Account sidebar in the current build; the interface follows the app's resolved locale.### The Slack or Email notification column is missing-The **Slack** column appears only if an admin connected the Slack integration for the company. **Email** notifications depend on your company's plan — without the `EMAIL_NOTIFICATIONS` feature, preferences are stored but only take effect once it's enabled.+Slack's column needs the integration connected. Email preferences are stored regardless but only take effect when the plan includes `EMAIL_NOTIFICATIONS`.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/change-orders/lifecycle.md b/apps/erp/app/modules/agent/kb/docs/reference/change-orders/lifecycle.mdindex 5cd25f2925..0ce792efad 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/change-orders/lifecycle.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/change-orders/lifecycle.md@@ -1,6 +1,6 @@# Lifecycle & release-> The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and exactly what release does when a change notice reaches Done.+> The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and what release does at Done.A change notice advances forward one stage at a time. There's no approval toggle — the stages *are* theworkflow, and the change notice is its own release gate. There are two ways back: **Reopen** atdiff --git a/apps/erp/app/modules/agent/kb/docs/reference/change-orders/setup.md b/apps/erp/app/modules/agent/kb/docs/reference/change-orders/setup.mdindex aa3519da85..44d6eb9d79 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/change-orders/setup.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/change-orders/setup.md@@ -1,6 +1,6 @@# Categories & actions-> The two company-scoped lookups that sit alongside change notices — the category list and the reusable action-task templates — plus linking an action task to Linear.+> The company-scoped lookups beside change notices: the category list and reusable action-task templates, plus linking a task to Linear.Two configuration lists live next to change notices in the Items nav. Both are company-scoped and edited byemployees with the `parts` permission.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.mdindex 4fe430758a..b7c73f45f7 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md@@ -2,120 +2,89 @@> The company record, its feature toggles, base currency, logos, and tags — the company-wide configuration every module reads from.-Everything in Carbon is scoped to a **company**. Your login can belong to several companies, and each one carries its own address, base currency, logos, feature toggles, and numbering. Two records hold this configuration: the `company` row (identity, address, currency, logos) and a paired `companySettings` row (one-to-one, keyed on the same id) that holds the company-wide feature flags and defaults. This page is the map of what lives where.--Settings live under **Settings** in the app, grouped into **Company**, **Modules**, and **System** (`apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx`). Every route is employee-only; a few are gated further — **Billing** needs company ownership and a Cloud environment, and **Companies** and **Backups** are internal-only.+Everything in Carbon is scoped to a **company**, and two records hold its configuration: the `company` row (identity, address, currency, logos) and a paired `companySettings` row holding the company-wide feature flags and defaults. Settings live under **Settings** in the app, grouped into **Company**, **Modules**, and **System**. Every route is employee-only; **Billing** additionally needs company ownership on a Cloud environment, and **Companies** and **Backups** are internal-only.## The company record-The `company` table is the tenant's identity. Its fields come from the `companyValidator` (`apps/erp/app/modules/settings/settings.models.ts:81`) and are edited under **Settings → Company**.+Edited under **Settings → Company**:- **name**: Company name.- **addressLine1 / addressLine2 / city / stateProvince / postalCode / countryCode**: The registered address. `addressLine1`, `city`, `postalCode`, and `countryCode` are required.- - **baseCurrencyCode**: The currency every posted amount is expressed in. See [base currency](#base-currency) below.+ - **baseCurrencyCode**: The currency every posted amount is expressed in. See [base currency](#base-currency).- **phone / fax / email / website**: Contact details.- **taxId / vatNumber / eori**: Tax registration identifiers printed on documents.- - **logoLight / logoDark / logoLightIcon / logoDarkIcon / logoWatermark**: Storage paths to the company's logos. See [logos](#logos).- - **parentCompanyId**: Set when this company is a subsidiary of another. See [multiple companies](#multiple-companies).- - **isEliminationEntity**: Marks a consolidation-only company used to eliminate intercompany pairs.+ - **logoLight / logoDark / logoLightIcon / logoDarkIcon / logoWatermark**: The five logo slots, edited under **Settings → Logos**: light/dark pairs for UI backgrounds, compact icon variants, and a watermark printed behind documents.+ - **parentCompanyId**: Set when this company is a subsidiary of another.+ - **isEliminationEntity**: Marks a consolidation-only company that nets intercompany pairs out of consolidated reports.- **companyGroupId**: Groups related companies for the company switcher.- **selectedModules**: Which modules this company turned on during onboarding.- - **industryId / customIndustryDescription**: The industry chosen at onboarding — collected on the industry step, not the general company form.- - **auditLogEnabled**: Whether change history is recorded. See `docs/reference/notifications`.- - **suggestionNotificationGroup**: Who is notified when the AI suggestion engine surfaces something.--The service reads it with `getCompany(client, companyId)`, which rewrites each stored logo path to a public URL before returning (`settings.service.ts:230`).--## Multiple companies--company membership is per-user, so one login can hold several companies and switch between them. `getCompanies(client, userId)` returns every company a user can enter (`settings.service.ts:139`); the ERP is an employee app, so supplier- and customer-only memberships are filtered out by `getEmployeeCompanies` (`settings.service.ts:183`). Switching happens through the company picker, and each company you enter carries its own settings, currency, and numbering — nothing crosses the boundary.+ - **industryId / customIndustryDescription**: The industry chosen at onboarding.+ - **auditLogEnabled**: Whether change history is recorded. See `docs/reference/audit-log`.-Companies can also nest. A company with a `parentCompanyId` is a **subsidiary** (`subsidiaryValidator`, `settings.models.ts:279`); an `isEliminationEntity` company exists only to net intercompany transactions out of consolidated reports.--The **Companies** management screen and **Backups** are gated to internal operators (`internalOnlyRoutes` in `useSettingsSubmodules.tsx`). Most tenants create and switch companies through onboarding and the company picker, not this screen.--For consolidated reporting and the elimination flow, see `docs/reference/intercompany`.+Company membership is per-user: one login can hold several companies and switch through the company picker, and each company carries its own settings, currency, and numbering. Nothing crosses the boundary. A company with a `parentCompanyId` is a subsidiary; consolidation and elimination are covered in `docs/reference/intercompany`.## Feature toggles and defaults-`companySettings` is a single row per company (one-to-one with `company`, keyed on the same id). It holds the company-wide switches and defaults that individual modules read at runtime. Read it with `getCompanySettings(client, companyId)` (`settings.service.ts:283`). Each group of fields is edited on its own **Settings → Modules** page and saved through a small dedicated validator.+`companySettings` is a single row per company, edited across the **Settings → Modules** pages. These are the real column names:-The flags below are the real column names from the `companySettings` row (`packages/database/src/types.ts:6653`).-- - **accountingEnabled**: Master switch for the ledger. When off, operations complete without posting journal entries. This is the gate the accounting flow checks before it posts anything.- - **timeCardEnabled**: Turns on shop-floor time cards. Edited via `timeCardSettingsValidator`.- - **consoleEnabled**: Enables the support/impersonation console. Edited via `consoleSettingsValidator`.- - **requireMfa**: Requires everyone to have an authenticator app before they can open this company. Edited from the **Two-Factor Authentication Enforcement** card on **Settings → System → Security**. Locked on and uneditable in controlled (ITAR) deployments. See `docs/reference/two-factor`.- - **useMetric**: Whether material units default to metric. Edited via `materialUnitsValidator`.- - **materialGeneratedIds**: Whether new materials get an auto-generated readable id. Edited via `materialIdsValidator`.+ - **accountingEnabled**: Master switch for the ledger. When off, operations complete without posting journal entries.+ - **timeCardEnabled**: Turns on shop-floor time cards.+ - **consoleEnabled**: Enables the support/impersonation console.+ - **requireMfa**: Everyone needs an authenticator app to open this company. Edited from **Settings → System → Security**; locked on in controlled (ITAR) deployments. See `docs/reference/two-factor`.+ - **useMetric**: Whether material units default to metric.+ - **materialGeneratedIds**: Whether new materials get an auto-generated readable id.- **plmReleaseControl**: The release-control policy for item revisions.- **kanbanOutput**: What a Kanban card prints: `label`, `qrcode`, or `url`.- - **productLabelSize / shelfLabelSize**: Default label sizes for product and shelf labels.+ - **productLabelSize / shelfLabelSize**: Default label sizes.- **updateLeadTimesOnReceipt**: Whether receiving recalculates supplier lead times.- **purchasePriceUpdateTiming**: When purchase prices refresh: `Purchase Invoice Post` or `Purchase Order Finalize`.- - **maintenanceGenerateInAdvance / maintenanceAdvanceDays**: Whether preventive-maintenance work is generated ahead of time, and by how many days (1–90).+ - **maintenanceGenerateInAdvance / maintenanceAdvanceDays**: Whether preventive maintenance is generated ahead of time, and by how many days (1–90).- **samplingStandard**: The default inspection sampling standard.- **enforceInspectionFourEyes**: Requires a second person to sign off inspections.- **qualityIssueTarget**: The quality issue target used in reporting.- **assetTaxDepreciationEnabled / assetTaxRate**: Whether a separate tax-depreciation schedule is tracked for fixed assets, and its rate.- **showCustomerReadableId / showSupplierReadableId**: Whether customer/supplier readable ids are surfaced in the UI.- - **inventoryShelfLife**: A single blob holding every shelf-life knob (near-expiry warning days, default shelf life, calculated-input scope, expired-entity policy). See `docs/reference/shelf-life`.+ - **inventoryShelfLife**: Every shelf-life knob in one blob. See `docs/reference/shelf-life`.- **digitalQuoteEnabled / digitalQuoteIncludesPurchaseOrders**: Whether customers get a digital quote, and whether it includes purchase orders.- - **quoteLineCategoryMarkups**: Per-category default markups (material, part, tool, labor, machine, overhead, outside…) applied to quote lines.+ - **quoteLineCategoryMarkups**: Per-category default markups applied to quote lines.-Several fields on the same row are **notification groups** — arrays of who to notify for a given event (`digitalQuoteNotificationGroup`, `rfqReadyNotificationGroup`, `supplierQuoteNotificationGroup`, `inventoryJobCompletedNotificationGroup`, `salesJobCompletedNotificationGroup`, the maintenance/quality/operations/other `*DispatchNotificationGroup`s, and `gaugeCalibrationExpiredNotificationGroup`). Two AP/AR email addresses (`accountsPayableEmail`, `accountsReceivableEmail`) and default CC lists (`defaultSupplierCc`, `defaultCustomerCc`) live here too. For how these fan out to people, see `docs/reference/notifications`.+The same row also carries the **notification groups** (who to notify for digital quotes, RFQ-ready, supplier quotes, job completions, dispatches, gauge-calibration expiry), the AP/AR email addresses, and default CC lists — see `docs/reference/notifications` for how they fan out.-`accountingEnabled` gates the *entire* ledger. If it is off, jobs, shipments, and invoices still complete, but nothing posts to the general ledger — there are no partial or per-transaction exceptions. Turning it on mid-stream doesn't backfill past activity.+`accountingEnabled` gates the *entire* ledger: off means jobs, shipments, and invoices complete but nothing posts, with no per-transaction exceptions. Turning it on mid-stream doesn't backfill past activity.## Base currency-Every company has one `baseCurrencyCode`, set on the `company` row and required by `companyValidator` (`settings.models.ts:77`). It is the currency that all *posted* amounts are stored and reported in. Transactions in other currencies are converted to base at their exchange rate before they post, so the ledger stays single-currency.--Base currency is chosen at onboarding and is not something you flip casually — it's the denomination of your whole history. A subsidiary can carry a different base currency from its parent; consolidation is where those meet.+Every company has one `baseCurrencyCode`: the currency all *posted* amounts are stored and reported in, with foreign-currency transactions converted at their exchange rate before posting. It's chosen at onboarding and is the denomination of your whole history, so it isn't something you flip casually. A subsidiary can carry a different base currency from its parent; consolidation is where they meet.-## Theme+## Theme and tags-Carbon ships eight themes, each supplying a full set of HSL CSS variables (`packages/utils/src/themes.ts`): **Modern** (`zinc`), **Brutal** (`neutral`), **Cherry** (`red`), **Apricot** (`orange`), **Lemon** (`yellow`), **Mint** (`green`), **Blueberry** (`blue`), and **Lavender** (`violet`). The set is validated by `themeValidator` (`settings.models.ts:306`).--Theme selection is stored in a cookie for the current user and browser, not on the company record — the action just sets a cookie via `setTheme` (`apps/erp/app/routes/x+/account+/theme.tsx`). Two people in the same company can each run a different theme. Document templates have their own, separate theme setting.--## Logos--The `company` row holds up to five logo slots: `logoLight`, `logoDark`, `logoLightIcon`, `logoDarkIcon`, and `logoWatermark`, edited under **Settings → Logos**. They are stored as storage paths; `getCompany` and `getCompanies` rewrite them to public URLs on read (`settings.service.ts:230`, `settings.service.ts:139`). The light/dark pairs cover light and dark UI backgrounds; the icon variants are the compact mark; the watermark prints behind documents.--## Tags--Tags are free-form labels scoped to a company and a table, stored in the `tag` table. They're loaded per table with `getTagsList(client, companyId, table)` and created with `insertTag` (`apps/erp/app/modules/shared/shared.service.ts:929`, `:987`). Because every tag carries both `companyId` and a `table`, the same label can mean different things on items versus jobs, and tag vocabularies never leak across companies.+Carbon ships eight color themes (Modern, Brutal, Cherry, Apricot, Lemon, Mint, Blueberry, Lavender). Theme is **per-person**, stored in a browser cookie rather than on the company record, so two people in one company can run different themes; document templates have their own separate theme setting. **Tags** are free-form labels scoped to a company *and* a table, so the same label can mean different things on items versus jobs, and vocabularies never leak across companies.## Related system configuration-A few more company-wide lookups live under **Settings → System** and have their own reference pages:-- Numbering sequences The per-company generators behind every readable document number.- API keys Scoped secrets that let external systems call the Carbon API.- Approvals Approval rules that gate documents above a threshold.- - Notifications How the notification groups above reach people.--Which company-wide features are available at all also depends on your plan and edition — see `docs/platform/licensing`.+ - Licensing Which features exist at all depends on plan and edition.-## Troubleshooting+## Internals and troubleshooting-Mostly "why can't I see or change setting X" — the answers are preconditions, not error strings.+Settings nav groups come from `useSettingsSubmodules.tsx` (internal gates in `internalOnlyRoutes`). Company fields are validated by `companyValidator` (`settings.models.ts:81`; `baseCurrencyCode` required at `:77`); subsidiaries by `subsidiaryValidator` (`:279`); themes by `themeValidator` (`:306`, definitions in `packages/utils/src/themes.ts`). Reads: `getCompany` (`settings.service.ts:230`, rewrites logo paths to public URLs), `getCompanies` (`:139`), `getEmployeeCompanies` (`:183`, filters supplier/customer-only memberships), `getCompanySettings` (`:283`). `companySettings` columns are in `packages/database/src/types.ts:6653`; each Modules page saves through its own small validator (`timeCardSettingsValidator`, `consoleSettingsValidator`, `materialUnitsValidator`, `materialIdsValidator`, …). Tags live in the `tag` table via `getTagsList` / `insertTag` (`shared.service.ts:929`, `:987`). Theme is set by a cookie action (`routes/x+/account+/theme.tsx`).### I can't find the Companies or Backups settings page-Both are internal-operator-only, gated by `internalOnlyRoutes` in `useSettingsSubmodules.tsx`. Regular tenants don't get these screens — create and switch companies through onboarding and the company picker instead.+Internal-operator-only (`internalOnlyRoutes`). Tenants create and switch companies through onboarding and the company picker.### I can't see the Billing settings page-Billing needs **company ownership** *and* a Cloud environment — it's gated on both (`useSettingsSubmodules.tsx`). Self-hosted/community editions and non-owner users won't see it.+Billing needs company ownership *and* a Cloud environment; self-hosted editions and non-owners don't get it.-### Nothing posts to the general ledger even though jobs and invoices complete-`accountingEnabled` is a company-wide master switch, not per-document. When it's off, jobs, shipments, and invoices still complete but nothing posts — there are no partial exceptions. Turn it on under **Settings → Modules**; note it does **not** backfill past activity.+### Nothing posts to the ledger though jobs and invoices complete+`accountingEnabled` is off. Turn it on under Settings → Modules; it does not backfill past activity.### My theme changed but a colleague still sees the old one-Theme is per-user, not per-company. The action just sets a cookie via `setTheme` (`apps/erp/app/routes/x+/account+/theme.tsx`), so each person in the same company runs their own theme. Document templates carry a separate theme setting.+Theme is per-user (a cookie), not per-company. Document templates carry a separate theme setting.### I can't change the base currency-Base currency (`baseCurrencyCode`) is the denomination of your whole posted history and is chosen at onboarding — it's not meant to be flipped casually. A subsidiary can carry a different base currency from its parent; that difference is reconciled at consolidation, not by switching a company's base.+By design: it's the denomination of the whole posted history, chosen at onboarding. Subsidiary/parent currency differences reconcile at consolidation, not by switching a base.-### A settings page (Modules) exists but the toggle does nothing I expect-`companySettings` flags are read by individual modules at runtime; the feature they gate may also depend on your plan and edition (see licensing). If a flag appears set but the feature is absent, check the edition gate before assuming the toggle is broken.+### A Modules toggle does nothing I expect+Flags are read by modules at runtime, and the feature may also be gated by plan/edition. Check licensing before assuming the toggle is broken.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/custom-fields.md b/apps/erp/app/modules/agent/kb/docs/reference/custom-fields.mdindex 520c3ca186..feccee1b81 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/custom-fields.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/custom-fields.md@@ -2,87 +2,45 @@> Company-defined extra fields that attach to core records like customers, parts, and orders.-Carbon ships a fixed schema for every entity, but your process almost always needs one more field the base tables don't have. A machine-shop customer might carry a "PPAP level"; a part might need a "RoHS status"; a job might track an internal "line number". Custom fields let each company add its own fields to a core record without a schema change. They surface on the record's form, save alongside the built-in fields, and are queryable through the API.+Carbon ships a fixed schema for every entity, but your process almost always needs one more field: a customer's "PPAP level", a part's "RoHS status", a job's internal "line number". Custom fields let each company add its own fields to a core record without a schema change. Define one under **Settings → Custom Fields** and every record of that entity shows it on its form, saves it alongside the built-in fields, and exposes it through the API.-A custom field is defined once, per company, and attaches to a **table** (a core entity like `customer` or `part`). Every record of that entity then shows the field on its form. Define them under **Settings → Custom Fields**.--## How a custom field is defined--Each field has a name, a data type, and the table it attaches to. The definition lives in the `customField` table (`packages/database/supabase/migrations/20240311021818_custom-fields.sql:21`), and the form validator that governs the create/edit UI is `customFieldValidator` (`apps/erp/app/modules/settings/settings.models.ts:109`).+## Defining a field- **Name**: The label shown on the record's form. Unique per table, per company.- - **Data Type**: One of the nine types below. **Once saved, the data type can't be changed** (the form disables it on edit, `apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx:116`) — delete and re-create to switch types.- - **List Options**: Required only for the **List** type: the set of choices the dropdown offers. Enforced by the validator (`settings.models.ts:121`).- - **Required**: When on, the field must be filled before the form saves. Boolean fields are never treated as required (`CustomFormFields.tsx:31`).- - **Tags**: Scopes the field to records carrying a matching tag. A tagged field only appears on records that share one of its tags — leave empty to show it on every record of the table.--## Data types--There are nine data types (`DataType` enum, `apps/erp/app/modules/shared/types.ts:83`). Each one renders a specific input on the form.+ - **Data Type**: One of nine types (below). **Once saved, the type can't be changed**; delete and re-create to switch.+ - **List Options**: Required only for the **List** type: the dropdown's choices.+ - **Required**: The field must be filled before the form saves. Boolean fields are never treated as required.+ - **Tags**: Scopes the field to records carrying a matching tag; leave empty to show it on every record of the table.-| # | Type | Renders as |-|---|------|------------|-| 1 | **Boolean** | A toggle |-| 2 | **Date** | A date picker |-| 3 | **List** | A dropdown of your defined options |-| 4 | **Numeric** | A number input with steppers |-| 5 | **Text** | A single-line text input |-| 6 | **User** | An employee picker |-| 7 | **Customer** | A customer picker |-| 8 | **Supplier** | A supplier picker |-| 9 | **File** | A file reference |+The nine data types each render a specific input: **Boolean** (toggle), **Date** (date picker), **List** (dropdown of your options), **Numeric**, **Text**, **File**, and three reference types (**User**, **Customer**, and **Supplier**) that store a pointer to an existing Carbon record rather than free text.-The `User`, `Customer`, and `Supplier` types store a reference to another Carbon record, so a custom field can point at an existing entity rather than just holding free text. The rendering switch lives in `CustomFormFields.tsx:75`.--Because existing values are stored as-is, Carbon locks the data type after creation. If you picked Text and need Numeric, create a new field and migrate the values — there's no in-place conversion.+Existing values are stored as-is, so Carbon locks the type after creation. Picked Text and need Numeric? Create a new field and migrate the values; there is no in-place conversion.## Which entities support custom fields-Custom fields attach to a curated set of core entities, not every table. The catalog of eligible tables is the `customFieldTable` table, grouped by module (`20240311021818_custom-fields.sql:2`), and it's seeded across migrations starting with `20240511125727_seed_custom_fields.sql`. On the **Settings → Custom Fields** page you'll see one row per eligible entity, showing its **Table**, **Module**, and how many **Fields** you've defined (`apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx:32`).--The eligible entities span most modules:--- **Sales** — customer, sales order, sales invoice, RFQ, and their contacts and lines.-- **Purchasing** — supplier, purchase invoice, supplier quote, and RFQ lines.-- **Items** — part, tool, material, consumable, and item costing/planning records. See `docs/reference/items` for the base fields these extend.-- **Resources** — employee job, work center, equipment, department, location.-- **Inventory** — shipment, warehouse transfer, picking list.-- **Production** — job.-- **Accounting** — account, payment term, journal.--Because the list is code-managed, an entity that isn't in `customFieldTable` can't take custom fields. If the entity you want isn't listed on the settings page, it isn't supported yet.--## How fields save on a form--Every entity form that supports custom fields drops in the shared `` component (`apps/erp/app/components/Form/CustomFormFields.tsx`), passing its own table name. The component reads the company's field definitions and renders each one below the built-in fields.--The values don't get their own columns. They serialize into a single `customFields` JSONB column on the record — the same extensibility column every core table carries. On submit, the route action calls `setCustomFields(formData)` (`apps/erp/app/utils/form.ts`), which collects the custom inputs (each named with a `custom-` prefix) and writes them into that JSONB blob. `getCustomFields` reverses it to repopulate the form on edit.--A required custom field is enforced by an additional validator the form registers at runtime (`CustomFormFields.tsx:44`), separate from the entity's own zod schema — so requiredness lives with the field definition, not the base form.--## CSV import and export+The catalog is curated, not universal — the settings page lists one row per eligible entity with its module and field count. Coverage spans most modules: **Sales** (customer, sales order, sales invoice, RFQ, their contacts and lines), **Purchasing** (supplier, purchase invoice, supplier quote, RFQ lines), **Items** (part, tool, material, consumable, costing/planning records; see `docs/reference/items`), **Resources** (employee job, work center, equipment, department, location), **Inventory** (shipment, warehouse transfer, picking list), **Production** (job), and **Accounting** (account, payment term, journal). An entity not listed on the settings page isn't supported yet.-Custom fields **do not participate in CSV import or export**. The `import-csv` edge function maps CSV columns to the entity's built-in fields only; it has no path for the `customFields` JSONB (`packages/database/supabase/functions/import-csv/index.ts`). Likewise, the table download does not emit custom-field columns. Import and export cover the base schema — populate custom fields on the record's form, or through the API. See `docs/reference/import-export` for what the CSV flow does cover.+## How values save, and where they reach-## API access+Custom inputs render below the built-in fields on the record's form and save into a single `customFields` JSON column that every core table carries — no schema change per field. That column is exposed on the API like any other: readable and filterable on the entity's endpoint, with the caveat that its keys are field IDs, not display names, so pair an API read with the definitions from the settings catalog.-The `customFields` JSONB column is exposed on the API. Because it's a real column on each core table, PostgREST surfaces it as a readable and filterable field on the entity's endpoint — the swagger schema references `rowFilter.<table>.customFields` for the tables that carry it (`packages/database/src/swagger-docs-schema.ts`). Reading a record returns the whole `customFields` object; the keys inside are the field IDs, not the display names, so pair an API read with the field definitions from the settings catalog to map IDs back to labels.+The CSV flows map built-in fields only; neither import nor the table download touches the `customFields` column. Populate custom fields on the form or through the API; see `docs/reference/import-export` for what CSV does cover.-## Troubleshooting+## Internals and troubleshooting-Where the custom-field form and the import/API paths trip people up.+Definitions live in the `customField` table (`20240311021818_custom-fields.sql:21`); the form validator is `customFieldValidator` (`settings.models.ts:109`). The eligible-entity catalog is `customFieldTable`, seeded from `20240511125727_seed_custom_fields.sql` onward; the settings page renders it in `CustomFieldsTable.tsx:32`. Forms drop in the shared `` (`components/Form/CustomFormFields.tsx`; rendering switch at `:75`), inputs are named with a `custom-` prefix, and route actions collect them via `setCustomFields(formData)` / repopulate via `getCustomFields` (`utils/form.ts`). The nine types are the `DataType` enum (`modules/shared/types.ts:83`). Swagger exposes `rowFilter.<table>.customFields`.-### "Required" (on a custom field that won't submit)-A required custom field is empty. Requiredness isn't in the entity's own schema — it's enforced by a runtime validator the form registers per table (`CustomFormFields.tsx:44`). Fill the field, or clear its **Required** flag in **Settings → Custom Fields**. Note **Boolean** fields are never treated as required, even with the flag on (`CustomFormFields.tsx:31`) — a Boolean that "must be filled" will never block a save.+### "Required" on a custom field that won't submit+Requiredness is enforced by a runtime validator the form registers per table (`CustomFormFields.tsx:44`), separate from the entity's zod schema. Fill the field or clear its Required flag. Boolean fields are never treated as required, even with the flag on (`CustomFormFields.tsx:31`).### List custom field rejected on save-A **List**-type field saved with no options, an empty option, or no listOptions at all fails the validator's refine (`settings.models.ts:121-131`). Give the List at least one non-empty choice under **List Options** before saving.+A List field with no options or an empty option fails the validator's refine (`settings.models.ts:121-131`). Give it at least one non-empty choice.-### The Data Type dropdown is disabled when editing a field-Not a bug. The data type is locked once the field is saved — the form sets `isReadOnly` on the Data Type select while editing and shows "Data type cannot be changed" (`CustomFieldForm.tsx:110-116`). Existing values are stored as-is with no in-place conversion, so to switch (e.g. Text → Numeric) you delete the field and re-create it, then migrate the values.+### The Data Type dropdown is disabled when editing+By design: the form sets `isReadOnly` on the type select and shows "Data type cannot be changed" (`CustomFieldForm.tsx:110-116`). Delete and re-create to switch types.-### A custom field's values aren't in my CSV import or export-Expected. Custom fields don't participate in CSV import or export — the `import-csv` edge function maps only built-in fields and the table download omits the `customFields` JSONB. Populate custom fields on the record's form or through the API.+### Custom-field values missing from CSV import/export+Expected — the `import-csv` edge function maps only built-in fields and the download omits the JSONB. Use the form or the API.### The entity I want has no Custom Fields row-Only entities in the code-managed `customFieldTable` catalog support custom fields. If an entity isn't listed on **Settings → Custom Fields**, it isn't eligible yet — there's no way to add it from the UI.+Only entities in the code-managed `customFieldTable` catalog are eligible; there's no way to add one from the UI.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/customer-portal.md b/apps/erp/app/modules/agent/kb/docs/reference/customer-portal.mdnew file mode 100644index 0000000000..7d1c048945--- /dev/null+++ b/apps/erp/app/modules/agent/kb/docs/reference/customer-portal.md@@ -0,0 +1,25 @@+# Customer portal++> A standing, read-only link where a customer watches their open orders and shop-floor progress, no Carbon account needed.++The customer portal is a **standing, read-only window** into one customer's work. Where a `docs/reference/quotes` closes a deal, the portal is what the buyer watches afterward: their sales order lines with status, the buyer and engineer contacts, order and due dates, part number and revision, quantity complete, quantity shipped, and per-operation job progress. There are no forms — the customer can look, not act.++## Creating a portal++Open **Sales → Portals** and create a portal for the customer. Each row carries the portal's private URL with a copy control; send that link to your customer contact. The link needs no login, so whoever holds the URL can open it — treat it like a password and send it only to the right person.++A portal is scoped to a single customer record: it lists that customer's orders and nothing else. Files attached to their job operations can be downloaded from the portal, limited to the customer's own jobs and rate-limited per visitor.++## Related++ - Digital quotes The customer-facing bookend before the order: accept or reject a sent quote.+ - Sales orders The orders and statuses the portal reflects.+ - External sharing How Carbon's private links work across quotes, supplier requests, and SCARs.++## Troubleshooting++### Why does the customer portal link show "Not found" / a 404?+The customer portal is gated behind the `CUSTOMER_PORTALS` plan feature (Business plan). A company without it gets a 404 on the portal URL (and a 403 on file downloads). Upgrade the plan to enable the portal.++### Why did downloads from the portal start failing (HTTP 429)?+File downloads on the portal are rate-limited to ten per minute per IP. Wait a minute and retry; the limit is per requesting IP address, not per file.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/issues.md b/apps/erp/app/modules/agent/kb/docs/reference/issues.mdindex dd135fa87f..f67ab50583 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/issues.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/issues.md@@ -56,6 +56,8 @@ The `issues` view computes a **containment status** from the action tasks. It reAction tasks run their own small lifecycle: **"Pending"** → **"In Progress"** → **"Completed"**, with **"Skipped"** as an off-path exit. Tasks start Pending and do *not* auto-start. Completing a task stamps its completed date. A completed or skipped task can be reopened back to Pending. Tasks can be reordered, given due dates, and tied to specific processes, and a supplier-facing action task can be shared externally as a **SCAR** (Supplier Corrective Action Request) report.+The SCAR is a private, login-free link the supplier opens to respond. They see the non-conformance details, the current status, and the action tasks assigned to them — not the rest of the issue: dispositions, approvals, and closure stay internal. For each task the supplier can update the status and write notes in an editor that auto-saves as they type; entering notes on a **"Pending"** task promotes it to **"In Progress"** automatically. Once the issue is **"Closed"**, the SCAR locks and the supplier can no longer make changes. Whoever holds the URL can open it, so send it only to the supplier contact.+## Approvals and the Material Review BoardBeyond actions, an issue can require **approvals**. The only approval requirement Carbon ships is MRB (Material Review Board). Adding it materializes an approval task and, when MRB is newly required, seeds two **reviewers** with titles **"Engineering"** and **"Quality"**. Remove MRB and those seeded reviewers are cleared; reviewers you added by hand are left alone. A reviewer is just a title on the issue. You manage the list inline on the issue.@@ -118,3 +120,6 @@ When an issue requires **MRB** approval, an approval task and reviewer rows (Eng### Permission-gated: you can't create, edit, close, or delete an issueListing issues needs `quality` **view**; creating needs `quality` **create**; editing, closing, splitting, and moving entities all need `quality` **update**; deleting needs `quality` **delete**. If an action is blocked, your role is missing the corresponding quality permission (Settings → Roles).++### "Issue has been closed already. Unable to make changes" (SCAR)+A supplier tried to update a SCAR action task after the parent issue was set to `Closed`. Once the issue is Closed the SCAR is read-only. Reopen the issue internally if further supplier action is needed.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/notifications.md b/apps/erp/app/modules/agent/kb/docs/reference/notifications.mdindex ae76e12069..5c71b37023 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/notifications.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/notifications.md@@ -2,144 +2,68 @@> Assignments, approvals, expirations, and reminders reach the right people over in-app, email, and Slack, with per-user channel opt-outs by topic.-A notification tells one person that something needs their attention: a job was assigned to them, an-approval is waiting, a gauge's calibration lapsed, a quote expired. Carbon raises these from across the-system and fans each one out to up to three channels: the **in-app inbox** (the bell in the top bar),-**email**, and **Slack**. In-app is always on; email and Slack are extras a user can mute per topic.--Say a purchasing manager assigns a purchase order to a buyer. The buyer gets a row in their in-app inbox-immediately, an email if the company has email notifications, and a Slack DM if the company connected Slack-and the buyer hasn't muted purchasing on Slack. If that buyer sent the assignment to themselves, they get-nothing — Carbon never notifies you about your own action.+A notification tells one person that something needs their attention: a job was assigned to them, an approval is waiting, a gauge's calibration lapsed. Carbon fans each one out to up to three channels: the **in-app inbox** (the bell in the top bar), **email**, and **Slack**. In-app is always on; email and Slack are extras a user can mute per topic. One rule holds everywhere: Carbon never notifies you about your own action.## What raises a notification-Every notification starts as a `carbon/notify` event with a specific type. The type-falls into one of three shapes:-- - **Assignments**: Someone is put on a record: a job, job operation, sales order, purchase order, RFQ, purchase invoice, supplier quote, issue, risk, procedure, picking list, stock transfer, maintenance dispatch, or training. The assignee is the recipient.- - **State changes & responses**: A record's state moved in a way someone should know about: an approval was **requested**, **approved**, or **rejected**; a job **completed**; a change notice entered a new stage; a quote **expired**; a customer or supplier responded to a digital quote or supplier quote.- - **Expirations & reminders**: Time-driven, raised by scheduled jobs rather than a user action: a **gauge calibration expired**, a **maintenance dispatch** was auto-created for a work center, or a weekly **training reminder** rolls up a person's outstanding trainings.- - **Workflow**: A `docs/reference/workflows` reached a **"Notify someone"** step. You write the subject and message yourself, and address it to a user or a group; it lands under the **General** topic with a **View details** button pointing at whichever record the step named.--The full set of event types lives in `NotificationEvent` (`packages/notifications/src/index.ts:7`). Adding a-notification anywhere in Carbon means dispatching one of these — the workflow step is the only path that-lets you compose the wording yourself.--Notifications are informational, never an approval step. Marking one read doesn't change any record, and there's no-"acknowledge" or "accept" on a notification itself. The action lives on the underlying document (approve the-PO, complete the job) — the notification just points you there.--## Topics--Every event maps to exactly one **topic** — a coarse bucket used for grouping the inbox and for the per-user-channel opt-outs. There are twelve, and the mapping is fixed in code-(`getNotificationTopic`, `packages/notifications/src/index.ts:114`):+ - **Assignments**: Someone is put on a record (job, order, RFQ, invoice, issue, risk, procedure, picking list, stock transfer, dispatch, training). The assignee is the recipient.+ - **State changes & responses**: An approval was **requested**, **approved**, or **rejected**; a job **completed**; a change notice entered a new stage; a quote **expired**; a customer or supplier responded to a digital or supplier quote.+ - **Expirations & reminders**: Time-driven, raised by scheduled jobs: a **gauge calibration expired**, a **maintenance dispatch** was auto-created, or the weekly **training reminder** rolls up a person's outstanding trainings.+ - **Workflow**: A `docs/reference/workflows` reached a **"Notify someone"** step, the only path where you compose the wording yourself. Lands under the **General** topic.-| Topic | Example events |-| --- | --- |-| Approval | Approval requested / approved / rejected |-| Job | Job assignment, job operation assignment, job operation message, job completed |-| Sales | Sales order assignment, sales RFQ assignment, RFQ ready |-| Quote | Quote assignment, quote expired, digital quote response, supplier quote assignment / response |-| Purchasing | Purchase order, purchasing RFQ, and purchase invoice assignments |-| Inventory | Picking list and stock transfer assignments |-| Quality | Issue assignment, risk assignment |-| Maintenance | Maintenance dispatch (assigned or created), gauge calibration expired |-| Training | Training and procedure assignments, resource training, training reminder |-| Suggestion | Suggestion response |-| Items | Change notice started / in implementation / complete |-| General | Workflow notifications, and anything without a specific bucket |+Notifications are informational, never an approval step. Marking one read changes no record; the action lives on the underlying document, and the notification just points you there.-The topic string is **stored** on every notification (`notification.topic`). It's what a user's opt-out row-matches on, so a topic is not just a label — it's the grouping key for muting. Eleven of the twelve topics are-user-facing on the settings page; only **Items** is not offered as a toggle.+## Topics and channels-## Channels+Every event maps to exactly one **topic**, the grouping key for the inbox and for muting: Approval, Job, Sales, Quote, Purchasing, Inventory, Quality, Maintenance, Training, Suggestion, Items, and General. Eleven are user-facing on the settings page; only **Items** has no toggle.-A single notification can go to three destinations, defined in `NotificationDestination`-(`packages/notifications/src/index.ts:108`):+The channels differ in what they require:- - **In-app**: The bell in the top bar. **Always written** for every recipient, on every event. It cannot be turned off — the fan-out adds it regardless of what the caller requests (`notify.ts:210`).- - **Email**: A per-notification email with a heading, a short description, and a **View** button linking to the record. Sent only when the company's plan includes email notifications.- - **Slack**: A direct message in the connected Slack workspace. Sent only when the company has an active Slack integration and the recipient has a matching Slack account.+ - **In-app**: The bell in the top bar. **Always written**, for every recipient, on every event — it cannot be turned off.+ - **Email**: A per-notification email with a **View** button. Sent only when the company's plan includes email notifications.+ - **Slack**: A DM in the connected workspace. Needs an active Slack integration *and* a matching Slack account for the recipient.-Each event has default channels (most assignments default to email + Slack), and the caller can override them-per dispatch. In-app is the constant: it's the one channel a user can never silence and the one the top bar-always reflects.+Email is **plan-gated**: companies without the `EMAIL_NOTIFICATIONS` plan feature skip the email channel entirely, regardless of the per-user switch. Slack has no plan gate — it only needs the integration. See `docs/platform/licensing`.-Email is **plan-gated.** The fan-out checks the `EMAIL_NOTIFICATIONS` plan feature and skips the email-channel entirely for companies without it (`notify.ts:509`). Slack has no plan gate — it only needs the-integration connected. See `docs/platform/licensing` for what each plan includes.+## Muting a topic-## Per-user preferences+Each user controls their own email and Slack delivery under **Account → Notifications**: a grid with one row per topic, a column per channel, a switch in each cell. In-app has no switch.-Each user controls their own email and Slack delivery under **Account → Notifications**. The settings page is-a grid: one row per user-facing topic, a column per channel, a switch in each cell. In-app has no switch —-it's not something a user opts out of.--Preferences are stored as **opt-out** rows, one per `(user, company, channel, topic)`-(`notificationPreference` table). The default is **on**: no row means the channel is enabled for that topic.-Flipping a switch off writes a row with `enabled = false`, which mutes that one topic on that one channel.-Flipping it back on removes the mute. The fan-out reads these rows and drops muted recipients from the email-and Slack lists before sending (`notify.ts:302`); the in-app row is never filtered.--Muting is **per topic and per channel**, scoped to the current company. Muting Purchasing on Slack still-leaves you Purchasing emails, still leaves you Slack DMs for Sales, and doesn't carry over to another company-you belong to. And whatever you mute, the in-app inbox still gets every notification.--The Slack column only appears when the company has Slack connected. The email column always shows; if the-company's plan doesn't include email notifications, the page notes that email won't be delivered even with the-switch on.+The default is **on**; flipping a switch off mutes that one topic on that one channel, scoped to the current company. Muting Purchasing on Slack still leaves Purchasing emails, still leaves Slack DMs for Sales, and doesn't carry to another company you belong to. The Slack column appears only when Slack is connected; the email column always shows, with a note when the plan won't deliver it.## Who receives an expiration or reminder-Assignments and responses have an obvious recipient — the assignee, or the person who raised the request. The-time-driven events don't, so each resolves its own audience:-- - **Gauge calibration expired**: Goes to a company-configured list of users — the `gaugeCalibrationExpiredNotificationGroup` array on company settings — not to a role or a single owner. Set it under gauge/calibration settings so the right people hear when a gauge lapses.- - **Maintenance dispatch created**: Goes to every employee attached to the dispatch's work center. Auto-created dispatches notify whoever staffs that station.- - **Training reminder**: A weekly digest per person, rolling that individual's outstanding trainings into one notification rather than one per course.--There's no general "notification group" entity. Only gauge-calibration expiry uses a configured user list;-everything else derives recipients from the record itself — the assignee, the approvers, the work center's-staff, or the person with outstanding trainings.+Assignments have an obvious recipient. The time-driven events resolve their own audience: a lapsed gauge calibration notifies a company-configured user list (set under `docs/reference/calibration` settings), an auto-created dispatch notifies every employee on that work center, and the training reminder is a weekly per-person digest. There is no general "notification group" entity — only gauge-calibration expiry uses a configured list; everything else derives recipients from the record itself.## The inbox-The bell in the top bar opens the in-app inbox. It shows recent notifications newest-first with an unread-count, each row carrying an icon for its event, a short description, who it came from, and a timestamp. Click a-row's link to jump to the record; mark a row read with its **mark read** button.--Recurring reminders don't nag forever. A repeating email notification for the same document stops after a few-successful deliveries (`MAX_NOTIFICATION_DELIVERIES`, `packages/notifications/src/index.ts:90`) — currently-only the weekly training reminder is recurring. The in-app row still stands until you read it.+The bell opens the inbox: recent notifications newest-first with an unread count, each row carrying an icon, a short description, who it came from, and a timestamp. Click through to the record, or mark a row read.## Related- - Approvals Approval requested, approved, and rejected each raise a notification to the approvers or the requester.- - Calibration A lapsed gauge calibration notifies the company's configured calibration group.- - Maintenance Auto-created dispatches notify the work center's staff.- - Webhooks For machine-to-machine events — an HTTP POST on record insert, update, or delete — rather than a person's inbox.+ - Approvals Requested, approved, and rejected each notify the approvers or the requester.+ - Calibration A lapsed calibration notifies the configured group.+ - Workflows Compose your own notification from a "Notify someone" step.+ - Webhooks For machine-to-machine events rather than a person's inbox.-## Troubleshooting+## Internals and troubleshooting-Delivery questions are almost always a missing precondition on the email or Slack channel — the in-app inbox always works.+Every notification starts as a `carbon/notify` event with a specific type; the full set is `NotificationEvent` (`packages/notifications/src/index.ts:7`), destinations are `NotificationDestination` (`index.ts:108`), and the fixed event→topic mapping is `getNotificationTopic` (`index.ts:114`). The topic string is stored on every row (`notification.topic`) and is what a user's opt-out row matches on. Preferences are opt-out rows, one per `(user, company, channel, topic)` in `notificationPreference`; no row means enabled. The fan-out always adds the in-app destination (`notify.ts:210`), drops muted recipients from email/Slack lists (`notify.ts:302`), and skips email entirely without the `EMAIL_NOTIFICATIONS` plan feature (`notify.ts:509`). Most assignments default to email + Slack; callers can override channels per dispatch.### Why am I not getting email notifications?-Email is **plan-gated.** The fan-out checks the `EMAIL_NOTIFICATIONS` plan feature and skips the email channel entirely for companies without it — regardless of the per-user switch. Check the company's plan first. If the plan includes it, then confirm the topic isn't muted for email (a `notificationPreference` row with `enabled = false` for that topic/channel) and that the specific event actually defaults to the email channel.+Email is plan-gated — check the company's plan first. Then confirm the topic isn't muted for email and that the specific event defaults to the email channel.### Why am I not getting Slack DMs?-Slack has no plan gate, but it needs two things: the company must have an **active Slack integration** connected, and *you* must have a **matching Slack account** in that workspace. Users without a matching Slack account are silently skipped. Also confirm you haven't muted the topic on Slack under Account → Notifications.+Slack needs an active integration and a matching Slack account for the recipient; users without one are silently skipped. Also check the topic's Slack mute.-### I muted a topic but I'm still getting in-app notifications-Expected — in-app is **always written** for every recipient on every event and cannot be turned off. The mute switches only affect email and Slack; the fan-out never filters the in-app row. The bell always reflects every notification.+### I muted a topic but still get in-app notifications+Expected: in-app is always written and cannot be turned off. Mutes affect only email and Slack.### I turned a channel on but it still doesn't deliver-Preferences default to **on** (no row = enabled), so flipping a switch on just removes the mute — it doesn't override the channel's own preconditions. Email still requires the `EMAIL_NOTIFICATIONS` plan; Slack still requires the integration + a matching account. The settings page notes when email won't be delivered even with the switch on because the plan doesn't include it.+On just removes the mute; it doesn't override the channel's preconditions (plan feature for email, integration + account for Slack).### I did something myself and got no notification-Carbon never notifies you about your own action — the sender is filtered out of the recipient list. If you assigned a record to yourself, that's why there's nothing in your inbox.+The sender is filtered out of the recipient list. Self-assignments notify nobody.### A recurring reminder stopped arriving-Repeating email notifications for the same document stop after a few successful deliveries (`MAX_NOTIFICATION_DELIVERIES`) — currently only the weekly training reminder is recurring. The in-app row still stands until you mark it read.+Repeating email notifications for the same document stop after a few successful deliveries (`MAX_NOTIFICATION_DELIVERIES`, `index.ts:90`); only the weekly training reminder is recurring. The in-app row stands until read.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/onboarding.md b/apps/erp/app/modules/agent/kb/docs/reference/onboarding.mdindex 45bf09ddbc..bf23654aad 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/onboarding.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/onboarding.md@@ -1,95 +1,32 @@# Getting started-> The first-run setup wizard that creates your company, and the Implementation Hub that guides a new company from an empty tenant to live on Carbon.+> The first-run setup wizard that creates your company, seeds its baseline configuration, and hands you a working tenant.-Getting started on Carbon has two distinct surfaces. The **setup wizard** runs once, right after you sign up: it creates the company record, your profile, and the address that becomes your first location, then hands you a working tenant. The **Implementation Hub** is the checklist that takes it from there — a step-by-step map from that empty tenant to your team running production on Carbon. The wizard is unavoidable; the Hub is opt-in, and a company enrolls itself.+A brand-new account has no company yet, so Carbon holds you in the setup wizard at `/onboarding` until one exists. Onboarding counts as complete when the company has a **name** and at least **one location**; those two facts are the gate, and finishing the Company step supplies both.-## The setup wizard+**Theme.** Pick a color theme (cosmetic, stored in a cookie).-A brand-new account has no company yet, so Carbon holds you in `/onboarding` until one exists. The layout loader treats onboarding as complete only when the company has a **name** and at least **one location** — there is no `onboarded` boolean, the presence of those two facts is the gate (`apps/erp/app/routes/onboarding+/_layout.tsx:33-44`). Until then, every step redirects back into the wizard.+**Your profile.** First and last name, both required.-The steps run in a fixed order (`apps/erp/app/utils/path.ts:2103-2109`):+**Company.** The substantive step: company name, full address, base currency, optional website. Submitting creates the company and everything a usable tenant needs.-**Theme.** Pick a color theme (`zinc`, `neutral`, `red`, `orange`, `yellow`, `green`, `blue`, or `violet`). This is a cosmetic choice stored in a cookie, not the database (`apps/erp/app/routes/onboarding+/theme.tsx`; validator at `apps/erp/app/modules/settings/settings.models.ts:306-311`).+Two steps appear conditionally: **Industry** (internal Carbon staff only: offers a `docs/platform/demo-data` or a `docs/platform/backups` restore) and **Plan** (Carbon Cloud only: Stripe checkout; self-hosted installs go straight to the app).-**Your profile.** First name and last name, both required. They write to your `user` record (`apps/erp/app/routes/onboarding+/user.tsx`; validator `onboardingUserValidator` at `apps/erp/app/modules/account/account.models.ts:12-17`).--**Company.** The substantive step. It collects the company **name**, a full address (address line 1 and 2, city, state or province, postal code, country), a **base currency**, and an optional website (`apps/erp/app/routes/onboarding+/company.tsx`; `addressValidator` at `apps/erp/app/modules/settings/settings.models.ts:95-107`). Submitting this creates the company and everything a usable tenant needs.--Two more steps appear conditionally, and only in specific circumstances (`apps/erp/app/routes/onboarding+/_layout.tsx:49-53`):--- **Industry** — shown only to internal Carbon staff accounts. It offers a `docs/platform/demo-data` or a `docs/platform/backups` restore, so a seeded example company can be stood up. Regular sign-ups never see it.-- **Plan** — shown only on Carbon Cloud, the hosted version at [app.carbon.ms](https://app.carbon.ms). It routes you to Stripe checkout to pick a plan before you enter the app. Self-hosted installs skip it entirely and go straight to `/x`.--Saving the company doesn't just insert one row. It also creates a **"Headquarters"** location from the address you entered (with your local timezone), links your user to the company as an employee, and seeds the tenant's baseline: chart of accounts, default posting accounts, numbering sequences, payment terms, and units of measure. This all happens under the hood via `provisionOnboardingCompany` and a background seed job (`apps/erp/app/services/onboarding.server.ts`; seed via `seedCompany` at `apps/erp/app/modules/settings/settings.service.ts:751-765`).--### What you don't choose during onboarding--Fiscal year, accounting periods, and the numbering sequences are **not** asked for in the wizard. They come pre-seeded with sensible defaults, and you tune them afterward under `docs/reference/company-settings`. The wizard's job is to get you into a working tenant fast, not to make you configure the whole system up front.--## The Implementation Hub--Once you're in the app, an empty tenant is still a long way from running production. The **Implementation Hub** (the "Get Started" area, at `/x/get-started`) is Carbon's structured onboarding checklist. It walks a new company through six phases from kickoff to go-live, with each phase deep-linking into the exact ERP screens you configure along the way (`apps/erp/app/routes/x+/get-started+/_layout.tsx`).--The Hub only exists for a company that has **enrolled**. Enrollment is self-serve: anyone who can update company settings can turn it on from the home-page card, no Carbon staff required (`apps/erp/app/routes/x+/get-started+/enroll.tsx:24-48`). While the Hub is active, it takes over the home page so the project stays front and center, and it emails your Admins that the Hub is ready (`apps/erp/app/routes/x+/_index.tsx:37-53`).--### The six phases--The Hub is organized around six sequential **gates** — each phase ends at exactly one milestone you sign off before moving on (`packages/onboarding/src/content/spine.ts:11-143`):-- - **Discovery**: Confirm how your company runs and lock the project scope. Ends at **"Scope signed"**. Paid tiers only.- - **Configure**: Set Carbon up around your business: sites, users, suppliers, parts, BOMs, and Bill of Process. Ends at **"System configured"** — this is the phase most of your setup work lives in.- - **Migrate data**: Load your real data and approve a validated sample. Ends at **"Data validated"**. Paid tiers only.- - **Train**: Your team leads learn Carbon via the in-app guides and Academy, then bring everyone else up. Ends at **"Team trained"**.- - **Acceptance**: Every in-scope test passes on your configured system, with your data. Ends at **"Acceptance passed"**. Paid tiers only.- - **Go-Live**: Cut over, freeze the old system, and confirm you're live on Carbon. Ends at **"Live on Carbon"**.--The **Configure** and **Acceptance** phases nest concrete "do this in Carbon" actions inside them — import your BOM, run MRP into purchase orders and jobs, serialize and sell a part. Those nested steps **auto-detect** their own completion against real tenant data (Carbon checks whether you actually have items, a job, a sales order) rather than relying on a manual tick (`packages/onboarding/src/content/spine.ts:38-131`).--### Tiers change what you see--The Hub adapts to how a company is being onboarded. There are three tiers — `self_serve`, `guided`, and `enterprise` — and self-serve enrollment defaults to `self_serve` (`apps/erp/app/routes/x+/get-started+/enroll.tsx:41`). The tier prunes the phases and pages that don't apply.--A self-serve company configures Carbon directly, so it skips the phases built for a Carbon-led project: **Discovery** (scoping), **Migrate data**, and **Acceptance** all fall away, along with their pages like Scope Summary, Roles, Requirements, and Data Migration. What's left is the core spine — Configure, Train, Go-Live — plus the pages every tier shares. The guided and enterprise tiers add the full commercial project structure back in (`packages/onboarding/src/content/registry.ts:8-115`).--### The Setup Map--The single most useful page for a hands-on operator is the **Setup Map** (in the "Configure Carbon" group). It's the first-run configuration checklist: every master, reference, and config entity a new company sets up before it starts transacting, grouped by module and labelled as it appears in that module's navigation (`packages/onboarding/src/content/setup.ts:32-436`). It covers, per module:-- - **Accounting**: Fiscal year, accounting periods, chart of accounts, default accounts, cost centers, dimensions, payment terms, exchange rates, asset classes.- - **Settings**: Company identity, document templates, logos, printing, sequences, custom fields, integrations, approval rules.- - **Resources**: Locations, work centers, processes, training abilities, failure modes, maintenance schedules.- - **People**: Employees, departments, shifts, holidays, attributes, employee types, permission groups.- - **Items**: Units, item groups, parts, materials, tools, consumables, and the material substances, shapes, grades, and finishes.- - **Sales**: Customers, customer types and statuses, price lists, pricing rules, no-quote reasons.- - **Purchasing**: Suppliers and supplier types.- - **Inventory**: Storage units, storage types, storage rules, shipping methods.- - **Production**: Scrap reasons.--Each row deep-links straight to the screen where you configure that thing (`apps/erp/app/routes/x+/get-started+/_layout.tsx:59-118`), and its "configured" state is tracked so the Plan page and the Setup Map can never disagree about the same work. Rows tagged to a module drop out when you exclude that module, so an org that doesn't run quality or accounting doesn't see setup it will never do. The Accounting group only appears at all when accounting is enabled for the company (`apps/erp/app/routes/x+/get-started+/_layout.tsx:230-232`).+Saving the company also creates a **"Headquarters"** location from your address, links you as an employee, and seeds the baseline: chart of accounts, posting accounts, numbering sequences, payment terms, units of measure. Fiscal year, periods, and sequences are deliberately *not* asked for — they come pre-seeded and you tune them later under `docs/reference/company-settings`.## Where to go next-The wizard gets you a tenant; the Hub gets you to production. For the settings the wizard seeds and you refine, see `docs/reference/company-settings`. For adding the rest of your team, their access, and permission groups, see `docs/reference/people`. And for the end-to-end story of how work actually flows through Carbon once you're set up, the [guides](/guides) walk it start to finish.+The wizard's job is a working tenant, not a configured one. Refine the seeded settings under `docs/reference/company-settings`, set up your document numbering under `docs/reference/sequences`, add your team under `docs/reference/people`, and read the [guides](/guides) for how work flows through Carbon once you're set up.-## Troubleshooting+## Internals and troubleshooting-Why onboarding won't let you into the app, and which steps show up — these are preconditions, not error messages.+The completion gate is the layout loader (`routes/onboarding+/_layout.tsx:33-44`); step order is `utils/path.ts:2103-2109`; conditional steps at `_layout.tsx:49-53`. Theme validator `settings.models.ts:306-311`; profile `onboardingUserValidator` (`account.models.ts:12-17`); company `addressValidator` (`settings.models.ts:95-107`). Provisioning runs `provisionOnboardingCompany` (`services/onboarding.server.ts`) with the seed via `seedCompany` (`settings.service.ts:751-765`).### Stuck in the setup wizard / keeps redirecting to /onboarding-Onboarding is complete only when the company has a **name** and at least **one location**. There is no `onboarded` flag — the presence of those two facts is the gate. Until both exist, every step redirects back into the wizard. Finishing the **Company** step supplies both at once (it creates the company and a "Headquarters" location from the address you enter), so complete that step to get in.+The company lacks a name or a location — there is no `onboarded` flag. Complete the Company step; it creates both at once.### The Industry step isn't showing-It appears only for internal Carbon staff accounts. It offers demo-data templates and backup restore to stand up a seeded example company; regular sign-ups never see it, and its absence is expected.+Internal Carbon staff accounts only. Its absence for regular sign-ups is expected.### The Plan step isn't showing-The plan / Stripe-checkout step appears only on Carbon Cloud (the hosted version at app.carbon.ms). Self-hosted installs skip it entirely and go straight into the app at `/x`.--### Can't enroll in the Implementation Hub-Enrollment is self-serve but gated: only someone who **can update company settings** can turn the Hub on from the home-page card. Without that permission, the enroll control won't work — have an admin enroll, or grant Settings update access.--### The Accounting group is missing from the Setup Map-The Setup Map's Accounting group only appears when accounting is enabled for the company. Rows tagged to a module also drop out when that module is excluded, so an org that doesn't run a module won't see setup it will never do.--### Some Hub phases are missing (Discovery, Migrate data, Acceptance)-The Hub prunes phases by tier. Self-serve enrollment defaults to the `self_serve` tier, which skips the Carbon-led phases — **Discovery**, **Migrate data**, and **Acceptance** — leaving Configure, Train, and Go-Live. The `guided` and `enterprise` tiers add the full project structure back.+Cloud-only (app.carbon.ms). Self-hosted installs skip it and land at `/x`.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/quotes.md b/apps/erp/app/modules/agent/kb/docs/reference/quotes.mdindex f53bd5554f..1ecf1c39ff 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/quotes.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/quotes.md@@ -28,9 +28,13 @@ Each line tracks its own progress too: **Not Started**, **In Progress**, **Compl## Digital quotes-A **Sent** quote can be shared with the customer over a private link, no login. From it the customer **accepts**, optionally entering their PO number, and the quote converts straight to a sales order; or they **reject**, and it moves to **Lost**. Internal notes are stripped before anything reaches the customer.+A **Sent** quote can be shared with the customer over a private link, no login — the URL is in the quote's share dialog. The page shows the quote lines with images, the quantity-break pricing, the totals (subtotal, discount, tax, shipping), the shipping method and payment term, and any external notes. Internal notes are stripped before anything renders, so the customer never sees your working comments.-Digital acceptance is gated: the quote must be **Sent** and the company must have digital quotes enabled. A companion customer portal then shows the buyer live order and job status as the work proceeds.+From that page the customer **accepts** — entering their name and email, picking the quantity break per line, and optionally attaching a purchase-order PDF — and the quote converts straight to a sales order, stamping who accepted it. Or they **reject**, again with a name and email, and the quote moves to **Lost**.++There is no account or password behind the link — whoever holds the URL can open the quote. Send it to the right person and don't post it anywhere public. Both actions are gated on status: only a **Sent** quote can be answered, and once the `expirationDate` passes the page shows an expired state and the buttons are gone.++A companion `docs/reference/customer-portal` then shows the buyer live order and job status as the work proceeds.## Becoming an order@@ -53,3 +57,9 @@ In the quote line's bill of materials, the item being made was selected as one o### "Failed to convert quote to order"The conversion action failed after line selection. Have the user retry with the lines re-selected; if it persists, check that the selected lines have valid quantities and pricing, and ask for the full error text.++### "This quote is no longer available for a response." (digital quote)+A customer tried to accept or reject a digital quote whose status is no longer `Sent` (it's already `Ordered`, `Partial`, `Cancelled`, or similar). Only a `Sent` quote can be answered — the accept/reject buttons are hidden once it leaves that state.++### "Oops! The link you're trying to access has expired or is no longer valid." (digital quote)+A `Sent` quote past its `expirationDate` shows the expired state on its public page and can no longer be accepted. Re-send a fresh quote with a new expiration date; the old link stays expired.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/sequences.md b/apps/erp/app/modules/agent/kb/docs/reference/sequences.mdindex 5a048ac2ff..4669f89a0e 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/sequences.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/sequences.md@@ -2,52 +2,33 @@> The per-company generator behind every readable document number — jobs, change notices, payments, and more.-Every document Carbon creates gets a human-readable number: a job is `J000001`, an engineering change notice is `CN-000001`, a payment is `PAY-2026-07-000001`. Those numbers come from sequences — one small counter per document type, per company. Each sequence knows its prefix, its suffix, how wide the number is, how much to step by, and what value comes next. When a document is created, Carbon reads the sequence, formats the next value, and advances the counter.+Every document Carbon creates gets a human-readable number: a job is `J000001`, a change notice is `CN-000001`, a payment is `PAY-2026-07-000001`. Those numbers come from sequences, one small counter per document type per company. Sequences live under **Settings → Sequences**; every company is seeded with a full set, and you can retune any of them (prefix, counter, padding) without touching code.-Sequences live under **Settings → Sequences**. Every company gets a full set seeded when it's created, and you can retune any of them — change the prefix, restart the counter, widen the padding — without touching code.--## What a sequence is--A sequence is a row in the `sequence` table, keyed by `("table", "companyId")` — one counter per document type per company (`packages/database/supabase/migrations/20230525025310_sequences.sql:1`, primary key moved to `("table", "companyId")` in `20240704105128_rfq.sql:120`). The `table` column names the document type it counts (`"job"`, `"changeOrder"`, `"payment"`), and `name` is the label you see in the UI ("Job", "Change Notice", "Payment").--When something needs a new number, Carbon assembles it from three parts:+When something needs a number, Carbon assembles it from three parts and advances the counter in the same operation, so two documents never collide:```{prefix}{next + step, zero-padded to size}{suffix}```-So a `job` sequence with prefix `J`, size `6`, step `1`, and `next` at `0` produces `J000001`, then `J000002`, and so on. The counter is advanced in the same operation that reads it, so two documents never collide (`packages/database/supabase/functions/shared/get-next-sequence.ts:23`).--Once a document is created, its number is written to the record and never changes — even if you later edit the sequence. Retuning a sequence only affects documents created **after** the change. It never renumbers what already exists.+Once created, a document's number never changes. Retuning a sequence only affects documents created **after** the change; it never renumbers what exists.## Fields-These are the columns you can tune per sequence. All of them are editable from the sequence form except the document type itself.-- - **Prefix**: Text prepended to the number. Optional. Supports date tokens (below), so `PAY-%{yyyy}-%{mm}-` renders as `PAY-2026-07-`. Stored in the `prefix` column.- - **Current**: The last value handed out — the `next` column. The next document gets `Current + Step`. Set this to restart or fast-forward numbering. Must be `≥ 0` (`apps/erp/app/modules/settings/settings.models.ts:288`).- - **Size**: How many digits the number is zero-padded to. Size `6` gives `000001`; size `4` gives `0001`. Accepted range is `1`–`20` (`apps/erp/app/modules/settings/settings.models.ts:291`). Most sequences ship at `6`.- - **Step**: How much the counter climbs each time. Almost always `1`. Must be `≥ 1`.- - **Suffix**: Text appended after the number. Optional. Supports the same date tokens as the prefix. Stored in the `suffix` column.--The sequence form previews the result live as you type, so you can see exactly what the next number will look like before saving (`apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx:38`).+ - **Prefix**: Text prepended to the number. Optional; supports date tokens, so `PAY-%{yyyy}-%{mm}-` renders as `PAY-2026-07-`.+ - **Current**: The last value handed out; the next document gets `Current + Step`. Set it to restart or fast-forward numbering. Must be `≥ 0`.+ - **Size**: Zero-padding width: size `6` gives `000001`. Accepted range `1`–`20`; most sequences ship at `6`.+ - **Step**: How much the counter climbs each time. Almost always `1`; must be `≥ 1`.+ - **Suffix**: Text appended after the number. Optional; same date tokens as the prefix.### Date tokens-Prefix and suffix can embed the current date, which is how payments and journal entries get their year/month partitioning. The tokens are interpolated when the number is generated, not when you save the sequence:-- - **%{yyyy}**: Full four-digit year, e.g. `2026`.- - **%{yy}**: Two-digit year, e.g. `26`.- - **%{mm}**: Zero-padded month, `01`–`12`.- - **%{dd}**: Zero-padded day, `01`–`31`.- - **%{hh}**: Zero-padded hour, `00`–`23`.- - **%{ss}**: Zero-padded second, `00`–`59`.+Prefix and suffix can embed the current date — how payments and journal entries get their year/month partitioning. Tokens are interpolated when the number is generated, not when you save: `%{yyyy}` (2026), `%{yy}` (26), `%{mm}` (01–12), `%{dd}` (01–31), plus `%{hh}` and `%{ss}` for hour and second.-Carbon has two code paths that expand these tokens. The document-creation edge functions support all six (`packages/database/supabase/functions/lib/utils.ts:33`). But some numbers — customers, suppliers, and quotes, which are stamped by a database trigger — go through the `get_next_sequence` database function, which only understands the four **date** tokens `%{yyyy}`, `%{yy}`, `%{mm}`, and `%{dd}` (`packages/database/supabase/migrations/20241115101526_rpc-get-next-sequence.sql:42`). Putting `%{hh}` or `%{ss}` in one of those sequences leaves the literal token in the number. Stick to date tokens unless you know the document type is generated by an edge function.+Customers, suppliers, and quotes are numbered by a database trigger that only understands the four **date** tokens; putting `%{hh}` or `%{ss}` in those sequences leaves the literal token in the number. Stick to date tokens unless you know the document type is generated by an edge function.-## Which documents use a sequence+## Seed defaults-A new company is seeded with a sequence for every numbered document type (`packages/database/supabase/functions/lib/seed.data.ts:222`). These are the defaults — the prefix and starting values you'd see on a fresh company:+A new company is seeded with a sequence for every numbered document type:| Document type | `table` | Prefix | Example ||---|---|---|---|@@ -80,45 +61,22 @@ A new company is seeded with a sequence for every numbered document type (`packa| Credit memo | `creditMemo` | `CR-%{yyyy}-%{mm}-` | `CR-2026-07-000001` || Debit memo | `debitMemo` | `DR-%{yyyy}-%{mm}-` | `DR-2026-07-000001` |-Payments are a good example of the pattern in action. A `payment`, a `creditMemo`, and a `debitMemo` each have their own sequence; the payment-creation path picks the right one by the memo's direction, so a credit memo draws from `CR-` and a debit memo from `DR-` (`packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql:567`).--The seed table above is what a brand-new company gets. When some sequences were added after launch, the migration that backfilled them for existing companies used a different prefix — jobs, for instance, were backfilled as `WO` for older companies (`packages/database/supabase/migrations/20240909194622_jobs.sql:363`) even though new companies seed as `J`. If a prefix on your company doesn't match the table above, it's likely one of these backfilled defaults. Either way, you can change it under **Settings → Sequences**.--Change notices are the reverse case: their sequence was re-prefixed from `ECO-` to `CN-` for every company during the rename, so only *new* records get `CN-000001`. Ids already minted as `ECO-000001` are left exactly as they were.--## How a number gets assigned--The flow is the same everywhere a number is minted:--- A document is created — you convert a sales order line to a `docs/reference/jobs`, open a `docs/reference/change-orders`, or record a payment.--- Carbon looks up the sequence for that document type and company, computes `next + step`, zero-pads it to `size`, and wraps it in the (date-interpolated) prefix and suffix.--- The counter advances in the same operation — `next` is written back before the number is returned — so concurrent creates never share a number (`packages/database/supabase/functions/shared/get-next-sequence.ts:28`).--- The formatted number is saved on the new document and stays fixed for its lifetime.---Accounting posts are the heaviest user of this machinery: every GL post — from shipments, receipts, invoices, inventory adjustments, and production events — pulls a fresh `journalEntry` number as it books, which is why the journal-entry sequence carries a month token by default.+A prefix on an older company may differ: a few sequences added after launch were backfilled with different defaults (jobs as `WO`, change notices re-prefixed from `ECO-` without renumbering existing records). Either way, change it under **Settings → Sequences**.-Sequences are company-scoped like everything else in Carbon, so two companies in the same `docs/reference/intercompany` number their documents independently, even when they share a chart of accounts.+Accounting posts are the heaviest user of this machinery: every GL post pulls a fresh `journalEntry` number as it books, which is why that sequence carries a month token by default. Sequences are company-scoped, so two companies in the same `docs/reference/intercompany` number independently even when they share a chart of accounts. Where the numbers land day to day: `docs/reference/jobs`, `docs/reference/change-orders`, and `docs/reference/payments`.-## Troubleshooting+## Internals and troubleshooting-The field bounds and the two-token-path gotcha that catch people.+A sequence is a row in the `sequence` table keyed by `("table", "companyId")` (`20230525025310_sequences.sql`, PK moved in `20240704105128_rfq.sql:120`). The counter advances in the same operation that reads it (`functions/shared/get-next-sequence.ts:23`). The form's live preview is `SequenceForm.tsx:38`; seed defaults are `functions/lib/seed.data.ts:222`. Payments pick the right sequence by memo direction — credit memos draw `CR-`, debit memos `DR-` (`20260630093809_ar-ap-payments.sql:567`).### A sequence field won't save (Current, Step, or Size)-The `sequenceValidator` bounds each numeric field (`settings.models.ts:285-292`): **Current** (`next`) must be `≥ 0`, **Step** must be `≥ 1`, and **Size** must be between `1` and `20`. A Step of `0`, a negative Current, or a Size above `20` is rejected. Set values inside those ranges.+`sequenceValidator` bounds them (`settings.models.ts:285-292`): Current `≥ 0`, Step `≥ 1`, Size `1`–`20`. Values outside those ranges are rejected.### My `%{hh}` or `%{ss}` token shows up literally in the number-Only some documents expand hour/second tokens. Customers, suppliers, and quotes are numbered by a database trigger through the `get_next_sequence` RPC, which interpolates only the four **date** tokens `%{yyyy}`, `%{yy}`, `%{mm}`, `%{dd}` (`20241115101526_rpc-get-next-sequence.sql:42-51`) — it never replaces `%{hh}` or `%{ss}`, so the literal token stays in the number. Edge-function-generated documents support all six. Stick to date tokens for customer/supplier/quote prefixes.+Customers, suppliers, and quotes are numbered by a database trigger through the `get_next_sequence` RPC, which interpolates only `%{yyyy}`, `%{yy}`, `%{mm}`, `%{dd}` (`20241115101526_rpc-get-next-sequence.sql:42-51`). Edge-function-generated documents support all six tokens. Use date tokens only for customer/supplier/quote prefixes.### Editing a sequence didn't renumber existing documents-By design. A document's number is written to the record when it's created and never recomputed. Retuning a sequence (prefix, Current, Size) only affects documents created **after** the change; it never renumbers history.+By design: numbers are written at creation and never recomputed.### A prefix on my company doesn't match the seed defaults-Some sequences were backfilled for existing companies with a different prefix than a fresh company seeds — jobs, for instance, were backfilled as `WO` even though new companies seed as `J` (`20240909194622_jobs.sql:363`). Change it under **Settings → Sequences** if you want the newer default.+Backfilled defaults for older companies differ in places — jobs were backfilled as `WO` (`20240909194622_jobs.sql:363`) though new companies seed `J`; change notices were re-prefixed `ECO-` → `CN-` for new records only, leaving minted `ECO-` ids untouched. Change it under Settings → Sequences.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/sharing.md b/apps/erp/app/modules/agent/kb/docs/reference/sharing.mdindex db6f9f0559..1570ec776f 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/sharing.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/sharing.md@@ -1,76 +1,16 @@-# External sharing and portals+# External sharing-> Private, login-free links that let a customer accept a quote, a supplier price an RFQ or answer a SCAR, and a buyer watch order status, all without a Carbon account.+> How Carbon's private, login-free links work — a customer accepts a quote, a supplier prices a request or answers a SCAR, a buyer watches order status.-Some of Carbon's work happens with people who don't have a Carbon login: the customer deciding whether to accept a quote, the supplier pricing your request, the buyer wondering where their order is. Rather than email a PDF and wait, Carbon hands each of them a **private link** to a single, live document. Open it and you act right there in the browser: no account, no password, just the one record the link points at.+Some of Carbon's work happens with people who don't have a Carbon login. Rather than email a PDF and wait, Carbon hands them a **private link** to a single, live document: open it and you act right there in the browser — no account, no password, just the one record the link points at. The link is the only credential, so guard it like a password: whoever holds the URL gets in.-Every one of these links resolves through an `externalLink` row. Sending a shareable document creates that row and stamps its id into the source record (`quote.externalLinkId`, `supplierQuote.externalLinkId`, and so on); the link you copy is `/share/<type>/<externalLinkId>`. The public page loads with a service-role client and no permission check, so anyone with the link gets in. Guard the link like a password: possession is the only credential.+Four things reach an outside party this way. Each is documented where the feature lives:-## What can be shared+ - Digital quotes A **"Sent"** quote the customer accepts or rejects.+ - Supplier quotes A request the supplier prices and submits, line by line.+ - Customer portal A standing, read-only view of a customer's orders and shop-floor progress.+ - SCARs A supplier corrective action request the supplier responds to.-Four things reach an outside party through a public link. Each maps to an `externalLinkDocumentType` value and a `/share/...` route.+Each link is only as live as the record behind it: an expired or answered quote turns its page read-only, and a closed issue locks its SCAR. There is no separate link-revocation step to remember.- - **Digital quote**: A **"Sent"** quote a customer can accept or reject. `documentType` **"Quote"**.- - **Supplier quote**: An RFQ a supplier prices and submits. `documentType` **"SupplierQuote"**.- - **Customer portal**: A live view of a customer's open orders and their shop-floor progress. `documentType` **"Customer"**.- - **SCAR**: A supplier corrective action request the supplier responds to. `documentType` **"Non-Conformance Supplier"**.--Two other routes live under `/share/` but are **not** public links, so they don't belong on this list. `/share/purchasing-rfq/:id` is an internal *preview* of how a supplier's request will look, gated by `requirePermissions` with purchasing view. `/share/training/:id` is an internal training assignment that requires an employee login. Neither hands anything to an outside party.--The public share pages skip authentication and load with a service-role client keyed on the `externalLinkId`. There is no password and no account behind the link, so whoever holds the URL can open the document. Send it to the right person, and don't post it anywhere public.--## Digital quotes--A **"Sent"** quote can be shared with the customer over its private link. The page shows the quote lines with images, the quantity-break pricing, the totals (subtotal, discount, tax, shipping), the shipping method and payment term, and any external notes. Internal notes are stripped before anything renders, so the customer never sees your working comments.--From that page the customer does one of two things. They **accept**, entering their name and email and optionally attaching a purchase-order PDF, and Carbon converts the quote straight to a sales order, stamping who accepted it. Or they **reject**, again with a name and email, and the quote moves to **"Lost"**. Line selection is per quantity break, so the customer can accept the tier they want.--Both actions are gated: the quote must be **"Sent"**. A quote that's already **"Ordered"**, **"Partial"**, **"Cancelled"**, or expired is read-only, its buttons gone. Expiry is automatic: once a **"Sent"** quote's `expirationDate` passes, the link shows an *expired* state and can no longer be accepted.--The `externalLink` row (and the quote's `externalLinkId`) is created when the quote is set up and again at finalization. The shareable URL is `/share/quote/<externalLinkId>`, surfaced in the quote's share dialog. See `docs/reference/quotes` for the quote lifecycle behind it.--## Supplier quotes--The mirror image, for the buy side. When you send a supplier quote, Carbon emails the supplier a link to `/share/supplier-quote/<externalLinkId>` along with the request. The supplier opens it with no login and prices the work directly on the page: for each quantity they choose, they enter a **unit price**, **lead time** in days, **shipping cost**, and **tax**, and can attach a note per line.--When every selected line has both a price and a lead time, the **"Submit Quote"** button lights up; the supplier enters their name and email and submits. They can instead **"Decline Quote"**, optionally leaving a reason. Both flows are open only while the quote is in **"Draft"**; once submitted or declined, the page is read-only. The link also expires: a **"Draft"** quote past its `expirationDate` shows the expired state. Each visit stamps `externalLink.lastAccessedAt`, so you can see whether the supplier has opened it.--`/share/purchasing-rfq/:id` is a preview for *your* team, showing how the request will look to a supplier with all the price cells blank. It requires a purchasing login and hands nothing to the supplier. The supplier-facing document is the supplier quote above. See `docs/reference/supplier-quotes` for the full flow.--## Customer portal--The customer portal is a **standing, read-only window** into a customer's work, not a one-document link. It's gated behind the `CUSTOMER_PORTALS` plan feature, so a company on a plan without it gets a 404. Where a digital quote is about closing one deal, the portal is about visibility after the deal: the buyer opens `/share/customer/<externalLinkId>` and watches their orders move.--The portal lists the customer's sales order lines with their status, the buyer and engineer contacts, order and due dates, part number and revision, quantity complete, quantity shipped, and per-operation job progress. There are no forms: the customer can look, not act. A splat route (`/share/customer/:id/*`) lets them download files attached to those job operations, rate-limited to ten downloads a minute per IP and scoped so the file must belong to that customer's own jobs.--A digital quote closes the sale; the customer portal is what the buyer watches afterward as the work proceeds. The two are the customer-facing bookends of an order.--## Supplier corrective action requests--When a supplier-caused defect needs the supplier to act, Carbon shares the corrective action externally as a SCAR (Supplier Corrective Action Request). The link points at `/share/scar/<externalLinkId>`, which resolves through the `externalLink` row to the underlying `docs/reference/issues` (a non-conformance) and its supplier.--The supplier sees the non-conformance details, the current status, the supplier's own name, and the list of **action tasks** assigned to them. For each task they can update the status and write notes in a rich-text editor that auto-saves as they type; entering notes on a **"Pending"** task promotes it to **"In Progress"** automatically. Once the parent issue is **"Closed"**, the record locks and the supplier can no longer make changes.--The SCAR shares the specific action tasks meant for the supplier, not the whole issue. The rest of the non-conformance workflow, dispositions, approvals, and closure stays internal. See `docs/reference/issues` for the action-task lifecycle that a SCAR plugs into.--## Troubleshooting--Exact messages and gates behind the public share links (digital quotes, supplier quotes, customer portal, SCAR).--### "This quote is no longer available for a response."-A customer tried to accept or reject a digital quote whose status is no longer `Sent` (it's already `Ordered`, `Partial`, `Cancelled`, or similar). Only a `Sent` quote can be answered — the accept/reject buttons are hidden once it leaves that state.--### "Oops! The link you're trying to access has expired or is no longer valid." (Quote expired)-A `Sent` quote (or a `Draft` supplier quote) is past its `expirationDate`, so the public page shows the expired state and can no longer be accepted or submitted. Re-send a fresh quote with a new expiration date; the old link stays expired.--### "Issue has been closed already. Unable to make changes"-A supplier tried to update a SCAR action task after the parent non-conformance issue was set to `Closed`. Once the issue is Closed the SCAR is read-only. Reopen the issue internally if further supplier action is needed.--### Why does the customer portal link show "Not found" / a 404?-The customer portal is gated behind the `CUSTOMER_PORTALS` plan feature (Business plan). A company without it gets a 404 on `/share/customer/…` (and a 403 on the file-download splat route). Upgrade the plan to enable the portal.--### Why is the supplier's "Submit Quote" button disabled?-Submit lights up only when every selected line has both a unit price and a lead time greater than zero, and only while the quote is in `Draft`. Fill in price and lead time for each selected quantity; once submitted or declined the page is read-only.--### Why did downloads from the customer portal start failing (HTTP 429)?-File downloads on the portal are rate-limited to ten per minute per IP. Wait a minute and retry; the limit is per requesting IP address, not per file.+Two other pages *look* shared but aren't: the RFQ preview is an internal view of how a supplier's request will look (purchasing login required), and training assignments require an employee login. Neither hands anything to an outside party.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/single-sign-on.md b/apps/erp/app/modules/agent/kb/docs/reference/single-sign-on.mdnew file mode 100644index 0000000000..03b3e98653--- /dev/null+++ b/apps/erp/app/modules/agent/kb/docs/reference/single-sign-on.md@@ -0,0 +1,84 @@+# Single sign-on++> Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.++Single sign-on hands control of Carbon sign-in to your own identity provider: Okta, Entra ID, Google Workspace, or any SAML 2.0 IdP. Register your email domains once, proving you own each with a DNS record, and everyone on them signs in to both ERP and MES with their normal work email — Carbon recognizes the domain and routes to your IdP automatically, no SSO button to find. Registering takes nothing away: the magic link and other methods keep working until you turn on [Require SSO](#requiring-sso).++## Requirements++SSO is an Enterprise feature of your own `docs/platform/self-hosting` deployment (`CARBON_EDITION=enterprise`, which requires a `docs/platform/licensing`). Carbon Cloud sign-in is unaffected. Enable it through `docs/platform/self-hosting/environment-variables`:++Add `sso` to the comma-separated list of sign-in methods.+Turns on the SAML engine in the auth service.+The SAML signing key: a base64-encoded PKCS#1 DER RSA key, minimum 2048-bit. The `openssl` command is in `.env.example`.++## Connect your identity provider++Everything lives on one screen: **Settings → Security**, under **"Single Sign-On"** (viewing needs `settings` view; saving needs `settings` update).++**Copy Carbon's service provider details.** The **"Service Provider Details"** card shows the **"ACS URL"** and **"SP Metadata URL"** with copy buttons.++**Register Carbon in your IdP** as a SAML application using those two URLs. The assertion must include an **email attribute**; the email is how Carbon matches each sign-in to a person and a company.++**Paste the IdP metadata back into Carbon.** In the **"Identity Provider"** card, provide the **"IdP Metadata URL"** *or* the raw **"IdP Metadata XML"** (exactly one), then **"Save"**. The card gaining a **"Require SSO"** switch and a **"Deactivate"** button is the sign the connection is active.++**Verify your email domains.** The **"Email Domains"** card appears once the connection exists. Add each domain your people sign in with, publish the DNS record it shows, and click **"Verify"**. Only verified domains route SSO sign-ins.++## Verifying a domain++Each added domain starts **Pending** with a unique TXT challenge shown on the card:++| Record | Value |+| --- | --- |+| **Host** | `_carbon-challenge.example.com` |+| **Type** | `TXT` |+| **Value** | `carbon-domain-verification=<your unique token>` |++Publish the record at your DNS host, click **"Verify"**, and on a match the domain flips to **Verified**. Verification is one-time; the TXT record can be deleted afterwards. A Pending domain has no effect anywhere, so adding one is always safe.++Only one company can hold a domain verified, first to prove DNS control wins, and the claim survives even if DNS control later changes hands. The clean handover is for the holding company to **Remove** the domain, which frees it for the new owner to verify.++## How sign-in works++The login page is email-first and the SSO fork is invisible: the user types their email, presses **"Continue"**, and Carbon either redirects to your IdP (active connection on that domain) or falls through to the ordinary magic-link flow. Before any session is created, the asserted email's domain must be one of the connection's **verified** domains, so even a misconfigured or hostile IdP can't sign someone into another company.++Provisioning is **invite-first**: no self-serve signup through SSO. An existing member signs straight in (their first SSO sign-in quietly links the SAML identity to their account; the magic link keeps working). Someone with a pending invite has it accepted by their first SSO sign-in, landing with exactly the invite's role. Anyone else is rejected by name and nothing is provisioned; create the invite in the `docs/reference/people` and the retry just works.++## Requiring SSO++Once a sign-in has worked, the **"Require SSO"** switch on the Identity Provider card makes the IdP the only way in for verified domains: magic links, Google, Outlook, and passkeys are all refused server-side. The switch exists only on an active connection, so the path is always *set up, prove a sign-in works, enforce last*. Turning it off — or **"Deactivate"**, which deletes the connection and releases the domain claims — immediately restores the other methods.++If enforcement is on and your IdP is unreachable, nobody on the covered domains can sign in to turn it off. Operators can lift it directly in the database, and magic-link sign-in works on the next attempt:++```sql+UPDATE "ssoConnection" SET "requireSso" = false WHERE "companyId" = '<id>';+```++SSO sessions skip Carbon's `docs/reference/two-factor` and the company-wide requirement in every environment, including controlled (ITAR) deployments: your IdP already enforced its own MFA policy at sign-in. Magic-link logins still get Carbon's own challenge.++## Behavior details and exact messages++Providers are registered directly against the auth service (GoTrue) with the service-role key; no Supabase account or plan is involved. The domain-has-SSO check on the login page is rate-limited and reveals nothing beyond yes/no.++Domain rules: lowercased bare hostnames only (no `@`, no spaces), punycode (`xn--`) for internationalized domains; public email providers (`gmail.com`, `outlook.com`, …) are refused. Several companies may hold a *pending* claim on the same domain at once — exclusivity kicks in at verification. Re-adding your own domain fails with "This domain has already been added". The metadata form rejects both-or-neither with "Provide either a metadata URL or metadata XML (exactly one)".++### Verification fails+Three causes, named in the message: the record isn't visible yet (DNS propagation — wait and retry); the value doesn't match the token (re-copy exactly); or the DNS lookup itself failed (the server's outbound DNS access is blocked). Gotcha: many DNS providers auto-append the domain to the record name — in Cloudflare enter only `_carbon-challenge` and check the preview shows the host once, not twice.++### "Verify" fails on a domain another company verified+Deliberately generic message so the button can't be used to probe which domains are registered where. Handover: the holder removes the domain, or a self-host operator deletes the claim (`DELETE FROM "ssoDomain" WHERE "domain" = 'example.com';`). The previous holder's provider registration keeps routing the domain until its connection is re-saved, but sign-ins on it are rejected once the row is gone.++### "SSO sign-in rejected: this email domain is not registered for your company's SSO connection."+The IdP asserted an email outside the connection's verified domains. Add and verify the domain, or fix the IdP's attribute mapping.++### "SSO sign-in succeeded but no invite exists for `[email protected]`. Contact your administrator."+Invite-first provisioning: the person authenticated at the IdP but is neither a member nor invited. Create the invite and have them retry. Invite emails for SSO-active domains link to the login page with the address prefilled instead of a magic-link code, so the IdP is never bypassed.++### "Complete your first SSO sign-in in Carbon ERP, then return here." (MES)+MES enforces the same domain rules but doesn't run first-time provisioning. One ERP sign-in fixes it permanently.++### "Your organization requires single sign-on. Sign in with your work email to continue."+Require SSO is on and the user tried a non-SSO method on a verified domain. Expected; they sign in via email → IdP redirect. A pending domain enforces nothing.++### "Deactivate Single Sign-On" confirmation+Warns "Users on your registered domains will no longer be able to sign in through your identity provider. This cannot be undone." — the registration is deleted outright and domain claims released; re-enabling means saving the connection again and re-verifying domains.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/supplier-quotes.md b/apps/erp/app/modules/agent/kb/docs/reference/supplier-quotes.mdindex a014b8a5cb..2c15d33701 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/supplier-quotes.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/supplier-quotes.md@@ -39,6 +39,12 @@ A quote is editable only while it's a **"Draft"**. Finalizing moves it to **"ActAny status other than Draft locks the quote. If a supplier revises their pricing after you've finalized, you record the new numbers on a fresh quote rather than editing the old one, which keeps the paper trail intact for the comparison.+## The supplier's link++Sending the quote emails the supplier a private link along with the request — no Carbon login needed. The supplier prices the work directly on the page: for each quantity they choose, they enter a **unit price**, a **lead time** in days, **shipping cost**, and **tax**, and can attach a note per line. When every selected line has both a price and a lead time, **"Submit Quote"** lights up; they enter their name and email and submit. They can instead **"Decline Quote"**, optionally leaving a reason.++Both flows are open only while the quote is a **"Draft"**; once submitted or declined the page is read-only, and a Draft past its expiration date shows an expired state. Each visit stamps the link's last-accessed time, so you can see whether the supplier has opened it. Whoever holds the URL can open the page — send it to the right contact and nowhere public.+## From quote to purchase orderWhen you've picked a winning quote, **"Convert to Order"** turns it into a purchase order. You choose which lines and which quantity tier to buy, and Carbon raises a purchase order for that supplier with the item lines, the supplier's contact and location, and the exchange rate all carried across from the quote. If the quote came from an RFQ, the new order is linked back to that RFQ.@@ -70,3 +76,9 @@ A supplier quote is editable only while its status is `Draft`. Any other status### Why is the Finalize or Send button disabled?Finalize/Send require the purchasing update permission and at least one line on the quote. Send is also disabled once the quote is already `Active`. Delete additionally requires the purchasing delete permission, an unlocked (Draft) quote, and an employee login.++### Why is the supplier's "Submit Quote" button disabled (on the public link)?+Submit lights up only when every selected line has both a unit price and a lead time greater than zero, and only while the quote is `Draft`. Once submitted or declined the page is read-only.++### The supplier's link shows "expired or is no longer valid"+A `Draft` supplier quote past its `expirationDate` shows the expired state and can no longer be submitted. Re-send a fresh request with a new expiration date.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/suppliers-and-customers.md b/apps/erp/app/modules/agent/kb/docs/reference/suppliers-and-customers.mdindex acf5a89f1b..1306caa0a2 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/suppliers-and-customers.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/suppliers-and-customers.md@@ -18,7 +18,7 @@ The asymmetry to remember: **supplier status is a fixed four-value set; customer## What they share-Both records carry the same satellite shape: **contacts**, **locations/addresses**, and **payment, shipping, and tax** defaults. Payment terms, currency, and tax settings live on those satellites, not on the core record. Both also have a human-readable id (`SUP…` / `CUS…`) on top of their internal key, and both can expose an external **portal**: suppliers respond to RFQs through a digital-quote link; customers track their orders through a customer portal.+Both records carry the same satellite shape: **contacts**, **locations/addresses**, and **payment, shipping, and tax** defaults. Payment terms, currency, and tax settings live on those satellites, not on the core record. Both also have a human-readable id (`SUP…` / `CUS…`) on top of their internal key, and both can expose an external **portal**: suppliers respond to RFQs through a digital-quote link; customers track their orders through a `docs/reference/customer-portal`.## Relateddiff --git a/apps/erp/app/modules/agent/kb/docs/reference/two-factor.md b/apps/erp/app/modules/agent/kb/docs/reference/two-factor.mdindex 831d9a67b6..cf24bd2d5b 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/two-factor.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/two-factor.md@@ -1,111 +1,60 @@# Two-factor authentication-> How authenticator-app codes work in Carbon, from setting one up to requiring them company-wide, and what happens when someone loses their phone.+> Add authenticator-app codes to sign-in, require them company-wide, and reset a lost device.-A password isn't the thing standing between an attacker and your production data — Carbon doesn't use one. You sign in with a magic link, an OAuth provider, or a passkey, and each of those comes down to something in your inbox or on your device. Two-factor authentication adds a second, independent proof: a six-digit code from an authenticator app on your phone, changing every thirty seconds.+Two-factor authentication adds a second proof to sign-in: a six-digit code from an authenticator app on your phone, changing every thirty seconds. You can turn it on for yourself, and an admin can require it for everyone in a company. The two are related but not the same: **the requirement belongs to a company; the authenticator belongs to you.**-You can turn it on for yourself from your own account. An admin can also require it for everyone in a company, which is the setting most organizations actually want. The two are related but not the same thing, and the difference matters: **the requirement belongs to a company, but the authenticator belongs to you**.+## Turn it on for yourself-## Turning it on for yourself+Open **Account → Security** and press **"Add Authenticator App"**.-Open **Account → Security**. It sits alongside your passkeys, because both answer the same question — how you prove it's you.+Scan the QR code with any TOTP app (Google Authenticator, 1Password, Authy), or tap the secret beneath it to copy and enter it by hand.-Press **"Add Authenticator App"**. Carbon shows a QR code and, beneath it, the same secret in text. Scan the QR with Google Authenticator, 1Password, Authy, or any TOTP app; if a camera isn't practical, tap the secret to copy it and enter it by hand. Your app immediately starts producing codes. Type the current one into the six-box field and press **"Verify"**.+Type the current code into the six-box field and press **"Verify"**. Nothing is active until the code checks out — abandoning the dialog halfway leaves nothing behind.-Nothing is active until that code checks out. Until then the factor is `unverified` and Carbon ignores it entirely, which is why abandoning the dialog halfway leaves nothing behind.+Carbon emails you a receipt the moment it's on; if one arrives that you didn't cause, remove the factor and tell an admin. To remove it yourself, press the trash icon next to the factor and enter a current code.-The moment it does check out, Carbon emails you a receipt — "Two-factor authentication is on". It isn't a notification you can turn off, because its whole purpose is to be the one signal you'd get if somebody else enrolled an authenticator against your account. If one arrives that you didn't cause, remove the factor and tell an admin.+Once verified, every sign-in asks for a code — magic link, Google, Outlook, and passkey alike. `docs/reference/single-sign-on` is the one exception: an SSO session arrives with your identity provider's MFA already enforced, so Carbon skips its own code screen.-The entry is labelled with the company you were in when you enrolled, over your email — `Carbon (Acme Manufacturing)` above `[email protected]`. That's deliberate. If you use Carbon at more than one organization, two entries both reading "Carbon" would be indistinguishable at the moment you need to tell them apart.+## Require it for everyone-The label is written into the QR when you enrol. Renaming the company later doesn't rewrite anyone's existing entry.+Open **Settings → System → Security** and turn on **Two-Factor Authentication Enforcement**. It takes effect on each person's next page load, and every active employee is emailed the announcement. Anyone without an authenticator then sees a full-screen **"Set up authenticator app"** prompt — they complete the same QR-and-code flow right there, or sign out; there is no way past it.-To remove it, press the trash icon next to the factor and enter a current code. Carbon asks for the code rather than just a confirmation click because removing your second factor is exactly the action an attacker who has your session would want to perform.+Once enforcement is on, **People → Employee accounts** shows a **Two-Factor** column reading **"Enabled"** or **"Not set up"** per person. The column only renders while the company requires two-factor.-## Signing in with a code--Once you have a verified authenticator, every sign-in asks for a code — magic link, Google, Outlook, and passkey alike. You'll land on a screen titled **"Two-factor authentication"** with a six-digit field; entering the last digit submits it.--Passkeys are challenged too, which surprises people. A passkey is strong, but in Carbon it resolves into an ordinary session like any other sign-in method, so exempting it would leave a way around the requirement. If you'd rather not be asked twice, that's an argument for using a passkey *instead of* two-factor, not alongside it.--`docs/platform/single-sign-on` is the one method that isn't challenged. An SSO session arrives with your identity provider's MFA policy already enforced at sign-in, so Carbon skips its own code screen and the company-wide requirement for those sessions — in every environment, including controlled (ITAR) deployments. Sign in with a magic link instead and the challenge applies as usual.--A code is valid for its thirty-second window plus one window either side, to absorb small drift. If codes are consistently rejected on a phone whose time is set manually, switch it to network time. It's the single most common cause of "the code is right but Carbon says no".--Repeated attempts are rate-limited on the same budget as sign-in itself, so guessing your way through isn't practical — and neither is retrying twenty times because you mistyped.--Sessions that already existed before you enrolled don't get a free pass. Carbon re-checks on each request, so a browser you left signed in on another machine is sent to the code screen the next time it's used rather than quietly staying trusted for the rest of the week.--## Requiring it for everyone--Open **Settings → System → Security** and find the **Two-Factor Authentication Enforcement** card. Turning the switch on means anyone opening that company has to have an authenticator set up. There's no grace period; it takes effect on their next page load.--Flipping the switch on also emails every active employee of the company, so nobody's first warning is a locked screen. The message names the company, links straight to **Account → Security**, and tells people who already have an authenticator that nothing changes for them.--It goes out on each off → on transition. Turning enforcement *off* sends nothing, and re-saving a setting that is already on sends nothing either. But if you disable enforcement and later switch it back on, everyone is emailed again — by that point they've been told the requirement was lifted, so they need telling that it's back.--Someone without one sees a full-screen prompt instead of the app, with a **"Set up authenticator app"** button that runs the same QR-and-code flow as the account page. They can complete it right there. The only other thing on that screen is **"Sign out"** — there is no way past it.--This is the part worth reading twice. If you belong to two companies and only one requires two-factor, you're prompted to set one up **only while you're in that company**. Switch to the other and the prompt is gone.--But once you've set one up, you're asked for a code at **every** sign-in, to either company. There's no such thing as being half-enrolled — the authenticator is attached to your account, not to a membership. Turning the requirement on in one company therefore does change how its people sign in everywhere else, which is worth saying out loud before you flip it.--Controlled environments are the exception to all of the above. When Carbon is deployed for ITAR or CMMC work, two-factor is mandatory and the switch is locked on, because NIST 800-171 requires it for network access to non-privileged accounts. Admins can see the setting but not turn it off, and the enrollment screen offers no way around it. SSO sessions remain exempt even here — the identity provider owns their MFA.--## Seeing who has set it up--Once enforcement is on, **People → Employee accounts** grows a **Two-Factor** column showing **"Enabled"** or **"Not set up"** for each person. It's blank for shop-floor PIN operators, who don't sign in at all.--The column only appears while the company requires two-factor. With the setting off it would be a wall of "Not set up" describing a policy nobody opted into.+If you belong to two companies and only one requires two-factor, you're prompted to enroll only while in that company — but once enrolled, you're asked for a code at **every** sign-in, to either company. In controlled (ITAR/CMMC) deployments two-factor is mandatory and the switch is locked on; SSO sessions stay exempt even there.## When someone loses their phone-There are no printed backup codes. Recovery is an admin action, which keeps it auditable and avoids a fallback secret that is itself worth stealing.--An admin with permission to update users opens **People → Employee accounts**, finds the person, and chooses **"Reset Two-Factor Auth"** from the row menu. That removes their authenticator; their next sign-in is an ordinary magic link, and they can enrol a fresh device.--Because the authenticator is attached to the account rather than to a membership, removing it removes it everywhere. An admin at one company can therefore clear two-factor for a user who also works at another. That's unavoidable given how the factor is stored, but worth knowing before you treat the reset as a purely local action.--It also means at least two people should hold user-management permission. If your only admin loses their phone and nobody else can reset it, there is no self-service way back in.--## What two-factor doesn't cover--Machine access is never challenged, and that's by design — there's nobody present to read a code off a phone.+There are no printed backup codes — recovery is an admin action, which keeps it auditable. An admin with permission to update users opens **People → Employee accounts** and chooses **"Reset Two-Factor Auth"** from the person's row menu. Their next sign-in is an ordinary magic link, and they enroll a fresh device.- - **API keys**: Keep working exactly as before. They carry their own scopes and rate limits; see `docs/building/api-keys`.- - **Integrations**: Anything authenticating as the company rather than as a person is unaffected.- - **Shop-floor PIN operators**: Never prompted. Operators pin in at a shared terminal rather than signing in, so there's no personal session to protect and no phone to scan with. The person who signed the terminal in is the one two-factor applies to.+The authenticator is attached to the account, not the membership, so removing it removes it everywhere. Keep user-management permission on at least two people — if your only admin loses their phone, there is no self-service way back in.-If you need to restrict what an authenticated person can reach, that's a different mechanism entirely — see `docs/reference/permissions`.+## What it doesn't cover-## Where each piece lives-- - **Account → Security**: Set up or remove your own authenticator, alongside your passkeys. See `docs/reference/account`.- - **Settings → System → Security**: The **Two-Factor Authentication Enforcement** switch for the whole company. See `docs/reference/company-settings`.- - **People → Employee accounts**: The **Two-Factor** status column and the **"Reset Two-Factor Auth"** row action. See `docs/reference/people`.+Machine access is never challenged: `docs/building/api-keys` and integrations keep working, and shop-floor PIN operators are never prompted — they pin in at a shared terminal, so two-factor applies to whoever signed the terminal in. To restrict what an authenticated person can *reach*, that's `docs/reference/permissions`.## Troubleshooting-### "That code isn't right" on a code you just read+Behavior details: a code is valid for its thirty-second window plus one window either side; repeated attempts are rate-limited on the sign-in budget. Sessions are re-checked on each request, so pre-existing sessions on other machines get the code screen on next use. The authenticator-app entry is labelled `Carbon (Company Name)` over the user's email — the company name is baked in at enrollment and doesn't update on rename. The enforcement announcement email goes out on each off → on transition only.-Almost always clock drift on the phone. Set the device to network time and try again. Failing that, confirm you're reading the entry for the right company — two Carbon entries are easy to mix up, which is why the label carries the company name.+### "That code isn't right" on a code the user just read+Almost always clock drift on the phone — set the device to network time. Failing that, confirm they're reading the entry for the right company; two Carbon entries are distinguished by the company name in the label.### Someone is stuck on the setup screen and can't get in--That's a company with enforcement on and a person without an authenticator. They complete setup on that screen and continue. If they can't (no phone to hand), the only other option on the screen is signing out.+That's a company with enforcement on and a person without an authenticator. They complete setup on that screen and continue. If they can't (no phone to hand), the only other option is signing out.### The Two-Factor column isn't in the employee list-The column only renders while the company requires two-factor. Turn the setting on in **Settings → System → Security** and it appears.### Turning enforcement on didn't prompt anyone--It applies on each person's next page load, not retroactively to sessions sitting idle. Anyone already looking at a stale tab sees it when they next navigate. The announcement email is what reaches them in the meantime.+It applies on each person's next page load, not retroactively to idle sessions. The announcement email is what reaches them in the meantime.### Nobody got the announcement email--It's sent only when the setting actually changes from off to on. If it was already on — someone else flipped it, or the deployment is a controlled environment where it's locked on — there's no transition to announce. It also goes only to **active** employees, so anyone deactivated isn't included.+It's sent only when the setting transitions from off to on, and only to active employees. If it was already on (someone else flipped it, or the deployment is a controlled environment where it's locked on), there's no transition to announce.### An admin can't turn enforcement off-The deployment is a controlled (ITAR) environment, where two-factor is mandatory and the switch is locked on.++### Passkey users are asked for a code — is that a bug?+No. A passkey resolves into an ordinary session like any other sign-in method, so exempting it would leave a way around the requirement. Only SSO sessions skip the challenge (the identity provider owns their MFA), in every environment including controlled ones.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md b/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.mdindex 7bd0c1f82b..53909d9742 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/workflow-runs.md@@ -1,6 +1,6 @@# Workflow runs-> Every firing of a workflow is recorded step by step. What the run list and run detail show, what each status means, how repeating steps are summarised, and how long history is kept.+> Every firing of a workflow, recorded step by step: the run list, run detail, statuses, repeating steps, and how long history is kept.Every time a workflow fires, Carbon records a workflow run: one row for the run and one row for each step it took, with the values that went in, the values that came out, and why it ended the way it did. Open **Automate → Runs** to see them all, or click the **"Last Run"** cell on the workflow list to jump straight to the most recent one.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/workflows.md b/apps/erp/app/modules/agent/kb/docs/reference/workflows.mdindex 1b58d1d504..753a263ca3 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/workflows.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/workflows.md@@ -1,6 +1,6 @@# Workflows-> Build an automation on a canvas — one trigger, conditions, and steps that notify people, update records, or call an outside service. Triggers, values, publishing, and versions.+> Build an automation on a canvas: one trigger, conditions, and steps that notify people, update records, or call an outside service.A workflow watches for something happening in Carbon and then does something about it: notify the account manager when a sales order changes hands, open an issue when a job is put on hold, or call your own service when a shipment is posted. You build one on a canvas under **Automate → Workflows**, wire the steps together, and press **"Publish"**.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex 8197a99974..760ef30a5f 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -1,5 +1,5 @@{- "_comment": "GENERATED by scripts/generate-agent-kb.ts from docs/content. Do not hand-edit — run `pnpm run generate:agent-kb`.",+ "_comment": "GENERATED by docs/scripts/generate-agent-kb.ts from docs/content. Do not hand-edit — run `pnpm run generate:agent-kb`.","docs": [{"slug": "docs/building/api-keys",@@ -8,19 +8,49 @@"keywords": ["api", "keys", "docs", "building"],"headings": ["Creating a key",- "How a key authenticates a request",- "Permission scoping",- "Rate limiting",+ "Authenticating a request",+ "Scopes and rate limit","What the key unlocks",- "The Carbon API",- "The Data API","Keys versus webhooks",- "Troubleshooting",+ "Internals and troubleshooting","\"API key lacks required permissions\"",+ "403 on every call despite correct scopes","\"Rate limit exceeded\"","\"API key has expired\"","\"API key not found\"",- "I lost the key / can't find where to see it again"+ "I lost the key / can't see it again"+ ]+ },+ {+ "slug": "docs/building/architecture",+ "title": "Architecture",+ "description": "One journey from a button click, through the server, into Postgres, out to background jobs, and back to the screen.",+ "keywords": ["architecture", "docs", "building"],+ "headings": [+ "Part 1: The map",+ "Part 2: Follow one click all the way down",+ "The short version",+ "The same story, with real files",+ "Part 3: Layer by layer",+ "3.1 The browser and the route file",+ "3.2 The gate: who is allowed to do what",+ "3.3 The service layer: four doors to the database",+ "3.4 The database",+ "Part 4: What happens after the write",+ "Part 5: The other engines",+ "Workflows: the customer's own automations",+ "The Assembler: the Rust service",+ "Part 6: The repo map",+ "Part 7: Where it all runs",+ "7.1 On a laptop",+ "7.2 The cloud Carbon runs",+ "7.3 On a customer's own server",+ "7.4 How a merge becomes production",+ "7.5 Knowing what is happening",+ "Part 8: There's a bug, where do I look?",+ "Part 9: House rules",+ "Glossary",+ "Related"]},{@@ -125,38 +155,6 @@"keywords": ["project", "management", "docs", "integrations"],"headings": ["Linear", "Jira", "Related"]},- {- "slug": "docs/platform/architecture",- "title": "Architecture",- "description": "One journey from a button click, through the server, into Postgres, out to background jobs, and back to the screen.",- "keywords": ["architecture", "docs", "platform"],- "headings": [- "Part 1: The map",- "Part 2: Follow one click all the way down",- "The short version",- "The same story, with real files",- "Part 3: Layer by layer",- "3.1 The browser and the route file",- "3.2 The gate: who is allowed to do what",- "3.3 The service layer: four doors to the database",- "3.4 The database",- "Part 4: What happens after the write",- "Part 5: The other engines",- "Workflows: the customer's own automations",- "The Assembler: the Rust service",- "Part 6: The repo map",- "Part 7: Where it all runs",- "7.1 On a laptop",- "7.2 The cloud Carbon runs",- "7.3 On a customer's own server",- "7.4 How a merge becomes production",- "7.5 Knowing what is happening",- "Part 8: There's a bug, where do I look?",- "Part 9: House rules",- "Glossary",- "Related"- ]- },{"slug": "docs/platform/backups","title": "Backups",@@ -279,33 +277,17 @@],"headings": ["Recipes"]},- {- "slug": "docs/platform/single-sign-on",- "title": "Single sign-on",- "description": "Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.",- "keywords": ["single", "sign-on", "docs", "platform", "sign"],- "headings": [- "Requirements",- "Connect your identity provider",- "Verifying a domain",- "How sign-in works",- "Existing accounts",- "Requiring SSO",- "Two-factor authentication"- ]- },{"slug": "docs/reference/account","title": "Your account",- "description": "Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language, kept separate from the company-wide settings an admin controls.",+ "description": "Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language — separate from company-wide settings.","keywords": ["your", "account", "docs", "reference"],"headings": ["Profile",- "Signing in — passkeys and two-factor",+ "Signing in","Notification preferences",- "Theme and language",- "Personal attributes",- "Troubleshooting",+ "Theme, language, and attributes",+ "Internals and troubleshooting","Can't change your email from the Account screen","There's no password to change","The passkey card isn't showing",@@ -458,7 +440,7 @@{"slug": "docs/reference/change-orders/lifecycle","title": "Lifecycle & release",- "description": "The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and exactly what release does when a change notice reaches Done.",+ "description": "The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and what release does at Done.","keywords": ["lifecycle","release",@@ -486,7 +468,7 @@{"slug": "docs/reference/change-orders/setup","title": "Categories & actions",- "description": "The two company-scoped lookups that sit alongside change notices — the category list and the reusable action-task templates — plus linking an action task to Linear.",+ "description": "The company-scoped lookups beside change notices: the category list and reusable action-task templates, plus linking a task to Linear.","keywords": ["categories","actions",@@ -529,20 +511,17 @@"keywords": ["company", "settings", "docs", "reference"],"headings": ["The company record",- "Multiple companies","Feature toggles and defaults","Base currency",- "Theme",- "Logos",- "Tags",+ "Theme and tags","Related system configuration",- "Troubleshooting",+ "Internals and troubleshooting","I can't find the Companies or Backups settings page","I can't see the Billing settings page",- "Nothing posts to the general ledger even though jobs and invoices complete",+ "Nothing posts to the ledger though jobs and invoices complete","My theme changed but a colleague still sees the old one","I can't change the base currency",- "A settings page (Modules) exists but the toggle does nothing I expect"+ "A Modules toggle does nothing I expect"]},{@@ -569,20 +548,30 @@"description": "Company-defined extra fields that attach to core records like customers, parts, and orders.","keywords": ["custom", "fields", "docs", "reference"],"headings": [- "How a custom field is defined",- "Data types",+ "Defining a field","Which entities support custom fields",- "How fields save on a form",- "CSV import and export",- "API access",- "Troubleshooting",- "\"Required\" (on a custom field that won't submit)",+ "How values save, and where they reach",+ "Internals and troubleshooting",+ "\"Required\" on a custom field that won't submit","List custom field rejected on save",- "The Data Type dropdown is disabled when editing a field",- "A custom field's values aren't in my CSV import or export",+ "The Data Type dropdown is disabled when editing",+ "Custom-field values missing from CSV import/export","The entity I want has no Custom Fields row"]},+ {+ "slug": "docs/reference/customer-portal",+ "title": "Customer portal",+ "description": "A standing, read-only link where a customer watches their open orders and shop-floor progress, no Carbon account needed.",+ "keywords": ["customer", "portal", "docs", "reference"],+ "headings": [+ "Creating a portal",+ "Related",+ "Troubleshooting",+ "Why does the customer portal link show \"Not found\" / a 404?",+ "Why did downloads from the portal start failing (HTTP 429)?"+ ]+ },{"slug": "docs/reference/dimensions","title": "Dimensions & cost centers",@@ -850,7 +839,8 @@"\"Split quantity (…) must be less than the current quantity (…)\"","\"Disposition changed while closing; please retry.\"","MRB review is holding the issue open",- "Permission-gated: you can't create, edit, close, or delete an issue"+ "Permission-gated: you can't create, edit, close, or delete an issue",+ "\"Issue has been closed already. Unable to make changes\" (SCAR)"]},{@@ -991,16 +981,15 @@"keywords": ["notifications", "docs", "reference"],"headings": ["What raises a notification",- "Topics",- "Channels",- "Per-user preferences",+ "Topics and channels",+ "Muting a topic","Who receives an expiration or reminder","The inbox","Related",- "Troubleshooting",+ "Internals and troubleshooting","Why am I not getting email notifications?","Why am I not getting Slack DMs?",- "I muted a topic but I'm still getting in-app notifications",+ "I muted a topic but still get in-app notifications","I turned a channel on but it still doesn't deliver","I did something myself and got no notification","A recurring reminder stopped arriving"@@ -1009,23 +998,14 @@{"slug": "docs/reference/onboarding","title": "Getting started",- "description": "The first-run setup wizard that creates your company, and the Implementation Hub that guides a new company from an empty tenant to live on Carbon.",+ "description": "The first-run setup wizard that creates your company, seeds its baseline configuration, and hands you a working tenant.","keywords": ["getting", "started", "docs", "reference", "onboarding"],"headings": [- "The setup wizard",- "What you don't choose during onboarding",- "The Implementation Hub",- "The six phases",- "Tiers change what you see",- "The Setup Map","Where to go next",- "Troubleshooting",+ "Internals and troubleshooting","Stuck in the setup wizard / keeps redirecting to /onboarding","The Industry step isn't showing",- "The Plan step isn't showing",- "Can't enroll in the Implementation Hub",- "The Accounting group is missing from the Setup Map",- "Some Hub phases are missing (Discovery, Migrate data, Acceptance)"+ "The Plan step isn't showing"]},{@@ -1292,7 +1272,9 @@"Troubleshooting","\"Cannot modify a locked quote. Reopen it first.\"","\"An item cannot be added to itself.\"",- "\"Failed to convert quote to order\""+ "\"Failed to convert quote to order\"",+ "\"This quote is no longer available for a response.\" (digital quote)",+ "\"Oops! The link you're trying to access has expired or is no longer valid.\" (digital quote)"]},{@@ -1409,12 +1391,10 @@"description": "The per-company generator behind every readable document number — jobs, change notices, payments, and more.","keywords": ["numbering", "sequences", "docs", "reference"],"headings": [- "What a sequence is","Fields","Date tokens",- "Which documents use a sequence",- "How a number gets assigned",- "Troubleshooting",+ "Seed defaults",+ "Internals and troubleshooting","A sequence field won't save (Current, Step, or Size)","My `%{hh}` or `%{ss}` token shows up literally in the number","Editing a sequence didn't renumber existing documents",@@ -1423,30 +1403,10 @@},{"slug": "docs/reference/sharing",- "title": "External sharing and portals",- "description": "Private, login-free links that let a customer accept a quote, a supplier price an RFQ or answer a SCAR, and a buyer watch order status, all without a Carbon account.",- "keywords": [- "external",- "sharing",- "and",- "portals",- "docs",- "reference"- ],- "headings": [- "What can be shared",- "Digital quotes",- "Supplier quotes",- "Customer portal",- "Supplier corrective action requests",- "Troubleshooting",- "\"This quote is no longer available for a response.\"",- "\"Oops! The link you're trying to access has expired or is no longer valid.\" (Quote expired)",- "\"Issue has been closed already. Unable to make changes\"",- "Why does the customer portal link show \"Not found\" / a 404?",- "Why is the supplier's \"Submit Quote\" button disabled?",- "Why did downloads from the customer portal start failing (HTTP 429)?"- ]+ "title": "External sharing",+ "description": "How Carbon's private, login-free links work — a customer accepts a quote, a supplier prices a request or answers a SCAR, a buyer watches order status.",+ "keywords": ["external", "sharing", "docs", "reference"],+ "headings": []},{"slug": "docs/reference/shelf-life",@@ -1488,6 +1448,27 @@"\"Failed to post shipment\""]},+ {+ "slug": "docs/reference/single-sign-on",+ "title": "Single sign-on",+ "description": "Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.",+ "keywords": ["single", "sign-on", "docs", "reference", "sign"],+ "headings": [+ "Requirements",+ "Connect your identity provider",+ "Verifying a domain",+ "How sign-in works",+ "Requiring SSO",+ "Behavior details and exact messages",+ "Verification fails",+ "\"Verify\" fails on a domain another company verified",+ "\"SSO sign-in rejected: this email domain is not registered for your company's SSO connection.\"",+ "\"SSO sign-in succeeded but no invite exists for `[email protected]`. Contact your administrator.\"",+ "\"Complete your first SSO sign-in in Carbon ERP, then return here.\" (MES)",+ "\"Your organization requires single sign-on. Sign in with your work email to continue.\"",+ "\"Deactivate Single Sign-On\" confirmation"+ ]+ },{"slug": "docs/reference/storage-rules","title": "Storage rules",@@ -1514,6 +1495,7 @@"Where a quote comes from","Lines and pricing","Lifecycle",+ "The supplier's link","From quote to purchase order","Troubleshooting","\"Expiration date must be today or after\"",@@ -1521,7 +1503,9 @@"\"Cannot convert to order: supplier is not approved (Active)\"","\"Failed to convert quote to order\"","Why is the quote read-only / why can't I edit lines?",- "Why is the Finalize or Send button disabled?"+ "Why is the Finalize or Send button disabled?",+ "Why is the supplier's \"Submit Quote\" button disabled (on the public link)?",+ "The supplier's link shows \"expired or is no longer valid\""]},{@@ -1576,7 +1560,7 @@{"slug": "docs/reference/two-factor","title": "Two-factor authentication",- "description": "How authenticator-app codes work in Carbon, from setting one up to requiring them company-wide, and what happens when someone loses their phone.",+ "description": "Add authenticator-app codes to sign-in, require them company-wide, and reset a lost device.","keywords": ["two-factor","authentication",@@ -1586,20 +1570,18 @@"factor"],"headings": [- "Turning it on for yourself",- "Signing in with a code",- "Requiring it for everyone",- "Seeing who has set it up",+ "Turn it on for yourself",+ "Require it for everyone","When someone loses their phone",- "What two-factor doesn't cover",- "Where each piece lives",+ "What it doesn't cover","Troubleshooting",- "\"That code isn't right\" on a code you just read",+ "\"That code isn't right\" on a code the user just read","Someone is stuck on the setup screen and can't get in","The Two-Factor column isn't in the employee list","Turning enforcement on didn't prompt anyone","Nobody got the announcement email",- "An admin can't turn enforcement off"+ "An admin can't turn enforcement off",+ "Passkey users are asked for a code — is that a bug?"]},{@@ -1618,7 +1600,7 @@{"slug": "docs/reference/workflow-runs","title": "Workflow runs",- "description": "Every firing of a workflow is recorded step by step. What the run list and run detail show, what each status means, how repeating steps are summarised, and how long history is kept.",+ "description": "Every firing of a workflow, recorded step by step: the run list, run detail, statuses, repeating steps, and how long history is kept.","keywords": ["workflow", "runs", "docs", "reference"],"headings": ["The run list",@@ -1632,7 +1614,7 @@{"slug": "docs/reference/workflows","title": "Workflows",- "description": "Build an automation on a canvas — one trigger, conditions, and steps that notify people, update records, or call an outside service. Triggers, values, publishing, and versions.",+ "description": "Build an automation on a canvas: one trigger, conditions, and steps that notify people, update records, or call an outside service.","keywords": ["workflows", "docs", "reference"],"headings": ["What starts a workflow",diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeStatus.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeStatus.tsxindex 0c3875c87e..d8accdd50e 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeStatus.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeStatus.tsx@@ -1,20 +1,7 @@import { Status } from "@carbon/react";+import { CHANGE_ORDER_STATUS_COLOR_MAP } from "@carbon/utils";import type { ChangeNoticeStatus as ChangeNoticeStatusType } from "../../types";-// Stage → badge color. Done is success (green); the open stages step through-// gray → blue → yellow → orange as work progresses; Cancelled is red.-const CHANGE_ORDER_STATUS_COLOR_MAP: Record<- string,- "green" | "orange" | "red" | "yellow" | "blue" | "gray" | "purple"-> = {- Draft: "gray",- Start: "blue",- "Engineering Complete": "yellow",- Implementation: "orange",- Done: "green",- Cancelled: "red"-};-type ChangeNoticeStatusProps = {status?: ChangeNoticeStatusType | null;};diff --git a/docs/app/docs/layout.tsx b/docs/app/docs/layout.tsxindex 9c0776912a..7ae7991e44 100644--- a/docs/app/docs/layout.tsx+++ b/docs/app/docs/layout.tsx@@ -19,11 +19,10 @@ type TreeNode = {const label = (name: unknown) =>typeof name === "string" ? name : String(name ?? "");-const byLabel = (a: DocsNavNode, b: DocsNavNode) =>- a.label.localeCompare(b.label);--/** Convert the Fumadocs page tree into our serializable nav shape, with the pages in- * each group sorted alphabetically. */+/** Convert the Fumadocs page tree into our serializable nav shape. Order is the page+ * tree's own order — i.e. each folder's meta.json `pages` array — so every section+ * can be curated there. (An earlier version alphabetized folder children, which made+ * meta.json ordering dead weight.) */function toNav(nodes: TreeNode[]): DocsNavNode[] {return nodes.flatMap((n) => {if (n.type === "separator") return [];@@ -32,7 +31,7 @@ function toNav(nodes: TreeNode[]): DocsNavNode[] {{label: label(n.name),url: n.index?.url,- children: toNav(n.children ?? []).sort(byLabel),+ children: toNav(n.children ?? []),},];}@@ -45,35 +44,61 @@ function toNav(nodes: TreeNode[]): DocsNavNode[] {// URLs (/docs/reference/<slug>) never move. Any reference page missing from this map is// appended ungrouped, so adding a new entity can never make it vanish from the nav.const REFERENCE_GROUPS: { label: string; slugs: string[] }[] = [+ { label: "Getting started", slugs: ["onboarding"] },+ {+ label: "Sales",+ slugs: ["quotes", "pricing", "sales-orders", "customer-portal"],+ },{- label: "Items & methods",+ label: "Items & engineering",slugs: ["items",+ "materials","methods",+ "routings","configurator",- "materials","change-orders",- "routings",],},+ { label: "Planning", slugs: ["planning", "forecast", "reordering"] },+ {+ label: "Purchasing",+ slugs: ["purchase-orders", "supplier-quotes", "suppliers-and-customers"],+ },{label: "Production",slugs: ["jobs","scheduling","kanban",- "mes","work-centers","maintenance",+ "mes",],},- { label: "Planning", slugs: ["planning", "forecast", "reordering"] },- { label: "Sales", slugs: ["quotes", "pricing", "sales-orders"] },{- label: "Purchasing",- slugs: ["purchase-orders", "supplier-quotes", "suppliers-and-customers"],+ label: "Inventory",+ slugs: [+ "inventory",+ "inventory-count",+ "storage-rules",+ "shelf-life",+ "scrap",+ "traceability",+ ],+ },+ { label: "Fulfillment", slugs: ["picking", "shipments", "receipts"] },+ {+ label: "Quality",+ slugs: [+ "quality",+ "inspections",+ "issues",+ "calibration",+ "quality-documents",+ "risks",+ ],},- { label: "Fulfillment", slugs: ["shipments", "picking", "receipts"] },{ label: "Invoicing & payments", slugs: ["invoices", "payments"] },{label: "Accounting",@@ -87,48 +112,34 @@ const REFERENCE_GROUPS: { label: string; slugs: string[] }[] = [],},{- label: "Quality",+ label: "People & access",slugs: [- "quality",- "issues",- "inspections",- "calibration",- "quality-documents",- "risks",+ "people",+ "training",+ "permissions",+ "two-factor",+ "single-sign-on",+ "account",],},{- label: "Inventory",- slugs: [- "inventory",- "inventory-count",- "scrap",- "storage-rules",- "shelf-life",- "traceability",- ],+ label: "Automation & alerts",+ slugs: ["workflows", "workflow-runs", "approvals", "notifications"],},{- label: "Configurations",+ label: "Administration",slugs: ["company-settings",- "printing",- "custom-fields",- "audit-log","sequences",- "import-export",+ "custom-fields","documents",- "api-keys",+ "printing",+ "import-export",+ "audit-log",+ "sharing",+ "agent",],},- {- label: "People & access",- slugs: ["people", "training", "permissions", "account"],- },- {- label: "System",- slugs: ["onboarding", "sharing", "agent", "approvals", "notifications"],- },];const slugOf = (url?: string) => url?.split("/").filter(Boolean).pop() ?? "";diff --git a/docs/app/llms-full.txt/route.ts b/docs/app/llms-full.txt/route.tsnew file mode 100644index 0000000000..6a88168496--- /dev/null+++ b/docs/app/llms-full.txt/route.ts@@ -0,0 +1,27 @@+import path from "node:path";+import { readCorpus } from "@/lib/markdown-corpus";+import { SITE } from "@/lib/seo";++/* /llms-full.txt — every docs page as component-stripped markdown in one file, for+ * AI assistants that want the whole corpus rather than the /llms.txt index. Shares+ * its stripper with the in-app agent's KB (docs/lib/markdown-corpus.ts), so the two+ * corpora can never disagree. Built once at build time. */++export const dynamic = "force-static";++export function GET() {+ const pages = readCorpus(path.join(process.cwd(), "content"));++ const body = pages+ .map(+ (p) =>+ `# ${p.title}\n\nURL: ${SITE.url}/${p.slug.replace(/\/index$/, "")}\n\n${+ p.description ? `> ${p.description}\n\n` : ""+ }${p.markdown}`+ )+ .join("\n\n---\n\n");++ return new Response(`${body}\n`, {+ headers: { "Content-Type": "text/plain; charset=utf-8" },+ });+}diff --git a/docs/app/llms.txt/route.ts b/docs/app/llms.txt/route.tsnew file mode 100644index 0000000000..23bff46f67--- /dev/null+++ b/docs/app/llms.txt/route.ts@@ -0,0 +1,49 @@+import path from "node:path";+import { readCorpus } from "@/lib/markdown-corpus";+import { SITE } from "@/lib/seo";++/* /llms.txt — the llmstxt.org index for AI crawlers and assistants: every page as+ * title + canonical URL + one-line description, grouped by section in sidebar order.+ * The full stripped content lives at /llms-full.txt. Built once at build time. */++export const dynamic = "force-static";++const SECTIONS: { label: string; prefix: string }[] = [+ { label: "Guides", prefix: "guides/" },+ { label: "Product reference", prefix: "docs/reference/" },+ { label: "Building on Carbon", prefix: "docs/building/" },+ { label: "Integrations", prefix: "docs/integrations/" },+ { label: "Platform", prefix: "docs/platform/" },+ { label: "Overview", prefix: "docs/" },+];++export function GET() {+ const pages = readCorpus(path.join(process.cwd(), "content"));++ const line = (p: (typeof pages)[number]) =>+ `- [${p.title}](${SITE.url}/${p.slug.replace(/\/index$/, "")})${+ p.description ? `: ${p.description}` : ""+ }`;++ const used = new Set<string>();+ const sections = SECTIONS.map(({ label, prefix }) => {+ const members = pages.filter(+ (p) => !used.has(p.slug) && (p.slug + "/").startsWith(prefix)+ );+ for (const m of members) used.add(m.slug);+ return members.length+ ? `## ${label}\n\n${members.map(line).join("\n")}`+ : null;+ }).filter(Boolean);++ const body = [+ "# Carbon Docs",+ "> Documentation for Carbon, a manufacturing ERP + MES: editorial guides that tour the flows, a product reference per entity, and platform/self-hosting docs. The full page contents in plain markdown are at " ++ `${SITE.url}/llms-full.txt; the REST API reference is at ${SITE.url}/api.`,+ ...sections,+ ].join("\n\n");++ return new Response(`${body}\n`, {+ headers: { "Content-Type": "text/plain; charset=utf-8" },+ });+}diff --git a/docs/app/reference.css b/docs/app/reference.cssindex 292e056e27..94ccab670d 100644--- a/docs/app/reference.css+++ b/docs/app/reference.css@@ -82,18 +82,21 @@border: 1px solid rgba(38, 35, 35, 0.08);border-radius: 5px;padding: 0.08em 0.36em;- white-space: nowrap;+ /* pre-wrap + break-word: a chip only wraps when the line runs out, and a single+ * identifier never splits mid-word unless it alone exceeds the line — nowrap here+ * made any over-long chip (a full SQL statement, a deep module path) overflow its+ * container on desktop instead of wrapping. */+ white-space: pre-wrap;+ overflow-wrap: break-word;}.prose :not(pre) > code::before,.prose :not(pre) > code::after {content: none !important;}-/* …but nowrap on a phone means one long inline path (a full `apps/erp/app/modules/…`- * reference) widens the whole document and every section scrolls sideways with it.- * Below the tablet breakpoint, let those chips wrap; desktop keeps identifiers intact. */+/* On a phone even a single long token must be able to break anywhere, or it widens+ * the whole document and every section scrolls sideways with it. */@media (max-width: 640px) {.prose :not(pre) > code {- white-space: pre-wrap;overflow-wrap: anywhere;}}diff --git a/docs/app/sitemap.ts b/docs/app/sitemap.tsindex 7f702c74a0..222c19e12e 100644--- a/docs/app/sitemap.ts+++ b/docs/app/sitemap.ts@@ -5,7 +5,7 @@ import { guideSource, source } from "@/lib/source";import { allToolParams } from "@/lib/tools-data";/** Every canonical, indexable URL on the docs site. `/` is intentionally omitted —- * it rewrites to /guides/order, which is listed as its own canonical entry. */+ * it rewrites to /docs, which is listed as its own canonical entry. */export default function sitemap(): MetadataRoute.Sitemap {const abs = (path: string) => `${SITE.url}${path}`;const out: MetadataRoute.Sitemap = [];diff --git a/docs/components/editorial/architecture-diagrams.tsx b/docs/components/editorial/architecture-diagrams.tsxindex b771e4028c..5663c0a3a9 100644--- a/docs/components/editorial/architecture-diagrams.tsx+++ b/docs/components/editorial/architecture-diagrams.tsx@@ -1,4 +1,4 @@-/* Hand-laid architecture diagrams for /docs/platform/architecture. See `architecture-kit.tsx`+/* Hand-laid architecture diagrams for /docs/building/architecture. See `architecture-kit.tsx`* for the shape vocabulary and why these are drawn by hand rather than generated.** Editing one means moving coordinates. That is the trade: an auto-layout engine isdiff --git a/docs/content/docs/building/api-keys.mdx b/docs/content/docs/building/api-keys.mdxindex 4ea7ef9ef1..34526388d6 100644--- a/docs/content/docs/building/api-keys.mdx+++ b/docs/content/docs/building/api-keys.mdx@@ -3,25 +3,25 @@ title: API keysdescription: A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions.----An <Term id="api-key">API key</Term> is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more.+An <Term id="api-key">API key</Term> is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their session's permissions, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more. Manage keys under **Settings → API Keys**.-Create and manage keys under **Settings → API Keys**. Every key you see is listed by **Name**, a masked **Key** preview (only the last five characters, e.g. `crbn_•••abcde`), its **Scopes**, **Rate Limit**, who created it, and when it expires.+<Callout type="tip" title="Connectors don't need a key">+Claude.ai, Claude Desktop, and ChatGPT connect over **OAuth**: add the server URL, approve in the browser, and the connection inherits the role and company of whoever authorized it. A key is for everything that can't do that browser dance: Claude Code, Cursor, VS Code, Codex, headless scripts, and CI (stdio-only clients bridge through `mcp-remote`). The [authentication reference](/api/authentication) covers both flows.+</Callout>## Creating a key-Click **New API Key** and give it a **Name** (unique within your company). Optionally set **Expires At** — a future date after which the key stops working; leave it blank and the key never expires. Then grant scopes with the permission matrix (covered below) and save.+<Screenshot label="Settings → API Keys: the key list with masked previews, scopes, and rate limit, plus the one-time 'You can only see this key once' dialog" caption="The full key is shown exactly once at creation." />-Carbon shows the full key exactly once, in a dialog headed "You can only see this key once. Store it safely." Copy it right then. Carbon never stores the raw key: it keeps only a SHA-256 hash for lookup and the five-character preview for display. There is no way to reveal a key again later, so if you lose it, delete the key and create a new one.+Click **New API Key**, give it a **Name** (unique within your company), optionally set **Expires At** (blank means never), grant scopes in the permission matrix, and save. Carbon shows the full key exactly once, in a dialog headed "You can only see this key once. Store it safely." — copy it right then. Only a SHA-256 hash and a five-character preview are kept, so a lost key means delete and recreate. The same dialog hands you a ready-to-paste MCP command that wires the key into an AI assistant.<Callout type="warn" title="The key is a bearer secret">-Anyone holding the key can act as it, within its scopes. Treat it like a password: store it in a secret manager, never commit it to source control, and rotate it (delete and recreate) if it leaks.+Anyone holding the key can act as it, within its scopes. Store it in a secret manager, never commit it, and rotate (delete and recreate) if it leaks.</Callout>-The full format is `crbn_` followed by a random token. The same dialog also hands you a ready-to-paste MCP command that wires the key into an AI assistant — see [The MCP endpoint](#the-mcp-endpoint) below.--## How a key authenticates a request+## Authenticating a request-Send the key as a bearer token on every request. The hosted Data API lives at `rest.carbon.ms`:+Send the key as a bearer token; the hosted Data API lives at `rest.carbon.ms`:```httpGET /salesOrder?select=id,salesOrderId,status@@ -29,66 +29,31 @@ Host: rest.carbon.msAuthorization: Bearer crbn_your_key_here```-Carbon hashes the incoming key, looks up the matching record, and checks two things before it lets the request through:--- **Expiry.** If the key has an `expiresAt` in the past, the request is rejected.-- **Rate limit.** The request is counted against the key's window; if the window is full, the request is rejected.--There is no separate login step and no token to refresh. The header is the whole handshake.+There is no login step and no token to refresh. Carbon hashes the incoming key, looks it up, and checks expiry and the rate limit before letting the request through.<Callout type="note" title="Bearer at the edge, carbon-key underneath">-`rest.carbon.ms` takes the key as `Authorization: Bearer crbn_…` and forwards it internally as the `carbon-key` header that the database reads. If you run Carbon yourself and call PostgREST directly, send `carbon-key: crbn_…` against `/rest/v1/<table>` instead. The MCP endpoint that fronts the Carbon API takes the same `Bearer` token either way.+`rest.carbon.ms` takes `Authorization: Bearer crbn_…` and forwards it internally as the `carbon-key` header. Calling PostgREST directly on a self-hosted install, send `carbon-key: crbn_…` against `/rest/v1/<table>` instead. The MCP endpoint takes the same Bearer token either way.</Callout>-## Permission scoping--A key does **not** inherit the permissions of the person who created it. It acts with exactly the scopes stored on the key, and only for the company it belongs to. A brand-new key with no scopes granted can authenticate but can read and write nothing.--You grant scopes in the permission matrix when you create or edit the key. Each cell is a `module_action` pair — the same shape Carbon uses for a user's permissions. So a key scoped to view sales and create inventory can read `salesOrder` rows and insert inventory records, but a call that needs, say, `purchasing_update` is refused with "API key lacks required permissions" unless you granted that exact scope.--<FieldTable>- <Field name="Scopes" type="module_action[]">The set of permissions the key carries, e.g. `sales_view`, `inventory_create`. Empty means no access. Edit them anytime from the key's form.</Field>- <Field name="Company">A key is bound to the single company it was created under. It can never reach another company's data, even one you also belong to.</Field>-</FieldTable>--Because scopes are checked on every request against the key's own record, tightening a key's scopes (or deleting the key) takes effect immediately — there is no cached session to wait out.--## Rate limiting+## Scopes and rate limit-Every key allows **60 requests per minute**. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.+A key does **not** inherit its creator's permissions: it acts with exactly the `module_action` scopes stored on it (`sales_view`, `inventory_create`, …), and only within its company. A key with no scopes can authenticate but read and write nothing. Scopes are checked on every request against the key's own record, so tightening them, or deleting the key, takes effect immediately. On Carbon Cloud, API access is a **Business-tier feature**: a company on the Starter plan gets `403` on every call regardless of the key's scopes; see [licensing](/docs/platform/licensing).-The limit is platform-controlled, not something you set: the key's form has no rate-limit field, and `insertApiKey`/`updateApiKey` strip the columns from whatever is submitted (`apps/erp/app/modules/settings/settings.service.ts:1282`). The **Rate Limit** column in the key list reports the limit in force; it is not an input.--The limit is counted per key, not per company, so one integration burning its allowance does not throttle another.--A rejected request comes back `429` with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `Retry-After` (`packages/auth/src/services/auth.server.ts:255`). Read `Retry-After` and wait it out rather than hammering through the rejection.+Every key allows **60 requests per minute**, counted per key, so one integration burning its allowance doesn't throttle another. The limit is platform-controlled: the form has no rate-limit field, and the list's **Rate Limit** column is a report, not an input. A rejected request comes back `429` with `Retry-After` and `X-RateLimit-*` headers; wait it out rather than hammering through.## What the key unlocks-One key unlocks two surfaces. Reach for the Carbon API first; drop to the Data API only when you need raw table access.--### The Carbon API--The [Carbon API](/api) is Carbon's service layer — the safe way to read and write, running the same validation, recalculation, and permission checks the app itself uses. Reach it over plain HTTP at `POST /api/v1/{module}/{operation}` — the key goes in an `Authorization: Bearer` header, and the full operation catalogue is described by [`/api/v1/openapi.json`](/api). The same surface is also exposed over MCP: the creation dialog hands you a ready-to-paste command that registers the key with an AI assistant, which then operates strictly within the key's scopes. See [Connect over MCP](/api/mcp).--### The Data API+One key unlocks two surfaces. Reach for the **[Carbon API](/api)** first: the service layer, the same code the app runs when you click a button, with every call validating its input, recalculating what depends on it, and enforcing your permissions. Every operation is reachable two ways with the same arguments, plain HTTP at `POST /api/v1/{module}/{operation}` or a tool over [MCP](/api/mcp), and each carries a `READ` / `WRITE` / `DESTRUCTIVE` classification so a client can filter or gate by risk. Each operation has its own reference page with copyable samples in six languages, and the published OpenAPI spec means a typed client in your language is one generator command away — see [Client SDKs](/api/sdks).-The same key also unlocks the [Data API](/api/data) — direct REST access to every table and view, hosted at `rest.carbon.ms` (the full endpoint catalogue is generated in the [reference](/api/data)). The same row-level security that governs the app governs these calls: the key is scoped to its company and permissions by the database itself, not just the application layer, so it can only ever touch data its scopes allow.+The **[Data API](/api/data)** is direct REST access to every table and view, governed by the same row-level security as the app.-<Callout type="warn" title="You are outside the service layer">-The Data API writes straight to tables, so Carbon does not recalculate the derived values — totals, statuses, ledger entries — that it maintains when you write through the Carbon API. It's the escape hatch: reach for the Carbon API first, and use the Data API when it doesn't cover what you need and you know exactly what the table touches.+<Callout type="warn" title="The Data API is outside the service layer">+It writes straight to tables, so Carbon does not recalculate the derived values (totals, statuses, ledger entries) it maintains when you write through the Carbon API. Use it when the Carbon API doesn't cover what you need and you know exactly what the table touches.</Callout>-The full endpoint catalogue, with request and response shapes per resource, lives in the generated [Data API reference](/api/data).-## Keys versus webhooks-API keys and [webhooks](/docs/building/webhooks) are two halves of an integration, pulling in opposite directions:--- An **API key** lets *you* call *Carbon* — poll for data, create records, run reports on demand.-- A **webhook** lets *Carbon* call *you* — an HTTP callback the moment a subscribed record changes.--They are independent: a webhook is not authenticated with an API key (Carbon does not sign webhook payloads at all), and an API key does not subscribe to anything. The common pattern is to use both together: let a webhook tell you *that* a record changed, then use your API key to fetch the full, current record from the REST API.+An **API key** lets *you* call *Carbon*; a **[webhook](/docs/building/webhooks)** lets *Carbon* call *you* when a subscribed record changes. They're independent — webhook payloads aren't signed with a key — and the common pattern is both together: the webhook tells you *that* a record changed, your key fetches the full, current record.<Cards><Card title="Webhooks" href="/docs/building/webhooks">@@ -100,22 +65,25 @@ They are independent: a webhook is not authenticated with an API key (Carbon doe</Cards><AgentContext>-## Troubleshooting+## Internals and troubleshooting-The exact rejections an API key can return, and the one-time-secret gotcha.+Key format is `crbn_` + random token; storage is SHA-256 hash + last-five preview. `insertApiKey`/`updateApiKey` strip rate-limit columns from any submission (`settings.service.ts:1282`). The 429 response headers come from `packages/auth/src/services/auth.server.ts:255`.### "API key lacks required permissions"-The call needs a `module_action` scope the key doesn't carry. Scopes are checked per request against the key's own record (`packages/database/supabase/functions/lib/supabase.ts:315`), not the creator's permissions — a key with no scopes can authenticate but read and write nothing. Add the exact `module_action` (e.g. `purchasing_update`) to the key in the permission matrix under **Settings → API Keys**. It takes effect immediately, no session to wait out.+The call needs a `module_action` scope the key doesn't carry — checked per request against the key's record (`functions/lib/supabase.ts:315`), never the creator's permissions. Add the exact scope in the permission matrix; it applies immediately.++### 403 on every call despite correct scopes+On Carbon Cloud, API access is Business-tier: the key path blocks Starter-plan companies outright (`packages/auth/src/services/auth.server.ts:312-330`). Upgrade the plan; the key itself is fine. A 403 on a single operation is the scope problem above instead. Connectors (OAuth) hit the same plan gate through the identity they inherit.### "Rate limit exceeded"-The key exceeded its allowance for the current window (`supabase.ts:304`). Every key allows 60 requests per minute, and the limit is platform-controlled — there is no field to raise it, and the API-key service strips the columns from any submitted value. The `429` carries `Retry-After` and `X-RateLimit-*` headers; wait out `Retry-After` rather than retrying immediately. If 60/minute is genuinely too tight for your integration, batch your reads (PostgREST `in.(...)` filters and embedded relations fetch in one call) or talk to us.+Over the key's 60/minute window (`supabase.ts:304`). Platform-controlled, no field to raise it. Honor `Retry-After`; if the ceiling is genuinely too tight, batch reads (PostgREST `in.(...)` filters, embedded relations) or talk to us.### "API key has expired"-The key's `expiresAt` is in the past, so it's rejected before any work (`supabase.ts:293`). Create a new key (optionally with a later **Expires At**, or leave it blank to never expire) and swap it in — expiry can't be extended on a used key.+`expiresAt` is in the past (`supabase.ts:293`). Expiry can't be extended on a used key — create a new one and swap it in.### "API key not found"-The `carbon-key` (or Bearer token) didn't hash to a key for this company (`supabase.ts:287`). Usually a mistyped/truncated key, a key from a different company, or one that was deleted. Carbon stores only a SHA-256 hash and the five-character preview, so verify the full key value.+The token didn't hash to a key for this company (`supabase.ts:287`): mistyped/truncated, a different company's key, or a deleted one. Verify the full value.-### I lost the key / can't find where to see it again-There's no way to reveal a key after creation. Carbon shows the full key exactly once, in the "You can only see this key once. Store it safely." dialog, and keeps only a hash afterward. If you lost it, delete the key and create a new one.+### I lost the key / can't see it again+Not possible by design — the full key is shown once at creation and only a hash is kept. Delete and recreate.</AgentContext>diff --git a/docs/content/docs/platform/architecture.mdx b/docs/content/docs/building/architecture.mdxsimilarity index 99%rename from docs/content/docs/platform/architecture.mdxrename to docs/content/docs/building/architecture.mdxindex b4123764e3..9ffa09284f 100644--- a/docs/content/docs/platform/architecture.mdx+++ b/docs/content/docs/building/architecture.mdx@@ -674,7 +674,7 @@ refuses to start without it.| `logger` | Structured logging, with request-id correlation. || `notifications` | The notification event taxonomy (enums only). || `printing` | Printer registry, label queue, physical print delivery. |-| `onboarding` | New-company setup, the "Implementation Hub". |+| `onboarding` | New-company setup content. || `kv` | Redis client plus rate limiting. || `stripe` | Billing. Cloud edition only. || `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |diff --git a/docs/content/docs/building/meta.json b/docs/content/docs/building/meta.jsonindex 3c2795090f..7566f21c0f 100644--- a/docs/content/docs/building/meta.json+++ b/docs/content/docs/building/meta.json@@ -1,5 +1,5 @@{"title": "Building on Carbon","defaultOpen": true,- "pages": ["api-keys", "webhooks", "local-development"]+ "pages": ["api-keys", "webhooks", "local-development", "architecture"]}diff --git a/docs/content/docs/index.mdx b/docs/content/docs/index.mdxindex c89dd0e9c7..56887f2bd3 100644--- a/docs/content/docs/index.mdx+++ b/docs/content/docs/index.mdx@@ -13,7 +13,7 @@ Come here when you already know the noun you need and want the precise detail be## How the docs are organized<Cards>- <Card title="Architecture" href="/docs/platform/architecture">+ <Card title="Architecture" href="/docs/building/architecture">How Carbon is built: apps, packages, database, events, jobs, and auth.</Card><Card title="Self-hosting" href="/docs/platform/self-hosting">diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex b18b7e2101..e1dd0bd4fd 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -1,10 +1,10 @@{"pages": ["index",- "glossary",- "platform","reference","building",- "integrations"+ "integrations",+ "platform",+ "glossary"]}diff --git a/docs/content/docs/platform/meta.json b/docs/content/docs/platform/meta.jsonindex c9fb8acb3f..6d8ef09ff9 100644--- a/docs/content/docs/platform/meta.json+++ b/docs/content/docs/platform/meta.json@@ -1,12 +1,5 @@{"title": "Platform","defaultOpen": true,- "pages": [- "architecture",- "backups",- "demo-data",- "self-hosting",- "single-sign-on",- "licensing"- ]+ "pages": ["self-hosting", "backups", "demo-data", "licensing"]}diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdxindex a43b38bb6b..a0c95b0af6 100644--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx@@ -15,7 +15,7 @@ Platform-wide behavior and edition.<EnvVars><EnvVar name="CARBON_EDITION" type="enum">One of `community`, `cloud`, `enterprise`, or `test`. Gates edition-specific features.</EnvVar><EnvVar name="CONTROLLED_ENVIRONMENT" type="boolean">Enables ITAR / controlled-environment restrictions: the US-Person certification gate, ITAR hostnames and branding, Slack and analytics disabled, and mandatory [two-factor authentication](/docs/reference/two-factor) that a company admin cannot turn off.</EnvVar>-<EnvVar name="AUTH_PROVIDERS" type="enum[]">Allowed sign-in methods: `email`, `google`, `azure`, `passkey`, `sso` ([single sign-on](/docs/platform/single-sign-on), Enterprise edition only).</EnvVar>+<EnvVar name="AUTH_PROVIDERS" type="enum[]">Allowed sign-in methods: `email`, `google`, `azure`, `passkey`, `sso` ([single sign-on](/docs/reference/single-sign-on), Enterprise edition only).</EnvVar><EnvVar name="DOMAIN" type="string">Base domain the apps are served from.</EnvVar><EnvVar name="ERP_URL" type="url">Public URL of the ERP app.</EnvVar><EnvVar name="MES_URL" type="url">Public URL of the MES app.</EnvVar>@@ -46,7 +46,7 @@ Carbon's single Postgres database. The first four are required and crash boot if<EnvVar name="DEV_BYPASS_EMAIL" type="string">Local only. Sign in as this email without a magic link.</EnvVar></EnvVars>-Enterprise [SAML single sign-on](/docs/platform/single-sign-on) adds two more:+Enterprise [SAML single sign-on](/docs/reference/single-sign-on) adds two more:<EnvVars><EnvVar name="SAML_ENABLED" type="boolean">Turns on the SAML engine in the auth service.</EnvVar>diff --git a/docs/content/docs/platform/single-sign-on.mdx b/docs/content/docs/platform/single-sign-on.mdxdeleted file mode 100644index 726efac5f0..0000000000--- a/docs/content/docs/platform/single-sign-on.mdx+++ /dev/null@@ -1,123 +0,0 @@-----title: Single sign-on-description: Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.------Single sign-on hands control of Carbon sign-in to your own <Term>identity provider</Term> — Okta, Entra ID, Google Workspace, or any SAML 2.0 IdP. You register your email domains once — proving you own each one with a DNS record — and from then on your IT team grants and revokes access centrally: everyone on those domains signs in to both ERP and MES with their normal work email — Carbon recognizes the domain and routes them to your IdP automatically, with no SSO button to find. Registering alone doesn't take anything away — the <Term>magic link</Term> and other methods keep working until you turn on [Require SSO](#requiring-sso).--## Requirements--SSO is an Enterprise feature. Automatic SSO routing on the login page and the settings section are active only when the instance runs the **Enterprise** edition (`CARBON_EDITION=enterprise`), which requires a [commercial license](/docs/platform/licensing). It is a capability of your own [self-hosted](/docs/platform/self-hosting) deployment — Carbon Cloud sign-in is unaffected.--Enable it through [environment variables](/docs/platform/self-hosting/environment-variables):--<EnvVars>-<EnvVar name="AUTH_PROVIDERS" type="enum[]">Add `sso` to the comma-separated list of sign-in methods. Without it, the button never renders.</EnvVar>-<EnvVar name="SAML_ENABLED" type="boolean">Turns on the SAML engine in the auth service (GoTrue).</EnvVar>-<EnvVar name="SAML_PRIVATE_KEY" type="string">The SAML signing key — a base64-encoded PKCS#1 DER RSA key, minimum 2048-bit. The exact `openssl` generation command is in `.env.example`.</EnvVar>-</EnvVars>--Carbon registers providers directly against the auth service with its service-role key — no Supabase account or plan is involved.--## Connect your identity provider--The whole exchange lives on one screen: **Settings** → **Security**, under the **"Single Sign-On"** heading. Viewing it requires the `settings` view permission; saving requires `settings` update.--<Steps>-<Step>--**Copy Carbon's service provider details.** The **"Service Provider Details"** card shows the **"ACS URL"** and **"SP Metadata URL"** with copy buttons. Copy them from the screen rather than constructing them by hand.--</Step>-<Step>--**Register Carbon in your IdP.** In Okta, Entra ID, or Google Workspace, create a SAML application using those two URLs. The assertion must include an **email attribute** — the email is how Carbon matches each sign-in to a person and a company.--</Step>-<Step>--**Paste the IdP metadata back into Carbon.** In the **"Identity Provider"** card, provide either the **"IdP Metadata URL"** or the raw **"IdP Metadata XML"** — exactly one of the two — then **"Save"**. After saving, the card gains a **"Require SSO"** switch and a **"Deactivate"** button — the sign that the connection is active.--</Step>-<Step>--**Verify your email domains.** The **"Email Domains"** card appears once the connection exists. Add each domain your people sign in with, publish the DNS record it shows you, and click **"Verify"** — see [Verifying a domain](#verifying-a-domain). Only verified domains route SSO sign-ins.--</Step>-</Steps>--<FieldTable>-<Field name="IdP Metadata URL" type="url">The SAML metadata URL published by your identity provider. Provide this *or* the XML, never both — the form rejects the submission with **"Provide either a metadata URL or metadata XML (exactly one)"**.</Field>-<Field name="IdP Metadata XML" type="xml">The raw metadata document, for IdPs that don't publish a metadata URL.</Field>-<Field name="Add a domain" type="text">One domain at a time, e.g. `example.com`. Domains are lowercased and must be bare hostnames — no `@`, no spaces; enter internationalized domains in punycode (`xn--`) form. Public email providers (`gmail.com`, `outlook.com`, …) are refused. Several companies may hold a **pending** claim on the same domain at once — a claim on its own blocks nobody. Exclusivity kicks in at verification: only one company can ever hold a domain **verified**, and only DNS control gets you there. Adding a domain your own company already has fails with **"This domain has already been added"**.</Field>-</FieldTable>--## Verifying a domain--A domain routes SSO sign-ins only after you prove your company controls it. Each added domain starts **Pending** with a DNS challenge — a unique TXT record shown right on the card:--| Record | Value |-| --- | --- |-| **Host** | `_carbon-challenge.example.com` |-| **Type** | `TXT` |-| **Value** | `carbon-domain-verification=<your unique token>` |--Add the record at your DNS host (copy both fields from the card — the token is unique to your company and this domain), then click **"Verify"**. Many DNS providers auto-append your domain to the record's name field: in Cloudflare, for example, enter only `_carbon-challenge` (plus any subdomain) and check the preview under the field shows the host once, not twice. Carbon looks the record up and, on a match, flips the domain to **Verified** — from then on it participates in sign-in routing and [Require SSO](#requiring-sso) enforcement. Verification is one-time: the domain stays verified until you remove it, and the TXT record may be deleted afterwards if you prefer a tidy zone.--If verification fails, the message tells you why: the record isn't visible yet (DNS changes can take a few minutes to propagate — wait and retry), the record's value doesn't match the token (re-copy it exactly), or the DNS lookup itself failed (the server couldn't reach the public resolvers; check its outbound DNS access). A **Pending** domain has no effect anywhere: it can't capture sign-ins, and it never triggers Require SSO — so adding a domain is always safe.--<Callout type="warn" title="Verified claims are exclusive until removed">-Only one company can hold a domain verified — first to prove DNS control wins. A **"Verify"** attempt on a domain another company already verified fails with a deliberately generic message, so the button can't be used to probe which domains are registered where. Verification is also permanent: the holder keeps the domain even if DNS control later changes hands (a domain sale, a rebrand). The clean handover is for the holding company to **Remove** the domain from its list, which frees it for the new owner to verify. Failing that, operators of a self-hosted deployment can delete the claim directly (`DELETE FROM "ssoDomain" WHERE "domain" = 'example.com';`) — note the previous holder's provider registration keeps routing the domain until its connection is re-saved, though sign-ins on it are rejected either way once the row is gone.-</Callout>--To turn SSO off, use the **"Deactivate"** button in the Identity Provider card. It opens a **"Deactivate Single Sign-On"** confirmation warning that "Users on your registered domains will no longer be able to sign in through your identity provider. This cannot be undone." — the provider registration is deleted outright and the domain claims are released, so re-enabling means saving the connection again and re-verifying your domains.--## How sign-in works--The login page is email-first, and the SSO fork is invisible. The user types their email and presses **"Continue"** — there is no separate SSO button to choose. Carbon checks whether the email's domain has an active connection (a rate-limited check that reveals nothing beyond yes or no); if it does, the browser redirects to your IdP, the user authenticates there, and lands back in Carbon signed in to the connection's company. If it doesn't, the same button falls through to the ordinary magic-link (or sign-up) flow. Users never have to know whether their company uses SSO.--Before any session is created, Carbon enforces the connection's boundaries itself: the asserted email's domain must be one of the connection's **verified** email domains. An assertion outside them is rejected with **"SSO sign-in rejected: this email domain is not registered for your company's SSO connection."** — even a misconfigured or hostile IdP can't sign someone into another company.--Provisioning is **invite-first** — there is no self-serve signup through SSO. Three outcomes:--- **Already a member** of the connection's company: signed straight in.-- **Has a pending invite**: the first SSO sign-in accepts it — the person lands in the company with exactly the invite's role and permissions.-- **Neither**: rejected with **"SSO sign-in succeeded but no invite exists for `[email protected]`. Contact your administrator."** (the message names the address). Nothing is provisioned, so creating the invite and retrying just works.--Invites cooperate with this automatically: when you invite someone whose email domain has an active SSO connection, the invite email links to the login page with their address prefilled instead of carrying a magic-link code — the IdP is never bypassed, even on day one.--<Callout type="note" title="First sign-in happens in ERP">-MES uses the same email-first sign-in and enforces the same domain rules, but it doesn't run first-time provisioning. A brand-new SSO user who starts at MES sees **"Complete your first SSO sign-in in Carbon ERP, then return here."** — after that one ERP sign-in, MES works normally.-</Callout>--## Existing accounts--People who already sign in with a magic link or OAuth don't lose anything when SSO arrives.--<Callout type="note" title="Existing accounts are linked automatically">-The first SSO sign-in quietly attaches the SAML identity to the existing account. Nothing changes for the user: it's the same account, the magic link keeps working, and no invite is needed, because an existing member is already authorized.-</Callout>--Coverage follows the registered domains: every existing member whose email domain is registered with the connection signs in with SSO automatically on their next login, no re-invite needed. People not yet in the company still need an invite from the [employees directory](/docs/reference/people); invite emails for these domains route to SSO automatically.--## Requiring SSO--Once the connection works, you can make it the only way in. The **"Identity Provider"** card carries a **"Require SSO"** switch: while it's on, anyone whose email domain is **verified** on the active connection can sign in **only** through your identity provider (a pending domain enforces nothing). Every other method is refused server-side — the magic-link form, Google and Outlook sign-in, and passkeys all answer with **"Your organization requires single sign-on. Sign in with your work email to continue."** and no session is created.--The ordering protects you from locking yourself out: the switch exists only on an active connection, so the path is always *set up SSO, prove a sign-in works, enforce last*. Turning the switch off — or deactivating the connection — immediately restores the other sign-in methods for those domains.--<Callout type="warn" title="Break-glass recovery">-If enforcement is on and your identity provider is unreachable, nobody on the covered domains can sign in to turn it off. Operators of a self-hosted deployment can lift the requirement directly in the database:--```sql-UPDATE "ssoConnection" SET "requireSso" = false WHERE "companyId" = '<id>';-```--Magic-link sign-in works again on the next attempt; re-enable the switch once the IdP is healthy.-</Callout>--## Two-factor authentication--<Callout type="tip" title="Your IdP owns MFA">-SSO sessions skip Carbon's [two-factor challenge](/docs/reference/two-factor) and the company-wide two-factor requirement in every environment, including controlled (ITAR) deployments. Your identity provider already enforced its own MFA policy during sign-in, and challenging twice is friction without security — MFA attestation for SSO sign-ins belongs to the IdP policy. Magic-link logins still go through Carbon's own two-factor challenge.-</Callout>diff --git a/docs/content/docs/reference/account.mdx b/docs/content/docs/reference/account.mdxindex 286241dd4e..9ccbb36b0e 100644--- a/docs/content/docs/reference/account.mdx+++ b/docs/content/docs/reference/account.mdx@@ -1,140 +1,61 @@---title: Your account-description: Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language, kept separate from the company-wide settings an admin controls.+description: Personal, self-service settings for profile, passkeys and two-factor, notification preferences, theme, and language — separate from company-wide settings.----Everything on the **Account** screen is yours alone. Your name and photo, the passkeys you sign in with,-which topics reach you by email, the theme you look at all day: these are personal preferences, scoped to-your user, and changing them touches nothing for anyone else on the team. That's the line to keep in mind.-Company-wide switches (locations, integrations, defaults, who can do what) live under **Settings** and are-gated by admin permissions. Your account settings need no special permission at all.--Open it from your avatar in the top bar. The sidebar has two sections, **Profile** and **Notifications**-(`apps/erp/app/modules/account/ui/useAccountSubmodules.tsx:9`); landing on `/x/account` redirects you-straight to Profile (`apps/erp/app/routes/x+/account+/_index.tsx:4`).+Everything on the **Account** screen is yours alone: your name and photo, the passkeys you sign in with, which topics reach you by email, the theme you look at all day. Changing them touches nothing for anyone else. Company-wide switches live under **Settings** and are gated by admin permissions; your account settings need no special permission at all. Open it from your avatar in the top bar.## Profile-Profile is the one card everyone shares. The description on it says it plainly: *"This information will be-visible to all users, so be careful what you share."* (`.../ui/Profile/ProfileForm.tsx:44`).+Profile is the one card everyone shares; the form itself warns *"This information will be visible to all users, so be careful what you share."*<FieldTable>- <Field name="First name / Last name" required>Your display name across Carbon. Both are required.</Field>- <Field name="Phone">Optional. A phone-formatted field, blank by default.</Field>- <Field name="About">A short bio, capped at 160 characters (`ProfileForm.tsx:62`).</Field>- <Field name="Photo">Your avatar. Uploading routes the image through Carbon's `image-resizer` before it's saved (`.../ui/Profile/ProfilePhotoForm.tsx`); you can also remove it and fall back to your initials.</Field>- <Field name="Email">Shown, but **read-only** — the field is disabled (`ProfileForm.tsx:53`). You can't change your sign-in email from here.</Field>+ <Field name="First name / Last name" required>Your display name across Carbon.</Field>+ <Field name="Phone">Optional.</Field>+ <Field name="About">A short bio, capped at 160 characters.</Field>+ <Field name="Photo">Your avatar; remove it to fall back to your initials.</Field>+ <Field name="Email">Shown but **read-only**. Your email is your sign-in identity, so changing it is handled outside these self-service settings.</Field></FieldTable>-Saving writes only to your own `user` row (`updatePublicAccount`, `.../account.service.ts:161`), so the-edit is always self-scoped.--<Callout type="note" title="Email is your identity, not a profile field">-Your email is how you sign in and how Carbon addresses notifications to you, so it isn't editable as a-casual profile field. Changing it is an identity change handled outside these self-service settings.-</Callout>--## Signing in — passkeys and two-factor+## Signing in-Carbon supports several sign-in methods, and which ones are available is a deployment-wide choice, not a-per-user one. The `AUTH_PROVIDERS` environment variable turns them on and off; the default set is-`email,google,azure` (`packages/env/src/index.ts:114`). That covers a **magic link** to your email, and-**Google** and **Microsoft (Azure)** OAuth. There's no password field on this screen — Carbon signs you in-by magic link or OAuth, not by a stored password you type each time.+Sign-in is a magic link, Google or Microsoft OAuth, or a passkey — there is no password. Which methods exist is a deployment-wide choice, not a per-user one.-The same screen is where you add an authenticator app for two-factor codes — see-[two-factor authentication](/docs/reference/two-factor) for setup, company-wide enforcement, and recovery.+<Screenshot label="Account → Security: passkey list with add/rename/remove, and the two-factor authenticator card" caption="Security holds everything you sign in with." />-<Callout type="note" title="There's no password on the account screen">-The codebase carries a password-change form, but it isn't wired into any account route today — the Account-sidebar exposes Profile, Security, and Notifications. Password management isn't a live self-service control here.-Sign-in is magic link, OAuth, or a passkey.-</Callout>--The sign-in controls you manage yourself live on **Account → Security**, not on Profile. The passkey card-only appears when the `passkey` provider is enabled (`isAuthProviderEnabled("passkey")`,-`.../account+/security.tsx`). A passkey lets you-sign in with biometrics — Face ID, Touch ID, or your device PIN — instead of waiting on a magic-link email.-From the Profile page you can:--<FieldTable>- <Field name="Add a passkey">Registers a new credential through your browser's WebAuthn prompt (`onAddPasskey`, `security.tsx`). You can hold more than one — a laptop and a phone, say.</Field>- <Field name="Rename a passkey">Give a credential a recognizable name (up to 100 characters) so you can tell your devices apart.</Field>- <Field name="Remove a passkey">Deletes it; that device can no longer sign you in. Each row shows when it was added, when it was last used, and whether it's synced across your devices.</Field>-</FieldTable>+**Account → Security** is where you manage your own credentials. Add a passkey through your browser's WebAuthn prompt to sign in with Face ID, Touch ID, or your device PIN; rename each one so you can tell devices apart; remove one to revoke that device. Each row shows when it was added and last used. The same screen holds the authenticator-app card — see [two-factor authentication](/docs/reference/two-factor) for setup, enforcement, and recovery.<Callout type="tip" title="Keep more than one way in">-A passkey is tied to a device. If you register only one and lose that device, fall back to the magic-link-email or your OAuth provider to get back in — then add a fresh passkey. Registering a second passkey up-front saves the round trip.+A passkey is tied to a device. Register a second one up front, or you'll be falling back to the magic-link email when the first device goes missing.</Callout>## Notification preferences-Which alerts reach you, and on which channel, is set on the **Notifications** page — and it's per-user.-In-app notifications (the bell in the top bar) are **always delivered**; the toggles only govern the extra-channels, **email** and, when your company has connected Slack, **Slack** (`.../account+/notifications.tsx`).-Each row is a topic — Approvals, Jobs, Inventory, Purchasing, Quality, and so on — with a switch per channel.--The default is *on*: an absent preference row counts as enabled (`notifications.tsx:130`), so you're opting-**out** of a channel for a topic, not opting in. Two things gate what you see:--- The **Slack** column appears only if an admin connected the Slack integration for the company- (`slackActive`, `notifications.tsx:47`).-- **Email** notifications depend on your company's plan. If the `EMAIL_NOTIFICATIONS` feature isn't in the- plan, Carbon tells you so, and your email preferences are stored but only take effect once it's enabled- (`notifications.tsx:49`, `:175`).--For the full picture of what raises a notification and how Carbon fans it out across channels, see the-[notifications reference](/docs/reference/notifications). This page is where you tune it for yourself.--## Theme and language--Carbon lets you pick a color theme; the choice is stored in a cookie on your browser, not in the database-(`.../account+/theme.tsx`), so it follows you per-device and applies to nobody else. That's the personal-end of theming. Company-wide branding — the logo, the default look a new user starts with — is an admin-setting elsewhere, not something you set from your account.--<Callout type="note" title="Language selection">-Carbon ships a translated interface across many locales, and a per-user language preference is part of the-account model. In the current build the language picker isn't surfaced on the Account sidebar — the-interface follows the app's resolved locale. Treat language as a preference Carbon carries for you rather-than a live toggle on this screen.-</Callout>+**Account → Notifications** is your personal grid of topic × channel switches: in-app is always delivered, and the toggles govern email and (when connected) Slack. The default is on; a switch off is an opt-out for that one topic and channel. What raises each notification and how channels are gated is the [notifications reference](/docs/reference/notifications) — this page is where you tune it for yourself.-## Personal attributes+## Theme, language, and attributes-Beyond the shared profile, your company can define **user attributes** — structured fields like a-certification date, a shirt size, or a shift preference — grouped into categories. Whether a given-attribute lands on your public profile or stays admin-only depends on its category being public, and whether-*you* can edit your own value depends on it being marked <Term id="attribute-self-managed">self-managed</Term>.-When it is, you can set the value yourself; when it isn't, only an admin can-(`.../account+/$userId.attribute.tsx:48`). Attribute types range from text and numbers to dates, booleans,-and pick-lists.+Your color theme is stored in a browser cookie, so it follows you per device and applies to nobody else; company-wide branding is an admin setting. Language is a preference Carbon carries for you rather than a live toggle on this screen. Your company can also define **user attributes** (a certification date, a shift preference) grouped into categories: whether one shows on your public profile depends on its category being public, and you can edit your own value only when the attribute is marked <Term id="attribute-self-managed">self-managed</Term>.-Your account is the small surface you own on a shared system: a profile the team can see, the keys you sign-in with, the alerts you let through, and the theme you stare at. None of it reaches past you. For the-switches that do — the ones that shape how the whole company works — see the company settings under-**Settings**, and read the [notifications reference](/docs/reference/notifications) for how alerts are-raised in the first place.+For the switches that shape the whole company, see [company settings](/docs/reference/company-settings) and [people](/docs/reference/people).<AgentContext>-## Troubleshooting+## Internals and troubleshooting-Why some sign-in controls aren't editable here — these are preconditions, not error messages.+Sidebar sections come from `useAccountSubmodules.tsx:9`; `/x/account` redirects to Profile (`routes/x+/account+/_index.tsx:4`). Profile saves via `updatePublicAccount` (`account.service.ts:161`), self-scoped to the user's own `user` row. Photo uploads route through the `image-resizer` function. The passkey card renders only when `isAuthProviderEnabled("passkey")` (`security.tsx`); passkey names cap at 100 characters. Notification preferences: absent row = enabled (`notifications.tsx:130`); Slack column gated by `slackActive` (`notifications.tsx:47`); email gated by the `EMAIL_NOTIFICATIONS` plan feature (`notifications.tsx:49, :175`). Theme is a cookie (`theme.tsx`). Attribute self-editing is gated by the self-managed flag (`$userId.attribute.tsx:48`).### Can't change your email from the Account screen-The Email field on Profile is shown but **read-only** (disabled). Your email is your sign-in identity and how Carbon addresses your notifications, so it isn't editable as a profile field. Changing it is an identity change handled outside these self-service settings, not something you do here.+The field is deliberately read-only. Email is the sign-in identity and the notification address; changing it is an identity change handled outside self-service.### There's no password to change-Carbon signs you in by magic link, OAuth, or a passkey — there's no stored password you type each time. A password-change form exists in the codebase but isn't wired into any account route, so password management is not a live control on this screen.+Sign-in is magic link, OAuth, or passkey. A password-change form exists in the codebase but isn't wired into any account route, so password management is not a live control here.### The passkey card isn't showing-Passkeys appear only when the `passkey` sign-in provider is enabled for the deployment. Which sign-in methods exist is a deployment-wide choice set by the `AUTH_PROVIDERS` environment variable (default `email,google,azure`), not a per-user setting. If passkey isn't in that set, the card won't render — sign in by magic link or OAuth instead.+The `passkey` provider isn't enabled for the deployment. `AUTH_PROVIDERS` (default `email,google,azure`) decides which sign-in methods exist; it's deployment-wide, not per-user.### There's no language picker-A per-user language preference is part of the account model, but in the current build the picker isn't surfaced on the Account sidebar — the interface follows the app's resolved locale. Treat language as a preference Carbon carries for you, not a live toggle here.+The per-user language preference exists in the account model, but the picker isn't surfaced on the Account sidebar in the current build; the interface follows the app's resolved locale.### The Slack or Email notification column is missing-The **Slack** column appears only if an admin connected the Slack integration for the company. **Email** notifications depend on your company's plan — without the `EMAIL_NOTIFICATIONS` feature, preferences are stored but only take effect once it's enabled.+Slack's column needs the integration connected. Email preferences are stored regardless but only take effect when the plan includes `EMAIL_NOTIFICATIONS`.</AgentContext>diff --git a/docs/content/docs/reference/calibration.mdx b/docs/content/docs/reference/calibration.mdxindex 99973ecc66..90af6fbb7c 100644--- a/docs/content/docs/reference/calibration.mdx+++ b/docs/content/docs/reference/calibration.mdx@@ -64,7 +64,7 @@ Logging a calibration never overwrites the last one. Each record is a dated row,A gauge carries a calibration status with three values, and Carbon sets it for you.-<StatusFlow>+<StatusFlow entity="gaugeCalibration"><Status name="Pending">The starting state. The gauge has a schedule but no passing calibration on record yet, so it's neither confirmed in nor out.</Status><Status name="In-Calibration" accent>The most recent calibration passed and the next-due date is still in the future. The gauge is trustworthy.</Status><Status name="Out-of-Calibration" terminal>The most recent calibration failed, the gauge is inactive, or the next-due date has passed. The gauge needs recalibrating.</Status>diff --git a/docs/content/docs/reference/change-orders/lifecycle.mdx b/docs/content/docs/reference/change-orders/lifecycle.mdxindex e59cc27331..747cb60a34 100644--- a/docs/content/docs/reference/change-orders/lifecycle.mdx+++ b/docs/content/docs/reference/change-orders/lifecycle.mdx@@ -1,6 +1,6 @@---title: Lifecycle & release-description: The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and exactly what release does when a change notice reaches Done.+description: The five change-notice stages, the Implementation lock and Reopen, the impact panel, the diff review, and what release does at Done.---A change notice advances forward one stage at a time. There's no approval toggle — the stages *are* the@@ -10,7 +10,7 @@ every open stage — closes it, after which **Reopen** returns it to **"Draft"**## The stages-<StatusFlow>+<StatusFlow entity="changeOrder"><Status name="Draft">The change notice is being written. Pick affected items, set change types, and edit each draft method. No notification is sent.</Status><Status name="Start">Work is underway. Advancing to Start notifies the assignee and every action-task assignee.</Status><Status name="Engineering Complete">The design edits are finished and ready for implementation review. Silent, no notification.</Status>diff --git a/docs/content/docs/reference/change-orders/setup.mdx b/docs/content/docs/reference/change-orders/setup.mdxindex 71908e0af6..4e5cb0925f 100644--- a/docs/content/docs/reference/change-orders/setup.mdx+++ b/docs/content/docs/reference/change-orders/setup.mdx@@ -1,6 +1,6 @@---title: Categories & actions-description: The two company-scoped lookups that sit alongside change notices — the category list and the reusable action-task templates — plus linking an action task to Linear.+description: "The company-scoped lookups beside change notices: the category list and reusable action-task templates, plus linking a task to Linear."---Two configuration lists live next to change notices in the Items nav. Both are company-scoped and edited bydiff --git a/docs/content/docs/reference/company-settings.mdx b/docs/content/docs/reference/company-settings.mdxindex 789af9b199..5a6a576d89 100644--- a/docs/content/docs/reference/company-settings.mdx+++ b/docs/content/docs/reference/company-settings.mdx@@ -3,134 +3,101 @@ title: Company settingsdescription: The company record, its feature toggles, base currency, logos, and tags — the company-wide configuration every module reads from.----Everything in Carbon is scoped to a **company**. Your login can belong to several companies, and each one carries its own address, base currency, logos, feature toggles, and numbering. Two records hold this configuration: the `company` row (identity, address, currency, logos) and a paired `companySettings` row (one-to-one, keyed on the same id) that holds the company-wide feature flags and defaults. This page is the map of what lives where.--Settings live under **Settings** in the app, grouped into **Company**, **Modules**, and **System** (`apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx`). Every route is employee-only; a few are gated further — **Billing** needs company ownership and a Cloud environment, and **Companies** and **Backups** are internal-only.+Everything in Carbon is scoped to a **company**, and two records hold its configuration: the `company` row (identity, address, currency, logos) and a paired `companySettings` row holding the company-wide feature flags and defaults. Settings live under **Settings** in the app, grouped into **Company**, **Modules**, and **System**. Every route is employee-only; **Billing** additionally needs company ownership on a Cloud environment, and **Companies** and **Backups** are internal-only.## The company record-The `company` table is the tenant's identity. Its fields come from the `companyValidator` (`apps/erp/app/modules/settings/settings.models.ts:81`) and are edited under **Settings → Company**.+Edited under **Settings → Company**:++<Screenshot label="Settings → Company: the company form with name, registered address, tax identifiers, and base currency" caption="The tenant's identity — one record every document and posting reads from." /><FieldTable><Field name="name" required>Company name.</Field><Field name="addressLine1 / addressLine2 / city / stateProvince / postalCode / countryCode" required>The registered address. `addressLine1`, `city`, `postalCode`, and `countryCode` are required.</Field>- <Field name="baseCurrencyCode" type="text" required>The currency every posted amount is expressed in. See [base currency](#base-currency) below.</Field>+ <Field name="baseCurrencyCode" type="text" required>The currency every posted amount is expressed in. See [base currency](#base-currency).</Field><Field name="phone / fax / email / website">Contact details.</Field><Field name="taxId / vatNumber / eori">Tax registration identifiers printed on documents.</Field>- <Field name="logoLight / logoDark / logoLightIcon / logoDarkIcon / logoWatermark" type="text">Storage paths to the company's logos. See [logos](#logos).</Field>- <Field name="parentCompanyId" type="text">Set when this company is a subsidiary of another. See [multiple companies](#multiple-companies).</Field>- <Field name="isEliminationEntity" type="boolean">Marks a consolidation-only company used to eliminate intercompany pairs.</Field>+ <Field name="logoLight / logoDark / logoLightIcon / logoDarkIcon / logoWatermark" type="text">The five logo slots, edited under **Settings → Logos**: light/dark pairs for UI backgrounds, compact icon variants, and a watermark printed behind documents.</Field>+ <Field name="parentCompanyId" type="text">Set when this company is a subsidiary of another.</Field>+ <Field name="isEliminationEntity" type="boolean">Marks a consolidation-only company that nets intercompany pairs out of consolidated reports.</Field><Field name="companyGroupId" type="text">Groups related companies for the company switcher.</Field><Field name="selectedModules" type="text[]">Which modules this company turned on during onboarding.</Field>- <Field name="industryId / customIndustryDescription" type="text">The industry chosen at onboarding — collected on the industry step, not the general company form.</Field>- <Field name="auditLogEnabled" type="boolean">Whether change history is recorded. See [audit logs](/docs/reference/notifications).</Field>- <Field name="suggestionNotificationGroup" type="text[]">Who is notified when the AI suggestion engine surfaces something.</Field>+ <Field name="industryId / customIndustryDescription" type="text">The industry chosen at onboarding.</Field>+ <Field name="auditLogEnabled" type="boolean">Whether change history is recorded. See [audit log](/docs/reference/audit-log).</Field></FieldTable>-The service reads it with `getCompany(client, companyId)`, which rewrites each stored logo path to a public URL before returning (`settings.service.ts:230`).--## Multiple companies--company membership is per-user, so one login can hold several companies and switch between them. `getCompanies(client, userId)` returns every company a user can enter (`settings.service.ts:139`); the ERP is an employee app, so supplier- and customer-only memberships are filtered out by `getEmployeeCompanies` (`settings.service.ts:183`). Switching happens through the company picker, and each company you enter carries its own settings, currency, and numbering — nothing crosses the boundary.--Companies can also nest. A company with a `parentCompanyId` is a **subsidiary** (`subsidiaryValidator`, `settings.models.ts:279`); an `isEliminationEntity` company exists only to net intercompany transactions out of consolidated reports.--<Callout type="note" title="Companies and Backups are internal-only">-The **Companies** management screen and **Backups** are gated to internal operators (`internalOnlyRoutes` in `useSettingsSubmodules.tsx`). Most tenants create and switch companies through onboarding and the company picker, not this screen.-</Callout>--For consolidated reporting and the elimination flow, see [intercompany accounting](/docs/reference/intercompany).+Company membership is per-user: one login can hold several companies and switch through the company picker, and each company carries its own settings, currency, and numbering. Nothing crosses the boundary. A company with a `parentCompanyId` is a subsidiary; consolidation and elimination are covered in [intercompany accounting](/docs/reference/intercompany).## Feature toggles and defaults-`companySettings` is a single row per company (one-to-one with `company`, keyed on the same id). It holds the company-wide switches and defaults that individual modules read at runtime. Read it with `getCompanySettings(client, companyId)` (`settings.service.ts:283`). Each group of fields is edited on its own **Settings → Modules** page and saved through a small dedicated validator.--The flags below are the real column names from the `companySettings` row (`packages/database/src/types.ts:6653`).+`companySettings` is a single row per company, edited across the **Settings → Modules** pages. These are the real column names:<FieldTable>- <Field name="accountingEnabled" type="boolean">Master switch for the ledger. When off, operations complete without posting journal entries. This is the gate the accounting flow checks before it posts anything.</Field>- <Field name="timeCardEnabled" type="boolean">Turns on shop-floor time cards. Edited via `timeCardSettingsValidator`.</Field>- <Field name="consoleEnabled" type="boolean">Enables the support/impersonation console. Edited via `consoleSettingsValidator`.</Field>- <Field name="requireMfa" type="boolean">Requires everyone to have an authenticator app before they can open this company. Edited from the **Two-Factor Authentication Enforcement** card on **Settings → System → Security**. Locked on and uneditable in controlled (ITAR) deployments. See [two-factor authentication](/docs/reference/two-factor).</Field>- <Field name="useMetric" type="boolean">Whether material units default to metric. Edited via `materialUnitsValidator`.</Field>- <Field name="materialGeneratedIds" type="boolean">Whether new materials get an auto-generated readable id. Edited via `materialIdsValidator`.</Field>+ <Field name="accountingEnabled" type="boolean">Master switch for the ledger. When off, operations complete without posting journal entries.</Field>+ <Field name="timeCardEnabled" type="boolean">Turns on shop-floor time cards.</Field>+ <Field name="consoleEnabled" type="boolean">Enables the support/impersonation console.</Field>+ <Field name="requireMfa" type="boolean">Everyone needs an authenticator app to open this company. Edited from **Settings → System → Security**; locked on in controlled (ITAR) deployments. See [two-factor authentication](/docs/reference/two-factor).</Field>+ <Field name="useMetric" type="boolean">Whether material units default to metric.</Field>+ <Field name="materialGeneratedIds" type="boolean">Whether new materials get an auto-generated readable id.</Field><Field name="plmReleaseControl" type="text">The release-control policy for item revisions.</Field><Field name="kanbanOutput" type="enum">What a Kanban card prints: `label`, `qrcode`, or `url`.</Field>- <Field name="productLabelSize / shelfLabelSize" type="text">Default label sizes for product and shelf labels.</Field>+ <Field name="productLabelSize / shelfLabelSize" type="text">Default label sizes.</Field><Field name="updateLeadTimesOnReceipt" type="boolean">Whether receiving recalculates supplier lead times.</Field><Field name="purchasePriceUpdateTiming" type="enum">When purchase prices refresh: `Purchase Invoice Post` or `Purchase Order Finalize`.</Field>- <Field name="maintenanceGenerateInAdvance / maintenanceAdvanceDays" type="boolean / number">Whether preventive-maintenance work is generated ahead of time, and by how many days (1–90).</Field>+ <Field name="maintenanceGenerateInAdvance / maintenanceAdvanceDays" type="boolean / number">Whether preventive maintenance is generated ahead of time, and by how many days (1–90).</Field><Field name="samplingStandard" type="enum">The default inspection sampling standard.</Field><Field name="enforceInspectionFourEyes" type="boolean">Requires a second person to sign off inspections.</Field><Field name="qualityIssueTarget" type="number">The quality issue target used in reporting.</Field><Field name="assetTaxDepreciationEnabled / assetTaxRate" type="boolean / number">Whether a separate tax-depreciation schedule is tracked for fixed assets, and its rate.</Field><Field name="showCustomerReadableId / showSupplierReadableId" type="boolean">Whether customer/supplier readable ids are surfaced in the UI.</Field>- <Field name="inventoryShelfLife" type="jsonb">A single blob holding every shelf-life knob (near-expiry warning days, default shelf life, calculated-input scope, expired-entity policy). See [shelf life](/docs/reference/shelf-life).</Field>+ <Field name="inventoryShelfLife" type="jsonb">Every shelf-life knob in one blob. See [shelf life](/docs/reference/shelf-life).</Field><Field name="digitalQuoteEnabled / digitalQuoteIncludesPurchaseOrders" type="boolean">Whether customers get a digital quote, and whether it includes purchase orders.</Field>- <Field name="quoteLineCategoryMarkups" type="jsonb">Per-category default markups (material, part, tool, labor, machine, overhead, outside…) applied to quote lines.</Field>+ <Field name="quoteLineCategoryMarkups" type="jsonb">Per-category default markups applied to quote lines.</Field></FieldTable>-Several fields on the same row are **notification groups** — arrays of who to notify for a given event (`digitalQuoteNotificationGroup`, `rfqReadyNotificationGroup`, `supplierQuoteNotificationGroup`, `inventoryJobCompletedNotificationGroup`, `salesJobCompletedNotificationGroup`, the maintenance/quality/operations/other `*DispatchNotificationGroup`s, and `gaugeCalibrationExpiredNotificationGroup`). Two AP/AR email addresses (`accountsPayableEmail`, `accountsReceivableEmail`) and default CC lists (`defaultSupplierCc`, `defaultCustomerCc`) live here too. For how these fan out to people, see [notifications](/docs/reference/notifications).+The same row also carries the **notification groups** (who to notify for digital quotes, RFQ-ready, supplier quotes, job completions, dispatches, gauge-calibration expiry), the AP/AR email addresses, and default CC lists — see [notifications](/docs/reference/notifications) for how they fan out.<Callout type="warn" title="Accounting is a company-wide toggle, not per-document">-`accountingEnabled` gates the *entire* ledger. If it is off, jobs, shipments, and invoices still complete, but nothing posts to the general ledger — there are no partial or per-transaction exceptions. Turning it on mid-stream doesn't backfill past activity.+`accountingEnabled` gates the *entire* ledger: off means jobs, shipments, and invoices complete but nothing posts, with no per-transaction exceptions. Turning it on mid-stream doesn't backfill past activity.</Callout>## Base currency-Every company has one `baseCurrencyCode`, set on the `company` row and required by `companyValidator` (`settings.models.ts:77`). It is the currency that all *posted* amounts are stored and reported in. Transactions in other currencies are converted to base at their exchange rate before they post, so the ledger stays single-currency.+Every company has one `baseCurrencyCode`: the currency all *posted* amounts are stored and reported in, with foreign-currency transactions converted at their exchange rate before posting. It's chosen at onboarding and is the denomination of your whole history, so it isn't something you flip casually. A subsidiary can carry a different base currency from its parent; consolidation is where they meet.-Base currency is chosen at onboarding and is not something you flip casually — it's the denomination of your whole history. A subsidiary can carry a different base currency from its parent; consolidation is where those meet.+## Theme and tags-## Theme--Carbon ships eight themes, each supplying a full set of HSL CSS variables (`packages/utils/src/themes.ts`): **Modern** (`zinc`), **Brutal** (`neutral`), **Cherry** (`red`), **Apricot** (`orange`), **Lemon** (`yellow`), **Mint** (`green`), **Blueberry** (`blue`), and **Lavender** (`violet`). The set is validated by `themeValidator` (`settings.models.ts:306`).--<Callout type="note" title="Theme is per-person, not per-company">-Theme selection is stored in a cookie for the current user and browser, not on the company record — the action just sets a cookie via `setTheme` (`apps/erp/app/routes/x+/account+/theme.tsx`). Two people in the same company can each run a different theme. Document templates have their own, separate theme setting.-</Callout>--## Logos--The `company` row holds up to five logo slots: `logoLight`, `logoDark`, `logoLightIcon`, `logoDarkIcon`, and `logoWatermark`, edited under **Settings → Logos**. They are stored as storage paths; `getCompany` and `getCompanies` rewrite them to public URLs on read (`settings.service.ts:230`, `settings.service.ts:139`). The light/dark pairs cover light and dark UI backgrounds; the icon variants are the compact mark; the watermark prints behind documents.--## Tags--Tags are free-form labels scoped to a company and a table, stored in the `tag` table. They're loaded per table with `getTagsList(client, companyId, table)` and created with `insertTag` (`apps/erp/app/modules/shared/shared.service.ts:929`, `:987`). Because every tag carries both `companyId` and a `table`, the same label can mean different things on items versus jobs, and tag vocabularies never leak across companies.+Carbon ships eight color themes (Modern, Brutal, Cherry, Apricot, Lemon, Mint, Blueberry, Lavender). Theme is **per-person**, stored in a browser cookie rather than on the company record, so two people in one company can run different themes; document templates have their own separate theme setting. **Tags** are free-form labels scoped to a company *and* a table, so the same label can mean different things on items versus jobs, and vocabularies never leak across companies.## Related system configuration-A few more company-wide lookups live under **Settings → System** and have their own reference pages:-<Cards><Card title="Numbering sequences" href="/docs/reference/sequences">The per-company generators behind every readable document number.</Card><Card title="API keys" href="/docs/building/api-keys">Scoped secrets that let external systems call the Carbon API.</Card><Card title="Approvals" href="/docs/reference/approvals">Approval rules that gate documents above a threshold.</Card>- <Card title="Notifications" href="/docs/reference/notifications">How the notification groups above reach people.</Card>+ <Card title="Licensing" href="/docs/platform/licensing">Which features exist at all depends on plan and edition.</Card></Cards>-Which company-wide features are available at all also depends on your plan and edition — see [licensing](/docs/platform/licensing).-<AgentContext>-## Troubleshooting+## Internals and troubleshooting-Mostly "why can't I see or change setting X" — the answers are preconditions, not error strings.+Settings nav groups come from `useSettingsSubmodules.tsx` (internal gates in `internalOnlyRoutes`). Company fields are validated by `companyValidator` (`settings.models.ts:81`; `baseCurrencyCode` required at `:77`); subsidiaries by `subsidiaryValidator` (`:279`); themes by `themeValidator` (`:306`, definitions in `packages/utils/src/themes.ts`). Reads: `getCompany` (`settings.service.ts:230`, rewrites logo paths to public URLs), `getCompanies` (`:139`), `getEmployeeCompanies` (`:183`, filters supplier/customer-only memberships), `getCompanySettings` (`:283`). `companySettings` columns are in `packages/database/src/types.ts:6653`; each Modules page saves through its own small validator (`timeCardSettingsValidator`, `consoleSettingsValidator`, `materialUnitsValidator`, `materialIdsValidator`, …). Tags live in the `tag` table via `getTagsList` / `insertTag` (`shared.service.ts:929`, `:987`). Theme is set by a cookie action (`routes/x+/account+/theme.tsx`).### I can't find the Companies or Backups settings page-Both are internal-operator-only, gated by `internalOnlyRoutes` in `useSettingsSubmodules.tsx`. Regular tenants don't get these screens — create and switch companies through onboarding and the company picker instead.+Internal-operator-only (`internalOnlyRoutes`). Tenants create and switch companies through onboarding and the company picker.### I can't see the Billing settings page-Billing needs **company ownership** *and* a Cloud environment — it's gated on both (`useSettingsSubmodules.tsx`). Self-hosted/community editions and non-owner users won't see it.+Billing needs company ownership *and* a Cloud environment; self-hosted editions and non-owners don't get it.-### Nothing posts to the general ledger even though jobs and invoices complete-`accountingEnabled` is a company-wide master switch, not per-document. When it's off, jobs, shipments, and invoices still complete but nothing posts — there are no partial exceptions. Turn it on under **Settings → Modules**; note it does **not** backfill past activity.+### Nothing posts to the ledger though jobs and invoices complete+`accountingEnabled` is off. Turn it on under Settings → Modules; it does not backfill past activity.### My theme changed but a colleague still sees the old one-Theme is per-user, not per-company. The action just sets a cookie via `setTheme` (`apps/erp/app/routes/x+/account+/theme.tsx`), so each person in the same company runs their own theme. Document templates carry a separate theme setting.+Theme is per-user (a cookie), not per-company. Document templates carry a separate theme setting.### I can't change the base currency-Base currency (`baseCurrencyCode`) is the denomination of your whole posted history and is chosen at onboarding — it's not meant to be flipped casually. A subsidiary can carry a different base currency from its parent; that difference is reconciled at consolidation, not by switching a company's base.+By design: it's the denomination of the whole posted history, chosen at onboarding. Subsidiary/parent currency differences reconcile at consolidation, not by switching a base.-### A settings page (Modules) exists but the toggle does nothing I expect-`companySettings` flags are read by individual modules at runtime; the feature they gate may also depend on your plan and edition (see licensing). If a flag appears set but the feature is absent, check the edition gate before assuming the toggle is broken.+### A Modules toggle does nothing I expect+Flags are read by modules at runtime, and the feature may also be gated by plan/edition. Check licensing before assuming the toggle is broken.</AgentContext>diff --git a/docs/content/docs/reference/custom-fields.mdx b/docs/content/docs/reference/custom-fields.mdxindex 002fd32555..e55cfb87bd 100644--- a/docs/content/docs/reference/custom-fields.mdx+++ b/docs/content/docs/reference/custom-fields.mdx@@ -3,105 +3,55 @@ title: Custom fieldsdescription: Company-defined extra fields that attach to core records like customers, parts, and orders.----Carbon ships a fixed schema for every entity, but your process almost always needs one more field the base tables don't have. A machine-shop customer might carry a "PPAP level"; a part might need a "RoHS status"; a job might track an internal "line number". <Term id="custom-field">Custom fields</Term> let each company add its own fields to a core record without a schema change. They surface on the record's form, save alongside the built-in fields, and are queryable through the API.+Carbon ships a fixed schema for every entity, but your process almost always needs one more field: a customer's "PPAP level", a part's "RoHS status", a job's internal "line number". <Term id="custom-field">Custom fields</Term> let each company add its own fields to a core record without a schema change. Define one under **Settings → Custom Fields** and every record of that entity shows it on its form, saves it alongside the built-in fields, and exposes it through the API.-A custom field is defined once, per company, and attaches to a **table** (a core entity like `customer` or `part`). Every record of that entity then shows the field on its form. Define them under **Settings → Custom Fields**.+## Defining a field-## How a custom field is defined--Each field has a name, a data type, and the table it attaches to. The definition lives in the `customField` table (`packages/database/supabase/migrations/20240311021818_custom-fields.sql:21`), and the form validator that governs the create/edit UI is `customFieldValidator` (`apps/erp/app/modules/settings/settings.models.ts:109`).+<Screenshot label="Settings → Custom Fields: the entity catalog with Table, Module, and Fields columns, and the field form with name, data type, and tags" caption="One row per eligible entity; the field form locks its data type after creation." /><FieldTable>- <Field name="Name" type="text" required>- The label shown on the record's form. Unique per table, per company.- </Field>- <Field name="Data Type" type="enum" required>- One of the nine types below. **Once saved, the data type can't be changed** (the form disables it on edit, `apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx:116`) — delete and re-create to switch types.- </Field>- <Field name="List Options" type="text[]">- Required only for the **List** type: the set of choices the dropdown offers. Enforced by the validator (`settings.models.ts:121`).- </Field>- <Field name="Required" type="boolean">- When on, the field must be filled before the form saves. Boolean fields are never treated as required (`CustomFormFields.tsx:31`).- </Field>- <Field name="Tags" type="text[]">- Scopes the field to records carrying a matching tag. A tagged field only appears on records that share one of its tags — leave empty to show it on every record of the table.- </Field>+ <Field name="Name" type="text" required>The label shown on the record's form. Unique per table, per company.</Field>+ <Field name="Data Type" type="enum" required>One of nine types (below). **Once saved, the type can't be changed**; delete and re-create to switch.</Field>+ <Field name="List Options" type="text[]">Required only for the **List** type: the dropdown's choices.</Field>+ <Field name="Required" type="boolean">The field must be filled before the form saves. Boolean fields are never treated as required.</Field>+ <Field name="Tags" type="text[]">Scopes the field to records carrying a matching tag; leave empty to show it on every record of the table.</Field></FieldTable>-## Data types--There are nine data types (`DataType` enum, `apps/erp/app/modules/shared/types.ts:83`). Each one renders a specific input on the form.--| # | Type | Renders as |-|---|------|------------|-| 1 | **Boolean** | A toggle |-| 2 | **Date** | A date picker |-| 3 | **List** | A dropdown of your defined options |-| 4 | **Numeric** | A number input with steppers |-| 5 | **Text** | A single-line text input |-| 6 | **User** | An employee picker |-| 7 | **Customer** | A customer picker |-| 8 | **Supplier** | A supplier picker |-| 9 | **File** | A file reference |--The `User`, `Customer`, and `Supplier` types store a reference to another Carbon record, so a custom field can point at an existing entity rather than just holding free text. The rendering switch lives in `CustomFormFields.tsx:75`.+The nine data types each render a specific input: **Boolean** (toggle), **Date** (date picker), **List** (dropdown of your options), **Numeric**, **Text**, **File**, and three reference types (**User**, **Customer**, and **Supplier**) that store a pointer to an existing Carbon record rather than free text.<Callout type="note" title="The data type is permanent">-Because existing values are stored as-is, Carbon locks the data type after creation. If you picked Text and need Numeric, create a new field and migrate the values — there's no in-place conversion.+Existing values are stored as-is, so Carbon locks the type after creation. Picked Text and need Numeric? Create a new field and migrate the values; there is no in-place conversion.</Callout>## Which entities support custom fields-Custom fields attach to a curated set of core entities, not every table. The catalog of eligible tables is the `customFieldTable` table, grouped by module (`20240311021818_custom-fields.sql:2`), and it's seeded across migrations starting with `20240511125727_seed_custom_fields.sql`. On the **Settings → Custom Fields** page you'll see one row per eligible entity, showing its **Table**, **Module**, and how many **Fields** you've defined (`apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx:32`).--The eligible entities span most modules:--- **Sales** — customer, sales order, sales invoice, RFQ, and their contacts and lines.-- **Purchasing** — supplier, purchase invoice, supplier quote, and RFQ lines.-- **Items** — part, tool, material, consumable, and item costing/planning records. See [Items](/docs/reference/items) for the base fields these extend.-- **Resources** — employee job, work center, equipment, department, location.-- **Inventory** — shipment, warehouse transfer, picking list.-- **Production** — job.-- **Accounting** — account, payment term, journal.+The catalog is curated, not universal — the settings page lists one row per eligible entity with its module and field count. Coverage spans most modules: **Sales** (customer, sales order, sales invoice, RFQ, their contacts and lines), **Purchasing** (supplier, purchase invoice, supplier quote, RFQ lines), **Items** (part, tool, material, consumable, costing/planning records; see [items](/docs/reference/items)), **Resources** (employee job, work center, equipment, department, location), **Inventory** (shipment, warehouse transfer, picking list), **Production** (job), and **Accounting** (account, payment term, journal). An entity not listed on the settings page isn't supported yet.-Because the list is code-managed, an entity that isn't in `customFieldTable` can't take custom fields. If the entity you want isn't listed on the settings page, it isn't supported yet.+## How values save, and where they reach-## How fields save on a form+Custom inputs render below the built-in fields on the record's form and save into a single `customFields` JSON column that every core table carries — no schema change per field. That column is exposed on the API like any other: readable and filterable on the entity's endpoint, with the caveat that its keys are field IDs, not display names, so pair an API read with the definitions from the settings catalog.-Every entity form that supports custom fields drops in the shared `<CustomFormFields table="…" />` component (`apps/erp/app/components/Form/CustomFormFields.tsx`), passing its own table name. The component reads the company's field definitions and renders each one below the built-in fields.--The values don't get their own columns. They serialize into a single `customFields` JSONB column on the record — the same extensibility column every core table carries. On submit, the route action calls `setCustomFields(formData)` (`apps/erp/app/utils/form.ts`), which collects the custom inputs (each named with a `custom-` prefix) and writes them into that JSONB blob. `getCustomFields` reverses it to repopulate the form on edit.--<Callout type="note" title="Required custom fields are validated client-side">-A required custom field is enforced by an additional validator the form registers at runtime (`CustomFormFields.tsx:44`), separate from the entity's own zod schema — so requiredness lives with the field definition, not the base form.+<Callout type="warn" title="CSV import and export skip custom fields">+The CSV flows map built-in fields only; neither import nor the table download touches the `customFields` column. Populate custom fields on the form or through the API; see [import and export](/docs/reference/import-export) for what CSV does cover.</Callout>-## CSV import and export--Custom fields **do not participate in CSV import or export**. The `import-csv` edge function maps CSV columns to the entity's built-in fields only; it has no path for the `customFields` JSONB (`packages/database/supabase/functions/import-csv/index.ts`). Likewise, the table download does not emit custom-field columns. Import and export cover the base schema — populate custom fields on the record's form, or through the API. See [Import and export](/docs/reference/import-export) for what the CSV flow does cover.--## API access--The `customFields` JSONB column is exposed on the API. Because it's a real column on each core table, PostgREST surfaces it as a readable and filterable field on the entity's endpoint — the swagger schema references `rowFilter.<table>.customFields` for the tables that carry it (`packages/database/src/swagger-docs-schema.ts`). Reading a record returns the whole `customFields` object; the keys inside are the field IDs, not the display names, so pair an API read with the field definitions from the settings catalog to map IDs back to labels.-<AgentContext>-## Troubleshooting+## Internals and troubleshooting-Where the custom-field form and the import/API paths trip people up.+Definitions live in the `customField` table (`20240311021818_custom-fields.sql:21`); the form validator is `customFieldValidator` (`settings.models.ts:109`). The eligible-entity catalog is `customFieldTable`, seeded from `20240511125727_seed_custom_fields.sql` onward; the settings page renders it in `CustomFieldsTable.tsx:32`. Forms drop in the shared `<CustomFormFields table="…" />` (`components/Form/CustomFormFields.tsx`; rendering switch at `:75`), inputs are named with a `custom-` prefix, and route actions collect them via `setCustomFields(formData)` / repopulate via `getCustomFields` (`utils/form.ts`). The nine types are the `DataType` enum (`modules/shared/types.ts:83`). Swagger exposes `rowFilter.<table>.customFields`.-### "Required" (on a custom field that won't submit)-A required custom field is empty. Requiredness isn't in the entity's own schema — it's enforced by a runtime validator the form registers per table (`CustomFormFields.tsx:44`). Fill the field, or clear its **Required** flag in **Settings → Custom Fields**. Note **Boolean** fields are never treated as required, even with the flag on (`CustomFormFields.tsx:31`) — a Boolean that "must be filled" will never block a save.+### "Required" on a custom field that won't submit+Requiredness is enforced by a runtime validator the form registers per table (`CustomFormFields.tsx:44`), separate from the entity's zod schema. Fill the field or clear its Required flag. Boolean fields are never treated as required, even with the flag on (`CustomFormFields.tsx:31`).### List custom field rejected on save-A **List**-type field saved with no options, an empty option, or no listOptions at all fails the validator's refine (`settings.models.ts:121-131`). Give the List at least one non-empty choice under **List Options** before saving.+A List field with no options or an empty option fails the validator's refine (`settings.models.ts:121-131`). Give it at least one non-empty choice.-### The Data Type dropdown is disabled when editing a field-Not a bug. The data type is locked once the field is saved — the form sets `isReadOnly` on the Data Type select while editing and shows "Data type cannot be changed" (`CustomFieldForm.tsx:110-116`). Existing values are stored as-is with no in-place conversion, so to switch (e.g. Text → Numeric) you delete the field and re-create it, then migrate the values.+### The Data Type dropdown is disabled when editing+By design: the form sets `isReadOnly` on the type select and shows "Data type cannot be changed" (`CustomFieldForm.tsx:110-116`). Delete and re-create to switch types.-### A custom field's values aren't in my CSV import or export-Expected. Custom fields don't participate in CSV import or export — the `import-csv` edge function maps only built-in fields and the table download omits the `customFields` JSONB. Populate custom fields on the record's form or through the API.+### Custom-field values missing from CSV import/export+Expected — the `import-csv` edge function maps only built-in fields and the download omits the JSONB. Use the form or the API.### The entity I want has no Custom Fields row-Only entities in the code-managed `customFieldTable` catalog support custom fields. If an entity isn't listed on **Settings → Custom Fields**, it isn't eligible yet — there's no way to add it from the UI.+Only entities in the code-managed `customFieldTable` catalog are eligible; there's no way to add one from the UI.</AgentContext>diff --git a/docs/content/docs/reference/customer-portal.mdx b/docs/content/docs/reference/customer-portal.mdxnew file mode 100644index 0000000000..7719b4f494--- /dev/null+++ b/docs/content/docs/reference/customer-portal.mdx@@ -0,0 +1,35 @@+---+title: Customer portal+description: A standing, read-only link where a customer watches their open orders and shop-floor progress, no Carbon account needed.+plan: Business+---++The customer portal is a **standing, read-only window** into one customer's work. Where a [digital quote](/docs/reference/quotes#digital-quotes) closes a deal, the portal is what the buyer watches afterward: their sales order lines with status, the buyer and engineer contacts, order and due dates, part number and revision, quantity complete, quantity shipped, and per-operation job progress. There are no forms — the customer can look, not act.++## Creating a portal++<Screenshot label="Sales → Portals: the portal list with per-row URL copy control and the new-portal drawer with the customer picker" caption="One portal per customer, each with its own private URL." />++Open **Sales → Portals** and create a portal for the customer. Each row carries the portal's private URL with a copy control; send that link to your customer contact. The link needs no login, so whoever holds the URL can open it — treat it like a password and send it only to the right person.++<Callout type="note" title="One portal, one customer">+A portal is scoped to a single customer record: it lists that customer's orders and nothing else. Files attached to their job operations can be downloaded from the portal, limited to the customer's own jobs and rate-limited per visitor.+</Callout>++## Related++<Cards>+ <Card title="Digital quotes" href="/docs/reference/quotes#digital-quotes">The customer-facing bookend before the order: accept or reject a sent quote.</Card>+ <Card title="Sales orders" href="/docs/reference/sales-orders">The orders and statuses the portal reflects.</Card>+ <Card title="External sharing" href="/docs/reference/sharing">How Carbon's private links work across quotes, supplier requests, and SCARs.</Card>+</Cards>++<AgentContext>+## Troubleshooting++### Why does the customer portal link show "Not found" / a 404?+The customer portal is gated behind the `CUSTOMER_PORTALS` plan feature (Business plan). A company without it gets a 404 on the portal URL (and a 403 on file downloads). Upgrade the plan to enable the portal.++### Why did downloads from the portal start failing (HTTP 429)?+File downloads on the portal are rate-limited to ten per minute per IP. Wait a minute and retry; the limit is per requesting IP address, not per file.+</AgentContext>diff --git a/docs/content/docs/reference/inspections.mdx b/docs/content/docs/reference/inspections.mdxindex d7a7164e9f..4184edf958 100644--- a/docs/content/docs/reference/inspections.mdx+++ b/docs/content/docs/reference/inspections.mdx@@ -11,7 +11,7 @@ This page is the deep dive. The [quality overview](/docs/reference/quality) hasInspection is **lot-based**: one inspection per received line (the `receiptLineId` is unique, so a line can't spawn two lots). The lot carries a snapshot of the resolved plan — sample size, acceptance number, rejection number, the standard, the code letter — frozen at receipt so later plan edits never rewrite history.-<StatusFlow>+<StatusFlow entity="inspection"><Status name="Pending">The lot exists but no samples are recorded yet. Its tracked entities were posted **On Hold** at receipt, not Available.</Status><Status name="In Progress">At least one sample has been inspected. The inspector is working through the sample size, recording each unit as Passed or Failed.</Status><Status name="Passed" accent>The lot was **accepted** on disposition. Un-sampled entities are released to Available; sampled passes stay Available, sampled failures stay Rejected.</Status>diff --git a/docs/content/docs/reference/intercompany.mdx b/docs/content/docs/reference/intercompany.mdxindex 368bc9c351..995763f234 100644--- a/docs/content/docs/reference/intercompany.mdx+++ b/docs/content/docs/reference/intercompany.mdx@@ -34,7 +34,7 @@ The source and target are picked from the group's active companies, and **eliminEvery intercompany transaction carries a **status**. It starts life at **"Unmatched"**, is paired to its counterpart by matching, and is retired by elimination.-<StatusFlow>+<StatusFlow entity="intercompanyTransaction"><Status name="Unmatched">The transaction has been created and posted on its source company, but Carbon has not yet found the mirror-image transaction on the other company. This is the default on creation.</Status><Status name="Matched" accent>Matching found the counterpart: a transaction in the reverse direction (its source is this one's target, and vice versa) for the **same amount** in the same group. Both sides flip to Matched together and each records the other's journal line.</Status><Status name="Eliminated" terminal>Elimination has generated the reversing journal that cancels the pair for consolidation. The transaction is retired and stops counting toward the intercompany balance.</Status>diff --git a/docs/content/docs/reference/inventory-count.mdx b/docs/content/docs/reference/inventory-count.mdxindex 3c507ee3ff..0f9dad62b3 100644--- a/docs/content/docs/reference/inventory-count.mdx+++ b/docs/content/docs/reference/inventory-count.mdx@@ -9,7 +9,7 @@ An inventory count freezes what Carbon thinks is on hand, sends someone to countA count moves through three statuses in order. Posting is atomic, so a count is never left half-applied.-<StatusFlow>+<StatusFlow entity="inventoryCount"><Status name="Draft">The count is being set up and counted. Carbon has snapshotted on-hand into the lines, and counters enter what they physically find. Lines can still be regenerated from scratch while the count is Draft.</Status>diff --git a/docs/content/docs/reference/issues.mdx b/docs/content/docs/reference/issues.mdxindex de8aa97a23..379d07b4ba 100644--- a/docs/content/docs/reference/issues.mdx+++ b/docs/content/docs/reference/issues.mdx@@ -11,7 +11,7 @@ An issue opens several ways: by hand from the issues list, from the shop floor iA `nonConformanceStatus` has three values. A new issue defaults to **"Registered"**; **"Closed"** is terminal and locks the record.-<StatusFlow>+<StatusFlow entity="issue"><Status name="Registered">The issue exists but no one has picked it up. The DB default for a new `nonConformance`. Editable.</Status><Status name="In Progress" accent>Someone is working it. An issue auto-advances here the first time a user types into a task note while still Registered, or when you click **"Start"** in the header.</Status><Status name="Closed" terminal>Resolved and locked. `isIssueLocked(status)` is true only for Closed, which blocks edits to the issue and its task assignments. Closing clears the assignee and stamps `closeDate`. **"Reopen"** sends it back to Registered.</Status>@@ -67,6 +67,8 @@ The `issues` view computes a **containment status** from the action tasks. It reAction tasks run their own small lifecycle: **"Pending"** → **"In Progress"** → **"Completed"**, with **"Skipped"** as an off-path exit. Tasks start Pending and do *not* auto-start. Completing a task stamps its completed date. A completed or skipped task can be reopened back to Pending. Tasks can be reordered, given due dates, and tied to specific processes, and a supplier-facing action task can be shared externally as a **SCAR** (Supplier Corrective Action Request) report.+The SCAR is a private, login-free link the supplier opens to respond. They see the non-conformance details, the current status, and the action tasks assigned to them — not the rest of the issue: dispositions, approvals, and closure stay internal. For each task the supplier can update the status and write notes in an editor that auto-saves as they type; entering notes on a **"Pending"** task promotes it to **"In Progress"** automatically. Once the issue is **"Closed"**, the SCAR locks and the supplier can no longer make changes. Whoever holds the URL can open it, so send it only to the supplier contact.+## Approvals and the Material Review BoardBeyond actions, an issue can require **approvals**. The only approval requirement Carbon ships is <Term id="mrb">MRB (Material Review Board)</Term>. Adding it materializes an approval task and, when MRB is newly required, seeds two **reviewers** with titles **"Engineering"** and **"Quality"**. Remove MRB and those seeded reviewers are cleared; reviewers you added by hand are left alone. A reviewer is just a title on the issue. You manage the list inline on the issue.@@ -144,4 +146,7 @@ When an issue requires **MRB** approval, an approval task and reviewer rows (Eng### Permission-gated: you can't create, edit, close, or delete an issueListing issues needs `quality` **view**; creating needs `quality` **create**; editing, closing, splitting, and moving entities all need `quality` **update**; deleting needs `quality` **delete**. If an action is blocked, your role is missing the corresponding quality permission (Settings → Roles).++### "Issue has been closed already. Unable to make changes" (SCAR)+A supplier tried to update a SCAR action task after the parent issue was set to `Closed`. Once the issue is Closed the SCAR is read-only. Reopen the issue internally if further supplier action is needed.</AgentContext>diff --git a/docs/content/docs/reference/meta.json b/docs/content/docs/reference/meta.jsonindex 6b556d5df1..2469b361e9 100644--- a/docs/content/docs/reference/meta.json+++ b/docs/content/docs/reference/meta.json@@ -20,6 +20,7 @@"quotes","pricing","sales-orders",+ "customer-portal","approvals","purchase-orders","supplier-quotes",@@ -58,6 +59,7 @@"training","permissions","two-factor",+ "single-sign-on","account","onboarding","sharing",diff --git a/docs/content/docs/reference/notifications.mdx b/docs/content/docs/reference/notifications.mdxindex f237deca37..96ecf5a561 100644--- a/docs/content/docs/reference/notifications.mdx+++ b/docs/content/docs/reference/notifications.mdx@@ -3,174 +3,90 @@ title: Notificationsdescription: Assignments, approvals, expirations, and reminders reach the right people over in-app, email, and Slack, with per-user channel opt-outs by topic.----A <Term>notification</Term> tells one person that something needs their attention: a job was assigned to them, an-approval is waiting, a gauge's calibration lapsed, a quote expired. Carbon raises these from across the-system and fans each one out to up to three channels: the **in-app inbox** (the bell in the top bar),-**email**, and **Slack**. In-app is always on; email and Slack are extras a user can mute per topic.--Say a purchasing manager assigns a purchase order to a buyer. The buyer gets a row in their in-app inbox-immediately, an email if the company has email notifications, and a Slack DM if the company connected Slack-and the buyer hasn't muted purchasing on Slack. If that buyer sent the assignment to themselves, they get-nothing — Carbon never notifies you about your own action.+A <Term>notification</Term> tells one person that something needs their attention: a job was assigned to them, an approval is waiting, a gauge's calibration lapsed. Carbon fans each one out to up to three channels: the **in-app inbox** (the bell in the top bar), **email**, and **Slack**. In-app is always on; email and Slack are extras a user can mute per topic. One rule holds everywhere: Carbon never notifies you about your own action.## What raises a notification-Every notification starts as a `carbon/notify` event with a specific type. The type-falls into one of three shapes:-<FieldTable>- <Field name="Assignments">Someone is put on a record: a job, job operation, sales order, purchase order, RFQ, purchase invoice, supplier quote, issue, risk, procedure, picking list, stock transfer, maintenance dispatch, or training. The assignee is the recipient.</Field>- <Field name="State changes & responses">A record's state moved in a way someone should know about: an approval was **requested**, **approved**, or **rejected**; a job **completed**; a change notice entered a new stage; a quote **expired**; a customer or supplier responded to a digital quote or supplier quote.</Field>- <Field name="Expirations & reminders">Time-driven, raised by scheduled jobs rather than a user action: a **gauge calibration expired**, a **maintenance dispatch** was auto-created for a work center, or a weekly **training reminder** rolls up a person's outstanding trainings.</Field>- <Field name="Workflow">A [workflow](/docs/reference/workflows) reached a **"Notify someone"** step. You write the subject and message yourself, and address it to a user or a group; it lands under the **General** topic with a **View details** button pointing at whichever record the step named.</Field>+ <Field name="Assignments">Someone is put on a record (job, order, RFQ, invoice, issue, risk, procedure, picking list, stock transfer, dispatch, training). The assignee is the recipient.</Field>+ <Field name="State changes & responses">An approval was **requested**, **approved**, or **rejected**; a job **completed**; a change notice entered a new stage; a quote **expired**; a customer or supplier responded to a digital or supplier quote.</Field>+ <Field name="Expirations & reminders">Time-driven, raised by scheduled jobs: a **gauge calibration expired**, a **maintenance dispatch** was auto-created, or the weekly **training reminder** rolls up a person's outstanding trainings.</Field>+ <Field name="Workflow">A [workflow](/docs/reference/workflows) reached a **"Notify someone"** step, the only path where you compose the wording yourself. Lands under the **General** topic.</Field></FieldTable>-The full set of event types lives in `NotificationEvent` (`packages/notifications/src/index.ts:7`). Adding a-notification anywhere in Carbon means dispatching one of these — the workflow step is the only path that-lets you compose the wording yourself.-<Callout type="note">-Notifications are informational, never an approval step. Marking one read doesn't change any record, and there's no-"acknowledge" or "accept" on a notification itself. The action lives on the underlying document (approve the-PO, complete the job) — the notification just points you there.+Notifications are informational, never an approval step. Marking one read changes no record; the action lives on the underlying document, and the notification just points you there.</Callout>-## Topics--Every event maps to exactly one **topic** — a coarse bucket used for grouping the inbox and for the per-user-channel opt-outs. There are twelve, and the mapping is fixed in code-(`getNotificationTopic`, `packages/notifications/src/index.ts:114`):--| Topic | Example events |-| --- | --- |-| Approval | Approval requested / approved / rejected |-| Job | Job assignment, job operation assignment, job operation message, job completed |-| Sales | Sales order assignment, sales RFQ assignment, RFQ ready |-| Quote | Quote assignment, quote expired, digital quote response, supplier quote assignment / response |-| Purchasing | Purchase order, purchasing RFQ, and purchase invoice assignments |-| Inventory | Picking list and stock transfer assignments |-| Quality | Issue assignment, risk assignment |-| Maintenance | Maintenance dispatch (assigned or created), gauge calibration expired |-| Training | Training and procedure assignments, resource training, training reminder |-| Suggestion | Suggestion response |-| Items | Change notice started / in implementation / complete |-| General | Workflow notifications, and anything without a specific bucket |+## Topics and channels-<Callout type="warn">-The topic string is **stored** on every notification (`notification.topic`). It's what a user's opt-out row-matches on, so a topic is not just a label — it's the grouping key for muting. Eleven of the twelve topics are-user-facing on the settings page; only **Items** is not offered as a toggle.-</Callout>+Every event maps to exactly one **topic**, the grouping key for the inbox and for muting: Approval, Job, Sales, Quote, Purchasing, Inventory, Quality, Maintenance, Training, Suggestion, Items, and General. Eleven are user-facing on the settings page; only **Items** has no toggle.-## Channels--A single notification can go to three destinations, defined in `NotificationDestination`-(`packages/notifications/src/index.ts:108`):+The channels differ in what they require:<FieldTable>- <Field name="In-app">The bell in the top bar. **Always written** for every recipient, on every event. It cannot be turned off — the fan-out adds it regardless of what the caller requests (`notify.ts:210`).</Field>- <Field name="Email">A per-notification email with a heading, a short description, and a **View** button linking to the record. Sent only when the company's plan includes email notifications.</Field>- <Field name="Slack">A direct message in the connected Slack workspace. Sent only when the company has an active Slack integration and the recipient has a matching Slack account.</Field>+ <Field name="In-app">The bell in the top bar. **Always written**, for every recipient, on every event — it cannot be turned off.</Field>+ <Field name="Email">A per-notification email with a **View** button. Sent only when the company's plan includes email notifications.</Field>+ <Field name="Slack">A DM in the connected workspace. Needs an active Slack integration *and* a matching Slack account for the recipient.</Field></FieldTable>-Each event has default channels (most assignments default to email + Slack), and the caller can override them-per dispatch. In-app is the constant: it's the one channel a user can never silence and the one the top bar-always reflects.-<Callout type="warn">-Email is **plan-gated.** The fan-out checks the `EMAIL_NOTIFICATIONS` plan feature and skips the email-channel entirely for companies without it (`notify.ts:509`). Slack has no plan gate — it only needs the-integration connected. See [licensing](/docs/platform/licensing) for what each plan includes.+Email is **plan-gated**: companies without the `EMAIL_NOTIFICATIONS` plan feature skip the email channel entirely, regardless of the per-user switch. Slack has no plan gate — it only needs the integration. See [licensing](/docs/platform/licensing).</Callout>-## Per-user preferences+## Muting a topic-Each user controls their own email and Slack delivery under **Account → Notifications**. The settings page is-a grid: one row per user-facing topic, a column per channel, a switch in each cell. In-app has no switch —-it's not something a user opts out of.+Each user controls their own email and Slack delivery under **Account → Notifications**: a grid with one row per topic, a column per channel, a switch in each cell. In-app has no switch.-Preferences are stored as **opt-out** rows, one per `(user, company, channel, topic)`-(`notificationPreference` table). The default is **on**: no row means the channel is enabled for that topic.-Flipping a switch off writes a row with `enabled = false`, which mutes that one topic on that one channel.-Flipping it back on removes the mute. The fan-out reads these rows and drops muted recipients from the email-and Slack lists before sending (`notify.ts:302`); the in-app row is never filtered.--<Callout type="info">-Muting is **per topic and per channel**, scoped to the current company. Muting Purchasing on Slack still-leaves you Purchasing emails, still leaves you Slack DMs for Sales, and doesn't carry over to another company-you belong to. And whatever you mute, the in-app inbox still gets every notification.-</Callout>+<Screenshot label="Account → Notifications preferences grid: topic rows, Email and Slack columns, switches per cell" caption="Muting is per topic, per channel, per company. The in-app inbox always gets everything." />-The Slack column only appears when the company has Slack connected. The email column always shows; if the-company's plan doesn't include email notifications, the page notes that email won't be delivered even with the-switch on.+The default is **on**; flipping a switch off mutes that one topic on that one channel, scoped to the current company. Muting Purchasing on Slack still leaves Purchasing emails, still leaves Slack DMs for Sales, and doesn't carry to another company you belong to. The Slack column appears only when Slack is connected; the email column always shows, with a note when the plan won't deliver it.## Who receives an expiration or reminder-Assignments and responses have an obvious recipient — the assignee, or the person who raised the request. The-time-driven events don't, so each resolves its own audience:--<FieldTable>- <Field name="Gauge calibration expired">Goes to a company-configured list of users — the `gaugeCalibrationExpiredNotificationGroup` array on company settings — not to a role or a single owner. Set it under gauge/calibration settings so the right people hear when a gauge lapses.</Field>- <Field name="Maintenance dispatch created">Goes to every employee attached to the dispatch's work center. Auto-created dispatches notify whoever staffs that station.</Field>- <Field name="Training reminder">A weekly digest per person, rolling that individual's outstanding trainings into one notification rather than one per course.</Field>-</FieldTable>--<Callout type="note">-There's no general "notification group" entity. Only gauge-calibration expiry uses a configured user list;-everything else derives recipients from the record itself — the assignee, the approvers, the work center's-staff, or the person with outstanding trainings.-</Callout>+Assignments have an obvious recipient. The time-driven events resolve their own audience: a lapsed gauge calibration notifies a company-configured user list (set under [calibration](/docs/reference/calibration) settings), an auto-created dispatch notifies every employee on that work center, and the training reminder is a weekly per-person digest. There is no general "notification group" entity — only gauge-calibration expiry uses a configured list; everything else derives recipients from the record itself.## The inbox-The bell in the top bar opens the in-app inbox. It shows recent notifications newest-first with an unread-count, each row carrying an icon for its event, a short description, who it came from, and a timestamp. Click a-row's link to jump to the record; mark a row read with its **mark read** button.--<Callout type="info">-Recurring reminders don't nag forever. A repeating email notification for the same document stops after a few-successful deliveries (`MAX_NOTIFICATION_DELIVERIES`, `packages/notifications/src/index.ts:90`) — currently-only the weekly training reminder is recurring. The in-app row still stands until you read it.-</Callout>+The bell opens the inbox: recent notifications newest-first with an unread count, each row carrying an icon, a short description, who it came from, and a timestamp. Click through to the record, or mark a row read.## Related<Cards><Card title="Approvals" href="/docs/reference/approvals">- Approval requested, approved, and rejected each raise a notification to the approvers or the requester.+ Requested, approved, and rejected each notify the approvers or the requester.</Card><Card title="Calibration" href="/docs/reference/calibration">- A lapsed gauge calibration notifies the company's configured calibration group.+ A lapsed calibration notifies the configured group.</Card>- <Card title="Maintenance" href="/docs/reference/maintenance">- Auto-created dispatches notify the work center's staff.+ <Card title="Workflows" href="/docs/reference/workflows">+ Compose your own notification from a "Notify someone" step.</Card><Card title="Webhooks" href="/docs/building/webhooks">- For machine-to-machine events — an HTTP POST on record insert, update, or delete — rather than a person's inbox.+ For machine-to-machine events rather than a person's inbox.</Card></Cards><AgentContext>-## Troubleshooting+## Internals and troubleshooting-Delivery questions are almost always a missing precondition on the email or Slack channel — the in-app inbox always works.+Every notification starts as a `carbon/notify` event with a specific type; the full set is `NotificationEvent` (`packages/notifications/src/index.ts:7`), destinations are `NotificationDestination` (`index.ts:108`), and the fixed event→topic mapping is `getNotificationTopic` (`index.ts:114`). The topic string is stored on every row (`notification.topic`) and is what a user's opt-out row matches on. Preferences are opt-out rows, one per `(user, company, channel, topic)` in `notificationPreference`; no row means enabled. The fan-out always adds the in-app destination (`notify.ts:210`), drops muted recipients from email/Slack lists (`notify.ts:302`), and skips email entirely without the `EMAIL_NOTIFICATIONS` plan feature (`notify.ts:509`). Most assignments default to email + Slack; callers can override channels per dispatch.### Why am I not getting email notifications?-Email is **plan-gated.** The fan-out checks the `EMAIL_NOTIFICATIONS` plan feature and skips the email channel entirely for companies without it — regardless of the per-user switch. Check the company's plan first. If the plan includes it, then confirm the topic isn't muted for email (a `notificationPreference` row with `enabled = false` for that topic/channel) and that the specific event actually defaults to the email channel.+Email is plan-gated — check the company's plan first. Then confirm the topic isn't muted for email and that the specific event defaults to the email channel.### Why am I not getting Slack DMs?-Slack has no plan gate, but it needs two things: the company must have an **active Slack integration** connected, and *you* must have a **matching Slack account** in that workspace. Users without a matching Slack account are silently skipped. Also confirm you haven't muted the topic on Slack under Account → Notifications.+Slack needs an active integration and a matching Slack account for the recipient; users without one are silently skipped. Also check the topic's Slack mute.-### I muted a topic but I'm still getting in-app notifications-Expected — in-app is **always written** for every recipient on every event and cannot be turned off. The mute switches only affect email and Slack; the fan-out never filters the in-app row. The bell always reflects every notification.+### I muted a topic but still get in-app notifications+Expected: in-app is always written and cannot be turned off. Mutes affect only email and Slack.### I turned a channel on but it still doesn't deliver-Preferences default to **on** (no row = enabled), so flipping a switch on just removes the mute — it doesn't override the channel's own preconditions. Email still requires the `EMAIL_NOTIFICATIONS` plan; Slack still requires the integration + a matching account. The settings page notes when email won't be delivered even with the switch on because the plan doesn't include it.+On just removes the mute; it doesn't override the channel's preconditions (plan feature for email, integration + account for Slack).### I did something myself and got no notification-Carbon never notifies you about your own action — the sender is filtered out of the recipient list. If you assigned a record to yourself, that's why there's nothing in your inbox.+The sender is filtered out of the recipient list. Self-assignments notify nobody.### A recurring reminder stopped arriving-Repeating email notifications for the same document stop after a few successful deliveries (`MAX_NOTIFICATION_DELIVERIES`) — currently only the weekly training reminder is recurring. The in-app row still stands until you mark it read.+Repeating email notifications for the same document stop after a few successful deliveries (`MAX_NOTIFICATION_DELIVERIES`, `index.ts:90`); only the weekly training reminder is recurring. The in-app row stands until read.</AgentContext>diff --git a/docs/content/docs/reference/onboarding.mdx b/docs/content/docs/reference/onboarding.mdxindex 694386c221..4bca82cf23 100644--- a/docs/content/docs/reference/onboarding.mdx+++ b/docs/content/docs/reference/onboarding.mdx@@ -1,116 +1,45 @@---title: Getting started-description: The first-run setup wizard that creates your company, and the Implementation Hub that guides a new company from an empty tenant to live on Carbon.+description: The first-run setup wizard that creates your company, seeds its baseline configuration, and hands you a working tenant.----Getting started on Carbon has two distinct surfaces. The **setup wizard** runs once, right after you sign up: it creates the company record, your profile, and the address that becomes your first location, then hands you a working tenant. The **Implementation Hub** is the checklist that takes it from there — a step-by-step map from that empty tenant to your team running production on Carbon. The wizard is unavoidable; the Hub is opt-in, and a company enrolls itself.+A brand-new account has no company yet, so Carbon holds you in the setup wizard at `/onboarding` until one exists. Onboarding counts as complete when the company has a **name** and at least **one location**; those two facts are the gate, and finishing the Company step supplies both.-## The setup wizard--A brand-new account has no company yet, so Carbon holds you in `/onboarding` until one exists. The layout loader treats onboarding as complete only when the company has a **name** and at least **one location** — there is no `onboarded` boolean, the presence of those two facts is the gate (`apps/erp/app/routes/onboarding+/_layout.tsx:33-44`). Until then, every step redirects back into the wizard.--The steps run in a fixed order (`apps/erp/app/utils/path.ts:2103-2109`):+<Screenshot label="The setup wizard's Company step: name, address, base currency, and website fields" caption="The one step that creates a working tenant." /><Steps>-<Step>-**Theme.** Pick a color theme (`zinc`, `neutral`, `red`, `orange`, `yellow`, `green`, `blue`, or `violet`). This is a cosmetic choice stored in a cookie, not the database (`apps/erp/app/routes/onboarding+/theme.tsx`; validator at `apps/erp/app/modules/settings/settings.models.ts:306-311`).+**Theme.** Pick a color theme (cosmetic, stored in a cookie).</Step>-<Step>-**Your profile.** First name and last name, both required. They write to your `user` record (`apps/erp/app/routes/onboarding+/user.tsx`; validator `onboardingUserValidator` at `apps/erp/app/modules/account/account.models.ts:12-17`).+**Your profile.** First and last name, both required.</Step>-<Step>-**Company.** The substantive step. It collects the company **name**, a full address (address line 1 and 2, city, state or province, postal code, country), a **base currency**, and an optional website (`apps/erp/app/routes/onboarding+/company.tsx`; `addressValidator` at `apps/erp/app/modules/settings/settings.models.ts:95-107`). Submitting this creates the company and everything a usable tenant needs.+**Company.** The substantive step: company name, full address, base currency, optional website. Submitting creates the company and everything a usable tenant needs.</Step>-</Steps>-Two more steps appear conditionally, and only in specific circumstances (`apps/erp/app/routes/onboarding+/_layout.tsx:49-53`):--- **Industry** — shown only to internal Carbon staff accounts. It offers a [demo-data template](/docs/platform/demo-data) or a [backup](/docs/platform/backups) restore, so a seeded example company can be stood up. Regular sign-ups never see it.-- **Plan** — shown only on Carbon Cloud, the hosted version at [app.carbon.ms](https://app.carbon.ms). It routes you to Stripe checkout to pick a plan before you enter the app. Self-hosted installs skip it entirely and go straight to `/x`.+Two steps appear conditionally: **Industry** (internal Carbon staff only: offers a [demo-data template](/docs/platform/demo-data) or a [backup](/docs/platform/backups) restore) and **Plan** (Carbon Cloud only: Stripe checkout; self-hosted installs go straight to the app).<Callout type="note" title="The company step does a lot of quiet work">-Saving the company doesn't just insert one row. It also creates a **"Headquarters"** location from the address you entered (with your local timezone), links your user to the company as an employee, and seeds the tenant's baseline: chart of accounts, default posting accounts, numbering sequences, payment terms, and units of measure. This all happens under the hood via `provisionOnboardingCompany` and a background seed job (`apps/erp/app/services/onboarding.server.ts`; seed via `seedCompany` at `apps/erp/app/modules/settings/settings.service.ts:751-765`).+Saving the company also creates a **"Headquarters"** location from your address, links you as an employee, and seeds the baseline: chart of accounts, posting accounts, numbering sequences, payment terms, units of measure. Fiscal year, periods, and sequences are deliberately *not* asked for — they come pre-seeded and you tune them later under [company settings](/docs/reference/company-settings).</Callout>-### What you don't choose during onboarding--Fiscal year, accounting periods, and the numbering sequences are **not** asked for in the wizard. They come pre-seeded with sensible defaults, and you tune them afterward under [Company settings](/docs/reference/company-settings). The wizard's job is to get you into a working tenant fast, not to make you configure the whole system up front.--## The Implementation Hub--Once you're in the app, an empty tenant is still a long way from running production. The **Implementation Hub** (the "Get Started" area, at `/x/get-started`) is Carbon's structured onboarding checklist. It walks a new company through six phases from kickoff to go-live, with each phase deep-linking into the exact ERP screens you configure along the way (`apps/erp/app/routes/x+/get-started+/_layout.tsx`).--The Hub only exists for a company that has **enrolled**. Enrollment is self-serve: anyone who can update company settings can turn it on from the home-page card, no Carbon staff required (`apps/erp/app/routes/x+/get-started+/enroll.tsx:24-48`). While the Hub is active, it takes over the home page so the project stays front and center, and it emails your Admins that the Hub is ready (`apps/erp/app/routes/x+/_index.tsx:37-53`).--### The six phases--The Hub is organized around six sequential **gates** — each phase ends at exactly one milestone you sign off before moving on (`packages/onboarding/src/content/spine.ts:11-143`):--<StatusFlow>- <Status name="Discovery">Confirm how your company runs and lock the project scope. Ends at **"Scope signed"**. Paid tiers only.</Status>- <Status name="Configure" accent>Set Carbon up around your business: sites, users, suppliers, parts, BOMs, and Bill of Process. Ends at **"System configured"** — this is the phase most of your setup work lives in.</Status>- <Status name="Migrate data">Load your real data and approve a validated sample. Ends at **"Data validated"**. Paid tiers only.</Status>- <Status name="Train">Your team leads learn Carbon via the in-app guides and Academy, then bring everyone else up. Ends at **"Team trained"**.</Status>- <Status name="Acceptance">Every in-scope test passes on your configured system, with your data. Ends at **"Acceptance passed"**. Paid tiers only.</Status>- <Status name="Go-Live" terminal>Cut over, freeze the old system, and confirm you're live on Carbon. Ends at **"Live on Carbon"**.</Status>-</StatusFlow>--The **Configure** and **Acceptance** phases nest concrete "do this in Carbon" actions inside them — import your BOM, run MRP into purchase orders and jobs, serialize and sell a part. Those nested steps **auto-detect** their own completion against real tenant data (Carbon checks whether you actually have items, a job, a sales order) rather than relying on a manual tick (`packages/onboarding/src/content/spine.ts:38-131`).--### Tiers change what you see--The Hub adapts to how a company is being onboarded. There are three tiers — `self_serve`, `guided`, and `enterprise` — and self-serve enrollment defaults to `self_serve` (`apps/erp/app/routes/x+/get-started+/enroll.tsx:41`). The tier prunes the phases and pages that don't apply.--<Callout type="info" title="Self-serve is the lean path">-A self-serve company configures Carbon directly, so it skips the phases built for a Carbon-led project: **Discovery** (scoping), **Migrate data**, and **Acceptance** all fall away, along with their pages like Scope Summary, Roles, Requirements, and Data Migration. What's left is the core spine — Configure, Train, Go-Live — plus the pages every tier shares. The guided and enterprise tiers add the full commercial project structure back in (`packages/onboarding/src/content/registry.ts:8-115`).-</Callout>--### The Setup Map--The single most useful page for a hands-on operator is the **Setup Map** (in the "Configure Carbon" group). It's the first-run configuration checklist: every master, reference, and config entity a new company sets up before it starts transacting, grouped by module and labelled as it appears in that module's navigation (`packages/onboarding/src/content/setup.ts:32-436`). It covers, per module:--<FieldTable>- <Field name="Accounting">Fiscal year, accounting periods, chart of accounts, default accounts, cost centers, dimensions, payment terms, exchange rates, asset classes.</Field>- <Field name="Settings">Company identity, document templates, logos, printing, sequences, custom fields, integrations, approval rules.</Field>- <Field name="Resources">Locations, work centers, processes, training abilities, failure modes, maintenance schedules.</Field>- <Field name="People">Employees, departments, shifts, holidays, attributes, employee types, permission groups.</Field>- <Field name="Items">Units, item groups, parts, materials, tools, consumables, and the material substances, shapes, grades, and finishes.</Field>- <Field name="Sales">Customers, customer types and statuses, price lists, pricing rules, no-quote reasons.</Field>- <Field name="Purchasing">Suppliers and supplier types.</Field>- <Field name="Inventory">Storage units, storage types, storage rules, shipping methods.</Field>- <Field name="Production">Scrap reasons.</Field>-</FieldTable>--Each row deep-links straight to the screen where you configure that thing (`apps/erp/app/routes/x+/get-started+/_layout.tsx:59-118`), and its "configured" state is tracked so the Plan page and the Setup Map can never disagree about the same work. Rows tagged to a module drop out when you exclude that module, so an org that doesn't run quality or accounting doesn't see setup it will never do. The Accounting group only appears at all when accounting is enabled for the company (`apps/erp/app/routes/x+/get-started+/_layout.tsx:230-232`).-## Where to go next-The wizard gets you a tenant; the Hub gets you to production. For the settings the wizard seeds and you refine, see [Company settings](/docs/reference/company-settings). For adding the rest of your team, their access, and permission groups, see [People](/docs/reference/people). And for the end-to-end story of how work actually flows through Carbon once you're set up, the [guides](/guides) walk it start to finish.+The wizard's job is a working tenant, not a configured one. Refine the seeded settings under [company settings](/docs/reference/company-settings), set up your document numbering under [sequences](/docs/reference/sequences), add your team under [people](/docs/reference/people), and read the [guides](/guides) for how work flows through Carbon once you're set up.<AgentContext>-## Troubleshooting+## Internals and troubleshooting-Why onboarding won't let you into the app, and which steps show up — these are preconditions, not error messages.+The completion gate is the layout loader (`routes/onboarding+/_layout.tsx:33-44`); step order is `utils/path.ts:2103-2109`; conditional steps at `_layout.tsx:49-53`. Theme validator `settings.models.ts:306-311`; profile `onboardingUserValidator` (`account.models.ts:12-17`); company `addressValidator` (`settings.models.ts:95-107`). Provisioning runs `provisionOnboardingCompany` (`services/onboarding.server.ts`) with the seed via `seedCompany` (`settings.service.ts:751-765`).### Stuck in the setup wizard / keeps redirecting to /onboarding-Onboarding is complete only when the company has a **name** and at least **one location**. There is no `onboarded` flag — the presence of those two facts is the gate. Until both exist, every step redirects back into the wizard. Finishing the **Company** step supplies both at once (it creates the company and a "Headquarters" location from the address you enter), so complete that step to get in.+The company lacks a name or a location — there is no `onboarded` flag. Complete the Company step; it creates both at once.### The Industry step isn't showing-It appears only for internal Carbon staff accounts. It offers demo-data templates and backup restore to stand up a seeded example company; regular sign-ups never see it, and its absence is expected.+Internal Carbon staff accounts only. Its absence for regular sign-ups is expected.### The Plan step isn't showing-The plan / Stripe-checkout step appears only on Carbon Cloud (the hosted version at app.carbon.ms). Self-hosted installs skip it entirely and go straight into the app at `/x`.--### Can't enroll in the Implementation Hub-Enrollment is self-serve but gated: only someone who **can update company settings** can turn the Hub on from the home-page card. Without that permission, the enroll control won't work — have an admin enroll, or grant Settings update access.--### The Accounting group is missing from the Setup Map-The Setup Map's Accounting group only appears when accounting is enabled for the company. Rows tagged to a module also drop out when that module is excluded, so an org that doesn't run a module won't see setup it will never do.--### Some Hub phases are missing (Discovery, Migrate data, Acceptance)-The Hub prunes phases by tier. Self-serve enrollment defaults to the `self_serve` tier, which skips the Carbon-led phases — **Discovery**, **Migrate data**, and **Acceptance** — leaving Configure, Train, and Go-Live. The `guided` and `enterprise` tiers add the full project structure back.+Cloud-only (app.carbon.ms). Self-hosted installs skip it and land at `/x`.</AgentContext>diff --git a/docs/content/docs/reference/payments.mdx b/docs/content/docs/reference/payments.mdxindex c769cb1cbe..9d45b982c6 100644--- a/docs/content/docs/reference/payments.mdx+++ b/docs/content/docs/reference/payments.mdx@@ -62,7 +62,7 @@ Settlements are **staged while their source is Draft** and only go live when itPayments and memos share one lifecycle. Draft is freely editable; posting books the GL entries and freezes the applications; voiding reverses. Voided is terminal.-<StatusFlow>+<StatusFlow entity="payment"><Status name="Draft">The document is being composed. You edit the amount, party, and staged applications, and you can delete it outright. Nothing has hit the ledger.</Status><Status name="Posted" accent>The GL journal is written and the settlements go live. Applications are frozen — to change how a posted payment lands, void it and re-enter it.</Status><Status name="Voided" terminal>A reversing (mirror-image) journal is written and the document is closed. It can't be edited or reused.</Status>diff --git a/docs/content/docs/reference/people.mdx b/docs/content/docs/reference/people.mdxindex 3e4e3265c9..61385b54da 100644--- a/docs/content/docs/reference/people.mdx+++ b/docs/content/docs/reference/people.mdx@@ -94,7 +94,7 @@ A **time card** is a clock-in / clock-out record for an employee. Time trackingEach entry captures the employee, a clock-in time, an optional clock-out time, and a note. An entry with no clock-out is still open — Carbon derives its **Status** from that:-<StatusFlow>+<StatusFlow entity="timecard"><Status name="Active" accent>Clocked in with no clock-out yet — the employee is on the clock.</Status><Status name="Complete" terminal>Clocked out. The entry is closed and its duration is fixed.</Status></StatusFlow>diff --git a/docs/content/docs/reference/period-close.mdx b/docs/content/docs/reference/period-close.mdxindex 8fc8900d00..dc0e8d2ed0 100644--- a/docs/content/docs/reference/period-close.mdx+++ b/docs/content/docs/reference/period-close.mdx@@ -11,7 +11,7 @@ The whole surface is gated on **accounting enabled** (`companySettings.accountinA period carries a **close status** (`periodCloseStatus`) that moves in one direction, then back only by explicit reopen. This is a separate axis from the legacy `Active`/`Inactive` flag, which just marks the current period for lazy auto-creation.-<StatusFlow>+<StatusFlow entity="accountingPeriod"><Status name="Open">Postings land freely. Operational documents (receipts, shipments, invoices, payments) and journals both post by their date.</Status><Status name="Locked" accent>Operational postings are refused; accounting adjustments can still be posted. The staging state you review in before finalizing.</Status><Status name="Closed" terminal>The month is final. Nothing enters, leaves, or changes. Balances are snapshotted. Reopen to post again.</Status>diff --git a/docs/content/docs/reference/permissions.mdx b/docs/content/docs/reference/permissions.mdxindex 64bb997397..dd36917341 100644--- a/docs/content/docs/reference/permissions.mdx+++ b/docs/content/docs/reference/permissions.mdx@@ -70,7 +70,7 @@ You don't create passwords for people. You **invite** them by email, and they seBecause an invite is a real record, an employee has a clear **status** derived from it and their account (the `employees` view, `packages/database/supabase/migrations/20260529160000_employees-view-status.sql:16`):-<StatusFlow>+<StatusFlow entity="employeeAccount"><Status name="Invited">The invite has been sent but not yet accepted. The person can't sign in until they follow the link.</Status><Status name="Active" accent>The invite was accepted and the account is live. This is the normal working state.</Status><Status name="Inactive" terminal>The account has been deactivated, or the invite was revoked before acceptance. No access.</Status>diff --git a/docs/content/docs/reference/picking.mdx b/docs/content/docs/reference/picking.mdxindex 48e0d284f1..7138afdc22 100644--- a/docs/content/docs/reference/picking.mdx+++ b/docs/content/docs/reference/picking.mdx@@ -19,7 +19,7 @@ A material needs picking only when its lineside bin doesn't already cover the opA picking list header moves through four states. It starts at **"Draft"**, flips to **"In Progress"** on the first pick, and reaches **"Completed"** when every line is resolved. **"Cancelled"** is a terminal off-ramp.-<StatusFlow>+<StatusFlow entity="pickingList"><Status name="Draft">Generated and assigned, nothing picked yet.</Status><Status name="In Progress">At least one line has been picked, or the list was reopened with prior progress.</Status><Status name="Completed" accent>Every line is fully picked or Cancelled. The list locks.</Status>@@ -30,7 +30,7 @@ The header status is *derived from its lines* by a database trigger, not set byEach line carries its own status:-<StatusFlow>+<StatusFlow entity="pickingListLine"><Status name="Pending">Not yet picked. Still outstanding work.</Status><Status name="Picked" accent>The pick quantity has been moved to the lineside bin.</Status><Status name="Short">Picked less than required, and the shortage is acknowledged.</Status>diff --git a/docs/content/docs/reference/quality-documents.mdx b/docs/content/docs/reference/quality-documents.mdxindex 42df2737c7..ffdcd2636d 100644--- a/docs/content/docs/reference/quality-documents.mdx+++ b/docs/content/docs/reference/quality-documents.mdx@@ -11,7 +11,7 @@ The point of controlling it is auditability: you never overwrite a live procedurA quality document has exactly three states, and only one version of a given document is ever **Active** at a time.-<StatusFlow>+<StatusFlow entity="qualityDocument"><Status name="Draft">The starting state. You edit the name, the work-instruction body, and the steps freely. Not yet authoritative.</Status><Status name="Active" accent>The published, in-force revision. Publishing it archives any other Active version with the same name automatically.</Status><Status name="Archived">A retired revision. Superseded by a newer Active version, or manually pulled. Still readable; can be reactivated.</Status>diff --git a/docs/content/docs/reference/quotes.mdx b/docs/content/docs/reference/quotes.mdxindex 39b2c02282..ae02d0547b 100644--- a/docs/content/docs/reference/quotes.mdx+++ b/docs/content/docs/reference/quotes.mdx@@ -33,12 +33,16 @@ Each line tracks its own progress too: **Not Started**, **In Progress**, **Compl## Digital quotes-A **Sent** quote can be shared with the customer over a private link, no login. From it the customer **accepts**, optionally entering their PO number, and the quote converts straight to a sales order; or they **reject**, and it moves to **Lost**. Internal notes are stripped before anything reaches the customer.+A **Sent** quote can be shared with the customer over a private link, no login — the URL is in the quote's share dialog. The page shows the quote lines with images, the quantity-break pricing, the totals (subtotal, discount, tax, shipping), the shipping method and payment term, and any external notes. Internal notes are stripped before anything renders, so the customer never sees your working comments.-<Callout type="note">-Digital acceptance is gated: the quote must be **Sent** and the company must have digital quotes enabled. A companion customer portal then shows the buyer live order and job status as the work proceeds.+From that page the customer **accepts** — entering their name and email, picking the quantity break per line, and optionally attaching a purchase-order PDF — and the quote converts straight to a sales order, stamping who accepted it. Or they **reject**, again with a name and email, and the quote moves to **Lost**.++<Callout type="note" title="The link is the only credential">+There is no account or password behind the link — whoever holds the URL can open the quote. Send it to the right person and don't post it anywhere public. Both actions are gated on status: only a **Sent** quote can be answered, and once the `expirationDate` passes the page shows an expired state and the buttons are gone.</Callout>+A companion [customer portal](/docs/reference/customer-portal) then shows the buyer live order and job status as the work proceeds.+## Becoming an orderConverting a quote, internally or by the customer accepting, builds a sales order from its lines at the negotiated price. It opens at **To Ship and Invoice** when a line ships physical goods, or **To Invoice** for a service-only order with nothing to ship. The quote itself flips to **Ordered**, or **Partial** if only some lines converted.@@ -69,4 +73,10 @@ In the quote line's bill of materials, the item being made was selected as one o### "Failed to convert quote to order"The conversion action failed after line selection. Have the user retry with the lines re-selected; if it persists, check that the selected lines have valid quantities and pricing, and ask for the full error text.++### "This quote is no longer available for a response." (digital quote)+A customer tried to accept or reject a digital quote whose status is no longer `Sent` (it's already `Ordered`, `Partial`, `Cancelled`, or similar). Only a `Sent` quote can be answered — the accept/reject buttons are hidden once it leaves that state.++### "Oops! The link you're trying to access has expired or is no longer valid." (digital quote)+A `Sent` quote past its `expirationDate` shows the expired state on its public page and can no longer be accepted. Re-send a fresh quote with a new expiration date; the old link stays expired.</AgentContext>diff --git a/docs/content/docs/reference/risks.mdx b/docs/content/docs/reference/risks.mdxindex 2e8d0ca7ca..d155df8e50 100644--- a/docs/content/docs/reference/risks.mdx+++ b/docs/content/docs/reference/risks.mdx@@ -37,7 +37,7 @@ Because the two ratings are independent, a low-likelihood, high-severity risk (aStatus is a free-set enum (`riskStatus`, `quality.models.ts:96`). Carbon does not enforce a state machine — any status can move to any other; you set where the entry stands.-<StatusFlow>+<StatusFlow entity="risk"><Status name="Open">A newly raised risk, not yet worked. The default for a new entry.</Status><Status name="In Review">Being assessed — someone is deciding whether and how to act on it.</Status><Status name="Mitigating">A treatment is in progress: you're actively reducing the severity or likelihood.</Status>diff --git a/docs/content/docs/reference/sequences.mdx b/docs/content/docs/reference/sequences.mdxindex 5b7b9b1813..5c8bb469a4 100644--- a/docs/content/docs/reference/sequences.mdx+++ b/docs/content/docs/reference/sequences.mdx@@ -3,70 +3,41 @@ title: Numbering sequencesdescription: The per-company generator behind every readable document number — jobs, change notices, payments, and more.----Every document Carbon creates gets a <Term id="readable-id">human-readable number</Term>: a job is `J000001`, an engineering change notice is `CN-000001`, a payment is `PAY-2026-07-000001`. Those numbers come from <Term id="numbering-sequence">sequences</Term> — one small counter per document type, per company. Each sequence knows its prefix, its suffix, how wide the number is, how much to step by, and what value comes next. When a document is created, Carbon reads the sequence, formats the next value, and advances the counter.+Every document Carbon creates gets a <Term id="readable-id">human-readable number</Term>: a job is `J000001`, a change notice is `CN-000001`, a payment is `PAY-2026-07-000001`. Those numbers come from <Term id="numbering-sequence">sequences</Term>, one small counter per document type per company. Sequences live under **Settings → Sequences**; every company is seeded with a full set, and you can retune any of them (prefix, counter, padding) without touching code.-Sequences live under **Settings → Sequences**. Every company gets a full set seeded when it's created, and you can retune any of them — change the prefix, restart the counter, widen the padding — without touching code.--## What a sequence is--A sequence is a row in the `sequence` table, keyed by `("table", "companyId")` — one counter per document type per company (`packages/database/supabase/migrations/20230525025310_sequences.sql:1`, primary key moved to `("table", "companyId")` in `20240704105128_rfq.sql:120`). The `table` column names the document type it counts (`"job"`, `"changeOrder"`, `"payment"`), and `name` is the label you see in the UI ("Job", "Change Notice", "Payment").--When something needs a new number, Carbon assembles it from three parts:+When something needs a number, Carbon assembles it from three parts and advances the counter in the same operation, so two documents never collide:```{prefix}{next + step, zero-padded to size}{suffix}```-So a `job` sequence with prefix `J`, size `6`, step `1`, and `next` at `0` produces `J000001`, then `J000002`, and so on. The counter is advanced in the same operation that reads it, so two documents never collide (`packages/database/supabase/functions/shared/get-next-sequence.ts:23`).-<Callout type="note" title="The number is stored on the document, not recomputed">-Once a document is created, its number is written to the record and never changes — even if you later edit the sequence. Retuning a sequence only affects documents created **after** the change. It never renumbers what already exists.+Once created, a document's number never changes. Retuning a sequence only affects documents created **after** the change; it never renumbers what exists.</Callout>## Fields-These are the columns you can tune per sequence. All of them are editable from the sequence form except the document type itself.+<Screenshot label="Settings → Sequences: the sequence form with prefix, current, size, step, suffix, and the live preview of the next number" caption="The form previews the next number as you type." /><FieldTable>- <Field name="Prefix" type="text">- Text prepended to the number. Optional. Supports date tokens (below), so `PAY-%{yyyy}-%{mm}-` renders as `PAY-2026-07-`. Stored in the `prefix` column.- </Field>- <Field name="Current" type="integer">- The last value handed out — the `next` column. The next document gets `Current + Step`. Set this to restart or fast-forward numbering. Must be `≥ 0` (`apps/erp/app/modules/settings/settings.models.ts:288`).- </Field>- <Field name="Size" type="integer">- How many digits the number is zero-padded to. Size `6` gives `000001`; size `4` gives `0001`. Accepted range is `1`–`20` (`apps/erp/app/modules/settings/settings.models.ts:291`). Most sequences ship at `6`.- </Field>- <Field name="Step" type="integer">- How much the counter climbs each time. Almost always `1`. Must be `≥ 1`.- </Field>- <Field name="Suffix" type="text">- Text appended after the number. Optional. Supports the same date tokens as the prefix. Stored in the `suffix` column.- </Field>+ <Field name="Prefix" type="text">Text prepended to the number. Optional; supports date tokens, so `PAY-%{yyyy}-%{mm}-` renders as `PAY-2026-07-`.</Field>+ <Field name="Current" type="integer">The last value handed out; the next document gets `Current + Step`. Set it to restart or fast-forward numbering. Must be `≥ 0`.</Field>+ <Field name="Size" type="integer">Zero-padding width: size `6` gives `000001`. Accepted range `1`–`20`; most sequences ship at `6`.</Field>+ <Field name="Step" type="integer">How much the counter climbs each time. Almost always `1`; must be `≥ 1`.</Field>+ <Field name="Suffix" type="text">Text appended after the number. Optional; same date tokens as the prefix.</Field></FieldTable>-The sequence form previews the result live as you type, so you can see exactly what the next number will look like before saving (`apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx:38`).-### Date tokens-Prefix and suffix can embed the current date, which is how payments and journal entries get their year/month partitioning. The tokens are interpolated when the number is generated, not when you save the sequence:--<FieldTable>- <Field name="%{yyyy}">Full four-digit year, e.g. `2026`.</Field>- <Field name="%{yy}">Two-digit year, e.g. `26`.</Field>- <Field name="%{mm}">Zero-padded month, `01`–`12`.</Field>- <Field name="%{dd}">Zero-padded day, `01`–`31`.</Field>- <Field name="%{hh}">Zero-padded hour, `00`–`23`.</Field>- <Field name="%{ss}">Zero-padded second, `00`–`59`.</Field>-</FieldTable>+Prefix and suffix can embed the current date — how payments and journal entries get their year/month partitioning. Tokens are interpolated when the number is generated, not when you save: `%{yyyy}` (2026), `%{yy}` (26), `%{mm}` (01–12), `%{dd}` (01–31), plus `%{hh}` and `%{ss}` for hour and second.<Callout type="warn" title="Hour and second tokens don't work for every document type">-Carbon has two code paths that expand these tokens. The document-creation edge functions support all six (`packages/database/supabase/functions/lib/utils.ts:33`). But some numbers — customers, suppliers, and quotes, which are stamped by a database trigger — go through the `get_next_sequence` database function, which only understands the four **date** tokens `%{yyyy}`, `%{yy}`, `%{mm}`, and `%{dd}` (`packages/database/supabase/migrations/20241115101526_rpc-get-next-sequence.sql:42`). Putting `%{hh}` or `%{ss}` in one of those sequences leaves the literal token in the number. Stick to date tokens unless you know the document type is generated by an edge function.+Customers, suppliers, and quotes are numbered by a database trigger that only understands the four **date** tokens; putting `%{hh}` or `%{ss}` in those sequences leaves the literal token in the number. Stick to date tokens unless you know the document type is generated by an edge function.</Callout>-## Which documents use a sequence+## Seed defaults-A new company is seeded with a sequence for every numbered document type (`packages/database/supabase/functions/lib/seed.data.ts:222`). These are the defaults — the prefix and starting values you'd see on a fresh company:+A new company is seeded with a sequence for every numbered document type:| Document type | `table` | Prefix | Example ||---|---|---|---|@@ -99,51 +70,24 @@ A new company is seeded with a sequence for every numbered document type (`packa| Credit memo | `creditMemo` | `CR-%{yyyy}-%{mm}-` | `CR-2026-07-000001` || Debit memo | `debitMemo` | `DR-%{yyyy}-%{mm}-` | `DR-2026-07-000001` |-Payments are a good example of the pattern in action. A `payment`, a `creditMemo`, and a `debitMemo` each have their own sequence; the payment-creation path picks the right one by the memo's direction, so a credit memo draws from `CR-` and a debit memo from `DR-` (`packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql:567`).--<Callout type="note" title="A few sequences were re-seeded for existing companies with different prefixes">-The seed table above is what a brand-new company gets. When some sequences were added after launch, the migration that backfilled them for existing companies used a different prefix — jobs, for instance, were backfilled as `WO` for older companies (`packages/database/supabase/migrations/20240909194622_jobs.sql:363`) even though new companies seed as `J`. If a prefix on your company doesn't match the table above, it's likely one of these backfilled defaults. Either way, you can change it under **Settings → Sequences**.--Change notices are the reverse case: their sequence was re-prefixed from `ECO-` to `CN-` for every company during the rename, so only *new* records get `CN-000001`. Ids already minted as `ECO-000001` are left exactly as they were.-</Callout>--## How a number gets assigned--The flow is the same everywhere a number is minted:--<Steps>- <Step>- A document is created — you convert a sales order line to a [job](/docs/reference/jobs), open a [change notice](/docs/reference/change-orders), or record a payment.- </Step>- <Step>- Carbon looks up the sequence for that document type and company, computes `next + step`, zero-pads it to `size`, and wraps it in the (date-interpolated) prefix and suffix.- </Step>- <Step>- The counter advances in the same operation — `next` is written back before the number is returned — so concurrent creates never share a number (`packages/database/supabase/functions/shared/get-next-sequence.ts:28`).- </Step>- <Step>- The formatted number is saved on the new document and stays fixed for its lifetime.- </Step>-</Steps>--Accounting posts are the heaviest user of this machinery: every GL post — from shipments, receipts, invoices, inventory adjustments, and production events — pulls a fresh `journalEntry` number as it books, which is why the journal-entry sequence carries a month token by default.+A prefix on an older company may differ: a few sequences added after launch were backfilled with different defaults (jobs as `WO`, change notices re-prefixed from `ECO-` without renumbering existing records). Either way, change it under **Settings → Sequences**.-Sequences are company-scoped like everything else in Carbon, so two companies in the same [group](/docs/reference/intercompany) number their documents independently, even when they share a chart of accounts.+Accounting posts are the heaviest user of this machinery: every GL post pulls a fresh `journalEntry` number as it books, which is why that sequence carries a month token by default. Sequences are company-scoped, so two companies in the same [group](/docs/reference/intercompany) number independently even when they share a chart of accounts. Where the numbers land day to day: [jobs](/docs/reference/jobs), [change notices](/docs/reference/change-orders), and [payments](/docs/reference/payments).<AgentContext>-## Troubleshooting+## Internals and troubleshooting-The field bounds and the two-token-path gotcha that catch people.+A sequence is a row in the `sequence` table keyed by `("table", "companyId")` (`20230525025310_sequences.sql`, PK moved in `20240704105128_rfq.sql:120`). The counter advances in the same operation that reads it (`functions/shared/get-next-sequence.ts:23`). The form's live preview is `SequenceForm.tsx:38`; seed defaults are `functions/lib/seed.data.ts:222`. Payments pick the right sequence by memo direction — credit memos draw `CR-`, debit memos `DR-` (`20260630093809_ar-ap-payments.sql:567`).### A sequence field won't save (Current, Step, or Size)-The `sequenceValidator` bounds each numeric field (`settings.models.ts:285-292`): **Current** (`next`) must be `≥ 0`, **Step** must be `≥ 1`, and **Size** must be between `1` and `20`. A Step of `0`, a negative Current, or a Size above `20` is rejected. Set values inside those ranges.+`sequenceValidator` bounds them (`settings.models.ts:285-292`): Current `≥ 0`, Step `≥ 1`, Size `1`–`20`. Values outside those ranges are rejected.### My `%{hh}` or `%{ss}` token shows up literally in the number-Only some documents expand hour/second tokens. Customers, suppliers, and quotes are numbered by a database trigger through the `get_next_sequence` RPC, which interpolates only the four **date** tokens `%{yyyy}`, `%{yy}`, `%{mm}`, `%{dd}` (`20241115101526_rpc-get-next-sequence.sql:42-51`) — it never replaces `%{hh}` or `%{ss}`, so the literal token stays in the number. Edge-function-generated documents support all six. Stick to date tokens for customer/supplier/quote prefixes.+Customers, suppliers, and quotes are numbered by a database trigger through the `get_next_sequence` RPC, which interpolates only `%{yyyy}`, `%{yy}`, `%{mm}`, `%{dd}` (`20241115101526_rpc-get-next-sequence.sql:42-51`). Edge-function-generated documents support all six tokens. Use date tokens only for customer/supplier/quote prefixes.### Editing a sequence didn't renumber existing documents-By design. A document's number is written to the record when it's created and never recomputed. Retuning a sequence (prefix, Current, Size) only affects documents created **after** the change; it never renumbers history.+By design: numbers are written at creation and never recomputed.### A prefix on my company doesn't match the seed defaults-Some sequences were backfilled for existing companies with a different prefix than a fresh company seeds — jobs, for instance, were backfilled as `WO` even though new companies seed as `J` (`20240909194622_jobs.sql:363`). Change it under **Settings → Sequences** if you want the newer default.+Backfilled defaults for older companies differ in places — jobs were backfilled as `WO` (`20240909194622_jobs.sql:363`) though new companies seed `J`; change notices were re-prefixed `ECO-` → `CN-` for new records only, leaving minted `ECO-` ids untouched. Change it under Settings → Sequences.</AgentContext>diff --git a/docs/content/docs/reference/sharing.mdx b/docs/content/docs/reference/sharing.mdxindex 428f94da11..1b11454c59 100644--- a/docs/content/docs/reference/sharing.mdx+++ b/docs/content/docs/reference/sharing.mdx@@ -1,93 +1,21 @@----title: External sharing and portals-description: Private, login-free links that let a customer accept a quote, a supplier price an RFQ or answer a SCAR, and a buyer watch order status, all without a Carbon account.+title: External sharing+description: How Carbon's private, login-free links work — a customer accepts a quote, a supplier prices a request or answers a SCAR, a buyer watches order status.----Some of Carbon's work happens with people who don't have a Carbon login: the customer deciding whether to accept a quote, the supplier pricing your request, the buyer wondering where their order is. Rather than email a PDF and wait, Carbon hands each of them a **private link** to a single, live document. Open it and you act right there in the browser: no account, no password, just the one record the link points at.+Some of Carbon's work happens with people who don't have a Carbon login. Rather than email a PDF and wait, Carbon hands them a **private link** to a single, live document: open it and you act right there in the browser — no account, no password, just the one record the link points at. The link is the only credential, so guard it like a password: whoever holds the URL gets in.-Every one of these links resolves through an `externalLink` row. Sending a shareable document creates that row and stamps its id into the source record (`quote.externalLinkId`, `supplierQuote.externalLinkId`, and so on); the link you copy is `/share/<type>/<externalLinkId>`. The public page loads with a service-role client and no permission check, so anyone with the link gets in. Guard the link like a password: possession is the only credential.+Four things reach an outside party this way. Each is documented where the feature lives:-## What can be shared+<Cards>+ <Card title="Digital quotes" href="/docs/reference/quotes#digital-quotes">A **"Sent"** quote the customer accepts or rejects.</Card>+ <Card title="Supplier quotes" href="/docs/reference/supplier-quotes">A request the supplier prices and submits, line by line.</Card>+ <Card title="Customer portal" href="/docs/reference/customer-portal">A standing, read-only view of a customer's orders and shop-floor progress.</Card>+ <Card title="SCARs" href="/docs/reference/issues">A supplier corrective action request the supplier responds to.</Card>+</Cards>-Four things reach an outside party through a public link. Each maps to an `externalLinkDocumentType` value and a `/share/...` route.--<FieldTable>- <Field name="Digital quote" type="/share/quote/:id">A **"Sent"** quote a customer can accept or reject. `documentType` **"Quote"**.</Field>- <Field name="Supplier quote" type="/share/supplier-quote/:id">An RFQ a supplier prices and submits. `documentType` **"SupplierQuote"**.</Field>- <Field name="Customer portal" type="/share/customer/:id">A live view of a customer's open orders and their shop-floor progress. `documentType` **"Customer"**. <PlanBadge plan="Business" /></Field>- <Field name="SCAR" type="/share/scar/:id">A supplier corrective action request the supplier responds to. `documentType` **"Non-Conformance Supplier"**.</Field>-</FieldTable>--Two other routes live under `/share/` but are **not** public links, so they don't belong on this list. `/share/purchasing-rfq/:id` is an internal *preview* of how a supplier's request will look, gated by `requirePermissions` with purchasing view. `/share/training/:id` is an internal training assignment that requires an employee login. Neither hands anything to an outside party.--<Callout type="note" title="The link is the only credential">-The public share pages skip authentication and load with a service-role client keyed on the `externalLinkId`. There is no password and no account behind the link, so whoever holds the URL can open the document. Send it to the right person, and don't post it anywhere public.-</Callout>--## Digital quotes--A **"Sent"** quote can be shared with the customer over its private link. The page shows the quote lines with images, the quantity-break pricing, the totals (subtotal, discount, tax, shipping), the shipping method and payment term, and any external notes. Internal notes are stripped before anything renders, so the customer never sees your working comments.--From that page the customer does one of two things. They **accept**, entering their name and email and optionally attaching a purchase-order PDF, and Carbon converts the quote straight to a <Term id="sales-order">sales order</Term>, stamping who accepted it. Or they **reject**, again with a name and email, and the quote moves to **"Lost"**. Line selection is per quantity break, so the customer can accept the tier they want.--Both actions are gated: the quote must be **"Sent"**. A quote that's already **"Ordered"**, **"Partial"**, **"Cancelled"**, or expired is read-only, its buttons gone. Expiry is automatic: once a **"Sent"** quote's `expirationDate` passes, the link shows an *expired* state and can no longer be accepted.--<Callout type="tip" title="Sending is what mints the link">-The `externalLink` row (and the quote's `externalLinkId`) is created when the quote is set up and again at finalization. The shareable URL is `/share/quote/<externalLinkId>`, surfaced in the quote's share dialog. See [quotes](/docs/reference/quotes#digital-quotes) for the quote lifecycle behind it.-</Callout>--## Supplier quotes--The mirror image, for the buy side. When you send a <Term id="supplier-quote">supplier quote</Term>, Carbon emails the supplier a link to `/share/supplier-quote/<externalLinkId>` along with the request. The supplier opens it with no login and prices the work directly on the page: for each quantity they choose, they enter a **unit price**, **lead time** in days, **shipping cost**, and **tax**, and can attach a note per line.--When every selected line has both a price and a lead time, the **"Submit Quote"** button lights up; the supplier enters their name and email and submits. They can instead **"Decline Quote"**, optionally leaving a reason. Both flows are open only while the quote is in **"Draft"**; once submitted or declined, the page is read-only. The link also expires: a **"Draft"** quote past its `expirationDate` shows the expired state. Each visit stamps `externalLink.lastAccessedAt`, so you can see whether the supplier has opened it.--<Callout type="note" title="The RFQ preview is internal-only">-`/share/purchasing-rfq/:id` is a preview for *your* team, showing how the request will look to a supplier with all the price cells blank. It requires a purchasing login and hands nothing to the supplier. The supplier-facing document is the supplier quote above. See [supplier quotes](/docs/reference/supplier-quotes) for the full flow.-</Callout>--## Customer portal--<PlanBadge plan="Business" />--The customer portal is a **standing, read-only window** into a customer's work, not a one-document link. It's gated behind the `CUSTOMER_PORTALS` plan feature, so a company on a plan without it gets a 404. Where a digital quote is about closing one deal, the portal is about visibility after the deal: the buyer opens `/share/customer/<externalLinkId>` and watches their orders move.--The portal lists the customer's sales order lines with their status, the buyer and engineer contacts, order and due dates, part number and revision, quantity complete, quantity shipped, and per-operation job progress. There are no forms: the customer can look, not act. A splat route (`/share/customer/:id/*`) lets them download files attached to those job operations, rate-limited to ten downloads a minute per IP and scoped so the file must belong to that customer's own jobs.--<Callout type="tip" title="Pairs with digital quotes">-A digital quote closes the sale; the customer portal is what the buyer watches afterward as the work proceeds. The two are the customer-facing bookends of an order.-</Callout>--## Supplier corrective action requests--When a supplier-caused defect needs the supplier to act, Carbon shares the corrective action externally as a <Term id="scar">SCAR (Supplier Corrective Action Request)</Term>. The link points at `/share/scar/<externalLinkId>`, which resolves through the `externalLink` row to the underlying [issue](/docs/reference/issues) (a non-conformance) and its supplier.--The supplier sees the non-conformance details, the current status, the supplier's own name, and the list of **action tasks** assigned to them. For each task they can update the status and write notes in a rich-text editor that auto-saves as they type; entering notes on a **"Pending"** task promotes it to **"In Progress"** automatically. Once the parent issue is **"Closed"**, the record locks and the supplier can no longer make changes.--<Callout type="note" title="Only supplier-facing tasks get a SCAR">-The SCAR shares the specific action tasks meant for the supplier, not the whole issue. The rest of the non-conformance workflow, dispositions, approvals, and closure stays internal. See [issues](/docs/reference/issues#required-actions-and-their-system-categories) for the action-task lifecycle that a SCAR plugs into.+<Callout type="note" title="Links expire with the document">+Each link is only as live as the record behind it: an expired or answered quote turns its page read-only, and a closed issue locks its SCAR. There is no separate link-revocation step to remember.</Callout>-<AgentContext>-## Troubleshooting--Exact messages and gates behind the public share links (digital quotes, supplier quotes, customer portal, SCAR).--### "This quote is no longer available for a response."-A customer tried to accept or reject a digital quote whose status is no longer `Sent` (it's already `Ordered`, `Partial`, `Cancelled`, or similar). Only a `Sent` quote can be answered — the accept/reject buttons are hidden once it leaves that state.--### "Oops! The link you're trying to access has expired or is no longer valid." (Quote expired)-A `Sent` quote (or a `Draft` supplier quote) is past its `expirationDate`, so the public page shows the expired state and can no longer be accepted or submitted. Re-send a fresh quote with a new expiration date; the old link stays expired.--### "Issue has been closed already. Unable to make changes"-A supplier tried to update a SCAR action task after the parent non-conformance issue was set to `Closed`. Once the issue is Closed the SCAR is read-only. Reopen the issue internally if further supplier action is needed.--### Why does the customer portal link show "Not found" / a 404?-The customer portal is gated behind the `CUSTOMER_PORTALS` plan feature (Business plan). A company without it gets a 404 on `/share/customer/…` (and a 403 on the file-download splat route). Upgrade the plan to enable the portal.--### Why is the supplier's "Submit Quote" button disabled?-Submit lights up only when every selected line has both a unit price and a lead time greater than zero, and only while the quote is in `Draft`. Fill in price and lead time for each selected quantity; once submitted or declined the page is read-only.--### Why did downloads from the customer portal start failing (HTTP 429)?-File downloads on the portal are rate-limited to ten per minute per IP. Wait a minute and retry; the limit is per requesting IP address, not per file.-</AgentContext>+Two other pages *look* shared but aren't: the RFQ preview is an internal view of how a supplier's request will look (purchasing login required), and training assignments require an employee login. Neither hands anything to an outside party.diff --git a/docs/content/docs/reference/single-sign-on.mdx b/docs/content/docs/reference/single-sign-on.mdxnew file mode 100644index 0000000000..feec6b8980--- /dev/null+++ b/docs/content/docs/reference/single-sign-on.mdx@@ -0,0 +1,102 @@+---+title: Single sign-on+description: Route sign-in for your company's email domains through your own identity provider with enterprise SAML SSO.+---++Single sign-on hands control of Carbon sign-in to your own <Term>identity provider</Term>: Okta, Entra ID, Google Workspace, or any SAML 2.0 IdP. Register your email domains once, proving you own each with a DNS record, and everyone on them signs in to both ERP and MES with their normal work email — Carbon recognizes the domain and routes to your IdP automatically, no SSO button to find. Registering takes nothing away: the <Term>magic link</Term> and other methods keep working until you turn on [Require SSO](#requiring-sso).++## Requirements++SSO is an Enterprise feature of your own [self-hosted](/docs/platform/self-hosting) deployment (`CARBON_EDITION=enterprise`, which requires a [commercial license](/docs/platform/licensing)). Carbon Cloud sign-in is unaffected. Enable it through [environment variables](/docs/platform/self-hosting/environment-variables):++<EnvVars>+<EnvVar name="AUTH_PROVIDERS" type="enum[]">Add `sso` to the comma-separated list of sign-in methods.</EnvVar>+<EnvVar name="SAML_ENABLED" type="boolean">Turns on the SAML engine in the auth service.</EnvVar>+<EnvVar name="SAML_PRIVATE_KEY" type="string">The SAML signing key: a base64-encoded PKCS#1 DER RSA key, minimum 2048-bit. The `openssl` command is in `.env.example`.</EnvVar>+</EnvVars>++## Connect your identity provider++Everything lives on one screen: **Settings → Security**, under **"Single Sign-On"** (viewing needs `settings` view; saving needs `settings` update).++<Screenshot label="Settings → Security, Single Sign-On section with an active connection: Service Provider Details, Identity Provider card with Require SSO switch, and the Email Domains card" caption="The whole SSO exchange happens on one settings screen." />++<Steps>+<Step>+**Copy Carbon's service provider details.** The **"Service Provider Details"** card shows the **"ACS URL"** and **"SP Metadata URL"** with copy buttons.+</Step>+<Step>+**Register Carbon in your IdP** as a SAML application using those two URLs. The assertion must include an **email attribute**; the email is how Carbon matches each sign-in to a person and a company.+</Step>+<Step>+**Paste the IdP metadata back into Carbon.** In the **"Identity Provider"** card, provide the **"IdP Metadata URL"** *or* the raw **"IdP Metadata XML"** (exactly one), then **"Save"**. The card gaining a **"Require SSO"** switch and a **"Deactivate"** button is the sign the connection is active.+</Step>+<Step>+**Verify your email domains.** The **"Email Domains"** card appears once the connection exists. Add each domain your people sign in with, publish the DNS record it shows, and click **"Verify"**. Only verified domains route SSO sign-ins.+</Step>+</Steps>++## Verifying a domain++Each added domain starts **Pending** with a unique TXT challenge shown on the card:++| Record | Value |+| --- | --- |+| **Host** | `_carbon-challenge.example.com` |+| **Type** | `TXT` |+| **Value** | `carbon-domain-verification=<your unique token>` |++Publish the record at your DNS host, click **"Verify"**, and on a match the domain flips to **Verified**. Verification is one-time; the TXT record can be deleted afterwards. A Pending domain has no effect anywhere, so adding one is always safe.++<Callout type="warn" title="Verified claims are exclusive">+Only one company can hold a domain verified, first to prove DNS control wins, and the claim survives even if DNS control later changes hands. The clean handover is for the holding company to **Remove** the domain, which frees it for the new owner to verify.+</Callout>++## How sign-in works++The login page is email-first and the SSO fork is invisible: the user types their email, presses **"Continue"**, and Carbon either redirects to your IdP (active connection on that domain) or falls through to the ordinary magic-link flow. Before any session is created, the asserted email's domain must be one of the connection's **verified** domains, so even a misconfigured or hostile IdP can't sign someone into another company.++Provisioning is **invite-first**: no self-serve signup through SSO. An existing member signs straight in (their first SSO sign-in quietly links the SAML identity to their account; the magic link keeps working). Someone with a pending invite has it accepted by their first SSO sign-in, landing with exactly the invite's role. Anyone else is rejected by name and nothing is provisioned; create the invite in the [employees directory](/docs/reference/people) and the retry just works.++## Requiring SSO++Once a sign-in has worked, the **"Require SSO"** switch on the Identity Provider card makes the IdP the only way in for verified domains: magic links, Google, Outlook, and passkeys are all refused server-side. The switch exists only on an active connection, so the path is always *set up, prove a sign-in works, enforce last*. Turning it off — or **"Deactivate"**, which deletes the connection and releases the domain claims — immediately restores the other methods.++<Callout type="warn" title="Break-glass recovery">+If enforcement is on and your IdP is unreachable, nobody on the covered domains can sign in to turn it off. Operators can lift it directly in the database, and magic-link sign-in works on the next attempt:++```sql+UPDATE "ssoConnection" SET "requireSso" = false WHERE "companyId" = '<id>';+```+</Callout>++SSO sessions skip Carbon's [two-factor challenge](/docs/reference/two-factor) and the company-wide requirement in every environment, including controlled (ITAR) deployments: your IdP already enforced its own MFA policy at sign-in. Magic-link logins still get Carbon's own challenge.++<AgentContext>+## Behavior details and exact messages++Providers are registered directly against the auth service (GoTrue) with the service-role key; no Supabase account or plan is involved. The domain-has-SSO check on the login page is rate-limited and reveals nothing beyond yes/no.++Domain rules: lowercased bare hostnames only (no `@`, no spaces), punycode (`xn--`) for internationalized domains; public email providers (`gmail.com`, `outlook.com`, …) are refused. Several companies may hold a *pending* claim on the same domain at once — exclusivity kicks in at verification. Re-adding your own domain fails with "This domain has already been added". The metadata form rejects both-or-neither with "Provide either a metadata URL or metadata XML (exactly one)".++### Verification fails+Three causes, named in the message: the record isn't visible yet (DNS propagation — wait and retry); the value doesn't match the token (re-copy exactly); or the DNS lookup itself failed (the server's outbound DNS access is blocked). Gotcha: many DNS providers auto-append the domain to the record name — in Cloudflare enter only `_carbon-challenge` and check the preview shows the host once, not twice.++### "Verify" fails on a domain another company verified+Deliberately generic message so the button can't be used to probe which domains are registered where. Handover: the holder removes the domain, or a self-host operator deletes the claim (`DELETE FROM "ssoDomain" WHERE "domain" = 'example.com';`). The previous holder's provider registration keeps routing the domain until its connection is re-saved, but sign-ins on it are rejected once the row is gone.++### "SSO sign-in rejected: this email domain is not registered for your company's SSO connection."+The IdP asserted an email outside the connection's verified domains. Add and verify the domain, or fix the IdP's attribute mapping.++### "SSO sign-in succeeded but no invite exists for `[email protected]`. Contact your administrator."+Invite-first provisioning: the person authenticated at the IdP but is neither a member nor invited. Create the invite and have them retry. Invite emails for SSO-active domains link to the login page with the address prefilled instead of a magic-link code, so the IdP is never bypassed.++### "Complete your first SSO sign-in in Carbon ERP, then return here." (MES)+MES enforces the same domain rules but doesn't run first-time provisioning. One ERP sign-in fixes it permanently.++### "Your organization requires single sign-on. Sign in with your work email to continue."+Require SSO is on and the user tried a non-SSO method on a verified domain. Expected; they sign in via email → IdP redirect. A pending domain enforces nothing.++### "Deactivate Single Sign-On" confirmation+Warns "Users on your registered domains will no longer be able to sign in through your identity provider. This cannot be undone." — the registration is deleted outright and domain claims released; re-enabling means saving the connection again and re-verifying domains.+</AgentContext>diff --git a/docs/content/docs/reference/supplier-quotes.mdx b/docs/content/docs/reference/supplier-quotes.mdxindex 17347e2d8d..e8e7a6f444 100644--- a/docs/content/docs/reference/supplier-quotes.mdx+++ b/docs/content/docs/reference/supplier-quotes.mdx@@ -38,7 +38,7 @@ The unit price, shipping, and extended price you type are the supplier's numbersA quote is editable only while it's a **"Draft"**. Finalizing moves it to **"Active"**, which is the state comparison and conversion read from. Everything past Draft is locked.-<StatusFlow>+<StatusFlow entity="supplierQuote"><Status name="Draft">Being built. The only editable state: you can add lines, enter prices, and adjust dates here.</Status><Status name="Active" accent>Finalized. Locked, and the state the comparison and convert-to-order flows read.</Status><Status name="Expired" terminal>Past its expiration date. Pricing is no longer trustworthy.</Status>@@ -50,6 +50,12 @@ A quote is editable only while it's a **"Draft"**. Finalizing moves it to **"ActAny status other than Draft locks the quote. If a supplier revises their pricing after you've finalized, you record the new numbers on a fresh quote rather than editing the old one, which keeps the paper trail intact for the comparison.</Callout>+## The supplier's link++Sending the quote emails the supplier a private link along with the request — no Carbon login needed. The supplier prices the work directly on the page: for each quantity they choose, they enter a **unit price**, a **lead time** in days, **shipping cost**, and **tax**, and can attach a note per line. When every selected line has both a price and a lead time, **"Submit Quote"** lights up; they enter their name and email and submit. They can instead **"Decline Quote"**, optionally leaving a reason.++Both flows are open only while the quote is a **"Draft"**; once submitted or declined the page is read-only, and a Draft past its expiration date shows an expired state. Each visit stamps the link's last-accessed time, so you can see whether the supplier has opened it. Whoever holds the URL can open the page — send it to the right contact and nowhere public.+## From quote to purchase orderWhen you've picked a winning quote, **"Convert to Order"** turns it into a purchase order. You choose which lines and which quantity tier to buy, and Carbon raises a purchase order for that supplier with the item lines, the supplier's contact and location, and the exchange rate all carried across from the quote. If the quote came from an RFQ, the new order is linked back to that RFQ.@@ -84,4 +90,10 @@ A supplier quote is editable only while its status is `Draft`. Any other status### Why is the Finalize or Send button disabled?Finalize/Send require the purchasing update permission and at least one line on the quote. Send is also disabled once the quote is already `Active`. Delete additionally requires the purchasing delete permission, an unlocked (Draft) quote, and an employee login.++### Why is the supplier's "Submit Quote" button disabled (on the public link)?+Submit lights up only when every selected line has both a unit price and a lead time greater than zero, and only while the quote is `Draft`. Once submitted or declined the page is read-only.++### The supplier's link shows "expired or is no longer valid"+A `Draft` supplier quote past its `expirationDate` shows the expired state and can no longer be submitted. Re-send a fresh request with a new expiration date.</AgentContext>diff --git a/docs/content/docs/reference/suppliers-and-customers.mdx b/docs/content/docs/reference/suppliers-and-customers.mdxindex eb16919359..db039d0245 100644--- a/docs/content/docs/reference/suppliers-and-customers.mdx+++ b/docs/content/docs/reference/suppliers-and-customers.mdx@@ -23,7 +23,7 @@ The asymmetry to remember: **supplier status is a fixed four-value set; customer## What they share-Both records carry the same satellite shape: **contacts**, **locations/addresses**, and **payment, shipping, and tax** defaults. Payment terms, currency, and tax settings live on those satellites, not on the core record. Both also have a human-readable id (`SUP…` / `CUS…`) on top of their internal key, and both can expose an external **portal**: suppliers respond to <Term id="rfq">RFQs</Term> through a digital-quote link; customers track their orders through a customer portal.+Both records carry the same satellite shape: **contacts**, **locations/addresses**, and **payment, shipping, and tax** defaults. Payment terms, currency, and tax settings live on those satellites, not on the core record. Both also have a human-readable id (`SUP…` / `CUS…`) on top of their internal key, and both can expose an external **portal**: suppliers respond to <Term id="rfq">RFQs</Term> through a digital-quote link; customers track their orders through a [customer portal](/docs/reference/customer-portal).## Relateddiff --git a/docs/content/docs/reference/training.mdx b/docs/content/docs/reference/training.mdxindex e3624fcb66..ebab4d5a5e 100644--- a/docs/content/docs/reference/training.mdx+++ b/docs/content/docs/reference/training.mdx@@ -24,7 +24,7 @@ Each training is one row in the `training` table (`packages/database/supabase/miThe status enum is a simple linear lifecycle on the training record — not to be confused with an employee's *completion* status further down.-<StatusFlow>+<StatusFlow entity="trainingCourse"><Status name="Draft">Being authored. Not yet meant for assignment.</Status><Status name="Active" accent>Published and in use. Assignments and reminders operate against active trainings.</Status><Status name="Archived" terminal>Retired. Kept for history, no longer assigned.</Status>@@ -68,7 +68,7 @@ The **period** is the heart of the recurring logic (`20251206000000_training_assAn employee's status is *computed*, not stored — Carbon evaluates it from whether a completion exists for the current period and when the employee started. There are four possible values (`apps/erp/app/modules/resources/resources.models.ts:318`):-<StatusFlow>+<StatusFlow entity="trainingAssignment"><Status name="Pending">Assigned, in the current period, not yet completed. The default state.</Status><Status name="Completed" accent>A completion row exists for this employee and period.</Status><Status name="Overdue" branch>A recurring period has already ended and the employee never completed it.</Status>diff --git a/docs/content/docs/reference/two-factor.mdx b/docs/content/docs/reference/two-factor.mdxindex b96c7b3b88..5b3089d794 100644--- a/docs/content/docs/reference/two-factor.mdx+++ b/docs/content/docs/reference/two-factor.mdx@@ -1,124 +1,75 @@---title: Two-factor authentication-description: How authenticator-app codes work in Carbon, from setting one up to requiring them company-wide, and what happens when someone loses their phone.+description: Add authenticator-app codes to sign-in, require them company-wide, and reset a lost device.----A password isn't the thing standing between an attacker and your production data — Carbon doesn't use one. You sign in with a magic link, an OAuth provider, or a passkey, and each of those comes down to something in your inbox or on your device. Two-factor authentication adds a second, independent proof: a six-digit code from an authenticator app on your phone, changing every thirty seconds.+Two-factor authentication adds a second proof to sign-in: a six-digit code from an authenticator app on your phone, changing every thirty seconds. You can turn it on for yourself, and an admin can require it for everyone in a company. The two are related but not the same: **the requirement belongs to a company; the authenticator belongs to you.**-You can turn it on for yourself from your own account. An admin can also require it for everyone in a company, which is the setting most organizations actually want. The two are related but not the same thing, and the difference matters: **the requirement belongs to a company, but the authenticator belongs to you**.+## Turn it on for yourself-## Turning it on for yourself+<Screenshot label="Account → Security: the Add Authenticator App dialog with QR code, copyable secret, and six-box verify field" caption="Nothing is active until the first code checks out." />-Open **Account → Security**. It sits alongside your passkeys, because both answer the same question — how you prove it's you.+<Steps>+<Step>+Open **Account → Security** and press **"Add Authenticator App"**.+</Step>+<Step>+Scan the QR code with any TOTP app (Google Authenticator, 1Password, Authy), or tap the secret beneath it to copy and enter it by hand.+</Step>+<Step>+Type the current code into the six-box field and press **"Verify"**. Nothing is active until the code checks out — abandoning the dialog halfway leaves nothing behind.+</Step>+</Steps>-Press **"Add Authenticator App"**. Carbon shows a QR code and, beneath it, the same secret in text. Scan the QR with Google Authenticator, 1Password, Authy, or any TOTP app; if a camera isn't practical, tap the secret to copy it and enter it by hand. Your app immediately starts producing codes. Type the current one into the six-box field and press **"Verify"**.+Carbon emails you a receipt the moment it's on; if one arrives that you didn't cause, remove the factor and tell an admin. To remove it yourself, press the trash icon next to the factor and enter a current code.-Nothing is active until that code checks out. Until then the factor is `unverified` and Carbon ignores it entirely, which is why abandoning the dialog halfway leaves nothing behind.+Once verified, every sign-in asks for a code — magic link, Google, Outlook, and passkey alike. [Single sign-on](/docs/reference/single-sign-on) is the one exception: an SSO session arrives with your identity provider's MFA already enforced, so Carbon skips its own code screen.-The moment it does check out, Carbon emails you a receipt — "Two-factor authentication is on". It isn't a notification you can turn off, because its whole purpose is to be the one signal you'd get if somebody else enrolled an authenticator against your account. If one arrives that you didn't cause, remove the factor and tell an admin.+## Require it for everyone-<Callout type="info" title="What you'll see in your authenticator app">-The entry is labelled with the company you were in when you enrolled, over your email — `Carbon (Acme Manufacturing)` above `[email protected]`. That's deliberate. If you use Carbon at more than one organization, two entries both reading "Carbon" would be indistinguishable at the moment you need to tell them apart.+Open **Settings → System → Security** and turn on **Two-Factor Authentication Enforcement**. It takes effect on each person's next page load, and every active employee is emailed the announcement. Anyone without an authenticator then sees a full-screen **"Set up authenticator app"** prompt — they complete the same QR-and-code flow right there, or sign out; there is no way past it.-The label is written into the QR when you enrol. Renaming the company later doesn't rewrite anyone's existing entry.-</Callout>--To remove it, press the trash icon next to the factor and enter a current code. Carbon asks for the code rather than just a confirmation click because removing your second factor is exactly the action an attacker who has your session would want to perform.--## Signing in with a code--Once you have a verified authenticator, every sign-in asks for a code — magic link, Google, Outlook, and passkey alike. You'll land on a screen titled **"Two-factor authentication"** with a six-digit field; entering the last digit submits it.--Passkeys are challenged too, which surprises people. A passkey is strong, but in Carbon it resolves into an ordinary session like any other sign-in method, so exempting it would leave a way around the requirement. If you'd rather not be asked twice, that's an argument for using a passkey *instead of* two-factor, not alongside it.--[Single sign-on](/docs/platform/single-sign-on) is the one method that isn't challenged. An SSO session arrives with your identity provider's MFA policy already enforced at sign-in, so Carbon skips its own code screen and the company-wide requirement for those sessions — in every environment, including controlled (ITAR) deployments. Sign in with a magic link instead and the challenge applies as usual.--<Callout type="warn" title="Codes are time-based, so your clock matters">-A code is valid for its thirty-second window plus one window either side, to absorb small drift. If codes are consistently rejected on a phone whose time is set manually, switch it to network time. It's the single most common cause of "the code is right but Carbon says no".--Repeated attempts are rate-limited on the same budget as sign-in itself, so guessing your way through isn't practical — and neither is retrying twenty times because you mistyped.-</Callout>--Sessions that already existed before you enrolled don't get a free pass. Carbon re-checks on each request, so a browser you left signed in on another machine is sent to the code screen the next time it's used rather than quietly staying trusted for the rest of the week.--## Requiring it for everyone--Open **Settings → System → Security** and find the **Two-Factor Authentication Enforcement** card. Turning the switch on means anyone opening that company has to have an authenticator set up. There's no grace period; it takes effect on their next page load.--Flipping the switch on also emails every active employee of the company, so nobody's first warning is a locked screen. The message names the company, links straight to **Account → Security**, and tells people who already have an authenticator that nothing changes for them.--It goes out on each off → on transition. Turning enforcement *off* sends nothing, and re-saving a setting that is already on sends nothing either. But if you disable enforcement and later switch it back on, everyone is emailed again — by that point they've been told the requirement was lifted, so they need telling that it's back.--Someone without one sees a full-screen prompt instead of the app, with a **"Set up authenticator app"** button that runs the same QR-and-code flow as the account page. They can complete it right there. The only other thing on that screen is **"Sign out"** — there is no way past it.+Once enforcement is on, **People → Employee accounts** shows a **Two-Factor** column reading **"Enabled"** or **"Not set up"** per person. The column only renders while the company requires two-factor.<Callout type="note" title="The requirement is per company; the authenticator is per person">-This is the part worth reading twice. If you belong to two companies and only one requires two-factor, you're prompted to set one up **only while you're in that company**. Switch to the other and the prompt is gone.--But once you've set one up, you're asked for a code at **every** sign-in, to either company. There's no such thing as being half-enrolled — the authenticator is attached to your account, not to a membership. Turning the requirement on in one company therefore does change how its people sign in everywhere else, which is worth saying out loud before you flip it.+If you belong to two companies and only one requires two-factor, you're prompted to enroll only while in that company — but once enrolled, you're asked for a code at **every** sign-in, to either company. In controlled (ITAR/CMMC) deployments two-factor is mandatory and the switch is locked on; SSO sessions stay exempt even there.</Callout>-Controlled environments are the exception to all of the above. When Carbon is deployed for ITAR or CMMC work, two-factor is mandatory and the switch is locked on, because NIST 800-171 requires it for network access to non-privileged accounts. Admins can see the setting but not turn it off, and the enrollment screen offers no way around it. SSO sessions remain exempt even here — the identity provider owns their MFA.--## Seeing who has set it up--Once enforcement is on, **People → Employee accounts** grows a **Two-Factor** column showing **"Enabled"** or **"Not set up"** for each person. It's blank for shop-floor PIN operators, who don't sign in at all.--The column only appears while the company requires two-factor. With the setting off it would be a wall of "Not set up" describing a policy nobody opted into.-## When someone loses their phone-There are no printed backup codes. Recovery is an admin action, which keeps it auditable and avoids a fallback secret that is itself worth stealing.--An admin with permission to update users opens **People → Employee accounts**, finds the person, and chooses **"Reset Two-Factor Auth"** from the row menu. That removes their authenticator; their next sign-in is an ordinary magic link, and they can enrol a fresh device.+There are no printed backup codes — recovery is an admin action, which keeps it auditable. An admin with permission to update users opens **People → Employee accounts** and chooses **"Reset Two-Factor Auth"** from the person's row menu. Their next sign-in is an ordinary magic link, and they enroll a fresh device.<Callout type="warn" title="A reset reaches every company that person belongs to">-Because the authenticator is attached to the account rather than to a membership, removing it removes it everywhere. An admin at one company can therefore clear two-factor for a user who also works at another. That's unavoidable given how the factor is stored, but worth knowing before you treat the reset as a purely local action.--It also means at least two people should hold user-management permission. If your only admin loses their phone and nobody else can reset it, there is no self-service way back in.+The authenticator is attached to the account, not the membership, so removing it removes it everywhere. Keep user-management permission on at least two people — if your only admin loses their phone, there is no self-service way back in.</Callout>-## What two-factor doesn't cover--Machine access is never challenged, and that's by design — there's nobody present to read a code off a phone.--<FieldTable>- <Field name="API keys">Keep working exactly as before. They carry their own scopes and rate limits; see [API keys](/docs/building/api-keys).</Field>- <Field name="Integrations">Anything authenticating as the company rather than as a person is unaffected.</Field>- <Field name="Shop-floor PIN operators">Never prompted. Operators pin in at a shared terminal rather than signing in, so there's no personal session to protect and no phone to scan with. The person who signed the terminal in is the one two-factor applies to.</Field>-</FieldTable>+## What it doesn't cover-If you need to restrict what an authenticated person can reach, that's a different mechanism entirely — see [permissions and access](/docs/reference/permissions).--## Where each piece lives--<FieldTable>- <Field name="Account → Security">Set up or remove your own authenticator, alongside your passkeys. See [account settings](/docs/reference/account).</Field>- <Field name="Settings → System → Security">The **Two-Factor Authentication Enforcement** switch for the whole company. See [company settings](/docs/reference/company-settings).</Field>- <Field name="People → Employee accounts">The **Two-Factor** status column and the **"Reset Two-Factor Auth"** row action. See [people](/docs/reference/people).</Field>-</FieldTable>+Machine access is never challenged: [API keys](/docs/building/api-keys) and integrations keep working, and shop-floor PIN operators are never prompted — they pin in at a shared terminal, so two-factor applies to whoever signed the terminal in. To restrict what an authenticated person can *reach*, that's [permissions](/docs/reference/permissions).+<AgentContext>## Troubleshooting-### "That code isn't right" on a code you just read+Behavior details: a code is valid for its thirty-second window plus one window either side; repeated attempts are rate-limited on the sign-in budget. Sessions are re-checked on each request, so pre-existing sessions on other machines get the code screen on next use. The authenticator-app entry is labelled `Carbon (Company Name)` over the user's email — the company name is baked in at enrollment and doesn't update on rename. The enforcement announcement email goes out on each off → on transition only.-Almost always clock drift on the phone. Set the device to network time and try again. Failing that, confirm you're reading the entry for the right company — two Carbon entries are easy to mix up, which is why the label carries the company name.+### "That code isn't right" on a code the user just read+Almost always clock drift on the phone — set the device to network time. Failing that, confirm they're reading the entry for the right company; two Carbon entries are distinguished by the company name in the label.### Someone is stuck on the setup screen and can't get in--That's a company with enforcement on and a person without an authenticator. They complete setup on that screen and continue. If they can't (no phone to hand), the only other option on the screen is signing out.+That's a company with enforcement on and a person without an authenticator. They complete setup on that screen and continue. If they can't (no phone to hand), the only other option is signing out.### The Two-Factor column isn't in the employee list-The column only renders while the company requires two-factor. Turn the setting on in **Settings → System → Security** and it appears.### Turning enforcement on didn't prompt anyone--It applies on each person's next page load, not retroactively to sessions sitting idle. Anyone already looking at a stale tab sees it when they next navigate. The announcement email is what reaches them in the meantime.+It applies on each person's next page load, not retroactively to idle sessions. The announcement email is what reaches them in the meantime.### Nobody got the announcement email--It's sent only when the setting actually changes from off to on. If it was already on — someone else flipped it, or the deployment is a controlled environment where it's locked on — there's no transition to announce. It also goes only to **active** employees, so anyone deactivated isn't included.+It's sent only when the setting transitions from off to on, and only to active employees. If it was already on (someone else flipped it, or the deployment is a controlled environment where it's locked on), there's no transition to announce.### An admin can't turn enforcement off-The deployment is a controlled (ITAR) environment, where two-factor is mandatory and the switch is locked on.++### Passkey users are asked for a code — is that a bug?+No. A passkey resolves into an ordinary session like any other sign-in method, so exempting it would leave a way around the requirement. Only SSO sessions skip the challenge (the identity provider owns their MFA), in every environment including controlled ones.+</AgentContext>diff --git a/docs/content/docs/reference/workflow-runs.mdx b/docs/content/docs/reference/workflow-runs.mdxindex de39a83f20..757c5c4a4a 100644--- a/docs/content/docs/reference/workflow-runs.mdx+++ b/docs/content/docs/reference/workflow-runs.mdx@@ -1,6 +1,6 @@---title: Workflow runs-description: Every firing of a workflow is recorded step by step. What the run list and run detail show, what each status means, how repeating steps are summarised, and how long history is kept.+description: "Every firing of a workflow, recorded step by step: the run list, run detail, statuses, repeating steps, and how long history is kept."plan: Business---diff --git a/docs/content/docs/reference/workflows.mdx b/docs/content/docs/reference/workflows.mdxindex 16e6117794..3cdd727ea0 100644--- a/docs/content/docs/reference/workflows.mdx+++ b/docs/content/docs/reference/workflows.mdx@@ -1,6 +1,6 @@---title: Workflows-description: Build an automation on a canvas — one trigger, conditions, and steps that notify people, update records, or call an outside service. Triggers, values, publishing, and versions.+description: "Build an automation on a canvas: one trigger, conditions, and steps that notify people, update records, or call an outside service."plan: Business---diff --git a/scripts/generate-agent-kb.ts b/docs/lib/markdown-corpus.tssimilarity index 51%rename from scripts/generate-agent-kb.tsrename to docs/lib/markdown-corpus.tsindex 54d1c5f4f9..6427610452 100644--- a/scripts/generate-agent-kb.ts+++ b/docs/lib/markdown-corpus.ts@@ -1,40 +1,20 @@/**- * generate-agent-kb — build the in-app agent's read-only knowledge base from the docs site.+ * Shared "docs as plain markdown" toolkit — the single definition of how a Carbon+ * MDX page becomes component-free markdown a machine can read.*- * The Fumadocs MDX under `docs/content/**` is the source of truth. The in-app agent- * (apps/erp `modules/agent`) reads a flattened, component-stripped copy of every page from- * `apps/erp/app/modules/agent/kb/<slug>.md`, plus a `manifest.json` keyword index that- * `search_docs` scans. This script regenerates both and prunes stale files.+ * Two consumers, one stripper (keep it that way):+ * - `docs/scripts/generate-agent-kb.ts` — the in-app agent's committed KB corpus.+ * - `docs/app/llms.txt` + `docs/app/llms-full.txt` — the public index/corpus for+ * AI crawlers and assistants (llmstxt.org convention).*- * Committed output ships inside the erp Docker image, so the agent reads it with a bundled- * import / fs read at runtime (no docs-app dependency). Mirrors the `generate-mcp.ts` pattern.- *- * Run it manually after editing docs/content, and commit the regenerated kb/ alongside- * the docs change — same model as filling .po files before a commit. The check-and-commit- * skill runs it automatically when docs/content or this script is in the change set.- * See .ai/rules/agent-knowledge-base.md.- *- * Run: pnpm run generate:agent-kb+ * Everything here is pure (fs helpers take explicit paths); no app imports, so the+ * repo-root tsx script can import it directly.*/import fs from "node:fs";import path from "node:path";-// Run from repo root via `pnpm run generate:agent-kb`.-const ROOT = process.cwd();-const CONTENT_DIR = path.join(ROOT, "docs/content");-const KB_DIR = path.join(ROOT, "apps/erp/app/modules/agent/kb");-const MANIFEST_PATH = path.join(KB_DIR, "manifest.json");--type ManifestEntry = {- slug: string;- title: string;- description: string;- keywords: string[];- headings: string[];-};-/** Recursively collect every .mdx file under a directory. */-function walkMdx(dir: string): string[] {+export function walkMdx(dir: string): string[] {const out: string[] = [];for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {const p = path.join(dir, entry.name);@@ -45,14 +25,14 @@ function walkMdx(dir: string): string[] {}/** Split `---\n...\n---\n body` into raw frontmatter block + body. */-function splitFrontmatter(raw: string): { fm: string; body: string } {+export function splitFrontmatter(raw: string): { fm: string; body: string } {const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if (!m) return { fm: "", body: raw };return { fm: m[1], body: m[2] };}/** Read a single-line `key: value` (value may be quoted) from a frontmatter block. */-function fmValue(fm: string, key: string): string {+export function fmValue(fm: string, key: string): string {const line = fm.split("\n").find((l) => l.trimStart().startsWith(`${key}:`));if (!line) return "";let v = line.slice(line.indexOf(":") + 1).trim();@@ -72,7 +52,7 @@ function fmValue(fm: string, key: string): string {* has a single definition — code samples containing `<Generic>` or `## comment` lines* are never mangled or mistaken for headings.*/-function splitByCodeFence(md: string): { code: boolean; text: string }[] {+export function splitByCodeFence(md: string): { code: boolean; text: string }[] {const segments: { code: boolean; text: string }[] = [];let buf: string[] = [];let inCode = false;@@ -102,7 +82,7 @@ function splitByCodeFence(md: string): { code: boolean; text: string }[] {}/** Strip MDX components down to plain markdown/text the LLM can read. */-function stripComponents(body: string): string {+export function stripComponents(body: string): string {// Only transform prose; leave fenced code blocks byte-for-byte intact.const out = splitByCodeFence(body).map((seg) => (seg.code ? seg.text : stripComponentsFromProse(seg.text)))@@ -148,7 +128,8 @@ function stripComponentsFromProse(body: string): string {out = out.replace(/<Figure\b[^>]*>[\s\S]*?<\/Figure>/g, "");// <AgentContext> is agent-only: invisible on the site (renders null), but its inner- // content is meant FOR this KB. Unwrap it — keep the content, drop the tags.+ // content is meant FOR the machine-readable corpora. Unwrap it — keep the content,+ // drop the tags.out = out.replace(/<\/?AgentContext\b[^>]*>/g, "");// Unwrap container components — keep the inner content, drop the tags.@@ -169,8 +150,8 @@ function stripComponentsFromProse(body: string): string {return out;}-/** Collect `##`/`###` heading texts for the search manifest (ignoring code blocks). */-function headings(body: string): string[] {+/** Collect `##`/`###` heading texts (ignoring code blocks). */+export function headings(body: string): string[] {return splitByCodeFence(body).filter((seg) => !seg.code).flatMap((seg) => seg.text.split("\n"))@@ -179,7 +160,7 @@ function headings(body: string): string[] {}/** Derive keywords from the title + slug segments (docs frontmatter has none). */-function keywords(title: string, slug: string): string[] {+export function keywords(title: string, slug: string): string[] {const words = `${title} ${slug.replace(/[/-]/g, " ")}`.toLowerCase().split(/\s+/)@@ -187,103 +168,34 @@ function keywords(title: string, slug: string): string[] {return Array.from(new Set(words));}-function main() {- const files = walkMdx(CONTENT_DIR).sort();- const written = new Set<string>();- const manifest: ManifestEntry[] = [];-- for (const file of files) {- const raw = fs.readFileSync(file, "utf8");- const slug = path- .relative(CONTENT_DIR, file)- .replace(/\.mdx$/, "")- .split(path.sep)- .join("/");-- const { fm, body } = splitFrontmatter(raw);- const title = fmValue(fm, "title") || slug;- const description = fmValue(fm, "description");- const clean = stripComponents(body);-- const md = `# ${title}\n\n${description ? `> ${description}\n\n` : ""}${clean}\n`;- const outPath = path.join(KB_DIR, `${slug}.md`);- fs.mkdirSync(path.dirname(outPath), { recursive: true });- fs.writeFileSync(outPath, md, "utf8");- written.add(path.resolve(outPath));+export type CorpusPage = {+ /** Content-relative slug, e.g. `docs/reference/quotes` or `guides/order`. */+ slug: string;+ title: string;+ description: string;+ /** Component-stripped markdown body. */+ markdown: string;+ headings: string[];+};- manifest.push({- slug,- title,- description,- keywords: keywords(title, slug),- headings: headings(body),+/** Read every page under a content dir as stripped markdown, sorted by slug. */+export function readCorpus(contentDir: string): CorpusPage[] {+ return walkMdx(contentDir)+ .sort()+ .map((file) => {+ const raw = fs.readFileSync(file, "utf8");+ const slug = path+ .relative(contentDir, file)+ .replace(/\.mdx$/, "")+ .split(path.sep)+ .join("/");+ const { fm, body } = splitFrontmatter(raw);+ return {+ slug,+ title: fmValue(fm, "title") || slug,+ description: fmValue(fm, "description"),+ markdown: stripComponents(body),+ headings: headings(body),+ };});- }-- manifest.sort((a, b) => a.slug.localeCompare(b.slug));- fs.mkdirSync(KB_DIR, { recursive: true });- fs.writeFileSync(- MANIFEST_PATH,- `${JSON.stringify(- {- _comment:- "GENERATED by scripts/generate-agent-kb.ts from docs/content. Do not hand-edit — run `pnpm run generate:agent-kb`.",- docs: manifest,- },- null,- 2- )}\n`,- "utf8"- );-- // Drop a README so nobody hand-edits this folder. Added to `written` so the- // prune step below doesn't delete it.- const readmePath = path.join(KB_DIR, "README.md");- fs.writeFileSync(- readmePath,- `# Agent knowledge base (auto-generated — do not edit)--Every file in this folder is generated from the docs site (\`docs/content/**\`) by-\`scripts/generate-agent-kb.ts\`. It is the read-only corpus the in-app agent searches-(\`search_docs\`) and reads (\`read_doc\`), bundled into the erp image so it ships with the app.--**Do not edit these files by hand — your changes will be overwritten.**--To update the content, edit the source docs under \`docs/content/\` and regenerate, then-commit the result **in the same commit** as the docs change (same model as filling \`.po\`-translations before committing):--\`\`\`bash-pnpm run generate:agent-kb-\`\`\`--The check-and-commit skill runs this automatically when \`docs/content/**\` or the generator-is in the change set. See \`.ai/rules/agent-knowledge-base.md\`.-`,- "utf8"- );- written.add(path.resolve(readmePath));-- // Prune stale generated .md (source docs removed).- const pruned: string[] = [];- const walkKb = (dir: string) => {- if (!fs.existsSync(dir)) return;- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const p = path.join(dir, entry.name);- if (entry.isDirectory()) {- walkKb(p);- if (fs.readdirSync(p).length === 0) fs.rmdirSync(p);- } else if (entry.name.endsWith(".md") && !written.has(path.resolve(p))) {- fs.rmSync(p);- pruned.push(path.relative(KB_DIR, p));- }- }- };- walkKb(KB_DIR);-- console.log(`Wrote ${manifest.length} docs -> ${path.relative(ROOT, KB_DIR)}`);- console.log(`Manifest: ${path.relative(ROOT, MANIFEST_PATH)}`);- if (pruned.length) console.log(`Pruned ${pruned.length} stale: ${pruned.join(", ")}`);}--main();diff --git a/docs/next.config.mjs b/docs/next.config.mjsindex 7cedf9b6b0..7b0fadeb85 100644--- a/docs/next.config.mjs+++ b/docs/next.config.mjs@@ -31,12 +31,12 @@ const config = {"*.ngrok.app","*.ngrok.io",],- // Serve the Architecture reference at "/" without changing the URL — a server-side+ // Serve the docs Overview at "/" without changing the URL — a server-side// rewrite, not a client/redirect bounce. `beforeFiles` runs ahead of the app router// so it takes precedence (app/page.tsx is removed).async rewrites() {return {- beforeFiles: [{ source: "/", destination: "/docs/platform/architecture" }],+ beforeFiles: [{ source: "/", destination: "/docs" }],};},// Deployment moved under Self-hosting as the "AWS with SST" recipe; keep the old@@ -48,6 +48,19 @@ const config = {destination: "/docs/platform/self-hosting",permanent: true,},+ // Architecture is developer content, so it moved under Building on Carbon;+ // single sign-on is admin content, so it moved into the Product reference+ // next to two-factor.+ {+ source: "/docs/platform/architecture",+ destination: "/docs/building/architecture",+ permanent: true,+ },+ {+ source: "/docs/platform/single-sign-on",+ destination: "/docs/reference/single-sign-on",+ permanent: true,+ },// The Data API moved from its own root to a section inside /api, so the whole// surface lives under one header entry, one sidebar and one host/API-key// configurator. Paths below the root are unchanged, so :path* maps 1:1 —diff --git a/docs/scripts/generate-agent-kb.ts b/docs/scripts/generate-agent-kb.tsnew file mode 100644index 0000000000..81bc4f972f--- /dev/null+++ b/docs/scripts/generate-agent-kb.ts@@ -0,0 +1,133 @@+/**+ * generate-agent-kb (docs/scripts) — build the in-app agent's read-only knowledge base from the docs site.+ *+ * The Fumadocs MDX under `docs/content/**` is the source of truth. The in-app agent+ * (apps/erp `modules/agent`) reads a flattened, component-stripped copy of every page from+ * `apps/erp/app/modules/agent/kb/<slug>.md`, plus a `manifest.json` keyword index that+ * `search_docs` scans. This script regenerates both and prunes stale files.+ *+ * The MDX→markdown stripping lives in `docs/lib/markdown-corpus.ts`, shared with the+ * public `/llms.txt` + `/llms-full.txt` routes so the agent corpus and the AI-crawler+ * corpus can never disagree about what a page says.+ *+ * Committed output ships inside the erp Docker image, so the agent reads it with a bundled+ * import / fs read at runtime (no docs-app dependency). Mirrors the `generate-mcp.ts` pattern.+ *+ * Run it manually after editing docs/content, and commit the regenerated kb/ alongside+ * the docs change — same model as filling .po files before a commit. The check-and-commit+ * skill runs it automatically when docs/content or this script is in the change set.+ * See .ai/rules/agent-knowledge-base.md.+ *+ * Run: pnpm run generate:agent-kb+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { keywords, readCorpus } from "../lib/markdown-corpus";++// Paths resolve from this file's location, so the script works from any cwd+// (run via `pnpm run generate:agent-kb` at the repo root).+const DOCS_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");+const ROOT = path.join(DOCS_ROOT, "..");+const CONTENT_DIR = path.join(DOCS_ROOT, "content");+const KB_DIR = path.join(ROOT, "apps/erp/app/modules/agent/kb");+const MANIFEST_PATH = path.join(KB_DIR, "manifest.json");++type ManifestEntry = {+ slug: string;+ title: string;+ description: string;+ keywords: string[];+ headings: string[];+};++function main() {+ const pages = readCorpus(CONTENT_DIR);+ const written = new Set<string>();+ const manifest: ManifestEntry[] = [];++ for (const page of pages) {+ const md = `# ${page.title}\n\n${+ page.description ? `> ${page.description}\n\n` : ""+ }${page.markdown}\n`;+ const outPath = path.join(KB_DIR, `${page.slug}.md`);+ fs.mkdirSync(path.dirname(outPath), { recursive: true });+ fs.writeFileSync(outPath, md, "utf8");+ written.add(path.resolve(outPath));++ manifest.push({+ slug: page.slug,+ title: page.title,+ description: page.description,+ keywords: keywords(page.title, page.slug),+ headings: page.headings,+ });+ }++ manifest.sort((a, b) => a.slug.localeCompare(b.slug));+ fs.mkdirSync(KB_DIR, { recursive: true });+ fs.writeFileSync(+ MANIFEST_PATH,+ `${JSON.stringify(+ {+ _comment:+ "GENERATED by docs/scripts/generate-agent-kb.ts from docs/content. Do not hand-edit — run `pnpm run generate:agent-kb`.",+ docs: manifest,+ },+ null,+ 2+ )}\n`,+ "utf8"+ );++ // Drop a README so nobody hand-edits this folder. Added to `written` so the+ // prune step below doesn't delete it.+ const readmePath = path.join(KB_DIR, "README.md");+ fs.writeFileSync(+ readmePath,+ `# Agent knowledge base (auto-generated — do not edit)++Every file in this folder is generated from the docs site (\`docs/content/**\`) by+\`docs/scripts/generate-agent-kb.ts\`. It is the read-only corpus the in-app agent searches+(\`search_docs\`) and reads (\`read_doc\`), bundled into the erp image so it ships with the app.++**Do not edit these files by hand — your changes will be overwritten.**++To update the content, edit the source docs under \`docs/content/\` and regenerate, then+commit the result **in the same commit** as the docs change (same model as filling \`.po\`+translations before committing):++\`\`\`bash+pnpm run generate:agent-kb+\`\`\`++The check-and-commit skill runs this automatically when \`docs/content/**\` or the generator+is in the change set. See \`.ai/rules/agent-knowledge-base.md\`.+`,+ "utf8"+ );+ written.add(path.resolve(readmePath));++ // Prune stale generated .md (source docs removed).+ const pruned: string[] = [];+ const walkKb = (dir: string) => {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ walkKb(p);+ if (fs.readdirSync(p).length === 0) fs.rmdirSync(p);+ } else if (entry.name.endsWith(".md") && !written.has(path.resolve(p))) {+ fs.rmSync(p);+ pruned.push(path.relative(KB_DIR, p));+ }+ }+ };+ walkKb(KB_DIR);++ console.log(`Wrote ${manifest.length} docs -> ${path.relative(ROOT, KB_DIR)}`);+ console.log(`Manifest: ${path.relative(ROOT, MANIFEST_PATH)}`);+ if (pruned.length) console.log(`Pruned ${pruned.length} stale: ${pruned.join(", ")}`);+}++main();diff --git a/package.json b/package.jsonindex 256423efdc..d6d4331c60 100755--- a/package.json+++ b/package.json@@ -57,7 +57,7 @@"dev:packages": "turbo run dev --filter=./packages/*","dev:starter": "turbo run dev --filter=./apps/starter --filter=./packages/","format": "biome format --write",- "generate:agent-kb": "tsx scripts/generate-agent-kb.ts",+ "generate:agent-kb": "tsx docs/scripts/generate-agent-kb.ts","generate:mcp": "tsx scripts/generate-mcp.ts","generate:swagger": "tsx scripts/generate-swagger-docs.ts && pnpm exec biome format ./packages/database/src/swagger-docs-schema.ts --write --files-max-size=20000000","generate:types": "tsx scripts/generate-db-types.ts",diff --git a/packages/utils/src/status-colors.ts b/packages/utils/src/status-colors.tsindex e9905798c8..81912c4eb9 100644--- a/packages/utils/src/status-colors.ts+++ b/packages/utils/src/status-colors.ts@@ -247,21 +247,132 @@ export const GAUGE_ROLE_COLOR_MAP = {Standard: "gray"} as const satisfies Record<string, StatusColor>;+// ChangeNoticeStatus.tsx — Done is success; open stages step gray → blue → yellow → orange.+export const CHANGE_ORDER_STATUS_COLOR_MAP = {+ Draft: "gray",+ Start: "blue",+ "Engineering Complete": "yellow",+ Implementation: "orange",+ Done: "green",+ Cancelled: "red"+} as const satisfies Record<string, StatusColor>;++// QualityDocumentStatus.tsx+export const QUALITY_DOCUMENT_STATUS_COLOR_MAP = {+ Draft: "gray",+ Active: "green",+ Archived: "red"+} as const satisfies Record<string, StatusColor>;++// InspectionStatus.tsx (`getInspectionStatusVariant`; the fallback variant covers Pending).+export const INSPECTION_STATUS_COLOR_MAP = {+ Pending: "gray",+ "In Progress": "blue",+ Passed: "green",+ Failed: "red",+ Partial: "yellow"+} as const satisfies Record<string, StatusColor>;++// PaymentStatus.tsx+export const PAYMENT_STATUS_COLOR_MAP = {+ Draft: "gray",+ Posted: "green",+ Voided: "red"+} as const satisfies Record<string, StatusColor>;++// TrainingStatus.tsx (course lifecycle).+export const TRAINING_COURSE_STATUS_COLOR_MAP = {+ Draft: "gray",+ Active: "green",+ Archived: "red"+} as const satisfies Record<string, StatusColor>;++// TrainingAssignmentForm.tsx StatusBadge ("Not Required" renders outline → gray token).+export const TRAINING_ASSIGNMENT_STATUS_COLOR_MAP = {+ Pending: "gray",+ Completed: "green",+ Overdue: "red",+ "Not Required": "gray"+} as const satisfies Record<string, StatusColor>;++// IntercompanyTransactionStatus.tsx+export const INTERCOMPANY_TRANSACTION_STATUS_COLOR_MAP = {+ Unmatched: "orange",+ Matched: "green",+ Eliminated: "gray"+} as const satisfies Record<string, StatusColor>;++// PickingListStatus.tsx+export const PICKING_LIST_STATUS_COLOR_MAP = {+ Draft: "gray",+ "In Progress": "blue",+ Partial: "orange",+ Completed: "green",+ Cancelled: "red"+} as const satisfies Record<string, StatusColor>;++/* Pick lines have no dedicated component; PickingListLines badges render picked=green,+ * short=orange. Pending/Cancelled follow the house not-started/dead conventions. */+export const PICKING_LIST_LINE_STATUS_COLOR_MAP = {+ Pending: "gray",+ Picked: "green",+ Short: "orange",+ Cancelled: "red"+} as const satisfies Record<string, StatusColor>;++// PeopleTable.tsx account-status badges (Inactive renders secondary → gray token).+export const EMPLOYEE_ACCOUNT_STATUS_COLOR_MAP = {+ Active: "green",+ Invited: "yellow",+ Inactive: "gray"+} as const satisfies Record<string, StatusColor>;++// TimecardsTable.tsx (Complete renders secondary → gray token).+export const TIMECARD_STATUS_COLOR_MAP = {+ Active: "green",+ Complete: "gray"+} as const satisfies Record<string, StatusColor>;+/* Registry keyed by a short entity id — lets a generic consumer (e.g. the docs StatusFlow)- * resolve a status name to its color without importing each map by hand. */+ * resolve a status name to its color without importing each map by hand. Every map above is+ * registered; `inventoryCount` aliases the receipt map because InventoryCountStatus.tsx+ * deliberately shares the Draft / Pending / Posted lifecycle with receipts. */export const statusColorMaps = {job: JOB_STATUS_COLOR_MAP,jobOperation: JOB_OPERATION_STATUS_COLOR_MAP,jobOperationBatch: BATCH_STATUS_COLOR_MAP,quote: QUOTE_STATUS_COLOR_MAP,salesOrder: SALES_STATUS_COLOR_MAP,+ salesRfq: SALES_RFQ_STATUS_COLOR_MAP,purchaseOrder: PURCHASE_ORDER_STATUS_COLOR_MAP,+ purchasingRfq: PURCHASING_RFQ_STATUS_COLOR_MAP,+ supplierQuote: SUPPLIER_QUOTE_STATUS_COLOR_MAP,receipt: RECEIPT_STATUS_COLOR_MAP,shipment: SHIPMENT_STATUS_COLOR_MAP,+ inventoryCount: RECEIPT_STATUS_COLOR_MAP,+ stockTransfer: STOCK_TRANSFER_STATUS_COLOR_MAP,+ pickingList: PICKING_LIST_STATUS_COLOR_MAP,+ pickingListLine: PICKING_LIST_LINE_STATUS_COLOR_MAP,maintenanceDispatch: MAINTENANCE_DISPATCH_STATUS_COLOR_MAP,fixedAsset: FIXED_ASSET_STATUS_COLOR_MAP,trackedEntity: TRACKED_ENTITY_STATUS_COLOR_MAP,- supplierQuote: SUPPLIER_QUOTE_STATUS_COLOR_MAP,+ salesInvoice: SALES_INVOICE_STATUS_COLOR_MAP,+ purchaseInvoice: PURCHASE_INVOICE_STATUS_COLOR_MAP,+ payment: PAYMENT_STATUS_COLOR_MAP,+ journalEntry: JOURNAL_ENTRY_STATUS_COLOR_MAP,+ accountingPeriod: PERIOD_CLOSE_STATUS_COLOR_MAP,+ intercompanyTransaction: INTERCOMPANY_TRANSACTION_STATUS_COLOR_MAP,+ issue: ISSUE_STATUS_COLOR_MAP,+ inspection: INSPECTION_STATUS_COLOR_MAP,+ qualityDocument: QUALITY_DOCUMENT_STATUS_COLOR_MAP,+ risk: RISK_STATUS_COLOR_MAP,+ gauge: GAUGE_STATUS_COLOR_MAP,+ gaugeCalibration: GAUGE_CALIBRATION_STATUS_COLOR_MAP,+ changeOrder: CHANGE_ORDER_STATUS_COLOR_MAP,+ trainingCourse: TRAINING_COURSE_STATUS_COLOR_MAP,+ trainingAssignment: TRAINING_ASSIGNMENT_STATUS_COLOR_MAP,+ employeeAccount: EMPLOYEE_ACCOUNT_STATUS_COLOR_MAP,+ timecard: TIMECARD_STATUS_COLOR_MAP,workflowRun: WORKFLOW_RUN_STATUS_COLOR_MAP} as const;