Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(ee): commercial entitlement pattern + gate starter-only features (#1677)

Brad Barbin5d5f9448fbce
diff --git a/.ai/plans/2026-09-18-move-permissions-to-ee.md b/.ai/plans/2026-09-18-move-permissions-to-ee.md
new file mode 100644
index 0000000000..3038b93835
--- /dev/null
+++ b/.ai/plans/2026-09-18-move-permissions-to-ee.md
@@ -0,0 +1,269 @@
+# Move permission management to the commercial (`.ee`) surface
+
+**Branch:** `move-permissions-to-ee`
+**Date:** 2026-09-18
+**Author:** [email protected]
+
+## Goal
+
+Relocate the *authoring* of RBAC — creating/editing employee types, editing an
+individual user's permissions, and console (kiosk) mode — behind the commercial
+license marker (`.ee`) and the existing plan gate, so the Community/Starter
+edition ships an "everyone is an admin" experience: you can **add users** but not
+**author roles** or **modify permissions**.
+
+This is a **posture + gating** change, not a mechanical build change. The `.ee`
+infix and `packages/ee` are *license* boundaries only — there is no build-time
+edition stripping. Restriction is delivered by the plan gate, not by the file move.
+
+## Non-goals (explicitly deferred to the license-server work)
+
+- Collapsing the 4-value `Edition` enum (`Cloud/Enterprise/Community/Test`) to two.
+- Unifying the ~8 existing gating mechanisms (inline `CarbonEdition` checks,
+ `canAccessBackups`/internal-email, `isCarbonOwnedCompany`, the hand-rolled
+ Starter-block in `auth.server.ts:325`, route-flag declarations, ITAR).
+- Making the **generic** plan gate enforce off-Cloud for the OTHER 11 features
+ (workflows, API keys, …). Those keep `requirePlan`/`companyHasPlan`, which
+ no-op off Cloud — a self-hosted community instance still gets them until the
+ license server. (UPDATE 2026-09-19: the permission/console features now DO
+ enforce on Community via the new `companyHasFeature`/`requireFeature` — see the
+ follow-up section. Only the broader "all features off on Community" question is
+ deferred.)
+- Migrating SSO's edition-gate (`isSsoEnabled`) to plan-based. (Note for later:
+ SSO is edition-gated only because cloud Supabase can't run SAML yet — once it
+ can, it should become a `FEATURE_PLANS` entry too.)
+
+## Enforcement stays everywhere — do NOT touch
+
+Runtime permission *enforcement* is community functionality and must keep working
+unchanged: `requirePermissions` (`@carbon/auth`, ~1,319 call sites), `get_claims`
+/ `has_company_permission` (Postgres), all RLS policies, `getUserClaims` / the
+Redis permission cache, and the client `usePermissions` hook. We only relocate and
+gate the **authoring** layer.
+
+## The product boundary
+
+| Capability | Edition | Community behavior |
+|---|---|---|
+| Add / invite / deactivate users; user list | Community ✅ | unchanged |
+| Enforcement (`requirePermissions`, RLS, claims) | Community ✅ | unchanged |
+| Create / edit / delete employee types | Business (`PERMISSIONS`) | hidden + gated |
+| Edit an individual user's permissions; bulk-edit; change a user's employee type | Business (`PERMISSIONS`) | hidden + gated |
+| Console (kiosk) mode + Console Operator type | Business (`PERMISSIONS`) | hidden + gated |
+
+**"Everyone is an admin" is emergent, not a new permission branch.** `seed-company`
+seeds exactly one employee type — `Admin` (`protected: true`, `systemType: 'Admin'`,
+full permissions). If Community never exposes employee-type creation *and* never
+exposes console mode (the only other type-creating path), `Admin` is the only type
+that can ever exist. The one required code change is the invite form: today it
+*requires* the inviter to pick a type from a dropdown (`employeeType: z.string().min(1)`
+in `users.models.ts`); in the gated case we hide the picker and resolve the
+`systemType='Admin'` type in the action so every new Community user is an admin.
+
+## Gate: one `FEATURE_PLANS` entry
+
+`packages/ee/src/plan.ts` — add:
+
+```ts
+PERMISSIONS: [Plan.Business, Plan.Partner],
+```
+
+Single key covering role authoring + console mode (per decision — not two keys).
+`packages/ee/AGENTS.md` lists changing `FEATURE_PLANS` as "Ask First" — approved.
+
+Server: wrap gated route loaders/actions with
+`requirePlan({ request, client, companyId, redirectTo, feature: "PERMISSIONS" })`
+(from `@carbon/ee/plan.server`). `redirectTo` → the users index / settings page.
+Client: hide nav entries + surfaces with `usePlanGate({ feature: "PERMISSIONS" })`
+(from `~/hooks/usePlanGate`).
+
+---
+
+## Tasks
+
+### 1. Add the `PERMISSIONS` feature key
+- Edit `packages/ee/src/plan.ts`: add `PERMISSIONS: [Plan.Business, Plan.Partner]`.
+- Update `.claude/rules/billing-system.md` FEATURE_PLANS list and
+ `packages/ee/AGENTS.md` if it enumerates features.
+- **Verify:** `pnpm --filter @carbon/ee typecheck`.
+
+### 2. Relocate role/permission *authoring* code to `.ee`
+The `moduleShape` check allows exactly one `users.service.ts` and one
+`users.models.ts` per module, but **unlimited `*.server.ts`** files. So:
+
+- Create `apps/erp/app/modules/users/users.permissions.ee.server.ts` and move the
+ authoring-**exclusive** writes into it (verified by caller-map — see below):
+ - Employee-type CRUD: `insertEmployeeType`, `upsertEmployeeType`,
+ `deleteEmployeeType`, `upsertEmployeeTypePermissions` (from `users.service.ts`
+ L590/608/151/629) — callers are only the employee-type routes.
+ - `updateEmployee` (from `users.server.ts` L1483) — sole caller is the gated
+ per-user editor `employees.$employeeId.tsx`. It calls `updatePermissions`
+ cross-file, which is fine.
+- **CORRECTION to the original plan — DO NOT move these; they are shared plumbing
+ a community path or a background job depends on:**
+ - `updatePermissions` (`users.server.ts` L1511) — also called by the
+ `@carbon/jobs` task `update-permissions.ts`.
+ - `setUserPermissions` (`users.server.ts` L1449, private) — called by
+ `acceptInvite` (community invite acceptance). Moving it into a gated file
+ would break invites.
+ - The `make*` translators (`makeEmptyPermissionsFromModules`,
+ `makeCompanyPermissionsFromClaims`, `makePermissionsFromClaims`,
+ `makeCompanyPermissionsFromEmployeeType`) — pure rendering helpers with no
+ commercial weight; leaving them avoids a mid-file dependency web. The gate is
+ delivered by `requirePlan` on the route + the `.ee` UI, not by relocating
+ these. `makeEmptyPermissionsFromModules` is also used by
+ `api+/users.empty-permissions.ts` (gate that route too).
+- **Leave in community** (invite path depends on them): `createEmployeeAccount`,
+ `getPermissionsByEmployeeType`, `makePermissionsFromEmployeeType`, `getModules`,
+ `getEmployeeType`/`getEmployeeTypes` reads.
+- Rename the UI to `.ee.tsx` (license marker; imports update to the literal path,
+ like `ConfigurationEditor.ee`):
+ - `modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx`,
+ `EmployeeTypesTable.tsx` → `.ee.tsx`.
+ - `modules/users/ui/Employees/EmployeePermissionsForm.tsx`,
+ `BulkEditPermissionsForm.tsx` → `.ee.tsx`.
+- Validators: `employeeTypeValidator`, `employeeTypePermissionsValidator`,
+ `userPermissionsValidator`, `bulkPermissionsValidator` — keep in
+ `users.models.ts` (the single models file; do not create a second models file),
+ OR move to the `.ee.server.ts` if they are used only by gated routes. Decide by
+ grepping their importers.
+- Update the `~/modules/users` barrel (`index.ts`) exports accordingly.
+- **Verify:** `pnpm exec turbo run typecheck --filter=@carbon/erp` after wiring;
+ `node scripts/... module-shape` (via `pnpm run lint` / the checks) passes — no
+ `extra-service` / missing-file findings.
+
+### 3. Gate the role/permission routes
+- `x+/users+/employee-types.tsx`, `employee-types.$employeeTypeId.tsx`,
+ `employee-types.new.tsx`, `employee-types.delete.$employeeTypeId.tsx`,
+ `employees.$employeeId.tsx`, `bulk-edit-permissions.tsx`: add `requirePlan({...,
+ feature: "PERMISSIONS" })` in loader **and** action, after `requirePermissions`.
+- Hide their nav/entry points. The Employee-Types settings nav lives via
+ `modules/settings/ui/useSettingsSubmodules.tsx` and/or the users module nav —
+ gate the entries with `usePlanGate({ feature: "PERMISSIONS" })`. In
+ `EmployeesTable.tsx`, hide the "Edit permissions" / bulk-edit affordances when
+ gated.
+- **Verify (Cloud path):** with `CARBON_EDITION=cloud` and a non-bypassed Starter
+ company, the routes redirect with the upgrade flash; a Business company reaches
+ them. Off-Cloud they pass (documented gap).
+
+### 4. Invite path → default to Admin in the gated case
+- `x+/users+/employees.new.tsx` + `modules/users/ui/Employees/CreateEmployeeModal.tsx`:
+ when `usePlanGate({ feature: "PERMISSIONS" }).isGated`, hide the employee-type
+ `<Select>`; the action resolves the `systemType='Admin'` employee type for the
+ company and passes its id as `employeeType` so `createEmployeeValidator`
+ (`employeeType` required) is satisfied and `createEmployeeAccount` snapshots the
+ full Admin permission set.
+- Keep the ungated (Business) behavior exactly as today (real picker).
+- **Verify:** on a gated company, inviting a user with no picker yields a user with
+ full Admin permissions on accept; on Business, the picker still drives the type.
+
+### 5. Console (kiosk) mode → Business
+- Locate the console-mode setting route + UI (grep `updateConsoleSetting`,
+ `consoleEnabled`/`console` in `apps/erp/app/routes/x+/settings+/` and
+ `modules/settings/ui/`). `updateConsoleSetting` is in
+ `apps/erp/app/modules/settings/settings.service.ts` (~L1390) and creates the
+ `Console Operator` protected type (L1411–1479).
+- Gate the console setting action/route with `requirePlan({..., feature:
+ "PERMISSIONS" })` and hide the toggle with `usePlanGate`.
+- Move the Console-Operator-type-creation block (the commercial part of
+ `updateConsoleSetting`) behind the license marker — extract it to
+ `users.permissions.ee.server.ts` (or a settings `.ee.server.ts`) and call it
+ from the gated action. `settings.service.ts` is the module's single service
+ file; do not add a second service file — extract to a `.server.ts`.
+- **Verify:** gated company cannot enable console mode / create a Console Operator
+ type; Business can.
+
+### 6. Docs / rules sync
+- Update `packages/ee/AGENTS.md` (new `PERMISSIONS` gate; note the relocated
+ authoring surface), `.claude/rules/billing-system.md` (FEATURE_PLANS list), and
+ `.claude/rules/authentication-system.md` if it describes where permission
+ authoring lives. Consider a short `.claude/rules/` note or an
+ `apps/erp/app/modules/users/AGENTS.md` update documenting the community/enterprise
+ cut and the "everyone is admin" emergent behavior.
+- If any user-facing docs describe employee types / permissions, note the edition
+ gating (carbon-docs skill).
+
+### 7. Full verification
+- `pnpm exec turbo run typecheck --filter=@carbon/erp`
+- `pnpm exec turbo run typecheck --filter=@carbon/ee`
+- `pnpm run lint` (module-shape + conformance checks green)
+- `pnpm --filter @carbon/ee test`
+- Browser (per UI-e2e-verification rule): boot `crbn up`, verify with
+ `CARBON_EDITION=cloud` + a Starter (non-bypass) company that the surfaces hide
+ and invite defaults to Admin; with a Business company that everything is present.
+
+## Consolidation follow-up (2026-09-19) — moved the valuable logic to `packages/ee`
+
+After the first pass (which relocated only the thin CRUD to an app-local
+`.ee.server.ts`), we moved the actual IP — the flattened-permission-object
+builder and translators — into the package, and deduped a hidden second copy:
+
+- New `@carbon/ee/permissions.server` (`packages/ee/src/permissions.server.ts`)
+ now holds `updatePermissions`, `updateEmployee`, the employee-type CRUD, and
+ the `make*` translators (`makeEmptyPermissionsFromModules`,
+ `makeCompanyPermissionsFromClaims`, `makeCompanyPermissionsFromEmployeeType`).
+ Local structural `CompanyPermission`/`Permission` types (no `~/` coupling).
+- The app-local `users.permissions.ee.server.ts` was **deleted**; all ERP
+ routes import from `@carbon/ee/permissions.server`.
+- **Dedup:** `@carbon/jobs` `update-permissions.ts` had its OWN full copy of
+ `updatePermissions` (drifted). It now imports the one in `@carbon/ee` and is
+ just the durable wrapper. `@carbon/jobs` already depends on `@carbon/ee`, and
+ `@carbon/ee` does not depend on `@carbon/jobs` — no cycle.
+- **Stayed in the app** (`users.server.ts`), community invite plumbing:
+ `setUserPermissions` (invite merge) and `makePermissionsFromEmployeeType`
+ (invite snapshot). The ERP `makePermissionsFromClaims` was **dead code**
+ (only `@carbon/auth` has a used copy) and was deleted.
+- **UI stays `.ee.tsx` in the app** — the forms import `~/components/Form`,
+ `~/hooks`, `~/utils/path`, which don't exist in the package.
+- `@carbon/ee` uses `noUncheckedIndexedAccess`; the ported translator needed a
+ `module === undefined` guard and a local-ref rewrite the ERP tsconfig didn't.
+
+Verified: `@carbon/ee`, `@carbon/jobs`, `erp` typecheck clean (only the
+pre-existing `root.tsx` typegen artifact); Biome clean; MCP digest unchanged
+(users 30, settings 95 — the moved fns were never in `*.service.ts`).
+
+## Execution status (2026-09-19)
+
+Implemented on branch `move-permissions-to-ee`. Verified: `@carbon/ee` + `erp`
+typecheck clean (only the pre-existing `root.tsx` `+types/root` typegen artifact,
+untouched by this work), Biome clean, MCP digest regenerated. **Not** done:
+browser e2e (stack not booted) and the license-server off-Cloud enforcement (out
+of scope by design).
+
+What landed:
+- `packages/ee/src/plan.ts`: `PERMISSIONS: [Plan.Business, Plan.Partner]`.
+- New commercial files: `apps/erp/app/modules/users/users.permissions.ee.server.ts`
+ (the 4 employee-type CRUD funcs + `updateEmployee`) and
+ `.../settings/settings.console.ee.server.ts` (`updateConsoleSetting`); removed
+ from `users.service.ts` / `settings.service.ts`.
+- UI renamed to `.ee.tsx`: `EmployeeTypeForm`, `EmployeeTypesTable`,
+ `EmployeePermissionsForm`, `BulkEditPermissionsForm` (barrels repointed).
+- `requirePlan({ feature: "PERMISSIONS" })` on all 7 authoring routes
+ (employee-types list/new/$id/delete, employees.$employeeId, bulk-edit,
+ api/users.empty-permissions). Console gated in `people.tsx` via an
+ edition/plan predicate (fetcher returns JSON, so no redirect).
+- Community "everyone is admin": invite (`employees.new` action) resolves the
+ seeded `systemType='Admin'` type when gated; `CreateEmployeeModal` hides the
+ picker + submits a Hidden Admin id. Nav ("Employee Types"), the bulk/per-user
+ "Edit Permissions" affordances, and the Console Mode card are hidden client-side
+ via `usePlanGate`.
+
+**MCP surface change (intentional):** moving the 5 write functions out of
+`*.service.ts` removed them as auto-generated MCP tools —
+`users_{insert,upsert,delete}EmployeeType`, `users_upsertEmployeeTypePermissions`,
+`settings_updateConsoleSetting`. This CLOSES a previously ungated path: the MCP
+tools called the service directly, bypassing the route `requirePlan`. Digest
+regenerated (`users` 30, `settings` 95).
+
+## Open risks to resolve during execution
+1. **Shared reads.** Some employee-type reads (`getEmployeeType(s)`,
+ `getPermissionsByEmployeeType`) are used by community paths (invite). Grep every
+ importer before moving; keep community-needed reads in `users.service.ts`.
+2. **`users.server.ts` duplicates `@carbon/auth`** (`getClaims`,
+ `getPermissionCacheKey`). Don't move those to `.ee`; they're enforcement-adjacent.
+ Optionally reconcile the duplication, but that's not required for this PR.
+3. **Client/server gate divergence** (§ non-goals): accept it; ensure the route
+ uses `requirePlan` so the future off-Cloud flip is one edit.
+4. **Console Operator uniqueness** — the partial unique index from
+ `20260401000000_protect-console-operator-type.sql` still holds; we don't change
+ schema, only who can trigger the insert.
diff --git a/.ai/plans/2026-09-20-commercial-gating-refactor.md b/.ai/plans/2026-09-20-commercial-gating-refactor.md
new file mode 100644
index 0000000000..90ea667689
--- /dev/null
+++ b/.ai/plans/2026-09-20-commercial-gating-refactor.md
@@ -0,0 +1,144 @@
+# Commercial Gating Refactor — overnight autonomous run
+
+**Branch:** `move-permissions-to-ee` · **Started:** 2026-09-20 · **Owner:** [email protected]
+**This file is the LEDGER.** It survives context resets — read it first, then continue
+from the STATUS table. The pattern spec is `.claude/rules/commercial-licensing.md`.
+
+## Goal
+Refactor every plan-gated commercial feature to the tamper-resistant pattern:
+1. Feature body lives in `packages/ee` (using it requires running commercial code).
+2. `requireEntitlement(client, companyId, FEATURE)` embedded INSIDE the ee authoring
+ functions (stripping the gate requires editing commercial code).
+3. Client UX: **visible + upgrade overlay**, never hidden. Route loaders DON'T
+ `requireFeature`-redirect the primary page; write routes/actions keep it.
+4. Gate helper: `companyHasFeature`/`requireFeature` (community-blocked) — NOT
+ `companyHasPlan`/`requirePlan` (Cloud-only no-op).
+
+## Per-feature refactor strategy (the loop)
+For each feature, one focused subagent does:
+1. Confirm/add the `FEATURE_PLANS` key.
+2. If the engine is in an app module / `packages/jobs`, relocate it to
+ `packages/ee/src/<feature>/` (or `<feature>.server.ts`). Fix `~/` deps
+ (`sanitize`→`@carbon/utils`; redefine `~/utils/query` types locally; keep
+ `trigger()`/`@carbon/notifications` in the ROUTE — `@carbon/ee` can't import
+ `@carbon/jobs`/`@carbon/notifications`).
+3. Embed `requireEntitlement` at the top of every authoring write fn; runtime reads
+ that must degrade use `companyHasFeature` → return empty/no-op.
+4. Repoint call sites; remove from the app module + barrel.
+5. **Bundling gotchas** (typecheck won't catch — only the dev build does): a client
+ barrel must NOT derive types via `ReturnType<service>` (derive from
+ `@carbon/database`); a `*.service.ts` must NOT import `@carbon/ee/<f>.server`
+ (move that caller to a `*.server.ts`). See the rule's "Bundling gotcha".
+6. UI: `.ee.tsx`; nav stays visible; gated page renders `usePlanGate` overlay
+ (`RulesUpgradeOverlay` for tables, `UpgradeOverlay` primitives / a modal for
+ editors — mirror `SalesRulesUpgradeOverlay` and the per-user permissions modal).
+7. `pnpm run generate:mcp` if functions left a `*.service.ts` (they drop as MCP tools —
+ usually correct; note it).
+
+## Verification per feature (what I CAN do autonomously)
+- `pnpm exec turbo run typecheck --filter=@carbon/ee`
+- `cd apps/erp && pnpm run typecheck` (ignore ONLY the pre-existing
+ `root.tsx(57) Cannot find module './+types/root'`)
+- `pnpm exec biome check --write <touched files>`
+- Relevant unit tests (`pnpm --filter @carbon/ee test`, app vitest).
+- **Add entitlement unit tests** exercising BOTH editions where practical
+ (`companyHasFeature`/`requireEntitlement`: Community→blocked, Enterprise/Cloud-Business→allowed).
+- `pnpm run translate` (or leave a note) to fill the new overlay strings.
+- Commit each feature as its own checkpoint (message `feat(ee): gate <FEATURE> …`).
+
+## Acceptance / testing — TWO PHASES (browser = human, in the morning)
+The dev build's `.server` client-graph check is the thing typecheck misses; I prevent
+it via the bundling rules but the **browser boot is the real proof** and is Brad's.
+1. **Gated case — `CARBON_EDITION=community`** (current `.env`): each feature's nav
+ entry is VISIBLE, the page shows the upgrade overlay, and writes are blocked
+ (direct-URL POST returns blocked / no effect). Inviting users still works.
+2. **Non-gated case — `CARBON_EDITION=enterprise`**: switch `.env`, restart stack.
+ Every feature is fully VISIBLE and FUNCTIONAL (create/edit/delete work, no overlay).
+ → This validates the embedded `requireEntitlement` passes for entitled companies and
+ nothing was over-gated.
+A per-feature browser checklist is maintained in the STATUS table's Notes.
+
+## Context-management protocol (how the overnight run stays alive)
+- This file is the ledger; update the STATUS table after every feature.
+- Heavy work → one subagent per feature (fresh context). I verify + commit + update
+ ledger + dispatch the next. Subagent completion re-invokes me, so the loop is
+ self-sustaining as long as one subagent is always in flight.
+- STOP and leave a `⚠ BLOCKED` note (don't guess) when a feature needs a product
+ decision (is X a Business feature? destructive surface? engine too woven into jobs).
+- Do NOT open a PR or merge — commits on the branch are the deliverable for review.
+
+## TODO (ranked — from inventory abfcc035)
+Default decision (matches permissions/approvals precedent): convert `requirePlan`/
+`companyHasPlan` → `requireFeature`/`companyHasFeature` (community-blocked) for every
+gated feature; move authoring bodies into `packages/ee` + embed `requireEntitlement`;
+runtime engines that live in `packages/jobs`/`@carbon/notifications` (can't move to ee)
+just swap to `companyHasFeature` (degrade). Do these autonomously (A–I). FLAG the LARGE
+product/architecture decisions (J–L) — don't guess.
+
+- **A. SALES_RULES + STORAGE_RULES** (together — shared `upsertEnforcementRule`/
+ `deleteEnforcementRule` in `shared.service.ts:619,651`). Evaluators already in
+ `packages/ee/src/rules/{sales,storage}/server.ts` → swap `companyHasPlan`→
+ `companyHasFeature` (`sales/server.ts:48`, `storage/server.ts:50`); move the shared
+ enforcement-rule CRUD + `assign/unassign*` into ee, embed `requireEntitlement`; routes
+ `requirePlan`→`requireFeature`. Watch `shared.service.ts` barrel client-graph.
+- **B. EMAIL_NOTIFICATIONS** — body in `packages/jobs` `notify.ts:537` (can't move). Just
+ `companyHasPlan`→`companyHasFeature` there + `account+/notifications.tsx:49`. Tiny.
+- **C. INTEGRATIONS** — bodies already in ee. Embed `requireEntitlement("INTEGRATIONS")`
+ in `integrations/hooks.server.ts`/`secrets.ts` install/save (honor
+ `isIntegrationWhitelisted`); routes `integrations.$id.tsx:1476`,
+ `integrations.deactivate.$id.tsx:26` → `requireFeature`.
+- **D. TWO_FACTOR** — move only the `requireMfa` company-policy writer into ee +
+ `requireEntitlement` (mirror `updateConsoleSetting`); `security.tsx:159`→`requireFeature`.
+ Leave GoTrue MFA.
+- **E. API_KEYS** — move `upsertApiKey`/`deleteApiKey` (`settings.service.ts:1317,98`) to
+ ee + `requireEntitlement`; routes→`requireFeature`. Leave `@carbon/auth` runtime verify.
+ Barrel client-graph risk.
+- **F. WEBHOOKS** — move `upsertWebhook`/`deleteWebhook` (`settings.service.ts:1478,112`)
+ to ee + `requireEntitlement`; routes→`requireFeature`; gate delivery via runtime
+ `companyHasFeature` in jobs. Barrel risk.
+- **G. FORECAST** — extract `upsertDemandForecasts`/`deleteDemandForecasts`
+ (`production.service.ts:4753,498`) to ee + `requireEntitlement`; routes→`requireFeature`.
+- **H. CUSTOMER_PORTALS** — move portal authoring (`shared.service.ts:256-298` + the
+ `upsertExternalLink` path) to ee + `requireEntitlement`; keep public share-page
+ (`share+/customer.$id*`) as runtime `companyHasFeature` degrade.
+- **I. AUDIT_LOG** — ⚠ RE-SCOPED → FLAGGED (see STATUS row). This original framing was
+ wrong: the `audit-logs.tsx:92` `requirePlan` is in the ACTION (enable intent), not a
+ loader redirect, and the list route ALREADY renders visible+overlay. The real gate target
+ is `enableAuditLog` (the enable write), which has ITAR/compliance callers that make a hard
+ `requireEntitlement` unsafe without a licensing-policy decision. Flagged for Brad.
+
+### FLAGGED — do NOT do autonomously (need Brad)
+- **J. AI_AGENT** ⚠ — LARGE; currently HIDDEN when gated (`useAgentAvailable.ts:12`).
+ Decision needed: hidden→visible+overlay? Core in `modules/agent` deeply `~/`-coupled
+ (AI SDK, cross-module tools) — big relocation.
+- **K. WORKFLOWS** ⚠ — authoring movable to ee, but the runtime ENGINE is a full inngest
+ system in `packages/jobs` (gate via `companyHasFeature`). LARGE; confirmed
+ `workflows.service.ts` `ReturnType`/`~/utils/query` client-graph gotcha to fix.
+- **L. BACKUPS** ⚠ — engine deeply in `packages/jobs`; rule says relocate LAST. Already
+ gated via `canManageBackups` (route-level). Big lift; keep the `canAccessBackups`
+ internal/local-dev escape hatch.
+
+**Every move:** no `*.service.ts` may import `@carbon/ee/<f>.server` (barrel→client graph —
+move the caller to `*.server.ts`); derive client types from `@carbon/database`, not
+`ReturnType<service>`; run `generate:mcp` when fns leave a `*.service.ts`.
+
+## STATUS
+| Feature | Size | State | Commit | Notes |
+|---|---|---|---|---|
+| PERMISSIONS | — | ✅ done | ba2787c2 | body in ee, requireEntitlement embedded, per-user modal overlay |
+| console (PERMISSIONS) | — | ✅ done | ba2787c2 | console.server in ee, embedded; card gated-state |
+| APPROVAL_RULES | — | ✅ done | ba2787c2 | approvals/ in ee, embedded, page overlay |
+| BACKUPS | gate-only | ◑ gated | ba2787c2 | gated via canManageBackups; engine still in packages/jobs (LARGE relocation deferred — do last) |
+| A. SALES_RULES + STORAGE_RULES | MEDIUM | ✅ done | (this) | CRUD → packages/ee/src/rules/service.server.ts (`@carbon/ee/rules.server`), requireEntitlement by `family`; evaluators swapped companyHasPlan→companyHasFeature; 12 write routes → requireFeature; verified (ee+erp typecheck, biome, 1041 ee tests, mcp shared 31→29). `unassignStorageRule` gained companyId arg. |
+| B. EMAIL_NOTIFICATIONS | SMALL | ✅ done | (this) | companyHasPlan→companyHasFeature at notify.ts:537 (jobs, runtime degrade — email channel off for community) + account/notifications.tsx:49. Body stays in jobs (can't move to ee — @carbon/notifications dep). Verified jobs+erp typecheck. |
+| C. INTEGRATIONS | MED (arch) | ⚠ FLAGGED — needs Brad | | No single ee choke point for the install/save WRITE: it goes through community `upsertCompanyIntegration` (settings.server.ts:330, inline vault write), NOT ee `persistIntegrationSecrets`. Shared install/update dispatcher (`hooks.server.ts:84`) also serves uninstall+read (can't gate). Per-provider hooks have HOLES (jira/linear/onshape/paperless-parts/slack have no onInstall/onUpdate). **Decision:** (A) relocate the universal integration secret/metadata write into ee `persistIntegrationSecrets` + embed requireEntitlement (complete, covers OAuth callbacks; bigger) — RECOMMENDED; or (B) embed in the 4 existing provider hooks + accept documented holes. Route swap requirePlan→requireFeature held pending this (else it's a UX-only mislabeled moat). |
+| D. TWO_FACTOR | SMALL-MED | ✅ done | (this) | updateRequireMfaSetting → packages/ee/src/two-factor.server.ts; requireEntitlement scoped to ENABLING only (downgrade can still disable); security.tsx route→requireFeature; mcp 1548→1547. Verified. |
+| E. API_KEYS | MEDIUM | ✅ done | (this) | upsert/deleteApiKey → packages/ee/src/api-keys.server.ts + requireEntitlement (companyId from payload/row); 3 routes→requireFeature; key-gen/hash stays in route; mcp 1547→1545. Runtime verify (@carbon/auth) untouched. Verified. Doc-sync TODO: settings/AGENTS.md lists upsert/deleteApiKey (stale). |
+| F. WEBHOOKS | MEDIUM | ✅ done | (this) | upsert/delete/deactivateWebhooks → packages/ee/src/webhooks.server.ts + requireEntitlement; delivery gated via companyHasFeature degrade in jobs events/webhook.ts:37; 3 routes→requireFeature; mcp −3. Verified. |
+| G. FORECAST (demandForecast fns) | MEDIUM | ✅ done | (this) | PREMISE MISMATCH found: upsert/deleteDemandForecasts had NO app callers (MCP-only) — moved to packages/ee/src/forecast.server.ts + requireEntitlement (closes ungated DESTRUCTIVE MCP write path); mcp 252→250. The REAL forecast UI uses demandProjection — see G2. |
+| G2. FORECAST (demandProjection = the real feature) | MEDIUM | ✅ done | 5446f132fa | upsert/deleteDemandProjections → packages/ee/src/forecast.server.ts + requireEntitlement("FORECAST"); 3 demand-forecasts.* routes → requireFeature; mcp 1540→1538. ALSO fixed a pre-existing red test: mcp-tool-metadata.test.ts "module-local type alias" case referenced shared_upsertApprovalRule (removed when approvals→ee, ba2787c2) — repointed to items_diffMethod (`input: DiffMethodInput`, same named-alias path). Verified ee+erp typecheck, biome, full mcp test 19/19. |
+| H. CUSTOMER_PORTALS | MEDIUM | ✅ done | 0716bea88e | New packages/ee/src/customer-portals.server.ts: upsertCustomerPortal(client, companyId, portal) + deleteCustomerPortal(client, id, companyId), each requireEntitlement("CUSTOMER_PORTALS"). Did NOT gate the shared upsertExternalLink (also used by quote/RFQ/supplier-quote finalize) — added portal-specific ee writers instead. deleteCustomerPortal removed from shared.service.ts (now companyId-scoped); reads + upsertExternalLink stay. 3 routes → ee + requireFeature; list route already visible+overlay. Public share pages companyHasPlan→companyHasFeature (degrade). UI Form/Table → .ee.tsx. mcp 1538→1537 (shared_deleteCustomerPortal drops). Verified: ee+erp typecheck, biome, client-graph grep clean. |
+| I. AUDIT_LOG | MEDIUM | ⚠ FLAGGED — needs Brad | | NOT a clean surgical gate. (1) ITAR CONFLICT: enableAuditLog (the enable "write") has non-route compliance callers — company.new.tsx/companies.new.tsx call it at company creation under CONTROLLED_ENVIRONMENT, and audit-logs.tsx loader force-enables for controlled companies (audit is MANDATORY + non-disableable under ITAR). A hard requireEntitlement("AUDIT_LOG") inside enableAuditLog would BREAK audit enablement on a self-hosted Community ITAR install — UNLESS the invariant "CONTROLLED_ENVIRONMENT ⇒ Enterprise edition" is guaranteed (then companyHasFeature returns true and the gate is safe). That is a licensing/compliance policy call. (2) Body lives in @carbon/database/audit + @carbon/jobs (write path + archiving are Inngest), like K/L — a large relocation, not an app-service move. (3) No broken state today: list route already visible+overlay (AuditLogUpgradeOverlay + usePlanGate), settings action already has requirePlan UX gate. Same "incomplete moat" status as BACKUPS. **Decision for Brad:** is CONTROLLED_ENVIRONMENT always Enterprise-licensed? If yes → gate enableAuditLog in ee (safe). If a Community ITAR install is supported → the gate needs a CONTROLLED_ENVIRONMENT bypass. |
+| J. AI_AGENT | LARGE | ⚠ FLAGGED | | hidden→overlay decision + big relocation; needs Brad |
+| K. WORKFLOWS | LARGE | ⚠ FLAGGED | | engine in jobs; needs Brad |
+| L. BACKUPS engine | LARGE | ⚠ FLAGGED | | relocate engine from jobs; do last; needs Brad |
diff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.md
index 7dabbd1a0d..fb009fb898 100644
--- a/.claude/rules/billing-system.md
+++ b/.claude/rules/billing-system.md
@@ -82,9 +82,38 @@ several `invoice.*` events are forwarded to GTM.
## Plan gating (`packages/ee/src/plan.ts` + `plan.server.ts`)
`FEATURE_PLANS` (`plan.ts`) is the source of truth — both client and server read it:
-`API_KEYS, WEBHOOKS, INTEGRATIONS, SALES_RULES, AUDIT_LOG, EMAIL_NOTIFICATIONS, STORAGE_RULES,
-CUSTOMER_PORTALS` → each `[Plan.Business, Plan.Partner]`. `INTEGRATION_WHITELIST`
-(`email`) bypasses the `INTEGRATIONS` gate.
+`API_KEYS, WEBHOOKS, MCP, INTEGRATIONS, SALES_RULES, AUDIT_LOG, EMAIL_NOTIFICATIONS, STORAGE_RULES,
+CUSTOMER_PORTALS, AI_AGENT, WORKFLOWS, FORECAST, TWO_FACTOR, PERMISSIONS, APPROVAL_RULES,
+BACKUPS` → each `[Plan.Business, Plan.Partner]`. `INTEGRATION_WHITELIST` (`email`) bypasses
+the `INTEGRATIONS` gate. `MCP` gates the MCP server (`POST /api/mcp`) via
+`companyHasFeature` at the route choke point — off on Community/Starter across both the
+OAuth-connector and `carbon-key` auth paths (`api+/mcp+/_index.ts`).
+
+`APPROVAL_RULES` gates the `x+/settings+/approval-rules.*` routes (via `requireFeature`
++ hidden nav); the runtime approval engine (`$supplierId.approval`, request/approve/reject)
+stays ungated — a Community company just has no rules to trigger it. `BACKUPS` gates the
+company backup/restore feature, but through `canManageBackups`
+(`~/modules/settings/backups.server`) = `canAccessBackups(email) ||
+companyHasFeature(BACKUPS)` — i.e. Business/Enterprise customers get it AND internal staff
+/ local dev keep the escape hatch. Demo Data (`x+/settings+/demo-data`) stays internal /
+local-dev only via the plain `canAccessBackups`.
+
+`PERMISSIONS` gates authoring RBAC — creating/editing employee types
+(`x+/users+/employee-types*`), editing an individual user's permissions
+(`employees.$employeeId`, `bulk-edit-permissions`), and console/kiosk mode
+(`x+/settings+/people.tsx`). The licensed logic — the flattened-permission-object
+builder `updatePermissions`, `updateEmployee`, the employee-type CRUD, and the
+claims/employee-type translators — lives once in **`@carbon/ee/permissions.server`**
+(consumed by the ERP authoring routes AND the `@carbon/jobs` bulk-edit task, which
+no longer carries its own copy). Console-operator provisioning is `@carbon/ee/console.server`
+(`updateConsoleSetting`); the authoring UI is `.ee.tsx` in the app (it can't move
+to the package — it imports `~/components/Form` etc.).
+The community primitives it does NOT include — `setUserPermissions` (invite merge)
+and `makePermissionsFromEmployeeType` (invite snapshot) — stay in the app's
+`users.server.ts`. Community/Starter ships "everyone is an admin": you can add
+users (every invite defaults to the seeded `Admin` employee type) but not author
+roles. Enforcement (`requirePermissions`, RLS, `get_claims`) is unaffected and
+stays in every edition.
Server checks (`plan.server.ts`) read `companyPlan.planId` (`.eq("id", companyId)`):
@@ -101,7 +130,19 @@ Server checks (`plan.server.ts`) read `companyPlan.planId` (`.eq("id", companyId
path — reading `companyPlan` directly — still accepted the keys).
**All three short-circuit when `CarbonEdition !== Edition.Cloud` or the company is
-bypass-listed** — gating only bites on Cloud.
+bypass-listed** — plan gating only bites on Cloud. This is a **self-hosted feature
+toggle**: Enterprise AND Community self-hosted both pass `companyHasPlan`.
+
+### `companyHasFeature` / `requireFeature` — Community is blocked, not toggled
+
+For features that must be OFF on the **Community** edition (not merely paywalled on
+Cloud) — RBAC authoring (`PERMISSIONS`), console/kiosk mode — use
+`companyHasFeature(client, companyId, spec)` / `requireFeature({...})` instead.
+They are identical to `companyHasPlan`/`requirePlan` EXCEPT they return
+`false`/throw when `CarbonEdition === Edition.Community`. So: Community → blocked,
+Enterprise/Test self-hosted → allowed (licensed), Cloud → plan-based,
+bypass/carbon-owned → allowed. `requirePlan`'s off-Cloud no-op is wrong for these
+— it would let a self-hosted Community instance author roles.
`spec` is a `GateSpec`: either `{ feature: Feature }` or `{ plan: Plan | Plan[] }`.
diff --git a/.claude/rules/commercial-licensing.md b/.claude/rules/commercial-licensing.md
new file mode 100644
index 0000000000..ebcf924253
--- /dev/null
+++ b/.claude/rules/commercial-licensing.md
@@ -0,0 +1,179 @@
+paths:
+ - "packages/ee/**"
+ - "apps/erp/app/routes/x+/settings+/**"
+ - "apps/erp/app/modules/users/**"
+
+# Commercial Feature Licensing & Entitlement Pattern
+
+How Carbon gates commercial (Enterprise/Business) features so they cannot be
+unlocked by editing open-licensed code. Grounded against `packages/ee/src/plan.ts`,
+`plan.server.ts`, `entitlements.server.ts`, and the reference implementations
+(`packages/ee/src/permissions.server.ts`, `console.server.ts`, `approvals/`).
+
+## The license boundary
+
+Carbon is open-core. The commercial license (root `LICENSE`) covers **`packages/ee`
+and every file whose name contains `.ee`** (e.g. `accounting.ee.service.ts`). Everything
+else is community-licensed. This is the same model as Twenty CRM (their marker is a
+`/* @license Enterprise */` header; ours is the `packages/ee` package + the `.ee` infix).
+
+## The bar this pattern hits (be honest about it)
+
+You cannot make a machine refuse to run code its operator has edited. What the pattern
+guarantees is: **there is no route around the paywall that stays in open-licensed code.**
+Using a commercial feature requires either executing commercial code or editing commercial
+code — both are license breaches. A deletable `if` in a community-licensed route is NOT a
+lock; a check inside `packages/ee` is.
+
+## The three rules
+
+1. **The feature body lives in `packages/ee`.** The service/engine that *does* the thing
+ is commercial. Community code may call into it but must never reimplement it — so using
+ the feature requires running commercial code.
+2. **The entitlement check lives INSIDE the ee function**, via `requireEntitlement` — not
+ as a call in the open route. So stripping the gate requires editing commercial code.
+3. **UI is `.ee.tsx` in the app module. Gated features stay VISIBLE with an upgrade
+ OVERLAY — never hidden from the nav, never redirected away.** The nav entry always
+ renders; the gated list/editor route renders an upgrade overlay via
+ `usePlanGate({ feature })` (`if (isGated) return <FeatureUpgradeOverlay />`), using the
+ shared `~/components/RulesUpgradeOverlay` (blurred mock preview + copy) or the lower-level
+ `~/components/UpgradeOverlay` primitives. This is UX — the server ee check is the
+ enforcement. Reference: `x+/sales+/sales-rules.tsx` + `SalesRulesUpgradeOverlay`.
+
+## The API — three helpers, know which to use
+
+All in `@carbon/ee`. `FEATURE_PLANS` (`plan.ts`) is the source of truth for which plans
+grant which `Feature`; every helper reads it.
+
+| Helper | Shape | Where | Use for |
+|---|---|---|---|
+| `companyHasFeature(client, companyId, { feature })` | `Promise<boolean>` | `plan.server` | RUNTIME paths that must DEGRADE (feature off = no-op), not throw |
+| `requireEntitlement(client, companyId, feature)` | throws `EntitlementError` | `entitlements.server` | **The LOCK.** Top of every commercial AUTHORING function, inside `packages/ee` |
+| `requireFeature({ request, client, companyId, redirectTo, feature })` | throws a `redirect` | `plan.server` | UX only, in the open route loader/action — a friendly upgrade redirect |
+
+- `companyHasFeature` semantics: **Community edition → false (blocked)**; Enterprise/Test
+ self-hosted → true; Cloud → plan-based; bypass/carbon-owned → true. It is the ONE place
+ the future license-key server plugs in (a signed, server-bound validity token) — so every
+ feature inherits it without a call-site change.
+- Do NOT use `companyHasPlan`/`requirePlan` for community-gated features — those no-op off
+ Cloud (a self-hosted feature toggle), so a self-hosted Community instance would pass.
+ They remain only for features that are Cloud-paywall-only.
+
+## The two layers (both, deliberately)
+
+- **Route (open, UX):** `requireFeature({ ..., feature: "X" })` in the loader/action →
+ redirect with an upgrade flash. Strippable, cosmetic.
+- **ee (commercial, LOCK):** `requireEntitlement(client, companyId, "X")` at the top of the
+ ee function → throws `EntitlementError`. Un-strippable without editing commercial code.
+
+**Route wiring for the visible+overlay UX:** the primary list/editor route's LOADER must NOT
+`requireFeature`-redirect (that would hide the page) — let it load and render the overlay
+client-side. Keep `requireFeature` on the WRITE routes/actions (`new`/`$id`/`delete`), which
+are only reachable by direct URL when gated; a redirect there is fine. The write action
+should catch `EntitlementError` or sit behind its `requireFeature` so the ee throw never
+surfaces as a raw 500.
+
+## File-layout convention
+
+```
+packages/ee/src/<feature>/
+├── models.ts # zod validators + const types (client-safe: @carbon/database, zod)
+├── service.ts # the engine — requireEntitlement at the top of authoring fns (server)
+├── types.ts # derived types (ReturnType<service>, input types) — type-only
+└── index.ts # export * from "./models"; export type * from "./types"
+```
+Exports in `packages/ee/package.json`: `@carbon/ee/<feature>` → `index.ts` (client-safe),
+`@carbon/ee/<feature>.server` → `service.ts` (server). Small features may be a single
+`<feature>.server.ts` (see `permissions.server.ts`, `console.server.ts`).
+
+UI stays `.ee.tsx` in `apps/erp/app/modules/<module>/ui/` (coupled to `~/components/Form`,
+`~/hooks` — cannot move to the package, and does not need to). Routes stay in the app.
+
+## Refactor checklist (per feature)
+
+1. Add/confirm the `Feature` key in `FEATURE_PLANS` (`plan.ts`).
+2. Move the feature's service/engine into `packages/ee/src/<feature>/` (or a
+ `<feature>.server.ts`). Fix `~/` deps: `sanitize` → `@carbon/utils`; redefine any
+ `~/utils/query` types locally; keep `trigger()`/notification calls in the ROUTE, not the
+ ee function (`@carbon/ee` does not depend on `@carbon/jobs`/`@carbon/notifications`).
+3. **Embed `requireEntitlement(client, companyId, "X")` at the top of every authoring
+ function.** Runtime functions that must degrade use `companyHasFeature` instead.
+4. Move the feature's validators/derived types with it; add the package exports.
+5. Repoint every call site from `~/modules/...` to `@carbon/ee/<feature>` / `.server`.
+ Remove the moved code from the community module + its barrel.
+6. UI → `.ee.tsx`. Route → keep `requireFeature` for the UX redirect + catch
+ `EntitlementError`.
+7. Verify: `pnpm --filter @carbon/ee typecheck`, `pnpm exec turbo run typecheck --filter=erp`,
+ Biome, and if service functions leave `*.service.ts` note the MCP digest changes
+ (`pnpm run generate:mcp`) — moving a function out of a scanned `*.service.ts` removes it
+ as an MCP tool, which is usually correct (an ungated MCP path would bypass the gate).
+
+## Rollout status (starter-only → new pattern)
+
+Refactor one at a time; each PR should leave the tree green.
+
+- ✅ **Permissions authoring / console** — body in `packages/ee` (`permissions.server.ts`,
+ `console.server.ts`); `requireEntitlement` embedded in every authoring function
+ (employee-type CRUD, `updateEmployee`, `updatePermissions`, `updateConsoleSetting`).
+- ✅ **Approvals** — reference implementation (`packages/ee/src/approvals/`);
+ `requireEntitlement` in `upsertApprovalRule`/`deleteApprovalRule`, graceful degrade in
+ `getApprovalRuleByAmount`.
+- ✅ **Sales rules / Storage rules** — both families' authoring writes live in
+ `packages/ee/src/rules/service.server.ts` (`@carbon/ee/rules.server`):
+ `requireEntitlement` embedded in `upsertEnforcementRule`/`deleteEnforcementRule`
+ (feature chosen by the `family` discriminator), `assignSalesRule`/`unassignSalesRule`
+ (`SALES_RULES`), and `assignStorageRule`/`unassignStorageRule` (`STORAGE_RULES`). The
+ runtime evaluators (`isSalesRulesEnabledForCompany`/`isStorageRulesEnabledForCompany`)
+ degrade via `companyHasFeature`; write routes gate with `requireFeature`. The
+ entitled writes are kept OUT of the client-safe `@carbon/ee/rules` barrel (which
+ client components reach via `useRuleViolations`) — the query getters stay there.
+- ✅ **API keys** — `upsertApiKey`/`deleteApiKey` in `packages/ee/src/api-keys.server.ts`,
+ `requireEntitlement("API_KEYS")`; routes gate with `requireFeature`.
+- ✅ **Webhooks** — authoring in `packages/ee/src/webhooks.server.ts`
+ (`requireEntitlement("WEBHOOKS")`); delivery degrades at runtime via `companyHasFeature`.
+- ✅ **Two-factor** — the `requireMfa` company policy in `packages/ee/src/two-factor.server.ts`,
+ `requireEntitlement("TWO_FACTOR")` scoped to ENABLING only (a downgrade can still disable).
+- ✅ **Forecast** — `upsert/deleteDemandForecasts` + `upsert/deleteDemandProjections` in
+ `packages/ee/src/forecast.server.ts`, `requireEntitlement("FORECAST")`.
+- ✅ **Customer portals** — `upsertCustomerPortal`/`deleteCustomerPortal` in
+ `packages/ee/src/customer-portals.server.ts`, `requireEntitlement("CUSTOMER_PORTALS")`;
+ the shared `upsertExternalLink` stays ungated (used by quote/RFQ finalize); public share
+ pages degrade via `companyHasFeature`.
+- ⬜ **Backups** — engine still in `packages/jobs`; gated via `canManageBackups` only
+ (route-level). Biggest lift — relocate the engine last.
+- ⬜ Still on `requirePlan`/`companyHasPlan`, pending an architecture/policy decision
+ (integrations, audit log, AI agent, workflows engine) — migrate to
+ `companyHasFeature`/`requireEntitlement` + move bodies into `packages/ee` when unblocked.
+
+## Bundling gotcha — the `.server` client-graph boundary
+
+The ee feature files import `entitlements.server`/`plan.server` (both `.server`), so
+the ee `service.ts` is transitively server-only. The React Router build **rejects any
+`.server` module that reaches the client graph** ("Server-only module referenced by
+client"). Two edges commonly (and silently — typecheck won't catch it, only the dev
+build does) pull the server file into the client:
+
+1. **The client barrel deriving types from the server file.** If `index.ts`
+ (`@carbon/ee/<feature>`) re-exports types from `types.ts`, and `types.ts` does
+ `import type … from "./service"` (e.g. `ApprovalRule = ReturnType<getApprovalRuleByAmount>`),
+ the client barrel transitively reaches `service.ts`. **Fix:** derive those types from
+ `@carbon/database` directly (`Database["public"]["Tables"|"Views"][…]["Row"]`), so
+ `types.ts` never imports `service.ts`.
+2. **A `.service.ts` importing `@carbon/ee/<feature>.server`.** Module `*.service.ts`
+ files are re-exported through the module barrel that client components import, so they
+ are browser-bundled — importing a `.server` module there reaches the client graph.
+ **Fix:** move that server-only helper into a `*.server.ts` (not barrel-exported) and
+ import it from the route directly. (Routes MAY import `.server` — RR strips it from the
+ client build; `*.service.ts` may NOT.)
+
+## Anti-patterns
+
+- A gate that is only a `usePlanGate` client check, or only a `requireFeature`/
+ `requirePlan` call in an open route file, with the feature body in community code. That is
+ UX, not a lock — deletable without breaching the license.
+- Reimplementing a commercial engine in community code "to avoid the import." That removes
+ the moat.
+- Putting `requireEntitlement` in an open (`apps/erp`) file. It must live in `packages/ee`.
+- **Hiding a gated feature from the nav, or redirecting its page away.** Gated features stay
+ visible and show the upgrade overlay (rule 3). Hiding it makes the feature undiscoverable
+ and gives the customer nothing to upgrade toward.
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 3c7538f848..8de8e81949 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -33,16 +33,28 @@ User-facing rules of the feature: backups require `settings` update permission
route and the `export-company` edge function), exclude secrets, and a restore is
reversible via an auto-snapshot.
-**Internal-only in real deployments, open to everyone on a local dev stack**,
-while the multi-tenant caveats below are unhardened. One gate:
+**Backups are a Business/Enterprise feature** (`BACKUPS` in `FEATURE_PLANS`), with
+an internal-staff / local-dev escape hatch. The authoritative gate is
+`canManageBackups(client, companyId, email)`
+(`apps/erp/app/modules/settings/backups.server.ts`) =
+`canAccessBackups(email) || companyHasFeature(client, companyId, { feature: "BACKUPS" })`.
`canAccessBackups(email)` (`apps/erp/app/utils/backups.ts`) = `IS_LOCAL_DEV ||
-isInternalEmail(email)`. `IS_LOCAL_DEV` (`packages/env`) is true only when neither
-`NODE_ENV` nor `VERCEL_ENV` is `production`/`preview` — so prod, preview, and
-self-hosted (all `NODE_ENV=production`) stay internal-only. Used by
-`requireBackupAccess` (route loader/action), every `api+/settings.backup-*`
-loader/action (404), and the nav (`localOrInternalRoutes` in
-`useSettingsSubmodules.tsx`, via `useFlags().isLocalDev`). Internal =
-`@carbon.ms` / `@carbon.us.org`. Drop `canAccessBackups` entirely to ship publicly.
+isInternalEmail(email)` stays a pure browser-safe predicate — the escape hatch, and the
+whole gate for **Demo Data** (`x+/settings+/demo-data`), which stays internal-only. Used
+by the `backups.tsx` loader/action and every `api+/settings.backup-*` loader/action (404
+on deny); the nav gates it in `useSettingsSubmodules.tsx` via `usePlanGate({ feature:
+"BACKUPS" })` OR `isInternal`/`isLocalDev` (Demo Data still uses `localOrInternalRoutes`).
+Internal = `@carbon.ms` / `@carbon.us.org`.
+
+The multi-tenant caveats below are real but are NOT a cross-tenant leak in the backup
+feature — every entry point is scoped to the caller's `companyId`. They were the reason
+this stayed internal-only, and exposing it to customers is a deliberate product decision:
+(1) restore is a full in-company wipe-and-reload (large destructive surface, snapshot-
+reversible); (2) the export HARD-REFUSES when a company's live data already holds
+cross-tenant references left by an upstream bug (tables like `jobOperationDependency`
+still lacking `companyId` in their PK — see `.ai/specs/2026-08-25-backup-durability.md`),
+offering a destructive "remove corrupted data" path. Closing that upstream schema hole
+is the remaining hardening.
## Shared engine — `company-backup.ts`
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 3fd343ec9f..2c685f78f6 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -77,6 +77,16 @@ Auth always yields an `McpContext` = `{ client, companyId, companyGroupId, userI
(`lib/types.ts`). `companyId`/`userId` come from the auth context and are injected
server-side — never trusted from tool arguments.
+**Edition/plan gate.** The MCP server is a Business+ feature. Immediately after
+`resolveAuth`, `action` calls `companyHasFeature(ctx.client, ctx.companyId, { feature: "MCP" })`
+and returns 402 when false — one check that covers BOTH auth paths and blocks the
+**Community** edition (self-hosted) as well as Cloud **Starter** companies. This is the
+edge enforcement (the MCP server code lives in `apps/erp`, community-licensed, so there is
+no `packages/ee` body to relocate); `companyHasFeature` is the same entitlement helper the
+rest of the gated features use. The unauthenticated discovery endpoints
+(`/.well-known/mcp.json`, `/agent-setup/prompt.md`) are NOT gated — they have no company
+context and only advertise the endpoint; enforcement is at `POST /api/mcp`.
+
## The 3 meta-tools (the ONLY tools actually registered)
To avoid context exhaustion, `server.registerTool` registers just three discovery
diff --git a/LICENSE b/LICENSE
index 7a9fc7c6a5..7e6ead9da7 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,188 +1,203 @@
-Copyright © 2025, Carbon Manufacturing Systems Corp.
+Copyright (C) Carbon Manufacturing Systems Corporation and contributors
-Portions of this software are licensed as follows:
+Carbon is licensed as follows:
-- All content that resides under https://github.com/crnbos/carbon/tree/main/packages/ee and all files that contains a `.ee` in this repository require the purchase of a commercial license
-- All third party components incorporated into the Carbon Software are licensed under the original license provided by the owner of the applicable component.
-- Any use of this software to sell Carbon source code as a hosted service is strictly prohibited without obtaining a commercial license.
-- Because Carbon is cloud-based software, any use of this software for internal production use is strictly prohibited unless the modifications are made open-source in accordance with the "AGPLv3" license or a commercial license is obtained.
+1. Except as described in items 2 and 3, everything in this repository is
+ licensed under the GNU Affero General Public License, version 3 only
+ ("AGPLv3"), printed in full below.
+2. The Enterprise files are (a) every file in the packages/ee directory,
+ including its subdirectories, and (b) every file anywhere in this
+ repository whose file name contains ".ee." (for example,
+ "ConfiguratorForm.ee.tsx"). The Enterprise files are not licensed under
+ the AGPLv3. They are licensed only under the Carbon Commercial License
+ in packages/ee/LICENSE.
+
+3. Third-party components included in this repository remain under the
+ licenses their owners provide.
+
+4. Neither the AGPLv3 nor the Carbon Commercial License gives you any right
+ to use the name "Carbon," Carbon's logos, or any other trademark of
+ Carbon Manufacturing Systems Corporation, except to truthfully say where
+ the software came from and to keep the notices these licenses require.
+
+===========================================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
-Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
-Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
Preamble
-The GNU Affero General Public License is a free, copyleft license for
+ The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
-The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
-When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
-Developers that use our General Public Licenses protect your rights
+ Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
-A secondary benefit of defending all users' freedom is that
+ A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
-The GNU Affero General Public License is designed specifically to
+ The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
+to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
+users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
-An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
-The precise terms and conditions for copying, distribution and
+ The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
-0. Definitions.
+ 0. Definitions.
-"This License" refers to version 3 of the GNU Affero General Public License.
+ "This License" refers to version 3 of the GNU Affero General Public License.
-"Copyright" also means copyright-like laws that apply to other kinds of
+ "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
-"The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
-To "modify" a work means to copy from or adapt all or part of the work
+ To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
+exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
-A "covered work" means either the unmodified Program or a work based
+ A "covered work" means either the unmodified Program or a work based
on the Program.
-To "propagate" a work means to do anything with it that, without
+ To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
+computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
-To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
-An interactive user interface displays "Appropriate Legal Notices"
+ An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
+work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
-1. Source Code.
+ 1. Source Code.
-The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
form of a work.
-A "Standard Interface" means an interface that either is an official
+ A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
-The "System Libraries" of an executable work include anything, other
+ The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
+implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
-The "Corresponding Source" for a work in object code form means all
+ The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
+control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
+which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
-The Corresponding Source need not include anything that users
+ The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
-The Corresponding Source for a work in source code form is that
+ The Corresponding Source for a work in source code form is that
same work.
-2. Basic Permissions.
+ 2. Basic Permissions.
-All rights granted under this License are granted for the term of
+ All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
+content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
-You may make, run and propagate covered works that you do not
+ You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
+in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
+not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
-Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
-3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-No covered work shall be deemed part of an effective technological
+ No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
-When you convey a covered work, you waive any legal power to forbid
+ When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
@@ -190,9 +205,9 @@ modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
-4. Conveying Verbatim Copies.
+ 4. Conveying Verbatim Copies.
-You may convey verbatim copies of the Program's source code as you
+ You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
@@ -200,12 +215,12 @@ non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
-You may charge any price or no price for each copy that you convey,
+ You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
-5. Conveying Modified Source Versions.
+ 5. Conveying Modified Source Versions.
-You may convey a work based on the Program, or the modifications to
+ You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
@@ -230,19 +245,19 @@ terms of section 4, provided that you also meet all of these conditions:
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
-A compilation of a covered work with other separate and independent
+ A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
+beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
-6. Conveying Non-Source Forms.
+ 6. Conveying Non-Source Forms.
-You may convey a covered work in object code form under the terms
+ You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
@@ -288,75 +303,75 @@ in one of these ways:
Source of the work are being offered to the general public at no
charge under subsection 6d.
-A separable portion of the object code, whose source code is excluded
+ A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
-A "User Product" is either (1) a "consumer product", which means any
+ A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
+actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
-"Installation Information" for a User Product means any methods,
+ "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
+a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
-If you convey an object code work under this section in, or with, or
+ If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
+by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
-The requirement to provide Installation Information does not include a
+ The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
+the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
-Corresponding Source conveyed, and Installation Information provided,
+ Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
-7. Additional Terms.
+ 7. Additional Terms.
-"Additional permissions" are terms that supplement the terms of this
+ "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
+that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
-When you convey a copy of a covered work, you may at your option
+ When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
-Notwithstanding any other provision of this License, for material you
+ Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
@@ -383,74 +398,74 @@ that material) supplement the terms of this License with terms:
any liability that these contractual assumptions directly impose on
those licensors and authors.
-All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
+restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
-If you add terms to a covered work in accord with this section, you
+ If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
-Additional terms, permissive or non-permissive, may be stated in the
+ Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
-8. Termination.
+ 8. Termination.
-You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
-However, if you cease all violation of this License, then your
+ However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
-Moreover, your license from a particular copyright holder is
+ Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
-Termination of your rights under this section does not terminate the
+ Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
+this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
-9. Acceptance Not Required for Having Copies.
+ 9. Acceptance Not Required for Having Copies.
-You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
+to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
-10. Automatic Licensing of Downstream Recipients.
+ 10. Automatic Licensing of Downstream Recipients.
-Each time you convey a covered work, the recipient automatically
+ Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
+propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
-An "entity transaction" is a transaction transferring control of an
+ An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
+organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
@@ -458,43 +473,43 @@ give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
-You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
-11. Patents.
+ 11. Patents.
-A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
-A contributor's "essential patent claims" are all patent claims
+ A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
+consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
-Each contributor grants you a non-exclusive, worldwide, royalty-free
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
-In the following three paragraphs, a "patent license" is any express
+ In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
+sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
-If you convey a covered work, knowingly relying on a patent license,
+ If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -502,13 +517,13 @@ then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
+license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
-If, pursuant to or in connection with a single transaction or
+ If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
@@ -516,10 +531,10 @@ or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
-A patent license is "discriminatory" if it does not include within
+ A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
+specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
@@ -531,83 +546,83 @@ for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
-Nothing in this License shall be construed as excluding or limiting
+ Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
-12. No Surrender of Others' Freedom.
+ 12. No Surrender of Others' Freedom.
-If conditions are imposed on you (whether by court order, agreement or
+ If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
+excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
+not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
-13. Remote Network Interaction; Use with the GNU General Public License.
+ 13. Remote Network Interaction; Use with the GNU General Public License.
-Notwithstanding any other provision of this License, if you modify the
+ Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
+means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
-Notwithstanding any other provision of this License, you have
+ Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
+combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
-14. Revised Versions of this License.
+ 14. Revised Versions of this License.
-The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
-Each version is given a distinguishing version number. If the
+ Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
+Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
-If the Program specifies that a proxy can decide which future
+ If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
-Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
-15. Disclaimer of Warranty.
+ 15. Disclaimer of Warranty.
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-16. Limitation of Liability.
+ 16. Limitation of Liability.
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -617,9 +632,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
-17. Interpretation of Sections 15 and 16.
+ 17. Interpretation of Sections 15 and 16.
-If the disclaimer of warranty and limitation of liability provided
+ If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
@@ -630,11 +645,11 @@ copy of the Program in return for a fee.
How to Apply These Terms to Your New Programs
-If you develop a new program, and you want it to be of the greatest
+ If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
-To do so, attach the following notices to the program. It is safest
+ To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
@@ -657,15 +672,15 @@ the "copyright" line and a pointer to where the full notice is found.
Also add information on how to contact you by electronic and paper mail.
-If your software can interact with users remotely through a computer
+ If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
+get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
+of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
-You should also get your employer (if you work as a programmer) or school,
+ You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
-<https://www.gnu.org/licenses/>.
\ No newline at end of file
+<https://www.gnu.org/licenses/>.
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index aed955e6e4..bbc8807573 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -1,4 +1,5 @@
"use client";
+import type { ApprovalDocumentType } from "@carbon/ee/approvals";
import { NotificationEvent, renderInlineLinks } from "@carbon/notifications";
import {
Badge,
@@ -49,7 +50,6 @@ import {
import { Link, useFetcher, useNavigate } from "react-router";
import { DateTime } from "~/components";
import { useNotifications, useUser } from "~/hooks";
-import type { ApprovalDocumentType } from "~/modules/shared";
import { usePeople } from "~/stores";
import type { Notification as NotificationRecord } from "~/types";
import { getRecordPath } from "~/utils/entity";
diff --git a/apps/erp/app/components/UpgradeOverlay/UpgradeOverlay.tsx b/apps/erp/app/components/UpgradeOverlay/UpgradeOverlay.tsx
index 7558a68d3a..276832e78d 100644
--- a/apps/erp/app/components/UpgradeOverlay/UpgradeOverlay.tsx
+++ b/apps/erp/app/components/UpgradeOverlay/UpgradeOverlay.tsx
@@ -5,8 +5,10 @@ import {
cn,
Modal,
ModalContent,
+ useEdition,
VStack
} from "@carbon/react";
+import { Edition } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import type { ReactNode } from "react";
import { Link } from "react-router";
@@ -177,14 +179,32 @@ function UpgradeOverlaySection({
function UpgradeOverlayUpgradeButton({
children,
- to = path.to.billing
+ to
}: {
children?: ReactNode;
to?: string;
}) {
+ // On Cloud the upgrade path is the Business plan (Stripe billing); everywhere
+ // else (self-hosted Community) it's an Enterprise license, which is a
+ // conversation off-app rather than a self-serve billing page.
+ const isCloud = useEdition() === Edition.Cloud;
+ const target = to ?? (isCloud ? path.to.billing : path.to.pricing);
+ const isExternal = target.startsWith("http");
+
return (
<Button asChild>
- <Link to={to}>{children ?? <Trans>Upgrade to Business</Trans>}</Link>
+ <Link
+ to={target}
+ reloadDocument={isExternal}
+ target={isExternal ? "_blank" : undefined}
+ >
+ {children ??
+ (isCloud ? (
+ <Trans>Upgrade to Business</Trans>
+ ) : (
+ <Trans>Upgrade to Enterprise</Trans>
+ ))}
+ </Link>
</Button>
);
}
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index bd3b2176c7..91b70697bd 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -96,7 +96,7 @@ Sibling feature to **sales rules** (`~/modules/sales`, sales-document surfaces).
- `getEnforcementRuleAssignmentCounts` (in `~/modules/shared`) spans BOTH assignment tables — a rule lives in exactly one, so the union of single-table counts is correct. Rule ids are globally unique, so counting by id needs no family predicate even though the item table is shared.
- Never widen the `enforcementRule_storage_surfaces` CHECK to admit sales-document surfaces — that CHECK is what replaced the old per-family enum typing.
-Service functions: the admin CRUD is NOT in `inventory.service.ts` — both families share one parametrized implementation in `~/modules/shared` (`getEnforcementRules` / `getEnforcementRule` / `upsertEnforcementRule` / `deleteEnforcementRule` / `getEnforcementRuleAssignmentCounts`), called with `"storage"` as the family. Cross-app `getActiveRulesForTargets` / `getRuleAssignmentsForTarget` / `getStorageRulesList` / `assignStorageRule` / `unassignStorageRule` are imported from `@carbon/ee/rules` DIRECTLY at the call site — this module's barrel deliberately does not re-export them. Routes: `x+/inventory+/storage-rules*`, plus assignment routes under `x+/items+/rules.*` (item targets) and `x+/resources+/work-centers.rules.*` (work-center targets).
+Service functions: the admin CRUD is NOT in `inventory.service.ts`. The read helpers (`getEnforcementRules` / `getEnforcementRule` / `getEnforcementRuleAssignmentCounts`) share one parametrized implementation in `~/modules/shared`, called with `"storage"` as the family. The entitlement-gated WRITES (`upsertEnforcementRule` / `deleteEnforcementRule`) moved to `@carbon/ee/rules.server` (`packages/ee/src/rules/service.server.ts`) — they embed `requireEntitlement("STORAGE_RULES")`. Cross-app READ queries `getActiveRulesForTargets` / `getRuleAssignmentsForTarget` / `getStorageRulesList` are imported from `@carbon/ee/rules` DIRECTLY at the call site; the gated writes `assignStorageRule` / `unassignStorageRule` are imported from `@carbon/ee/rules.server` — this module's barrel deliberately does not re-export any of them. Routes: `x+/inventory+/storage-rules*`, plus assignment routes under `x+/items+/rules.*` (item targets) and `x+/resources+/work-centers.rules.*` (work-center targets).
## Related Modules
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index b14b5b9d94..71c32f94fd 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -495,56 +495,6 @@ export async function calculateJobPriority(
return newPriority;
}
-export async function deleteDemandForecasts(
- client: SupabaseClient<Database>,
- params: {
- itemId: string;
- locationId: string;
- companyId: string;
- futurePeriodIds: string[];
- }
-) {
- const { itemId, locationId, companyId, futurePeriodIds } = params;
-
- const result = await client
- .from("demandForecast")
- .delete()
- .eq("itemId", itemId)
- .eq("locationId", locationId)
- .eq("companyId", companyId)
- .in("periodId", futurePeriodIds);
-
- return {
- data: result.data,
- error: result.error
- };
-}
-
-export async function deleteDemandProjections(
- client: SupabaseClient<Database>,
- params: {
- itemId: string;
- locationId: string;
- companyId: string;
- futurePeriodIds: string[];
- }
-) {
- const { itemId, locationId, companyId, futurePeriodIds } = params;
-
- const result = await client
- .from("demandProjection")
- .delete()
- .eq("itemId", itemId)
- .eq("locationId", locationId)
- .eq("companyId", companyId)
- .in("periodId", futurePeriodIds);
-
- return {
- data: result.data,
- error: result.error
- };
-}
-
export async function deleteJob(
client: SupabaseClient<Database>,
jobId: string
@@ -4750,118 +4700,6 @@ export async function upsertMaintenanceScheduleItem(
}
}
-export async function upsertDemandForecasts(
- client: SupabaseClient<Database>,
- forecasts: Array<{
- itemId: string;
- locationId: string;
- periodId: string;
- forecastQuantity: number;
- companyId: string;
- createdBy: string;
- updatedBy?: string;
- }>
-) {
- // Delete existing forecasts with 0 quantity, upsert others
- const toDelete = forecasts.filter((f) => f.forecastQuantity === 0);
- const toUpsert = forecasts.filter((f) => f.forecastQuantity > 0);
-
- const promises = [];
-
- if (toDelete.length > 0) {
- for (const forecast of toDelete) {
- promises.push(
- client
- .from("demandForecast")
- .delete()
- .eq("itemId", forecast.itemId)
- .eq("locationId", forecast.locationId)
- .eq("periodId", forecast.periodId)
- .eq("companyId", forecast.companyId)
- );
- }
- }
-
- if (toUpsert.length > 0) {
- promises.push(
- client.from("demandForecast").upsert(
- toUpsert.map((f) => ({
- ...f,
- updatedBy: f.updatedBy ?? f.createdBy ?? "system",
- updatedAt: new Date().toISOString()
- })),
- {
- onConflict: "itemId,locationId,periodId,companyId"
- }
- )
- );
- }
-
- const results = await Promise.all(promises);
- const hasError = results.some((r) => r.error);
-
- return {
- data: hasError ? null : toUpsert,
- error: hasError ? results.find((r) => r.error)?.error : null
- };
-}
-
-export async function upsertDemandProjections(
- client: SupabaseClient<Database>,
- forecasts: Array<{
- itemId: string;
- locationId: string;
- periodId: string;
- forecastQuantity: number;
- companyId: string;
- createdBy: string;
- updatedBy?: string;
- }>
-) {
- // Delete existing forecasts with 0 quantity, upsert others
- const toDelete = forecasts.filter((f) => f.forecastQuantity === 0);
- const toUpsert = forecasts.filter((f) => f.forecastQuantity > 0);
-
- const promises = [];
-
- if (toDelete.length > 0) {
- for (const forecast of toDelete) {
- promises.push(
- client
- .from("demandProjection")
- .delete()
- .eq("itemId", forecast.itemId)
- .eq("locationId", forecast.locationId)
- .eq("periodId", forecast.periodId)
- .eq("companyId", forecast.companyId)
- );
- }
- }
-
- if (toUpsert.length > 0) {
- promises.push(
- client.from("demandProjection").upsert(
- toUpsert.map((f) => ({
- ...f,
- updatedBy: f.updatedBy ?? f.createdBy ?? "system",
- updatedAt: new Date().toISOString()
- })),
- {
- onConflict: "itemId,locationId,periodId,companyId"
- }
- )
- );
- }
-
- const results = await Promise.all(promises);
- const hasError = results.some((r) => r.error);
-
- return {
- data: hasError ? null : toUpsert,
- error: hasError ? results.find((r) => r.error)?.error : null
- };
-}
-
export async function getPeopleAssignments(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/production/ui/ForecastUpgradeOverlay.tsx b/apps/erp/app/modules/production/ui/ForecastUpgradeOverlay.tsx
index 9bac750ce9..4000a604fe 100644
--- a/apps/erp/app/modules/production/ui/ForecastUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/production/ui/ForecastUpgradeOverlay.tsx
@@ -1,5 +1,4 @@
import { cn } from "@carbon/react";
-import { Trans } from "@lingui/react/macro";
import type { ReactNode } from "react";
import { LuChartLine } from "react-icons/lu";
import {
@@ -55,9 +54,7 @@ export default function ForecastUpgradeOverlay({
<UpgradeOverlayDescription>{description}</UpgradeOverlayDescription>
</UpgradeOverlayContent>
<UpgradeOverlayActions>
- <UpgradeOverlayUpgradeButton>
- <Trans>Upgrade to Business</Trans>
- </UpgradeOverlayUpgradeButton>
+ <UpgradeOverlayUpgradeButton />
</UpgradeOverlayActions>
</UpgradeOverlayCard>
</UpgradeOverlay>
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
new file mode 100644
index 0000000000..3595d803d3
--- /dev/null
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -0,0 +1,88 @@
+import type { Database } from "@carbon/database";
+import {
+ canApproveRequest,
+ getLatestApprovalRequestForDocument
+} from "@carbon/ee/approvals.server";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+/**
+ * Server-only purchasing helpers. Lives in a `.server.ts` (NOT the barrel-exported
+ * `purchasing.service.ts`) because it imports the commercial, server-only approval
+ * engine `@carbon/ee/approvals.server`; a `.server` import reaching the client
+ * graph via the module barrel is rejected by the React Router build.
+ */
+
+type ApprovalContext = {
+ approvalRequest: { id: string } | null;
+ canApprove: boolean;
+ decision: {
+ status: "Approved" | "Rejected";
+ decisionBy: string;
+ decisionAt: string;
+ } | null;
+};
+
+export async function getSupplierApprovalContext(
+ serviceRole: SupabaseClient<Database>,
+ supplierId: string,
+ status: string | null,
+ companyId: string,
+ userId: string
+): Promise<ApprovalContext> {
+ const latest = await getLatestApprovalRequestForDocument(
+ serviceRole,
+ "supplier",
+ supplierId
+ );
+
+ const req = latest.data;
+
+ const canApprove = await canApproveRequest(
+ serviceRole,
+ {
+ amount: req?.amount ?? null,
+ documentType: "supplier",
+ companyId
+ },
+ userId
+ );
+
+ // Look for the latest terminal decision (Approved or Rejected)
+ let decision: ApprovalContext["decision"] = null;
+ const terminalRequest = await serviceRole
+ .from("approvalRequest")
+ .select("status, decisionBy, decisionAt")
+ .eq("documentType", "supplier")
+ .eq("documentId", supplierId)
+ .in("status", ["Approved", "Rejected"])
+ .order("decisionAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ if (
+ terminalRequest.data?.decisionBy &&
+ terminalRequest.data?.decisionAt &&
+ (terminalRequest.data.status === "Approved" ||
+ terminalRequest.data.status === "Rejected")
+ ) {
+ decision = {
+ status: terminalRequest.data.status,
+ decisionBy: terminalRequest.data.decisionBy,
+ decisionAt: terminalRequest.data.decisionAt
+ };
+ }
+
+ if (!req || req.status !== "Pending" || !req.requestedBy || !req.id) {
+ return {
+ approvalRequest: null,
+ canApprove,
+ decision
+ };
+ }
+
+ return {
+ approvalRequest: { id: req.id },
+ canApprove,
+ decision
+ };
+}
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 5705891e1c..fd5ec417a9 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -27,11 +27,7 @@ import {
getExchangeRate
} from "../accounting/accounting.ee.service";
import type { PurchaseInvoice } from "../invoicing/types";
-import {
- canApproveRequest,
- getLatestApprovalRequestForDocument,
- upsertExternalLink
-} from "../shared/shared.service";
+import { upsertExternalLink } from "../shared/shared.service";
import type {
purchaseOrderDeliveryValidator,
purchaseOrderLineValidator,
@@ -583,81 +579,6 @@ export async function getSupplier(
return client.from("suppliers").select("*").eq("id", supplierId).single();
}
-type ApprovalContext = {
- approvalRequest: { id: string } | null;
- canApprove: boolean;
- decision: {
- status: "Approved" | "Rejected";
- decisionBy: string;
- decisionAt: string;
- } | null;
-};
-
-export async function getSupplierApprovalContext(
- serviceRole: SupabaseClient<Database>,
- supplierId: string,
- status: string | null,
- companyId: string,
- userId: string
-): Promise<ApprovalContext> {
- const latest = await getLatestApprovalRequestForDocument(
- serviceRole,
- "supplier",
- supplierId
- );
-
- const req = latest.data;
-
- const canApprove = await canApproveRequest(
- serviceRole,
- {
- amount: req?.amount ?? null,
- documentType: "supplier",
- companyId
- },
- userId
- );
-
- // Look for the latest terminal decision (Approved or Rejected)
- let decision: ApprovalContext["decision"] = null;
- const terminalRequest = await serviceRole
- .from("approvalRequest")
- .select("status, decisionBy, decisionAt")
- .eq("documentType", "supplier")
- .eq("documentId", supplierId)
- .in("status", ["Approved", "Rejected"])
- .order("decisionAt", { ascending: false })
- .limit(1)
- .maybeSingle();
-
- if (
- terminalRequest.data?.decisionBy &&
- terminalRequest.data?.decisionAt &&
- (terminalRequest.data.status === "Approved" ||
- terminalRequest.data.status === "Rejected")
- ) {
- decision = {
- status: terminalRequest.data.status,
- decisionBy: terminalRequest.data.decisionBy,
- decisionAt: terminalRequest.data.decisionAt
- };
- }
-
- if (!req || req.status !== "Pending" || !req.requestedBy || !req.id) {
- return {
- approvalRequest: null,
- canApprove,
- decision
- };
- }
-
- return {
- approvalRequest: { id: req.id },
- canApprove,
- decision
- };
-}
-
export async function getSupplierContact(
client: SupabaseClient<Database>,
supplierContactId: string
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
index 9d82e77cbe..6e296a44db 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderApprovalModal.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import { Hidden, ValidatedForm } from "@carbon/form";
import {
Button,
@@ -19,7 +20,6 @@ import {
SupplierContact
} from "~/components/Form";
import { useIntegrations } from "~/hooks/useIntegrations";
-import type { ApprovalDecision } from "~/modules/shared/types";
import { path } from "~/utils/path";
import { purchaseOrderApprovalValidator } from "../../purchasing.models";
import type { PurchaseOrder } from "../../types";
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
index 082d47fc47..d3d28256e3 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import { getPurchaseOrderDisplayId } from "@carbon/documents/utils";
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import {
Badge,
Button,
@@ -59,7 +60,6 @@ import { ReceiptStatus } from "~/modules/inventory/ui/Receipts";
import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import PurchaseInvoicingStatus from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus";
import { PurchaseReturnOrderStatus } from "~/modules/purchasing/ui/PurchaseReturnOrders";
-import type { ApprovalDecision } from "~/modules/shared/types";
import { useSuppliers } from "~/stores/suppliers";
import { path } from "~/utils/path";
import {
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
index ce068499f0..e265d35fbb 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierApprovalModal.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import { Hidden, TextArea, ValidatedForm } from "@carbon/form";
import {
Button,
@@ -11,7 +12,6 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import { useParams } from "react-router";
import { supplierApprovalDecisionValidator } from "~/modules/purchasing";
-import type { ApprovalDecision } from "~/modules/shared/types";
import { path } from "~/utils/path";
type SupplierApprovalModalProps = {
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
index 2e58da26f4..b18d4d3201 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import { ValidatedForm } from "@carbon/form";
import {
Button,
@@ -54,7 +55,6 @@ import {
} from "~/hooks";
import type { SupplierDetail } from "~/modules/purchasing";
import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
-import type { ApprovalDecision } from "~/modules/shared/types";
import type { action } from "~/routes/x+/settings+/tags";
import { path } from "~/utils/path";
import SupplierApprovalModal from "./SupplierApprovalModal";
diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
index 1533bb7e07..db057ae8cc 100644
--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentApprovalModal.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import { Hidden, TextArea, ValidatedForm } from "@carbon/form";
import {
Button,
@@ -11,7 +12,6 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import type { FetcherWithComponents } from "react-router";
import { useParams } from "react-router";
-import type { ApprovalDecision } from "~/modules/shared/types";
import { path } from "~/utils/path";
import { qualityDocumentApprovalValidator } from "../../quality.models";
import type { QualityDocument } from "../../types";
diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx
index 4ff72cdfa6..54d5c95a25 100644
--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx
+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDecision } from "@carbon/ee/approvals";
import {
Badge,
Button,
@@ -32,7 +33,6 @@ import { VersionMenu } from "~/components";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
import { usePermissions, useRouteData } from "~/hooks";
-import type { ApprovalDecision } from "~/modules/shared/types";
import { useDocumentStore } from "~/stores";
import { path } from "~/utils/path";
import type { QualityDocument } from "../../types";
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 8cefff9820..18155074ee 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -103,7 +103,7 @@ Distinct from **storage rules** (`~/modules/inventory`, warehouse/MES surfaces)
### Sales Rules safety
- MUST evaluate with the **service role** client in route actions AFTER `requirePermissions` — the check must see full truth regardless of the acting user's read permissions.
-- MUST gate write routes with `requirePlan({ feature: "SALES_RULES" })` (key in `packages/ee/src/plan.ts`).
+- MUST gate write routes with `requireFeature({ feature: "SALES_RULES" })` (key in `packages/ee/src/plan.ts`) — community-blocked, not merely Cloud-paywalled. The ee write functions also embed `requireEntitlement("SALES_RULES")` as the un-strippable lock.
- The shared rule-builder components (`RuleBuilder`, `SurfacesField`, `MessageWithTokens`, `SeveritySelect`, `ItemFilterSelector`) live in `~/modules/inventory/ui/StorageRules/` and are imported by **deep path**. Keep any parameterization **additive** (defaults preserve storage behavior), and never import a module *barrel* from these components — keep the dependency a one-way deep import from `sales` into the inventory UI folder to avoid a barrel cycle. The shared zod AST schema lives in `@carbon/utils` for the same reason.
- Never widen the `enforcementRule_sales_surfaces` CHECK to admit storage surfaces — that CHECK is what replaced the old per-family enum typing.
- Never duplicate `isBlocked`/`dedupeViolations`/the violation modal — import from `@carbon/ee/rules(.server)`.
@@ -114,7 +114,7 @@ Distinct from **storage rules** (`~/modules/inventory`, warehouse/MES surfaces)
| `enforcementRuleItemAssignment` | Explicit per-item pins, PK `(itemId, ruleId)` — SHARED with storage rules |
| `enforcementRuleAcknowledgment` | Append-only override/block evidence (INSERT via `sales_create`) |
-Service functions: the admin CRUD is NOT in `sales.service.ts` — both families share one parametrized implementation in `~/modules/shared` (`getEnforcementRules` / `getEnforcementRule` / `upsertEnforcementRule` / `deleteEnforcementRule` / `getEnforcementRuleAssignmentCounts`), called with `"sales"` as the family. Cross-app `getActiveSalesRulesForItems` / `getSalesRuleAssignmentsForItem` / `getSalesRulesList` / `assignSalesRule` / `unassignSalesRule` are imported from `@carbon/ee/rules` DIRECTLY at the call site — this module's barrel deliberately does not re-export them. Routes: `x+/sales+/sales-rules*` (list/new/edit/delete/assign/unassign), sidebar entry in `useSalesSubmodules`, per-item "Sales rules" card on `x+/part+/$itemId.inventory.tsx`. Enforcement: the quote, sales-order, and sales-invoice line create + edit actions, plus document gates (quote finalize/convert, RFQ convert, order confirm, shipment post, invoice post — the invoice-post gate runs in `x+/sales-invoice+/$invoiceId.post.tsx` BEFORE the optimistic `Pending` write). Every blocked or acknowledged outcome (line checks, gates, and the MCP backstops' blocks) is recorded through `recordSalesRuleOutcome` in `sales.server.ts` — one `enforcementRuleAcknowledgment` row per violation plus the `sales-rule-violation` notification; the RFQ-convert gate is the one exception (the table's documentType CHECK has no `salesRfq`; the minted quote re-records downstream).
+Service functions: the admin CRUD is NOT in `sales.service.ts`. The read helpers (`getEnforcementRules` / `getEnforcementRule` / `getEnforcementRuleAssignmentCounts`) share one parametrized implementation in `~/modules/shared`, called with `"sales"` as the family. The entitlement-gated WRITES (`upsertEnforcementRule` / `deleteEnforcementRule`) moved to `@carbon/ee/rules.server` (`packages/ee/src/rules/service.server.ts`) — they embed `requireEntitlement("SALES_RULES")`. Cross-app READ queries `getActiveSalesRulesForItems` / `getSalesRuleAssignmentsForItem` / `getSalesRulesList` are imported from `@carbon/ee/rules` DIRECTLY at the call site; the gated writes `assignSalesRule` / `unassignSalesRule` are imported from `@carbon/ee/rules.server` — this module's barrel deliberately does not re-export any of them. Routes: `x+/sales+/sales-rules*` (list/new/edit/delete/assign/unassign), sidebar entry in `useSalesSubmodules`, per-item "Sales rules" card on `x+/part+/$itemId.inventory.tsx`. Enforcement: the quote, sales-order, and sales-invoice line create + edit actions, plus document gates (quote finalize/convert, RFQ convert, order confirm, shipment post, invoice post — the invoice-post gate runs in `x+/sales-invoice+/$invoiceId.post.tsx` BEFORE the optimistic `Pending` write). Every blocked or acknowledged outcome (line checks, gates, and the MCP backstops' blocks) is recorded through `recordSalesRuleOutcome` in `sales.server.ts` — one `enforcementRuleAcknowledgment` row per violation plus the `sales-rule-violation` notification; the RFQ-convert gate is the one exception (the table's documentType CHECK has no `salesRfq`; the minted quote re-records downstream).
## Related Modules
diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalForm.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalForm.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalForm.tsx
rename to apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalForm.ee.tsx
diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.tsx
rename to apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx
diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
index 100f683a67..7e97492283 100644
--- a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
@@ -12,7 +12,7 @@ import {
UpgradeOverlayTitle,
UpgradeOverlayUpgradeButton
} from "~/components/UpgradeOverlay";
-import CustomerPortalsTable from "./CustomerPortalsTable";
+import CustomerPortalsTable from "./CustomerPortalsTable.ee";
type CustomerPortal = Database["public"]["Tables"]["externalLink"]["Row"];
diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/index.ts b/apps/erp/app/modules/sales/ui/CustomerPortals/index.ts
index 84cc10b62f..2a9c017718 100644
--- a/apps/erp/app/modules/sales/ui/CustomerPortals/index.ts
+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/index.ts
@@ -1,3 +1,3 @@
-export { default as CustomerPortalForm } from "./CustomerPortalForm";
-export { default as CustomerPortalsTable } from "./CustomerPortalsTable";
+export { default as CustomerPortalForm } from "./CustomerPortalForm.ee";
+export { default as CustomerPortalsTable } from "./CustomerPortalsTable.ee";
export { default as CustomerPortalsUpgradeOverlay } from "./CustomerPortalsUpgradeOverlay";
diff --git a/apps/erp/app/modules/settings/AGENTS.md b/apps/erp/app/modules/settings/AGENTS.md
index be6c99ddcd..a3d74b75ad 100644
--- a/apps/erp/app/modules/settings/AGENTS.md
+++ b/apps/erp/app/modules/settings/AGENTS.md
@@ -62,7 +62,7 @@ pnpm run lint
| `apiKey` | Hashed API keys with per-module scopes |
| `webhook` / `webhookTable` | Outbound webhooks and the tables they may subscribe to |
| `companyAccountsPayableBillingAddress` / `companyAccountsReceivableBillingAddress` | Remit-to / bill-to addresses printed on documents |
-| `employeeType` / `employeeTypePermission` / `employee` | Written only by `updateConsoleSetting`, which provisions a "Console Operator" type |
+| `employeeType` / `employeeTypePermission` / `employee` | Written only by `updateConsoleSetting` (now in the commercial `@carbon/ee/console.server`, gated to Business via the `PERMISSIONS` feature), which provisions a "Console Operator" type |
## Key Service Functions
@@ -73,7 +73,7 @@ pnpm run lint
- `getTerms` — company terms fallback for the Terms block; `getAccountsPayableBillingAddress` / `getAccountsReceivableBillingAddress` (+ `update*`) — addresses printed on documents
- `getCustomField(s)` / `getCustomFieldsTables`, plus `upsertCustomField` / `deleteCustomField` / `updateCustomFieldsSortOrder` (`settings.server.ts`, cache-clearing)
- `getIntegration(s)` / `getCompanyIntegrations` / `upsertCompanyIntegration` / `deactivateIntegration` / `getIntegrationsWithHealth`
-- `upsertApiKey` / `deleteApiKey`; `upsertWebhook` / `deleteWebhook` / `deactivateWebhooks` / `getWebhookTables`
+- Webhook + API-key READ helpers stay here (`getWebhook(s)` / `getWebhookTables`, `getApiKey(s)`); the commercial AUTHORING writers moved to `@carbon/ee` behind the entitlement lock — `upsertApiKey` / `deleteApiKey` (`@carbon/ee/api-keys.server`, `API_KEYS`) and `upsertWebhook` / `deleteWebhook` / `deactivateWebhooks` (`@carbon/ee/webhooks.server`, `WEBHOOKS`)
- `insertCompany` / `insertSubsidiary` / `updateSubsidiary` / `deleteSubsidiary` / `seedCompany` / `updateCompany` / `updateCompanyPlan`
- `updateLogoLight|LightIcon|Dark|DarkIcon|Watermark` — store the storage path on `company`, not a URL (readers prefix it)
- `exportCompanyBackup` / `listCompanyBackupFolders` / `deleteCompanyBackup` / `getCompanyRestoreRuns` / `getCompanyExportRun` (`backups.service.ts`); `getCompanyBackups` — the Backups loader's list, which computes each backup's live compatibility verdict via `@carbon/jobs/backups` — and the restore triggers live in `backups.server.ts`
diff --git a/apps/erp/app/modules/settings/backups.server.ts b/apps/erp/app/modules/settings/backups.server.ts
index e6dc640a98..90b8f2324e 100644
--- a/apps/erp/app/modules/settings/backups.server.ts
+++ b/apps/erp/app/modules/settings/backups.server.ts
@@ -1,5 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { trigger } from "@carbon/jobs";
import {
compatibilityStatus,
@@ -12,9 +13,24 @@ import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { getDatabaseClient } from "~/services/database.server";
+import { canAccessBackups } from "~/utils/backups";
const log = getLogger("erp", "backups");
+/**
+ * Backups are a Business/Enterprise feature (`BACKUPS`), plus an escape hatch for
+ * internal staff and local dev (`canAccessBackups`). Community/Starter cannot
+ * reach them. Shared by every backup route gate so they can never diverge.
+ */
+export async function canManageBackups(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ email: string | null | undefined
+): Promise<boolean> {
+ if (canAccessBackups(email)) return true;
+ return companyHasFeature(client, companyId, { feature: "BACKUPS" });
+}
+
import {
type CompanyBackupSummary,
listCompanyBackupFolders
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 3028c5b052..031031bce4 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -28,14 +28,12 @@ import { sanitize } from "~/utils/supabase";
import type {
accountsPayableBillingAddressValidator,
accountsReceivableBillingAddressValidator,
- apiKeyValidator,
companyValidator,
itemSerialSequenceValidator,
kanbanOutputTypes,
purchasePriceUpdateTimingTypes,
sequenceValidator,
- subsidiaryValidator,
- webhookValidator
+ subsidiaryValidator
} from "./settings.models";
const PUBLIC_STORAGE_URL_PREFIX = `${SUPABASE_URL}/storage/v1/object/public/public/`;
@@ -85,23 +83,6 @@ export async function updateAccountsReceivableBillingAddress(
.upsert(sanitize({ id: companyId, ...data, updatedBy }));
}
-export async function deactivateWebhooks(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("webhook")
- .update({ active: false })
- .eq("companyId", companyId);
-}
-
-export async function deleteApiKey(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("apiKey").delete().eq("id", id);
-}
-
export async function deleteSubsidiary(
client: SupabaseClient<Database>,
companyId: string
@@ -109,13 +90,6 @@ export async function deleteSubsidiary(
return client.from("company").delete().eq("id", companyId);
}
-export async function deleteWebhook(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("webhook").delete().eq("id", id);
-}
-
export async function getApiKeys(
client: SupabaseClient<Database>,
companyId: string,
@@ -1314,196 +1288,6 @@ export async function updateSupplierQuoteNotificationSetting(
.eq("id", companyId);
}
-export async function upsertApiKey(
- client: SupabaseClient<Database>,
- apiKey:
- | (Omit<z.infer<typeof apiKeyValidator>, "id" | "scopes" | "expiresAt"> & {
- createdBy: string;
- companyId: string;
- scopes: Record<string, string[]>;
- expiresAt?: string;
- rawKey: string;
- keyHash: string;
- keyPreview: string;
- })
- | (Omit<z.infer<typeof apiKeyValidator>, "id" | "scopes" | "expiresAt"> & {
- id: string;
- scopes: Record<string, string[]>;
- expiresAt?: string;
- })
-) {
- if ("createdBy" in apiKey) {
- // Create: store the hash, return the raw key (caller generates both)
- // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
- const {
- scopes,
- expiresAt,
- rawKey,
- keyHash,
- rateLimit: _rl,
- rateLimitWindow: _rlw,
- ...rest
- } = apiKey as any;
-
- const result = await client
- .from("apiKey")
- .insert(
- sanitize({
- ...rest,
- keyHash,
- scopes: scopes as any,
- expiresAt: expiresAt || null
- }) as any
- )
- .select("id")
- .single();
-
- if (result.error) {
- return { data: null, error: result.error };
- }
-
- // Return the raw key (shown to user once, never stored)
- return { data: { key: rawKey, id: result.data.id }, error: null };
- }
-
- // Update: update name, scopes, expiration (never the key itself)
- // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
- const {
- scopes,
- expiresAt,
- rateLimit: _rl,
- rateLimitWindow: _rlw,
- ...rest
- } = apiKey as any;
- return client
- .from("apiKey")
- .update(
- sanitize({
- ...rest,
- scopes: scopes as any,
- expiresAt: expiresAt || null
- }) as any
- )
- .eq("id", apiKey.id);
-}
-
-export async function updateConsoleSetting(
- client: SupabaseClient<Database>,
- companyId: string,
- consoleEnabled: boolean,
- userId?: string
-) {
- const update = await client
- .from("companySettings")
- .update(sanitize({ consoleEnabled }) as any)
- .eq("id", companyId);
-
- // When enabling, create "Console Operator" employee type if it doesn't exist
- if (consoleEnabled) {
- const existing = await client
- .from("employeeType")
- .select("id")
- .eq("companyId", companyId)
- .eq("systemType", "Console Operator")
- .maybeSingle();
-
- if (!existing.data) {
- const newType = await client
- .from("employeeType")
- .insert({
- name: "Console Operator",
- companyId,
- protected: true,
- systemType: "Console Operator"
- })
- .select("id")
- .single();
-
- // Create default permissions for the Console Operator type.
- // Only grant what's needed for MES operations — not ERP modules.
- if (newType.data) {
- const mesModules = [
- {
- module: "Production",
- create: true,
- update: true,
- delete: false,
- view: true
- },
- {
- module: "Inventory",
- create: true,
- update: true,
- delete: false,
- view: true
- },
- {
- module: "Resources",
- create: false,
- update: false,
- delete: false,
- view: true
- },
- {
- module: "Items",
- create: false,
- update: false,
- delete: false,
- view: true
- },
- {
- module: "Quality",
- create: true,
- update: true,
- delete: false,
- view: true
- },
- {
- module: "People",
- create: false,
- update: false,
- delete: false,
- view: true
- }
- ];
-
- const permissions = mesModules.map((m) => ({
- employeeTypeId: newType.data.id,
- module: m.module as "Accounting",
- create: m.create ? [companyId] : [],
- update: m.update ? [companyId] : [],
- delete: m.delete ? [companyId] : [],
- view: m.view ? [companyId] : []
- }));
-
- await client.from("employeeTypePermission").insert(permissions);
- }
- }
-
- // Auto-generate a PIN for the enabling user if they don't have one
- let generatedPin: string | null = null;
- if (userId) {
- const userEmployee = await client
- .from("employee")
- .select("id, pin" as any)
- .eq("id", userId)
- .eq("companyId", companyId)
- .maybeSingle();
-
- if (userEmployee.data && !(userEmployee.data as any).pin) {
- generatedPin = Math.floor(1000 + Math.random() * 9000).toString();
- await client
- .from("employee")
- .update({ pin: generatedPin } as any)
- .eq("id", userId)
- .eq("companyId", companyId);
- }
- }
- }
-
- return update;
-}
-
export async function updateDefaultSupplierCc(
client: SupabaseClient<Database>,
companyId: string,
@@ -1515,17 +1299,6 @@ export async function updateDefaultSupplierCc(
.eq("id", companyId);
}
-export async function updateRequireMfaSetting(
- client: SupabaseClient<Database>,
- companyId: string,
- requireMfa: boolean
-) {
- return client
- .from("companySettings")
- .update(sanitize({ requireMfa }))
- .eq("id", companyId);
-}
-
export async function updateShowCurrencyTrailingZerosSetting(
client: SupabaseClient<Database>,
companyId: string,
@@ -1591,20 +1364,3 @@ export async function updateReturnPickedMaterialTimingSetting(
.update(sanitize({ returnPickedMaterialTiming }))
.eq("id", companyId);
}
-
-export async function upsertWebhook(
- client: SupabaseClient<Database>,
- webhook:
- | (Omit<z.infer<typeof webhookValidator>, "id"> & {
- createdBy: string;
- companyId: string;
- })
- | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {
- id: string;
- })
-) {
- if ("createdBy" in webhook) {
- return client.from("webhook").insert(webhook).select("id").single();
- }
- return client.from("webhook").update(sanitize(webhook)).eq("id", webhook.id);
-}
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx
similarity index 98%
rename from apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx
rename to apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx
index a69d799082..08b7eac910 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx
@@ -1,3 +1,9 @@
+import {
+ type ApprovalDocumentType,
+ type ApprovalRule,
+ approvalDocumentTypeLabel,
+ approvalDocumentTypesWithAmounts
+} from "@carbon/ee/approvals";
import {
Accordion,
AccordionContent,
@@ -21,14 +27,8 @@ import { LuEllipsisVertical, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
import { useCurrencyFormatter, usePermissions, useUrlParams } from "~/hooks";
-import {
- type ApprovalDocumentType,
- type ApprovalRule,
- approvalDocumentTypeLabel,
- approvalDocumentTypesWithAmounts
-} from "~/modules/shared";
import { path } from "~/utils/path";
-import ApprovalRuleDetails from "./ApprovalRuleDetails";
+import ApprovalRuleDetails from "./ApprovalRuleDetails.ee";
type ApprovalRuleCardProps = {
rule: ApprovalRule & { approverGroupNames?: string[] };
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.ee.tsx
similarity index 98%
rename from apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.tsx
rename to apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.ee.tsx
index de6f5444c0..8d7e8dd790 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleDetails.ee.tsx
@@ -1,3 +1,4 @@
+import type { ApprovalDocumentType, ApprovalRule } from "@carbon/ee/approvals";
import { cn, HStack, VStack } from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { memo } from "react";
@@ -10,7 +11,6 @@ import {
} from "react-icons/lu";
import { DateTime, EmployeeAvatar } from "~/components";
import { UserSelect } from "~/components/Selectors";
-import type { ApprovalDocumentType, ApprovalRule } from "~/modules/shared";
type ApprovalRuleDetailsProps = {
rule: ApprovalRule & { approverGroupNames?: string[] };
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.ee.tsx
similarity index 98%
rename from apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx
rename to apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.ee.tsx
index dc7373a434..c9c53b99e4 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.ee.tsx
@@ -1,3 +1,9 @@
+import type { ApprovalRule } from "@carbon/ee/approvals";
+import {
+ type ApprovalDocumentType,
+ approvalDocumentTypesWithAmounts,
+ approvalRuleValidator
+} from "@carbon/ee/approvals";
import {
Boolean as FormBoolean,
Number as FormNumber,
@@ -20,12 +26,6 @@ import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { Employee, Users } from "~/components/Form";
import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
-import type { ApprovalRule } from "~/modules/shared";
-import {
- type ApprovalDocumentType,
- approvalDocumentTypesWithAmounts,
- approvalRuleValidator
-} from "~/modules/shared";
import { path } from "~/utils/path";
type ApprovalRuleFormProps = {
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx
similarity index 98%
rename from apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.tsx
rename to apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx
index 850193a369..df02a44adb 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRules.ee.tsx
@@ -1,3 +1,7 @@
+import {
+ type ApprovalRule,
+ approvalDocumentTypesWithAmounts
+} from "@carbon/ee/approvals";
import {
Button,
Card,
@@ -15,12 +19,8 @@ import { LuPlus } from "react-icons/lu";
import { Link } from "react-router";
import { Empty } from "~/components";
import { usePermissions } from "~/hooks";
-import {
- type ApprovalRule,
- approvalDocumentTypesWithAmounts
-} from "~/modules/shared";
import { path } from "~/utils/path";
-import ApprovalRuleCard from "./ApprovalRuleCard";
+import ApprovalRuleCard from "./ApprovalRuleCard.ee";
type ApprovalRulesProps = {
poRules: ApprovalRule[];
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx
new file mode 100644
index 0000000000..06291a6537
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRulesUpgradeOverlay.ee.tsx
@@ -0,0 +1,59 @@
+// Plan-gate overlay for Settings → Approval Rules. Mirrors
+// `SalesRulesUpgradeOverlay`: shared overlay chrome via
+// `~/components/RulesUpgradeOverlay`, with an approval-rules preview, mock
+// fixtures, and copy specific to this feature.
+
+import type { ApprovalRule } from "@carbon/ee/approvals";
+import { Trans } from "@lingui/react/macro";
+import RulesUpgradeOverlay from "~/components/RulesUpgradeOverlay";
+import ApprovalRules from "./ApprovalRules.ee";
+
+const mockPoRules: (ApprovalRule & { approverGroupNames?: string[] })[] = [
+ {
+ id: "mock-1",
+ companyId: "mock",
+ documentType: "purchaseOrder",
+ enabled: true,
+ lowerBoundAmount: 5000,
+ approverGroupIds: null,
+ defaultApproverId: null,
+ escalationDays: 2,
+ createdAt: "2026-05-04T10:00:00Z",
+ createdBy: "mock",
+ updatedAt: null,
+ updatedBy: null,
+ approverGroupNames: ["Purchasing Managers"]
+ },
+ {
+ id: "mock-2",
+ companyId: "mock",
+ documentType: "purchaseOrder",
+ enabled: true,
+ lowerBoundAmount: 25000,
+ approverGroupIds: null,
+ defaultApproverId: null,
+ escalationDays: 3,
+ createdAt: "2026-04-29T14:22:00Z",
+ createdBy: "mock",
+ updatedAt: null,
+ updatedBy: null,
+ approverGroupNames: ["Finance", "Executives"]
+ }
+];
+
+export default function ApprovalRulesUpgradeOverlay() {
+ return (
+ <RulesUpgradeOverlay
+ preview={
+ <ApprovalRules poRules={mockPoRules} qdRules={[]} supplierRules={[]} />
+ }
+ title={<Trans>Approval Rules</Trans>}
+ description={
+ <Trans>
+ Require tiered sign-off on purchase orders, quality documents, and
+ suppliers based on amount thresholds and approver groups.
+ </Trans>
+ }
+ />
+ );
+}
diff --git a/apps/erp/app/modules/settings/ui/Approvals/index.ts b/apps/erp/app/modules/settings/ui/Approvals/index.ts
index 9268a8b83e..22439361c4 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/index.ts
+++ b/apps/erp/app/modules/settings/ui/Approvals/index.ts
@@ -1,2 +1,3 @@
-export { default as ApprovalRuleForm } from "./ApprovalRuleForm";
-export { default as ApprovalRules } from "./ApprovalRules";
+export { default as ApprovalRuleForm } from "./ApprovalRuleForm.ee";
+export { default as ApprovalRules } from "./ApprovalRules.ee";
+export { default as ApprovalRulesUpgradeOverlay } from "./ApprovalRulesUpgradeOverlay.ee";
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index a375b82934..92b8e6aa13 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -29,23 +29,25 @@ import {
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
import { useFlags } from "~/hooks/useFlags";
+import { usePlanGate } from "~/hooks/usePlanGate";
import type { AuthenticatedRouteGroup, Role } from "~/types";
import { path } from "~/utils/path";
const internalOnlyRoutes = new Set<string>([path.to.companies]);
-// Internal-only in real deployments, but usable by anyone on a local dev stack —
-// mirrors `canAccessBackups`, which gates the route and the backup APIs.
-const localOrInternalRoutes = new Set<string>([
- path.to.backups,
- path.to.demoData
-]);
+// Demo Data (template seeding) stays internal / local-dev only — mirrors
+// `canAccessBackups`. Backups is now a Business/Enterprise feature gated
+// separately below (with the same internal/local-dev escape hatch).
+const localOrInternalRoutes = new Set<string>([path.to.demoData]);
export default function useSettingsSubmodules() {
const { t } = useLingui();
const permissions = usePermissions();
const { isCloud, isControlledEnvironment, isInternal, isLocalDev } =
useFlags();
+ // Enterprise: backups are a Business plan feature, but internal staff and
+ // local dev keep access (mirrors the server `canManageBackups`).
+ const { isGated: backupsGated } = usePlanGate({ feature: "BACKUPS" });
const settingsRoutes: AuthenticatedRouteGroup<{
requiresOwnership?: boolean;
@@ -252,6 +254,14 @@ export default function useSettingsSubmodules() {
if (!isInternal && internalOnlyRoutes.has(route.to)) return false;
if (!isInternal && !isLocalDev && localOrInternalRoutes.has(route.to))
return false;
+ // Backups: visible to Business/Enterprise, internal staff, or local dev.
+ if (
+ route.to === path.to.backups &&
+ backupsGated &&
+ !isInternal &&
+ !isLocalDev
+ )
+ return false;
return true;
};
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 37d7a4351c..59c44b72f3 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -1,75 +1,7 @@
-import type { Database } from "@carbon/database";
import { textToTiptap } from "@carbon/utils";
import { z } from "zod";
import { zfd } from "zod-form-data";
-export const approvalDecisionValidator = z.object({
- id: zfd.text(z.string().optional()),
- decision: z.enum(["Approved", "Rejected"], {
- error: "Decision is required"
- }),
- decisionNotes: zfd.text(z.string().optional())
-});
-
-export const approvalDocumentType = [
- "purchaseOrder",
- "qualityDocument",
- "supplier"
-] as const;
-
-export type ApprovalDocumentType =
- Database["public"]["Enums"]["approvalDocumentType"];
-
-export const approvalDocumentTypeLabel: Record<ApprovalDocumentType, string> = {
- purchaseOrder: "Purchase Order",
- qualityDocument: "Quality Document",
- supplier: "Supplier"
-};
-
-export const approvalDocumentTypesWithAmounts: ApprovalDocumentType[] = [
- "purchaseOrder"
-] as const;
-
-export const approvalFiltersValidator = z.object({
- documentType: z.enum(approvalDocumentType, {
- error: "Document type is required"
- }),
- status: zfd.text(z.string().optional()),
- dateFrom: zfd.text(z.string().optional()),
- dateTo: zfd.text(z.string().optional())
-});
-
-export const approvalRequestValidator = z.object({
- id: zfd.text(z.string().optional()),
- documentType: z.enum(approvalDocumentType, {
- error: "Document type is required"
- }),
- documentId: zfd.text(
- z.string().min(1, { message: "Document ID is required" })
- ),
- approverGroupIds: zfd.repeatableOfType(z.string()).optional()
-});
-
-export const approvalRuleValidator = z.object({
- id: zfd.text(z.string().optional()),
- documentType: z.enum(approvalDocumentType, {
- error: "Document type is required"
- }),
- approverGroupIds: z.array(
- z.string().min(1, { message: "Invalid selection" })
- ),
- defaultApproverId: zfd.text(z.string().optional()),
- lowerBoundAmount: zfd.numeric(z.number().gt(0).default(0)).optional(),
- enabled: zfd.checkbox()
-});
-
-export const approvalStatusType = [
- "Pending",
- "Approved",
- "Rejected",
- "Cancelled"
-] as const;
-
export const chartIntervals = [
{ key: "week", label: "Week" },
{ key: "month", label: "Month" },
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 8a8f63a144..8e232015b2 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1,10 +1,5 @@
-import type { Database, Json, Tables } from "@carbon/database";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import type { Database, Tables } from "@carbon/database";
import { getContentType, getFileExtension } from "@carbon/files";
-import { trackWorkEvent } from "@carbon/lib/telemetry";
-import { getLogger } from "@carbon/logger";
-import type { ConditionAst, Severity } from "@carbon/utils";
-import { datetime, getPurchaseOrderStatus } from "@carbon/utils";
import type {
PostgrestResponse,
PostgrestSingleResponse,
@@ -12,364 +7,8 @@ import type {
} from "@supabase/supabase-js";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
-import { sanitize } from "~/utils/supabase";
-import type {
- approvalDocumentType,
- PriceBreak,
- SupplierPriceMap
-} from "./shared.models";
-import type {
- ApprovalFilters,
- ApprovalRequestForApproveCheck,
- ApprovalRequestForCancelCheck,
- ApprovalRequestForViewCheck,
- ApprovalRule,
- CreateApprovalRequestInput,
- ItemModelUpload,
- UpsertApprovalRuleInput
-} from "./types";
-
-const logger = getLogger("erp", "shared-service");
-
-export async function approveRequest(
- db: Kysely<KyselyDatabase>,
- id: string,
- userId: string,
- notes?: string
-) {
- // Pre-flight check: verify approval request exists and is pending
- const approvalRequest = await db
- .selectFrom("approvalRequest")
- .select(["id", "status", "documentType", "documentId", "companyId"])
- .where("id", "=", id)
- .executeTakeFirst();
-
- if (!approvalRequest) {
- return { error: { message: "Approval request not found" }, data: null };
- }
-
- if (approvalRequest.status !== "Pending") {
- return {
- error: { message: "Approval request is not pending" },
- data: null
- };
- }
-
- const { documentType, documentId } = approvalRequest;
- const now = new Date().toISOString();
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- // 1. Update approval request to "Approved"
- const updatedApproval = await trx
- .updateTable("approvalRequest")
- .set({
- status: "Approved",
- decisionBy: userId,
- decisionAt: now,
- decisionNotes: notes || null,
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", id)
- .returning(["id", "documentType", "documentId"])
- .executeTakeFirstOrThrow();
-
- // 2. Update document status based on type
- if (documentType === "purchaseOrder") {
- // Fetch PO lines to calculate new status
- const lines = await trx
- .selectFrom("purchaseOrderLine")
- .select([
- "purchaseOrderLineType",
- "invoicedComplete",
- "receivedComplete"
- ])
- .where("purchaseOrderId", "=", documentId)
- .execute();
-
- const { status: calculatedStatus } = getPurchaseOrderStatus(lines);
-
- // Update PO status (only if currently "Needs Approval")
- const poUpdate = await trx
- .updateTable("purchaseOrder")
- .set({
- status: calculatedStatus,
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", documentId)
- .where("status", "=", "Needs Approval")
- .returning(["id"])
- .executeTakeFirst();
-
- if (!poUpdate) {
- throw new Error(
- "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
- );
- }
- } else if (documentType === "qualityDocument") {
- const qdUpdate = await trx
- .updateTable("qualityDocument")
- .set({
- status: "Active",
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", documentId)
- .returning(["id"])
- .executeTakeFirst();
-
- if (!qdUpdate) {
- throw new Error("Failed to update quality document status");
- }
- } else if (documentType === "supplier") {
- const supplierUpdate = await trx
- .updateTable("supplier")
- .set({
- supplierStatus: "Active",
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", documentId)
- .returning(["id"])
- .executeTakeFirst();
-
- if (!supplierUpdate) {
- throw new Error("Failed to update supplier status");
- }
- }
-
- return updatedApproval;
- });
-
- // After the transaction, so a rollback emits nothing. The order became
- // real here, not on the finalize route — that one stopped at the gate.
- // Without this, every order a customer routes through an approval
- // threshold is missing from "POs issued", and the shops that configure
- // approval thresholds are the larger ones.
- if (documentType === "purchaseOrder") {
- trackWorkEvent(
- "purchase_order_finalized",
- {
- companyId: approvalRequest.companyId,
- userId,
- purchaseOrderId: documentId,
- stage: "committed"
- },
- { discriminator: "committed" }
- );
- }
-
- return { data: result, error: null };
- } catch (error) {
- // Transaction automatically rolled back on error
- return {
- error: {
- message:
- error instanceof Error ? error.message : "Failed to process approval"
- },
- data: null
- };
- }
-}
-
-export async function canApproveRequest(
- client: SupabaseClient<Database>,
- approvalRequest: ApprovalRequestForApproveCheck,
- userId: string
-): Promise<boolean> {
- const rules = await getApprovalRulesForApprover(
- client,
- approvalRequest.documentType,
- approvalRequest.companyId
- );
-
- if (!rules.data || rules.data.length === 0) {
- return false;
- }
-
- // Authority flows upward only. Find the tier that matches this request's
- // amount; a user may approve at that tier or any HIGHER tier, but never
- // from a lower one (a $1k approver must not approve a $1M order).
- // Amount-less document types (quality, supplier) match the base tier
- // (lowerBoundAmount 0), so every rule qualifies and behavior is unchanged.
- const matched = await getApprovalRuleByAmount(
- client,
- approvalRequest.documentType,
- approvalRequest.companyId,
- approvalRequest.amount ?? undefined
- );
- const tierFloor = matched.data?.lowerBoundAmount ?? 0;
-
- const userGroups = await client.rpc("groups_for_user", { uid: userId });
- const userGroupIds = userGroups.data || [];
-
- return rules.data
- .filter((rule) => (rule.lowerBoundAmount ?? 0) >= tierFloor)
- .some((rule) => {
- if (rule.defaultApproverId === userId) {
- return true;
- }
-
- const approverGroupIds = rule.approverGroupIds;
- if (!approverGroupIds || approverGroupIds.length === 0) {
- return false;
- }
-
- // Direct individual approver
- if (approverGroupIds.includes(userId)) {
- return true;
- }
-
- // Member of an approver group
- return approverGroupIds.some((groupId) => userGroupIds.includes(groupId));
- });
-}
-
-/**
- * Checks if a user can approve a request based on the specific rule matching the amount.
- * This is the original approval check logic - user must be on the rule that matches the amount.
- * Used for "Assigned to Me" lists.
- */
-export async function canApproveRequestInWindow(
- client: SupabaseClient<Database>,
- approvalRequest: ApprovalRequestForApproveCheck,
- userId: string
-): Promise<boolean> {
- const rule = await getApprovalRuleByAmount(
- client,
- approvalRequest.documentType,
- approvalRequest.companyId,
- approvalRequest.amount ?? undefined
- );
-
- if (!rule.data) {
- return false;
- }
-
- if (rule.data.defaultApproverId === userId) {
- return true;
- }
-
- const approverGroupIds = rule.data.approverGroupIds;
- if (!approverGroupIds || approverGroupIds.length === 0) {
- return false;
- }
-
- // Check if user ID is directly in approverGroupIds (for individual approvers)
- if (approverGroupIds.includes(userId)) {
- return true;
- }
-
- // Check if user belongs to any of the approver groups
- const userGroups = await client.rpc("groups_for_user", { uid: userId });
- const userGroupIds = userGroups.data || [];
- return approverGroupIds.some((groupId) => userGroupIds.includes(groupId));
-}
-
-export function canCancelRequest(
- approvalRequest: ApprovalRequestForCancelCheck,
- userId: string
-): boolean {
- return (
- approvalRequest.requestedBy === userId &&
- approvalRequest.status === "Pending"
- );
-}
-
-export async function cancelApprovalRequest(
- client: SupabaseClient<Database>,
- id: string,
- userId: string
-) {
- const existing = await client
- .from("approvalRequest")
- .select("id, status, requestedBy")
- .eq("id", id)
- .single();
-
- if (existing.error || !existing.data) {
- return { error: { message: "Approval request not found" }, data: null };
- }
-
- if (existing.data.status !== "Pending") {
- return {
- error: { message: "Approval request is not pending" },
- data: null
- };
- }
-
- if (existing.data.requestedBy !== userId) {
- return {
- error: { message: "Only the requester can cancel an approval request" },
- data: null
- };
- }
-
- return client
- .from("approvalRequest")
- .update({
- status: "Cancelled",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", id)
- .select("id")
- .single();
-}
-
-export async function canViewApprovalRequest(
- client: SupabaseClient<Database>,
- approvalRequest: ApprovalRequestForViewCheck,
- userId: string
-): Promise<boolean> {
- if (approvalRequest.requestedBy === userId) {
- return true;
- }
-
- return canApproveRequest(
- client,
- {
- amount: approvalRequest.amount,
- documentType: approvalRequest.documentType,
- companyId: approvalRequest.companyId
- },
- userId
- );
-}
-
-export async function createApprovalRequest(
- client: SupabaseClient<Database>,
- request: CreateApprovalRequestInput & { amount?: number }
-) {
- return client
- .from("approvalRequest")
- .insert([
- {
- documentType: request.documentType,
- documentId: request.documentId,
- requestedBy: request.requestedBy,
- amount: request.amount ?? null,
- companyId: request.companyId,
- createdBy: request.createdBy
- }
- ])
- .select("id")
- .single();
-}
-
-export async function deleteApprovalRule(
- client: SupabaseClient<Database>,
- id: string,
- companyId: string
-) {
- return client
- .from("approvalRule")
- .delete()
- .eq("id", id)
- .eq("companyId", companyId);
-}
+import type { PriceBreak, SupplierPriceMap } from "./shared.models";
+import type { ItemModelUpload } from "./types";
export async function deleteNote(
client: SupabaseClient<Database>,
@@ -408,302 +47,6 @@ export async function generateEmbedding(
return response.data.embedding as number[];
}
-export async function getApprovalById(
- client: SupabaseClient<Database>,
- id: string
-) {
- const baseRequest = await client
- .from("approvalRequest")
- .select("*")
- .eq("id", id)
- .single();
-
- if (baseRequest.error || !baseRequest.data) {
- return baseRequest;
- }
-
- const viewData = await client
- .from("approvalRequests")
- .select("documentReadableId, documentDescription")
- .eq("id", id)
- .single();
-
- return {
- data: {
- ...baseRequest.data,
- documentReadableId: viewData.data?.documentReadableId ?? null,
- documentDescription: viewData.data?.documentDescription ?? null
- },
- error: null
- };
-}
-
-export async function getApprovalRequestsByDocument(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- documentId: string
-) {
- return client
- .from("approvalRequests")
- .select("*")
- .eq("documentType", documentType)
- .eq("documentId", documentId)
- .order("requestedAt", { ascending: false });
-}
-
-export async function getApprovalRuleByAmount(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- companyId: string,
- amount?: number
-) {
- let query = client
- .from("approvalRule")
- .select("*")
- .eq("documentType", documentType)
- .eq("companyId", companyId)
- .eq("enabled", true);
-
- if (amount !== undefined && amount !== null) {
- // The matching tier is the highest one whose floor is at or below the
- // amount; the next tier's floor is where its coverage ends.
- query = query.lte("lowerBoundAmount", amount);
- } else {
- query = query.eq("lowerBoundAmount", 0);
- }
-
- return query
- .order("lowerBoundAmount", { ascending: false })
- .order("id", { ascending: true })
- .limit(1)
- .maybeSingle();
-}
-
-export async function getApproverUserIdsForRule(
- client: SupabaseClient<Database>,
- rule: Pick<ApprovalRule, "approverGroupIds" | "defaultApproverId">
-): Promise<string[]> {
- const groupIds = rule.approverGroupIds?.filter(Boolean) ?? [];
- const defaultId = rule.defaultApproverId ?? null;
-
- const fromGroups =
- groupIds.length > 0
- ? await client.rpc("users_for_groups", { groups: groupIds })
- : { data: [] as string[], error: null };
-
- if (fromGroups.error) {
- logger.error(
- "getApproverUserIdsForRule: users_for_groups failed",
- fromGroups.error
- );
- return defaultId ? [defaultId] : [];
- }
-
- const ids = Array.isArray(fromGroups.data)
- ? (fromGroups.data as string[])
- : [];
- const combined = defaultId
- ? [...new Set([...ids, defaultId])]
- : [...new Set(ids)];
- return combined;
-}
-
-/**
- * "Notified of spend" cascade resolver. When a tiered approval lands at
- * a high tier, approvers of every enabled rule with a strictly lower
- * `lowerBoundAmount` get pinged — visibility into spend that bypassed
- * their tier. Returns deduped user IDs.
- */
-export async function getLowerTierApproverUserIds(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- companyId: string,
- amount: number | null | undefined
-): Promise<string[]> {
- if (amount == null) return [];
-
- const matched = await getApprovalRuleByAmount(
- client,
- documentType,
- companyId,
- amount
- );
- if (!matched.data) return [];
-
- const lowerRules = await client
- .from("approvalRule")
- .select("approverGroupIds, defaultApproverId")
- .eq("documentType", documentType)
- .eq("companyId", companyId)
- .eq("enabled", true)
- .lt("lowerBoundAmount", matched.data.lowerBoundAmount ?? 0);
-
- if (lowerRules.error || !lowerRules.data?.length) return [];
-
- const expanded = await Promise.all(
- lowerRules.data.map((rule) => getApproverUserIdsForRule(client, rule))
- );
- return [...new Set(expanded.flat())];
-}
-
-export async function getApprovalRuleById(
- client: SupabaseClient<Database>,
- id: string,
- companyId: string
-) {
- return client
- .from("approvalRule")
- .select("*")
- .eq("id", id)
- .eq("companyId", companyId)
- .single();
-}
-
-export async function getApprovalRules(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client.from("approvalRule").select("*").eq("companyId", companyId);
-}
-
-export async function getApprovalRulesForApprover(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- companyId: string
-) {
- return client
- .from("approvalRule")
- .select("*")
- .eq("documentType", documentType)
- .eq("companyId", companyId)
- .eq("enabled", true)
- .order("lowerBoundAmount", { ascending: false });
-}
-
-export async function getApprovalsForUser(
- client: SupabaseClient<Database>,
- userId: string,
- companyId: string,
- args?: GenericQueryFilters & ApprovalFilters
-) {
- let query = client
- .from("approvalRequest")
- .select("*", { count: "exact" })
- .eq("companyId", companyId)
- .eq("requestedBy", userId);
-
- if (args?.documentType) {
- query = query.eq("documentType", args.documentType);
- }
-
- if (args?.status) {
- query = query.eq("status", args.status);
- }
-
- if (args?.dateFrom) {
- query = query.gte("requestedAt", args.dateFrom);
- }
- if (args?.dateTo) {
- query = query.lte("requestedAt", args.dateTo);
- }
-
- const requestedByUserBase = await query;
-
- // Get readable fields from view for requestedByUser
- const requestedByUser = await Promise.all(
- (requestedByUserBase.data || []).map(async (approval) => {
- const viewData = await client
- .from("approvalRequests")
- .select("documentReadableId, documentDescription")
- .eq("id", approval.id)
- .single();
-
- return {
- ...approval,
- documentReadableId: viewData.data?.documentReadableId ?? null,
- documentDescription: viewData.data?.documentDescription ?? null
- };
- })
- );
-
- let pendingQuery = client
- .from("approvalRequest")
- .select("*")
- .eq("companyId", companyId)
- .eq("status", "Pending")
- .neq("requestedBy", userId);
-
- if (args?.documentType) {
- pendingQuery = pendingQuery.eq("documentType", args.documentType);
- }
-
- if (args?.dateFrom) {
- pendingQuery = pendingQuery.gte("requestedAt", args.dateFrom);
- }
- if (args?.dateTo) {
- pendingQuery = pendingQuery.lte("requestedAt", args.dateTo);
- }
-
- const allPending = await pendingQuery;
-
- const pendingWithReadableFields = await Promise.all(
- (allPending.data || []).map(async (approval) => {
- const viewData = await client
- .from("approvalRequests")
- .select("documentReadableId, documentDescription")
- .eq("id", approval.id)
- .single();
-
- return {
- ...approval,
- documentReadableId: viewData.data?.documentReadableId ?? null,
- documentDescription: viewData.data?.documentDescription ?? null
- };
- })
- );
-
- const canApprovePromises = pendingWithReadableFields.map(async (approval) => {
- const canApprove = await canApproveRequest(
- client,
- {
- amount: approval.amount,
- documentType: approval.documentType,
- companyId: approval.companyId
- },
- userId
- );
- return canApprove ? approval : null;
- });
-
- const approvableByUser = (await Promise.all(canApprovePromises)).filter(
- (approval): approval is NonNullable<typeof approval> => approval !== null
- );
-
- const allApprovals = [...requestedByUser, ...approvableByUser];
-
- let filtered = allApprovals;
- if (args?.status && args.status !== "Pending") {
- filtered = allApprovals.filter((a) => a.status === args.status);
- }
-
- filtered.sort((a, b) => {
- const aDate = new Date(a.requestedAt).getTime();
- const bDate = new Date(b.requestedAt).getTime();
- return bDate - aDate;
- });
-
- if (args?.limit) {
- const offset = args.offset || 0;
- filtered = filtered.slice(offset, offset + args.limit);
- }
-
- return {
- data: filtered,
- count: requestedByUserBase.count ?? allApprovals.length,
- error: null
- };
-}
-
export async function getBase64ImageFromSupabase(
client: SupabaseClient<Database>,
path: string
@@ -741,41 +84,6 @@ export async function getTimezoneNames(client: SupabaseClient<Database>) {
return client.rpc("get_timezone_names");
}
-export async function getLatestApprovalRequestForDocument(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- documentId: string
-) {
- const baseRequest = await client
- .from("approvalRequest")
- .select("*")
- .eq("documentType", documentType)
- .eq("documentId", documentId)
- .eq("status", "Pending")
- .order("requestedAt", { ascending: false })
- .limit(1)
- .maybeSingle();
-
- if (baseRequest.error || !baseRequest.data) {
- return baseRequest;
- }
-
- const viewData = await client
- .from("approvalRequests")
- .select("documentReadableId, documentDescription")
- .eq("id", baseRequest.data.id)
- .single();
-
- return {
- data: {
- ...baseRequest.data,
- documentReadableId: viewData.data?.documentReadableId ?? null,
- documentDescription: viewData.data?.documentDescription ?? null
- },
- error: null
- };
-}
-
export { getDocumentType } from "@carbon/files";
/**
@@ -836,62 +144,6 @@ export async function getNotes(
.order("createdAt");
}
-export async function getPendingApprovalsForApprover(
- client: SupabaseClient<Database>,
- userId: string,
- companyId: string
-) {
- const allPending = await client
- .from("approvalRequest")
- .select("*")
- .eq("companyId", companyId)
- .eq("status", "Pending")
- .order("requestedAt", { ascending: false });
-
- if (allPending.error || !allPending.data) {
- return allPending;
- }
-
- const pendingWithReadableFields = await Promise.all(
- allPending.data.map(async (approval) => {
- const viewData = await client
- .from("approvalRequests")
- .select("documentReadableId, documentDescription")
- .eq("id", approval.id)
- .single();
-
- return {
- ...approval,
- documentReadableId: viewData.data?.documentReadableId ?? null,
- documentDescription: viewData.data?.documentDescription ?? null
- };
- })
- );
-
- // Use canApproveRequestInWindow to only show requests within user's specific approval window
- const canApprovePromises = pendingWithReadableFields.map(async (approval) => {
- const canApprove = await canApproveRequestInWindow(
- client,
- {
- amount: approval.amount,
- documentType: approval.documentType,
- companyId: approval.companyId
- },
- userId
- );
- return canApprove ? approval : null;
- });
-
- const approvableByUser = (await Promise.all(canApprovePromises)).filter(
- (approval): approval is NonNullable<typeof approval> => approval !== null
- );
-
- return {
- data: approvableByUser,
- error: null
- };
-}
-
export async function getPeriods(
client: SupabaseClient<Database>,
{ startDate, endDate }: { startDate: string; endDate: string }
@@ -931,22 +183,6 @@ export async function getTagsList(
return query.order("name");
}
-export async function hasPendingApproval(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- documentId: string
-): Promise<boolean> {
- const result = await client
- .from("approvalRequest")
- .select("id")
- .eq("documentType", documentType)
- .eq("documentId", documentId)
- .eq("status", "Pending")
- .limit(1);
-
- return (result.data?.length ?? 0) > 0;
-}
-
export async function importCsv(
client: SupabaseClient<Database>,
args: {
@@ -982,26 +218,6 @@ export async function insertTag(
return client.from("tag").insert(tag).select("*").single();
}
-export async function isApprovalRequired(
- client: SupabaseClient<Database>,
- documentType: (typeof approvalDocumentType)[number],
- companyId: string,
- amount?: number
-): Promise<boolean> {
- const config = await getApprovalRuleByAmount(
- client,
- documentType,
- companyId,
- amount
- );
-
- if (!config.data) {
- return false;
- }
-
- return config.data.enabled;
-}
-
export async function getExternalLink(
client: SupabaseClient<Database>,
id: string
@@ -1076,13 +292,6 @@ export async function getCustomerPortal(
.single();
}
-export async function deleteCustomerPortal(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("externalLink").delete().eq("id", id);
-}
-
export async function updateModelThumbnail(
client: SupabaseClient<Database>,
modelId: string,
@@ -1121,135 +330,6 @@ export async function updateNote(
return client.from("note").update({ note }).eq("id", id);
}
-export async function rejectRequest(
- db: Kysely<KyselyDatabase>,
- id: string,
- userId: string,
- notes?: string
-) {
- // Pre-flight check: verify approval request exists and is pending
- const approvalRequest = await db
- .selectFrom("approvalRequest")
- .select(["id", "status", "documentType", "documentId"])
- .where("id", "=", id)
- .executeTakeFirst();
-
- if (!approvalRequest) {
- return { error: { message: "Approval request not found" }, data: null };
- }
-
- if (approvalRequest.status !== "Pending") {
- return {
- error: { message: "Approval request is not pending" },
- data: null
- };
- }
-
- const { documentType, documentId } = approvalRequest;
- const now = new Date().toISOString();
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- // 1. Update approval request to "Rejected"
- const updatedApproval = await trx
- .updateTable("approvalRequest")
- .set({
- status: "Rejected",
- decisionBy: userId,
- decisionAt: now,
- decisionNotes: notes || null,
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", id)
- .returning(["id", "documentType", "documentId"])
- .executeTakeFirstOrThrow();
-
- // 2. Update document status based on type
- if (documentType === "purchaseOrder") {
- const poUpdate = await trx
- .updateTable("purchaseOrder")
- .set({
- status: "Rejected",
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", documentId)
- .where("status", "=", "Needs Approval")
- .returning(["id"])
- .executeTakeFirst();
-
- if (!poUpdate) {
- throw new Error(
- "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
- );
- }
- }
- // Note: qualityDocument rejection doesn't change status (stays Draft)
-
- if (documentType === "supplier") {
- const supplierUpdate = await trx
- .updateTable("supplier")
- .set({
- supplierStatus: "Rejected",
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", documentId)
- .returning(["id"])
- .executeTakeFirst();
-
- if (!supplierUpdate) {
- throw new Error("Failed to update supplier status");
- }
- }
-
- return updatedApproval;
- });
-
- return { data: result, error: null };
- } catch (error) {
- // Transaction automatically rolled back on error
- return {
- error: {
- message:
- error instanceof Error ? error.message : "Failed to process rejection"
- },
- data: null
- };
- }
-}
-
-export async function upsertApprovalRule(
- client: SupabaseClient<Database>,
- rule: UpsertApprovalRuleInput
-) {
- if ("id" in rule) {
- const existing = await client
- .from("approvalRule")
- .select("companyId")
- .eq("id", rule.id)
- .single();
-
- if (existing.error || !existing.data) {
- return {
- data: null,
- error: existing.error || { message: "Rule not found" }
- };
- }
-
- return client
- .from("approvalRule")
- .update(sanitize(rule))
- .eq("id", rule.id)
- .eq("companyId", existing.data.companyId)
- .select("id")
- .single();
- }
-
- return client.from("approvalRule").insert([rule]).select("id").single();
-}
-
export async function upsertSavedView(
client: SupabaseClient<Database>,
view: {
@@ -1425,51 +505,11 @@ export type EnforcementRuleFamily =
export type EnforcementRuleRow =
Database["public"]["Tables"]["enforcementRule"]["Row"];
-/** Item-scoping columns shared by both families (empty arrays = every item). */
-type RuleItemFilterFields = {
- filteredItemTypes?: string[];
- filteredItemGroupIds?: string[];
- filteredItemMatchAll?: boolean;
-};
-
-/**
- * Storage-family-only shape. The DB pins sales rows to `targetType: 'item'` /
- * `appliesToAll: false` via the `enforcementRule_sales_shape` CHECK, so these
- * stay optional here and simply go unset for sales.
- */
-type RuleTargetFields = {
- targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"];
- appliesToAll?: boolean;
-};
-
-type RuleSurfaces = Database["public"]["Enums"]["enforcementRuleSurface"][];
-
-export type EnforcementRuleInsert = RuleItemFilterFields &
- RuleTargetFields & {
- name: string;
- description?: string | null;
- message: string;
- severity: Severity;
- conditionAst: ConditionAst;
- surfaces: RuleSurfaces;
- active: boolean;
- createdBy: string;
- customFields?: Json;
- };
-
-export type EnforcementRuleUpdate = RuleItemFilterFields &
- RuleTargetFields & {
- id: string;
- name: string;
- description?: string | null;
- message: string;
- severity: Severity;
- conditionAst: ConditionAst;
- surfaces: RuleSurfaces;
- active: boolean;
- updatedBy: string;
- customFields?: Json;
- };
+// Authoring writes (`upsertEnforcementRule` / `deleteEnforcementRule`) and their
+// `EnforcementRuleInsert` / `EnforcementRuleUpdate` input types moved to
+// `@carbon/ee/rules.server` (`packages/ee/src/rules/service.server.ts`), where
+// they embed the commercial `requireEntitlement` gate. The read helpers below
+// stay here (ERP admin surface, client-safe).
export async function getEnforcementRules(
client: SupabaseClient<Database>,
@@ -1526,52 +566,6 @@ export async function getEnforcementRule(
);
}
-export async function upsertEnforcementRule(
- client: SupabaseClient<Database>,
- family: EnforcementRuleFamily,
- companyId: string,
- rule: EnforcementRuleInsert | EnforcementRuleUpdate
-) {
- if ("createdBy" in rule) {
- return client
- .from("enforcementRule")
- .insert({
- ...rule,
- companyId,
- family,
- conditionAst: rule.conditionAst as unknown as Json
- })
- .select("id")
- .single();
- }
- return client
- .from("enforcementRule")
- .update({
- ...sanitize(rule),
- conditionAst: rule.conditionAst as unknown as Json,
- updatedAt: datetime.timestamp()
- })
- .eq("id", rule.id)
- .eq("family", family)
- .eq("companyId", companyId)
- .select("id")
- .single();
-}
-
-export async function deleteEnforcementRule(
- client: SupabaseClient<Database>,
- family: EnforcementRuleFamily,
- id: string,
- companyId: string
-) {
- return client
- .from("enforcementRule")
- .delete()
- .eq("id", id)
- .eq("family", family)
- .eq("companyId", companyId);
-}
-
/**
* Pin counts per rule id. Rule ids are globally unique, so counting by id needs
* no family predicate even though the item table is shared between families.
diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.ts
index 224d009139..0ab8e12ac6 100644
--- a/apps/erp/app/modules/shared/types.ts
+++ b/apps/erp/app/modules/shared/types.ts
@@ -1,11 +1,7 @@
-import type { Database } from "@carbon/database";
import type { ColumnPinningState } from "@tanstack/react-table";
import type { z } from "zod";
import type { ModelUpload, StorageItem } from "~/types";
import type {
- ApprovalDocumentType,
- approvalRequestValidator,
- approvalRuleValidator,
itemType,
methodItemType,
methodType,
@@ -17,55 +13,11 @@ import type {
sourcingType,
standardFactorType
} from "./shared.models";
-import type {
- getApprovalRequestsByDocument,
- getApprovalRuleByAmount,
- getNotes
-} from "./shared.service";
+import type { getNotes } from "./shared.service";
/** A `ModelUpload` read off an item, carrying the item it came from. */
export type ItemModelUpload = ModelUpload & { itemId: string | null };
-export type ApprovalFilters = {
- documentType?: ApprovalDocumentType | null;
- status?: ApprovalStatus | null;
- dateFrom?: string | null;
- dateTo?: string | null;
-};
-
-export type ApprovalHistory = NonNullable<
- Awaited<ReturnType<typeof getApprovalRequestsByDocument>>["data"]
->;
-
-export type ApprovalRequest =
- Database["public"]["Views"]["approvalRequests"]["Row"];
-
-export type ApprovalRequestForApproveCheck = {
- amount: number | null;
- documentType: ApprovalDocumentType;
- companyId: string;
-};
-
-export type ApprovalRequestForCancelCheck = {
- requestedBy: string;
- status: string;
-};
-
-export type ApprovalRequestForViewCheck = {
- requestedBy: string;
- amount: number | null;
- documentType: ApprovalDocumentType;
- companyId: string;
-};
-
-export type ApprovalRule = NonNullable<
- Awaited<ReturnType<typeof getApprovalRuleByAmount>>["data"]
->;
-
-export type ApprovalDecision = "Approved" | "Rejected";
-
-export type ApprovalStatus = Database["public"]["Enums"]["approvalStatus"];
-
export type BillOfMaterialNodeType =
| "parent"
| "line"
@@ -166,22 +118,3 @@ export type SavedView = {
};
export type StandardFactor = (typeof standardFactorType)[number];
-
-export type CreateApprovalRequestInput = Omit<
- z.infer<typeof approvalRequestValidator>,
- "id"
-> & {
- companyId: string;
- requestedBy: string;
- createdBy: string;
-};
-
-export type UpsertApprovalRuleInput =
- | (Omit<z.infer<typeof approvalRuleValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- })
- | (Omit<z.infer<typeof approvalRuleValidator>, "id"> & {
- id: string;
- updatedBy: string;
- });
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
rename to apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.ee.tsx
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.tsx
rename to apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx
new file mode 100644
index 0000000000..52ca3e01f0
--- /dev/null
+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx
@@ -0,0 +1,59 @@
+// Plan-gate overlay for Users → Configure → Employee Types. Mirrors
+// `SalesRulesUpgradeOverlay`: shared overlay chrome via
+// `~/components/RulesUpgradeOverlay`, with an employee-types preview table,
+// mock fixtures, and copy specific to this feature.
+
+import { Trans } from "@lingui/react/macro";
+import RulesUpgradeOverlay from "~/components/RulesUpgradeOverlay";
+import type { EmployeeType } from "~/modules/users";
+import EmployeeTypesTable from "./EmployeeTypesTable.ee";
+
+const mockEmployeeTypes: EmployeeType[] = [
+ {
+ id: "mock-1",
+ name: "Administrator",
+ companyId: "mock",
+ protected: true,
+ systemType: null,
+ createdAt: "2026-05-04T10:00:00Z",
+ updatedAt: null
+ },
+ {
+ id: "mock-2",
+ name: "Purchasing",
+ companyId: "mock",
+ protected: false,
+ systemType: null,
+ createdAt: "2026-04-29T14:22:00Z",
+ updatedAt: null
+ },
+ {
+ id: "mock-3",
+ name: "Shop Floor",
+ companyId: "mock",
+ protected: false,
+ systemType: null,
+ createdAt: "2026-04-21T09:15:00Z",
+ updatedAt: null
+ }
+];
+
+export default function EmployeeTypesUpgradeOverlay() {
+ return (
+ <RulesUpgradeOverlay
+ preview={
+ <EmployeeTypesTable
+ data={mockEmployeeTypes}
+ count={mockEmployeeTypes.length}
+ />
+ }
+ title={<Trans>Employee Types</Trans>}
+ description={
+ <Trans>
+ Define custom roles with fine-grained, per-module permissions and
+ assign them to your team.
+ </Trans>
+ }
+ />
+ );
+}
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/index.ts b/apps/erp/app/modules/users/ui/EmployeeTypes/index.ts
index 9e2debfaa4..3f16372ab8 100644
--- a/apps/erp/app/modules/users/ui/EmployeeTypes/index.ts
+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/index.ts
@@ -1,4 +1,5 @@
-import EmployeeTypeForm from "./EmployeeTypeForm";
-import EmployeeTypesTable from "./EmployeeTypesTable";
+import EmployeeTypeForm from "./EmployeeTypeForm.ee";
+import EmployeeTypesTable from "./EmployeeTypesTable.ee";
+import EmployeeTypesUpgradeOverlay from "./EmployeeTypesUpgradeOverlay.ee";
-export { EmployeeTypeForm, EmployeeTypesTable };
+export { EmployeeTypeForm, EmployeeTypesTable, EmployeeTypesUpgradeOverlay };
diff --git a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
rename to apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx
diff --git a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
index 837d5039c4..78e44a065d 100644
--- a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx
@@ -13,8 +13,16 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useFetcher, useNavigate } from "react-router";
-import { Boolean, Input, Location, Select, Submit } from "~/components/Form";
+import {
+ Boolean,
+ Hidden,
+ Input,
+ Location,
+ Select,
+ Submit
+} from "~/components/Form";
import { useFlags, useUser } from "~/hooks";
+import { usePlanGate } from "~/hooks/usePlanGate";
import type { getEmployeeTypes, getInvitable } from "~/modules/users";
import { createEmployeeValidator } from "~/modules/users";
import type { Result } from "~/types";
@@ -28,6 +36,10 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
const { t } = useLingui();
const { defaults } = useUser();
const { isControlledEnvironment } = useFlags();
+ // Enterprise: choosing an employee type on invite is gated to the Business
+ // plan. When gated (Community / Starter), every invite defaults to the seeded
+ // Admin type — "everyone is an admin".
+ const { isGated: permissionsGated } = usePlanGate({ feature: "PERMISSIONS" });
const navigate = useNavigate();
const formFetcher = useFetcher<Result>();
const employeeTypeFetcher =
@@ -37,11 +49,18 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
employeeTypeFetcher.load(path.to.api.employeeTypes);
});
- const employeeTypeOptions =
- employeeTypeFetcher.data?.data?.map((et) => ({
- value: et.id,
- label: et.name
- })) ?? [];
+ const employeeTypes = employeeTypeFetcher.data?.data ?? [];
+ const employeeTypeOptions = employeeTypes.map((et) => ({
+ value: et.id,
+ label: et.name
+ }));
+
+ // The seeded Admin type is the only type a gated company has; fall back
+ // gracefully if the shape ever changes.
+ const adminType =
+ employeeTypes.find((et) => et.systemType === "Admin") ??
+ employeeTypes.find((et) => et.protected) ??
+ employeeTypes[0];
return (
<Modal
@@ -75,13 +94,17 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
<Input name="firstName" label={t`First Name`} />
<Input name="lastName" label={t`Last Name`} />
</div>
- <Select
- name="employeeType"
- label={t`Employee Type`}
- termId="create-employee-employee-type"
- options={employeeTypeOptions}
- placeholder={t`Select Employee Type`}
- />
+ {permissionsGated ? (
+ <Hidden name="employeeType" value={adminType?.id ?? ""} />
+ ) : (
+ <Select
+ name="employeeType"
+ label={t`Employee Type`}
+ termId="create-employee-employee-type"
+ options={employeeTypeOptions}
+ placeholder={t`Select Employee Type`}
+ />
+ )}
<Location
name="locationId"
label={t`Location`}
@@ -98,7 +121,14 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {
</ModalBody>
<ModalFooter>
<HStack>
- <Submit isLoading={formFetcher.state !== "idle"}>
+ <Submit
+ isLoading={formFetcher.state !== "idle"}
+ // When gated, employeeType is a hidden field populated from the
+ // async-loaded Admin type. Block submit until it resolves, else
+ // an empty employeeType fails validation before the route's
+ // server-side Admin fallback can apply.
+ isDisabled={permissionsGated && !adminType}
+ >
<Trans>Invite</Trans>
</Submit>
</HStack>
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.ee.tsx
similarity index 100%
rename from apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.tsx
rename to apps/erp/app/modules/users/ui/Employees/EmployeePermissionsForm.ee.tsx
diff --git a/apps/erp/app/modules/users/ui/Employees/index.ts b/apps/erp/app/modules/users/ui/Employees/index.ts
index 625fee9ad7..a8b501ae4f 100644
--- a/apps/erp/app/modules/users/ui/Employees/index.ts
+++ b/apps/erp/app/modules/users/ui/Employees/index.ts
@@ -1,6 +1,6 @@
-import BulkEditPermissionsForm from "./BulkEditPermissionsForm";
+import BulkEditPermissionsForm from "./BulkEditPermissionsForm.ee";
import CreateEmployeeModal from "./CreateEmployeeModal";
-import EmployeePermissionsForm from "./EmployeePermissionsForm";
+import EmployeePermissionsForm from "./EmployeePermissionsForm.ee";
import EmployeesTable from "./EmployeesTable";
export {
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 013431aac5..348c58fcb6 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -1,6 +1,5 @@
-import { CONTROLLED_ENVIRONMENT, error, success } from "@carbon/auth";
+import { CONTROLLED_ENVIRONMENT, error } from "@carbon/auth";
import { deleteAuthAccount } from "@carbon/auth/auth.server";
-import { logPermissionChange } from "@carbon/auth/auth-events.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash, requireAuthSession } from "@carbon/auth/session.server";
import {
@@ -8,7 +7,7 @@ import {
deactivateEmployee,
deactivateSupplier
} from "@carbon/auth/users.server";
-import type { Database, Json } from "@carbon/database";
+import type { Database } from "@carbon/database";
import { redis } from "@carbon/kv";
import { now, parseAbsolute } from "@internationalized/date";
@@ -30,18 +29,9 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import { redirect } from "react-router";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
-import type {
- CompanyPermission,
- EmployeeInsert,
- EmployeeTypePermission,
- InviteInsert,
- Module,
- Permission,
- User
-} from "~/modules/users";
+import type { EmployeeInsert, InviteInsert, User } from "~/modules/users";
import { getPermissionsByEmployeeType } from "~/modules/users";
import { getDatabaseClient } from "~/services/database.server";
-import type { Result } from "~/types";
import { path } from "~/utils/path";
import { insertEmployeeJob } from "../people/people.service";
@@ -1178,15 +1168,6 @@ function makePermissionsFromEmployeeType({
return permissions;
}
-function isClaimPermission(key: string, value: unknown) {
- const action = key.split("_")[1];
- return (
- action !== undefined &&
- ["view", "create", "update", "delete"].includes(action) &&
- Array.isArray(value)
- );
-}
-
function makeCustomerPermissions(companyId: string) {
// TODO: this should be more dynamic
const permissions: Record<string, string[]> = {
@@ -1202,189 +1183,6 @@ function makeCustomerPermissions(companyId: string) {
return permissions;
}
-export function makeEmptyPermissionsFromModules(data: Module[]) {
- return data.reduce<
- Record<string, { name: string; permission: CompanyPermission }>
- >((acc, m) => {
- if (m.name && m.name !== "Messaging") {
- acc[m.name] = {
- name: m.name.toLowerCase(),
- permission: {
- view: false,
- create: false,
- update: false,
- delete: false
- }
- };
- }
- return acc;
- }, {});
-}
-
-export function makeCompanyPermissionsFromClaims(
- claims: Json[] | null,
- companyId: string
-) {
- if (typeof claims !== "object" || claims === null) return null;
- let permissions: Record<string, CompanyPermission> = {};
- let role: string | null = null;
-
- Object.entries(claims).forEach(([key, value]) => {
- if (isClaimPermission(key, value)) {
- const [module, action] = key.split("_");
- if (!(module in permissions)) {
- permissions[module] = {
- view: false,
- create: false,
- update: false,
- delete: false
- };
- }
-
- if (!Array.isArray(value)) {
- permissions[module] = {
- view: false,
- create: false,
- update: false,
- delete: false
- };
- } else {
- switch (action) {
- case "view":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["view"] = value.includes(companyId);
- break;
- case "create":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["create"] = value.includes(companyId);
- break;
- case "update":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["update"] = value.includes(companyId);
- break;
- case "delete":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["delete"] = value.includes(companyId);
- break;
- }
- }
- }
- });
-
- if ("role" in claims) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- role = claims["role"] as string;
- }
-
- if ("items" in permissions) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete permissions["items"];
- }
-
- if ("messaging" in permissions) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete permissions["messaging"];
- }
-
- return { permissions, role };
-}
-
-export function makePermissionsFromClaims(claims: Json[] | null) {
- if (typeof claims !== "object" || claims === null) return null;
- let permissions: Record<string, Permission> = {};
- let role: string | null = null;
-
- Object.entries(claims).forEach(([key, value]) => {
- if (isClaimPermission(key, value)) {
- const [module, action] = key.split("_");
- if (!(module in permissions)) {
- permissions[module] = {
- view: [],
- create: [],
- update: [],
- delete: []
- };
- }
-
- switch (action) {
- case "view":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["view"] = value as string[];
- break;
- case "create":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["create"] = value as string[];
- break;
- case "update":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["update"] = value as string[];
- break;
- case "delete":
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- permissions[module]["delete"] = value as string[];
- break;
- }
- }
- });
-
- if ("role" in claims) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- role = claims["role"] as string;
- }
-
- if ("items" in permissions) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete permissions["items"];
- }
-
- if ("messaging" in permissions) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete permissions["messaging"];
- }
-
- return { permissions, role };
-}
-
-export function makeCompanyPermissionsFromEmployeeType(
- data: EmployeeTypePermission[],
- companyId: string
-) {
- const result: Record<
- string,
- { name: string; permission: CompanyPermission }
- > = {};
- if (!data) return result;
- data.forEach((permission) => {
- if (!permission.module) {
- throw new Error(
- `Module is missing for permission ${JSON.stringify(permission)}`
- );
- } else {
- result[permission.module] = {
- name: permission.module.toLowerCase(),
- permission: {
- view: permission.view.includes(companyId),
- create: permission.create.includes(companyId),
- update: permission.update.includes(companyId),
- delete: permission.delete.includes(companyId)
- }
- };
- }
- });
-
- if ("items" in result) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete result["items"];
- }
-
- if ("Messaging" in result) {
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete result["Messaging"];
- }
-
- return result;
-}
-
function makeSupplierPermissions(companyId: string) {
// TODO: this should be more dynamic
const permissions: Record<string, string[]> = {
@@ -1479,205 +1277,3 @@ async function setUserPermissions(
return result;
}
-
-export async function updateEmployee(
- client: SupabaseClient<Database>,
- {
- id,
- employeeType,
- permissions,
- companyId,
- actorId,
- ip
- }: {
- id: string;
- employeeType: string;
- permissions: Record<string, CompanyPermission>;
- companyId: string;
- actorId?: string;
- ip?: string;
- }
-): Promise<Result> {
- const updateEmployeeEmployeeType = await client
- .from("employee")
- .upsert([{ id, companyId, employeeTypeId: employeeType }]);
-
- if (updateEmployeeEmployeeType.error)
- return error(updateEmployeeEmployeeType.error, "Failed to update employee");
-
- return updatePermissions(client, { id, permissions, companyId, actorId, ip });
-}
-
-export async function updatePermissions(
- client: SupabaseClient<Database>,
- {
- id,
- permissions,
- companyId,
- addOnly = false,
- actorId,
- ip
- }: {
- id: string;
- permissions: Record<string, CompanyPermission>;
- companyId: string;
- addOnly?: boolean;
- actorId?: string;
- ip?: string;
- }
-): Promise<Result> {
- if (await client.rpc("is_claims_admin", { company: companyId })) {
- const claims = await getClaims(client, id);
-
- if (claims.error) return error(claims.error, "Failed to get claims");
-
- const updatedPermissions = (
- typeof claims.data !== "object" ||
- Array.isArray(claims.data) ||
- claims.data === null
- ? {}
- : claims.data
- ) as Record<string, string[]>;
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- delete updatedPermissions["role"];
-
- // Snapshot the effective grant set BEFORE the in-place mutation below, so
- // the audit event carries an honest before/after diff (NIST 3.3.1/3.3.2).
- const beforePermissions = structuredClone(updatedPermissions);
-
- // add any missing claims to the current claims
- Object.keys(permissions).forEach((name) => {
- const module = name.toLowerCase();
- if (!(`${module}_view` in updatedPermissions)) {
- updatedPermissions[`${module}_view`] = [];
- }
- if (!(`${module}_create` in updatedPermissions)) {
- updatedPermissions[`${module}_create`] = [];
- }
- if (!(`${module}_update` in updatedPermissions)) {
- updatedPermissions[`${module}_update`] = [];
- }
- if (!(`${module}_delete` in updatedPermissions)) {
- updatedPermissions[`${module}_delete`] = [];
- }
- });
-
- if (addOnly) {
- Object.entries(permissions).forEach(([name, permission]) => {
- const module = name.toLowerCase();
- if (
- permission.view &&
- !updatedPermissions[`${module}_view`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_view`].push(companyId);
- }
- if (
- permission.create &&
- !updatedPermissions[`${module}_create`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_create`].push(companyId);
- }
- if (
- permission.update &&
- !updatedPermissions[`${module}_update`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_update`].push(companyId);
- }
- if (
- permission.delete &&
- !updatedPermissions[`${module}_delete`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_delete`].push(companyId);
- }
- });
- } else {
- Object.entries(permissions).forEach(([name, permission]) => {
- const module = name.toLowerCase();
- if (permission.view) {
- if (!updatedPermissions[`${module}_view`]?.includes(companyId)) {
- updatedPermissions[`${module}_view`] = [
- ...updatedPermissions[`${module}_view`],
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_view`] = (
- updatedPermissions[`${module}_view`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.create) {
- if (!updatedPermissions[`${module}_create`]?.includes(companyId)) {
- updatedPermissions[`${module}_create`] = [
- ...updatedPermissions[`${module}_create`],
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_create`] = (
- updatedPermissions[`${module}_create`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.update) {
- if (!updatedPermissions[`${module}_update`]?.includes(companyId)) {
- updatedPermissions[`${module}_update`] = [
- ...updatedPermissions[`${module}_update`],
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_update`] = (
- updatedPermissions[`${module}_update`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.delete) {
- if (!updatedPermissions[`${module}_delete`]?.includes(companyId)) {
- updatedPermissions[`${module}_delete`] = [
- ...updatedPermissions[`${module}_delete`],
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_delete`] = (
- updatedPermissions[`${module}_delete`] as string[]
- ).filter((c: string) => c !== companyId);
- }
- });
- }
-
- // The "0" global-company wildcard is retired (NIST 800-171 3.1.5). Strip it
- // from every array so it can never be persisted to the authoritative table.
- for (const key of Object.keys(updatedPermissions)) {
- const value = updatedPermissions[key];
- if (Array.isArray(value)) {
- updatedPermissions[key] = value.filter((c: string) => c !== "0");
- }
- }
-
- const permissionsUpdate = await getCarbonServiceRole()
- .from("userPermission")
- .update({ permissions: updatedPermissions })
- .eq("id", id);
- if (permissionsUpdate.error)
- return error(permissionsUpdate.error, "Failed to update claims");
-
- await redis.del(getPermissionCacheKey(id));
-
- // Audit the change (NIST 800-171 3.3.1/3.3.2): actor, target, before/after.
- logPermissionChange({
- actor: actorId,
- targetUserId: id,
- companyId,
- ip,
- before: beforePermissions,
- after: updatedPermissions,
- reason: addOnly ? "add" : "edit"
- });
-
- return success("Permissions updated");
- } else {
- return error(null, "You do not have permission to update permissions");
- }
-}
diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.ts
index b58c8f5a37..76232c2f0e 100644
--- a/apps/erp/app/modules/users/users.service.ts
+++ b/apps/erp/app/modules/users/users.service.ts
@@ -5,9 +5,7 @@ import { datetime } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
-import { capitalize } from "~/utils/string";
-import { sanitize } from "~/utils/supabase";
-import type { CompanyPermission, UserSelectGroupMembers } from "./types";
+import type { UserSelectGroupMembers } from "./types";
const logger = getLogger("erp", "users");
@@ -148,17 +146,6 @@ export async function getItarCertificationReport(
return { data, error: null };
}
-export async function deleteEmployeeType(
- client: SupabaseClient<Database>,
- employeeTypeId: string
-) {
- return client
- .from("employeeType")
- .delete()
- .eq("id", employeeTypeId)
- .eq("protected", false);
-}
-
export async function deleteGroup(
client: SupabaseClient<Database>,
groupId: string
@@ -587,17 +574,6 @@ export async function getUserEmails(
.filter((email): email is string => !!email);
}
-export async function insertEmployeeType(
- client: SupabaseClient<Database>,
- employeeType: { name: string; companyId: string }
-) {
- return client
- .from("employeeType")
- .insert([employeeType])
- .select("id")
- .single();
-}
-
export async function insertGroup(
client: SupabaseClient<Database>,
group: { name: string; companyId: string }
@@ -605,45 +581,6 @@ export async function insertGroup(
return client.from("group").insert(group).select("*").single();
}
-export async function upsertEmployeeType(
- client: SupabaseClient<Database>,
- employeeType:
- | { name: string; companyId: string }
- | { id: string; name: string }
-) {
- if ("id" in employeeType) {
- return client
- .from("employeeType")
- .update(sanitize(employeeType))
- .eq("id", employeeType.id)
- .select("id")
- .single();
- }
- return client
- .from("employeeType")
- .insert([employeeType])
- .select("id")
- .single();
-}
-
-export async function upsertEmployeeTypePermissions(
- client: SupabaseClient<Database>,
- employeeTypeId: string,
- companyId: string,
- permissions: { name: string; permission: CompanyPermission }[]
-) {
- const employeeTypePermissions = permissions.map(({ name, permission }) => ({
- employeeTypeId,
- module: capitalize(name) as "Accounting",
- view: permission.view ? [companyId] : [],
- create: permission.create ? [companyId] : [],
- update: permission.update ? [companyId] : [],
- delete: permission.delete ? [companyId] : []
- }));
-
- return client.from("employeeTypePermission").upsert(employeeTypePermissions);
-}
-
export async function upsertGroup(
client: SupabaseClient<Database>,
{
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index 3ac6be8c3e..0147c3c73b 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -3,6 +3,7 @@ import {
getCarbonServiceRole,
getUserScopedClient
} from "@carbon/auth/client.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { getAppUrl } from "@carbon/env";
import { Ratelimit, redis } from "@carbon/kv";
import { withLogContext } from "@carbon/logger/middleware.server";
@@ -81,6 +82,23 @@ function make429Response(reset: number, remaining: number): Response {
});
}
+// The MCP server is a commercial (Business+) feature. companyHasFeature returns
+// false on the Community edition and, on Cloud, for Starter-plan companies — so
+// this one gate makes the server unavailable to community/starter across BOTH
+// the OAuth-connector and carbon-key auth paths.
+function makeMcpDisabledResponse(): Response {
+ return new Response(
+ JSON.stringify({
+ error:
+ "The MCP server is available on the Business plan. Upgrade to connect an agent to Carbon."
+ }),
+ {
+ status: 402,
+ headers: corsHeaders
+ }
+ );
+}
+
function make401Response(request: Request): Response {
const origin = getAppUrl() || new URL(request.url).origin;
return new Response(null, {
@@ -159,6 +177,14 @@ async function resolveAuth(request: Request): Promise<{
export async function action({ request }: ActionFunctionArgs) {
const { ctx, request: authedRequest } = await resolveAuth(request);
+ // Gate the whole server behind the MCP feature (Business+). One check here
+ // covers every auth path, since both resolve to an McpContext first.
+ if (
+ !(await companyHasFeature(ctx.client, ctx.companyId, { feature: "MCP" }))
+ ) {
+ return addCorsHeaders(makeMcpDisabledResponse());
+ }
+
// Stamp the authenticated identity into the logging context so every log
// line in this request carries it alongside the middleware's requestId.
const response = await withLogContext(
diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
index 43fdc9a7a1..38025f3f26 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
@@ -12,10 +12,6 @@ export const MCP_BLOCKED_TOOL_NAMES: readonly string[] = [
// deletes the caller's tenant. Its "internal users only" gate lives in the
// settings ROUTE, which no API/MCP call passes through.
"settings_deleteSubsidiary",
- // Its first parameter is a service-role (RLS-bypassing) client. Blocking keeps
- // a privileged client off the public API rather than teaching the dispatcher to
- // hand one out.
- "purchasing_getSupplierApprovalContext",
// Internal sweep orchestration invoked by job/operation completion flows.
// Their args require a userId the MCP executor cannot inject (AuthField has
// no such payload field), so direct calls would only ever fail validation.
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index afdaa2f660..dff142b9d4 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1584,
+ "totalTools": 1543,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
@@ -209,7 +209,7 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"fec2a73f85a3","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"a908bc59a2d8","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"07d244c0f017","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -302,7 +302,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"fec2a73f85a3","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"a908bc59a2d8","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
@@ -407,7 +407,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"fec2a73f85a3","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"a908bc59a2d8","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -597,7 +597,7 @@
{"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view","paginates":true},
- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f5d41ef125f5","injectAuth":"companyId","permission":"people:view","paginates":false},
+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"df0f32d1fef7","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},
@@ -643,8 +643,6 @@
{"name":"production_deleteAssemblyInstructionStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteAssemblyInstructionStepTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteAssemblyUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
- {"name":"production_deleteDemandForecasts","classification":"DESTRUCTIVE","paramCount":3,"schema":"078059f848ea","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
- {"name":"production_deleteDemandProjections","classification":"DESTRUCTIVE","paramCount":3,"schema":"078059f848ea","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteFailureMode","classification":"DESTRUCTIVE","paramCount":1,"schema":"4a3e0384d72f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteInspectionDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"e92dda062549","injectAuth":"companyId","permission":"production:delete","paginates":false},
{"name":"production_deleteJob","classification":"DESTRUCTIVE","paramCount":1,"schema":"4999bd4be598","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},
@@ -787,13 +785,13 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"fec2a73f85a3","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"fec2a73f85a3","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"5026536c0eaf","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"fec2a73f85a3","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"9228829e193c","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"a908bc59a2d8","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
@@ -844,8 +842,6 @@
{"name":"production_upsertAssemblyInstructionStepSlide","classification":"WRITE","paramCount":9,"schema":"c6bc69cc2080","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
{"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","paramCount":5,"schema":"d64500fd5c94","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
{"name":"production_upsertAssemblyUnit","classification":"WRITE","paramCount":5,"schema":"74497d782594","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
- {"name":"production_upsertDemandForecasts","classification":"DESTRUCTIVE","paramCount":1,"schema":"52be92b5f4a5","response":"57a0b3d217fb","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
- {"name":"production_upsertDemandProjections","classification":"DESTRUCTIVE","paramCount":1,"schema":"52be92b5f4a5","response":"57a0b3d217fb","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
{"name":"production_upsertFailureMode","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
{"name":"production_upsertInspectionDocument","classification":"WRITE","paramCount":10,"schema":"68e08a92df7a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
{"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"73f73c34c970","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},
@@ -1402,11 +1398,8 @@
{"name":"sales_upsertSalesReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"f4a19f25c389","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesRFQ","classification":"WRITE","paramCount":15,"schema":"3875863b88c1","response":"2e56e1180d37","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesRFQLine","classification":"WRITE","paramCount":11,"schema":"24400721553b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
- {"name":"settings_deactivateWebhooks","classification":"WRITE","paramCount":0,"schema":"efddc7bd8bbc","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
- {"name":"settings_deleteApiKey","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:update","paginates":false},
{"name":"settings_deleteDocumentSection","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},
{"name":"settings_deleteItemSerialSequence","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},
- {"name":"settings_deleteWebhook","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},
{"name":"settings_getAccountsPayableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getAccountsReceivableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getApiKeys","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"eec810be5b96","injectAuth":"companyId","permission":"users:update","paginates":true},
@@ -1460,7 +1453,6 @@
{"name":"settings_updateCompany","classification":"WRITE","paramCount":17,"schema":"51b47fb4a6bd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateCompanyPlan","classification":"WRITE","paramCount":4,"schema":"dc5417676df7","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateCompanyWithBaseCurrencyChange","classification":"DESTRUCTIVE","paramCount":17,"schema":"51b47fb4a6bd","response":"none","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
- {"name":"settings_updateConsoleSetting","classification":"WRITE","paramCount":1,"schema":"2607ea1770b9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateDefaultCustomerCc","classification":"WRITE","paramCount":1,"schema":"69d7696df422","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateDefaultSupplierCc","classification":"WRITE","paramCount":1,"schema":"862b3d182ce1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateDigitalQuoteSetting","classification":"WRITE","paramCount":3,"schema":"01dcd07bf6d9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
@@ -1480,7 +1472,6 @@
{"name":"settings_updateProductLabelSize","classification":"WRITE","paramCount":1,"schema":"26bfb6ebfdda","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
- {"name":"settings_updateRequireMfaSetting","classification":"WRITE","paramCount":1,"schema":"1a5429a80ff2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateRfqReadySetting","classification":"WRITE","paramCount":1,"schema":"8828dbf1724d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateSalesRuleNotificationSetting","classification":"WRITE","paramCount":1,"schema":"fcb0888da832","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
@@ -1493,31 +1484,11 @@
{"name":"settings_updateSuggestionNotificationSetting","classification":"WRITE","paramCount":1,"schema":"ac461e36d464","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateSupplierQuoteNotificationSetting","classification":"WRITE","paramCount":1,"schema":"56a6d061d358","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
{"name":"settings_updateTimeCardSetting","classification":"WRITE","paramCount":1,"schema":"9389085b800b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},
- {"name":"settings_upsertApiKey","classification":"WRITE","paramCount":7,"schema":"81421c92f0dd","response":"5eaddbfb67de","injectAuth":"companyId+createdBy+updatedBy","permission":"users:update","paginates":false},
{"name":"settings_upsertDocumentSection","classification":"WRITE","paramCount":5,"schema":"b894407ce0d0","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},
{"name":"settings_upsertDocumentTemplate","classification":"WRITE","paramCount":6,"schema":"5d28da0e0ad6","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},
{"name":"settings_upsertItemSerialSequence","classification":"WRITE","paramCount":7,"schema":"95750d9ab5ae","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},
- {"name":"settings_upsertWebhook","classification":"WRITE","paramCount":10,"schema":"79ad29732124","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},
- {"name":"shared_approveRequest","classification":"WRITE","paramCount":2,"schema":"db4abb0e3532","response":"ce9d372b6b54","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},
- {"name":"shared_canApproveRequest","classification":"WRITE","paramCount":1,"schema":"47fa7730c828","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_canApproveRequestInWindow","classification":"WRITE","paramCount":1,"schema":"47fa7730c828","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_canCancelRequest","classification":"WRITE","paramCount":1,"schema":"4bf65a3268ec","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_cancelApprovalRequest","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_canViewApprovalRequest","classification":"WRITE","paramCount":1,"schema":"e198b4bc9fd3","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_createApprovalRequest","classification":"WRITE","paramCount":1,"schema":"e6294fee6965","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
- {"name":"shared_deleteApprovalRule","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_deleteCustomerPortal","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_deleteEnforcementRule","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa9ceafd871f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","paramCount":1,"schema":"1fbe3d41dab0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_generateEmbedding","classification":"WRITE","paramCount":1,"schema":"e3dce8d1afb8","response":"569f4d6b0385","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
- {"name":"shared_getApprovalById","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4ed114babb27","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalRequestsByDocument","classification":"READ","paramCount":2,"schema":"943dca4ef0da","response":"9b323eaa3f11","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalRuleByAmount","classification":"READ","paramCount":2,"schema":"0f2be7dc3ef9","response":"294486cea4b0","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalRuleById","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"294486cea4b0","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalRules","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"247632dde180","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalRulesForApprover","classification":"READ","paramCount":1,"schema":"38ad7ed76197","response":"247632dde180","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApprovalsForUser","classification":"READ","paramCount":2,"schema":"48cdb7c44686","response":"8a720d482238","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getApproverUserIdsForRule","classification":"READ","paramCount":1,"schema":"46007bdc770d","response":"681004346c78","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getBase64ImageFromSupabase","classification":"READ","paramCount":1,"schema":"923b083c9bca","response":"174e29b899b9","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getCountries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0e8a11b4e81c","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getCustomerPortal","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"none","paginates":false},
@@ -1526,33 +1497,24 @@
{"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","paramCount":1,"schema":"47af2b550d52","response":"ab5d5774b961","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getEnforcementRules","classification":"READ","paramCount":2,"schema":"fa46224dbc18","response":"a58a59f02a18","injectAuth":"companyId","permission":"none","paginates":true},
{"name":"shared_getExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0f7860db4299","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getLatestApprovalRequestForDocument","classification":"READ","paramCount":2,"schema":"943dca4ef0da","response":"a46647e8d6f1","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getLowerTierApproverUserIds","classification":"READ","paramCount":2,"schema":"63a69fed1f5d","response":"681004346c78","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getModelByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"none","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getNotes","classification":"READ","paramCount":1,"schema":"e7617eb689c8","response":"1a052a4417b5","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_getPendingApprovalsForApprover","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8a720d482238","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getPeriods","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"ab7e6c36be29","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getSavedViews","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"be2b0aada3eb","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getTagsList","classification":"READ","paramCount":1,"schema":"43c92414cb2f","response":"b837740e18f4","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_getTimezoneNames","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"93968ed2dcdb","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_hasPendingApproval","classification":"READ","paramCount":2,"schema":"943dca4ef0da","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_importCsv","classification":"WRITE","paramCount":4,"schema":"8f2d77f74ffb","response":"none","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_insertNote","classification":"WRITE","paramCount":2,"schema":"260839f76e18","response":"c2fb0e5225f8","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
{"name":"shared_insertTag","classification":"WRITE","paramCount":1,"schema":"11926edb131b","response":"27f67ae1958c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
- {"name":"shared_isApprovalRequired","classification":"READ","paramCount":2,"schema":"0f2be7dc3ef9","response":"7cb541e84f22","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_lookupBuyPriceFromMap","classification":"WRITE","paramCount":4,"schema":"4360b71230e3","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_lookupPriceFromBreaks","classification":"WRITE","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},
- {"name":"shared_rejectRequest","classification":"WRITE","paramCount":2,"schema":"db4abb0e3532","response":"ce9d372b6b54","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},
{"name":"shared_resolveBuyUnitCost","classification":"WRITE","paramCount":3,"schema":"4c58915f44dd","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_resolveSupplierPrice","classification":"WRITE","paramCount":4,"schema":"c92834c91ef5","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},
{"name":"shared_updateModelThumbnail","classification":"WRITE","paramCount":2,"schema":"7d1e1e5f7144","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},
{"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},
- {"name":"shared_upsertApprovalRule","classification":"WRITE","paramCount":1,"schema":"833ecfb8d78b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
- {"name":"shared_upsertEnforcementRule","classification":"WRITE","paramCount":2,"schema":"ec92de61cff6","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
{"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
{"name":"shared_upsertModelUpload","classification":"WRITE","paramCount":1,"schema":"b024a13e3afd","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
{"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},
- {"name":"users_deleteEmployeeType","classification":"DESTRUCTIVE","paramCount":1,"schema":"dba2936b2a4e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:delete","paginates":false},
{"name":"users_deleteGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"c4dcdfdf8647","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:delete","paginates":false},
{"name":"users_getCompaniesForUser","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},
{"name":"users_getConsoleOperators","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"42c3353a5284","injectAuth":"companyId","permission":"users:view","paginates":true},
@@ -1578,12 +1540,9 @@
{"name":"users_getUserSelectGroupMembers","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"b754519017cb","injectAuth":"companyId","permission":"users:view","paginates":false},
{"name":"users_getUserSelectGroups","classification":"READ","paramCount":4,"schema":"b459d00208b5","response":"51b54791b40a","injectAuth":"companyId","permission":"users:view","paginates":false},
{"name":"users_getUsersWithVerifiedMfa","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"4c1fdc714231","injectAuth":"companyId","permission":"users:view","paginates":false},
- {"name":"users_insertEmployeeType","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create","paginates":false},
{"name":"users_insertGroup","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"06c8b45796ca","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create","paginates":false},
{"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"62ac845cad71","injectAuth":"companyId","permission":"users:update","paginates":false},
{"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"80d2a04ba04a","injectAuth":"companyId","permission":"users:view","paginates":false},
- {"name":"users_upsertEmployeeType","classification":"WRITE","paramCount":1,"schema":"720ecfa5a78e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false},
- {"name":"users_upsertEmployeeTypePermissions","classification":"WRITE","paramCount":2,"schema":"f8547c82c3d3","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false},
{"name":"users_upsertGroup","classification":"WRITE","paramCount":2,"schema":"f06d2d858884","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false},
{"name":"users_upsertGroupMembers","classification":"DESTRUCTIVE","paramCount":2,"schema":"b32a69080685","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"users:create+update","paginates":false}
]
diff --git a/apps/erp/app/routes/api+/settings.backup-archive.$file.ts b/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
index a12cd9cf54..0374125fb0 100644
--- a/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
+++ b/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "react-router";
import { pack as tarPack } from "tar-stream";
-import { canAccessBackups } from "~/utils/backups";
+import { canManageBackups } from "~/modules/settings/backups.server";
/** List every object under a storage prefix, returning paths relative to it. */
async function listRelative(
@@ -44,7 +44,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
view: "settings"
});
- if (!canAccessBackups(email))
+ if (!(await canManageBackups(client, companyId, email)))
throw new Response("Not found", { status: 404 });
const name = params.file ?? "";
diff --git a/apps/erp/app/routes/api+/settings.backup-export-status.ts b/apps/erp/app/routes/api+/settings.backup-export-status.ts
index 045fcfd949..9468d81049 100644
--- a/apps/erp/app/routes/api+/settings.backup-export-status.ts
+++ b/apps/erp/app/routes/api+/settings.backup-export-status.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "react-router";
import { getCompanyExportRun } from "~/modules/settings";
-import { canAccessBackups } from "~/utils/backups";
+import { canManageBackups } from "~/modules/settings/backups.server";
// Polled by the export progress modal (and the in-progress list row) for live
// phase/done/total. One marker per company: the export job writes it while
@@ -12,7 +12,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
update: "settings"
});
- if (!canAccessBackups(email))
+ if (!(await canManageBackups(client, companyId, email)))
throw new Response("Not found", { status: 404 });
const run = await getCompanyExportRun(client, companyId);
diff --git a/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
index 6dc7706f26..39109ab2a6 100644
--- a/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
+++ b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "react-router";
import { getCompanyRestoreRuns } from "~/modules/settings";
-import { canAccessBackups } from "~/utils/backups";
+import { canManageBackups } from "~/modules/settings/backups.server";
// Polled by the restore progress modal. A restore run is "running" until its
// marker row appears (the job writes it once the wipe+load commits), then
@@ -11,7 +11,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
update: "settings"
});
- if (!canAccessBackups(email))
+ if (!(await canManageBackups(client, companyId, email)))
throw new Response("Not found", { status: 404 });
const restoreRunId = params.restoreRunId;
diff --git a/apps/erp/app/routes/api+/settings.backup-summary.ts b/apps/erp/app/routes/api+/settings.backup-summary.ts
index c79f0b64a7..295173f583 100644
--- a/apps/erp/app/routes/api+/settings.backup-summary.ts
+++ b/apps/erp/app/routes/api+/settings.backup-summary.ts
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "react-router";
import { BACKUP_SUMMARY_GROUPS } from "~/modules/settings/backups.areas";
-import { canAccessBackups } from "~/utils/backups";
+import { canManageBackups } from "~/modules/settings/backups.server";
async function countEntity(
client: SupabaseClient,
@@ -29,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
request,
{ view: "settings" }
);
- if (!canAccessBackups(email))
+ if (!(await canManageBackups(client, companyId, email)))
throw new Response("Not found", { status: 404 });
// Keys and counts only — the popover owns the labels (msg descriptors it
diff --git a/apps/erp/app/routes/api+/settings.backup-upload.ts b/apps/erp/app/routes/api+/settings.backup-upload.ts
index fbf0d380cb..b702f25d8f 100644
--- a/apps/erp/app/routes/api+/settings.backup-upload.ts
+++ b/apps/erp/app/routes/api+/settings.backup-upload.ts
@@ -1,8 +1,8 @@
import { Readable } from "node:stream";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { ActionFunctionArgs } from "react-router";
+import { canManageBackups } from "~/modules/settings/backups.server";
import { unpackBackupArchive } from "~/modules/settings/backups-archive.server";
-import { canAccessBackups } from "~/utils/backups";
/**
* Unpack an uploaded `.carbon.tar.gz` (a whole backup folder) into a fresh
@@ -17,7 +17,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
update: "settings"
});
- if (!canAccessBackups(email))
+ if (!(await canManageBackups(client, companyId, email)))
throw new Response("Not found", { status: 404 });
if (request.method !== "POST" || !request.body) {
throw new Response("Expected a tar.gz body", { status: 400 });
diff --git a/apps/erp/app/routes/api+/users.empty-permissions.ts b/apps/erp/app/routes/api+/users.empty-permissions.ts
index dcdb0e8760..3c3de615b4 100644
--- a/apps/erp/app/routes/api+/users.empty-permissions.ts
+++ b/apps/erp/app/routes/api+/users.empty-permissions.ts
@@ -1,17 +1,27 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { makeEmptyPermissionsFromModules } from "@carbon/ee/permissions.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
import { getModules } from "~/modules/users";
-import { makeEmptyPermissionsFromModules } from "~/modules/users/users.server";
+import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const modules = await getModules(client);
if (modules.error || modules.data === null) {
return data(
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index ee60fbece6..1ece46e6ce 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -1,5 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { companyHasPlan } from "@carbon/ee/plan.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { getContentType, MEDIA_CONTENT_TYPES } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { Ratelimit, redis } from "@carbon/kv";
@@ -42,9 +42,13 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {
throw new Error("Customer not found");
}
- const hasPlan = await companyHasPlan(serviceRole, customer.data.companyId, {
- feature: "CUSTOMER_PORTALS"
- });
+ const hasPlan = await companyHasFeature(
+ serviceRole,
+ customer.data.companyId,
+ {
+ feature: "CUSTOMER_PORTALS"
+ }
+ );
if (!hasPlan) {
return new Response(null, { status: 403 });
}
diff --git a/apps/erp/app/routes/share+/customer.$id.tsx b/apps/erp/app/routes/share+/customer.$id.tsx
index 5e035ea921..dbb70a9cb3 100644
--- a/apps/erp/app/routes/share+/customer.$id.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.tsx
@@ -1,5 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { companyHasPlan } from "@carbon/ee/plan.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { getLogger } from "@carbon/logger";
import { Avatar } from "@carbon/react";
import { SCALE_FORMAT } from "@carbon/utils";
@@ -65,9 +65,13 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
throw new Error("Customer not found");
}
- const hasPlan = await companyHasPlan(serviceRole, customer.data.companyId, {
- feature: "CUSTOMER_PORTALS"
- });
+ const hasPlan = await companyHasFeature(
+ serviceRole,
+ customer.data.companyId,
+ {
+ feature: "CUSTOMER_PORTALS"
+ }
+ );
if (!hasPlan) {
throw new Response("Not found", { status: 404 });
}
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index 26fb7578d2..774b506a37 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -348,9 +348,14 @@ function OnboardAgentWidget({ dismissed: initial }: { dismissed: boolean }) {
<button
type="button"
onClick={handleCopy}
- className="flex items-center gap-3 h-9 pl-4 pr-4 rounded-full border border-border bg-muted/30 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors active:scale-[0.98]"
+ className="flex items-center gap-3 h-9 pl-4 pr-4 max-w-full rounded-full border border-border bg-muted/30 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors active:scale-[0.98]"
>
- <Trans>Onboard your agent to Carbon</Trans>
+ {/* min-w-0 + overflow-hidden lets the label clip instead of
+ wrapping to a second line on narrow screens — the icons keep
+ their width and the text runs out of sight behind them. */}
+ <span className="min-w-0 overflow-hidden whitespace-nowrap">
+ <Trans>Onboard your agent to Carbon</Trans>
+ </span>
<span className="flex items-center gap-2 text-foreground">
{AGENT_TOOL_ICONS.map(({ Icon, className }, i) => (
<Icon key={i} className={cn("shrink-0", className)} />
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index dfee79ea15..20596696b1 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -17,6 +17,7 @@ import {
updateCompanySession
} from "@carbon/auth/session.server";
import { isAuditLogEnabled } from "@carbon/database/audit";
+import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { getPlan } from "@carbon/ee/plan.server";
import {
detectImplementationSignals,
@@ -73,10 +74,7 @@ import {
getEmployeeCompanies
} from "~/modules/settings";
import { getCustomFieldsSchemas } from "~/modules/shared/shared.server";
-import {
- getSavedViews,
- isApprovalRequired
-} from "~/modules/shared/shared.service";
+import { getSavedViews } from "~/modules/shared/shared.service";
import { getItarCertificationStatus } from "~/modules/users";
import {
getModulePreferences,
diff --git a/apps/erp/app/routes/x+/account+/notifications.tsx b/apps/erp/app/routes/x+/account+/notifications.tsx
index 51e57c2323..f02e8490a9 100644
--- a/apps/erp/app/routes/x+/account+/notifications.tsx
+++ b/apps/erp/app/routes/x+/account+/notifications.tsx
@@ -2,7 +2,7 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { companyHasPlan } from "@carbon/ee/plan.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import {
NotificationTopic,
@@ -46,7 +46,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
.eq("companyId", companyId)
.eq("id", "slack")
.maybeSingle(),
- companyHasPlan(client, companyId, { feature: "EMAIL_NOTIFICATIONS" })
+ companyHasFeature(client, companyId, { feature: "EMAIL_NOTIFICATIONS" })
]);
return {
diff --git a/apps/erp/app/routes/x+/accounting+/cost-centers.tsx b/apps/erp/app/routes/x+/accounting+/cost-centers.tsx
index 858e70f179..3c832db940 100644
--- a/apps/erp/app/routes/x+/accounting+/cost-centers.tsx
+++ b/apps/erp/app/routes/x+/accounting+/cost-centers.tsx
@@ -1,6 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { getApprovalRulesForApprover } from "@carbon/ee/approvals.server";
import {
Heading,
HStack,
@@ -19,7 +20,6 @@ import {
CostCentersListView,
CostCentersTreeView
} from "~/modules/accounting/ui/CostCenters";
-import { getApprovalRulesForApprover } from "~/modules/shared";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
index 6a7ac84994..8092405b4a 100644
--- a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.delete.tsx
@@ -1,11 +1,12 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { deleteEnforcementRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteEnforcementRule, getEnforcementRule } from "~/modules/shared";
+import { getEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -30,7 +31,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "inventory"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
index 99c3d554c0..8991890af8 100644
--- a/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.$id.tsx
@@ -1,14 +1,15 @@
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertEnforcementRule } from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
import type { ConditionAst } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import { storageRuleValidator } from "~/modules/inventory";
import StorageRuleForm from "~/modules/inventory/ui/StorageRules/StorageRuleForm";
-import { getEnforcementRule, upsertEnforcementRule } from "~/modules/shared";
+import { getEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -28,7 +29,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "inventory"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
index 0c7830c3dd..170602b45c 100644
--- a/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.new.tsx
@@ -1,14 +1,14 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertEnforcementRule } from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
import type { TargetType } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import { storageRuleValidator } from "~/modules/inventory";
import StorageRuleForm from "~/modules/inventory/ui/StorageRules/StorageRuleForm";
-import { upsertEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
const isTargetType = (value: string | null): value is TargetType =>
@@ -27,7 +27,7 @@ export async function action({ request }: ActionFunctionArgs) {
create: "inventory"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
index 1959683de3..d952e0aa3e 100644
--- a/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/rules.assign.$itemId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { assignStorageRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { assignStorageRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
create: "parts"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx b/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx
index 7beb49cccd..0a814e7553 100644
--- a/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx
+++ b/apps/erp/app/routes/x+/items+/rules.unassign.$itemId.$ruleId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { unassignStorageRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { unassignStorageRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "parts"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -27,7 +27,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const result = await unassignStorageRule(client, {
targetType: "item",
targetId: itemId,
- ruleId
+ ruleId,
+ companyId
});
if (result.error) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx
index f9915bc2fd..467d27dc00 100644
--- a/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx
@@ -1,16 +1,14 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertDemandProjections } from "@carbon/ee/forecast.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import { demandProjectionValidator } from "~/modules/production/production.models";
-import {
- getDemandProjections,
- upsertDemandProjections
-} from "~/modules/production/production.service";
+import { getDemandProjections } from "~/modules/production/production.service";
import DemandProjectionsForm from "~/modules/production/ui/DemandProjection/DemandProjectionForm";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
@@ -71,7 +69,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "production"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/production+/demand-forecasts.delete.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/demand-forecasts.delete.$itemId.$locationId.tsx
index 1f2b037306..8be9058842 100644
--- a/apps/erp/app/routes/x+/production+/demand-forecasts.delete.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.delete.$itemId.$locationId.tsx
@@ -1,11 +1,11 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { deleteDemandProjections } from "@carbon/ee/forecast.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
-import { deleteDemandProjections } from "~/modules/production/production.service";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
@@ -16,7 +16,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "production"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/production+/demand-forecasts.new.tsx b/apps/erp/app/routes/x+/production+/demand-forecasts.new.tsx
index 543e23f277..737d397715 100644
--- a/apps/erp/app/routes/x+/production+/demand-forecasts.new.tsx
+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.new.tsx
@@ -1,14 +1,14 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertDemandProjections } from "@carbon/ee/forecast.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useNavigate } from "react-router";
import { demandProjectionValidator } from "~/modules/production/production.models";
-import { upsertDemandProjections } from "~/modules/production/production.service";
import DemandProjectionForm from "~/modules/production/ui/DemandProjection/DemandProjectionForm";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
@@ -37,7 +37,7 @@ export async function action({ request }: ActionFunctionArgs) {
create: "production"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
index 94634cf9e5..0be5d0751f 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
@@ -2,15 +2,15 @@ import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { getLogger } from "@carbon/logger";
-import type { ActionFunctionArgs } from "react-router";
-import { redirect } from "react-router";
-import { deletePurchaseOrder, getPurchaseOrder } from "~/modules/purchasing";
import {
canApproveRequest,
canCancelRequest,
getLatestApprovalRequestForDocument
-} from "~/modules/shared";
+} from "@carbon/ee/approvals.server";
+import { getLogger } from "@carbon/logger";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { deletePurchaseOrder, getPurchaseOrder } from "~/modules/purchasing";
import { path } from "~/utils/path";
const logger = getLogger("erp", "orderid-delete");
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index 576a4a257b..b773b20438 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -4,6 +4,13 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { PurchaseOrderEmail } from "@carbon/documents/email";
import { getPurchaseOrderDisplayId } from "@carbon/documents/pdf";
+import {
+ createApprovalRequest,
+ getApprovalRuleByAmount,
+ getApproverUserIdsForRule,
+ hasPendingApproval,
+ isApprovalRequired
+} from "@carbon/ee/approvals.server";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -29,13 +36,6 @@ import {
updatePurchaseOrderStatus
} from "~/modules/purchasing";
import { getCompany, getCompanySettings } from "~/modules/settings";
-import {
- createApprovalRequest,
- getApprovalRuleByAmount,
- getApproverUserIdsForRule,
- hasPendingApproval,
- isApprovalRequired
-} from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$orderId[.]pdf";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
index c71a229ddf..cc8771c052 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { canApproveRequest } from "@carbon/ee/approvals.server";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -13,7 +14,6 @@ import {
reopenPurchaseOrderAsRevision,
updatePurchaseOrderStatus
} from "~/modules/purchasing";
-import { canApproveRequest } from "~/modules/shared";
import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 0b7f472a7e..829ba9b349 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -4,6 +4,14 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { PurchaseOrderEmail } from "@carbon/documents/email";
import { getPurchaseOrderDisplayId } from "@carbon/documents/pdf";
+import {
+ approveRequest,
+ canApproveRequest,
+ canCancelRequest,
+ getLatestApprovalRequestForDocument,
+ getLowerTierApproverUserIds,
+ rejectRequest
+} from "@carbon/ee/approvals.server";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -35,14 +43,6 @@ import {
PurchaseOrderProperties
} from "~/modules/purchasing/ui/PurchaseOrder";
import { getCompany, getCompanySettings } from "~/modules/settings";
-import {
- approveRequest,
- canApproveRequest,
- canCancelRequest,
- getLatestApprovalRequestForDocument,
- getLowerTierApproverUserIds,
- rejectRequest
-} from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$orderId[.]pdf";
import { getDatabaseClient } from "~/services/database.server";
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index 2be280efc3..a5626a6034 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -1,5 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { ApprovalRequest } from "@carbon/ee/approvals";
+import { getPendingApprovalsForApprover } from "@carbon/ee/approvals.server";
import {
Badge,
Button,
@@ -75,10 +77,6 @@ import { KPIs } from "~/modules/purchasing/purchasing.models";
import { PurchasingStatus } from "~/modules/purchasing/ui/PurchaseOrder";
import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
import { SupplierQuoteStatus } from "~/modules/purchasing/ui/SupplierQuote";
-import {
- type ApprovalRequest,
- getPendingApprovalsForApprover
-} from "~/modules/shared";
import type { loader as kpiLoader } from "~/routes/api+/purchasing.kpi.$key";
import { useSuppliers } from "~/stores/suppliers";
diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsx
index 884a79d2b2..54345634ee 100644
--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx
@@ -3,6 +3,14 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
+import {
+ approveRequest,
+ canApproveRequest,
+ canCancelRequest,
+ getLatestApprovalRequestForDocument,
+ isApprovalRequired,
+ rejectRequest
+} from "@carbon/ee/approvals.server";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -20,15 +28,7 @@ import {
import QualityDocumentEditor from "~/modules/quality/ui/Documents/QualityDocumentEditor";
import QualityDocumentHeader from "~/modules/quality/ui/Documents/QualityDocumentHeader";
import QualityDocumentProperties from "~/modules/quality/ui/Documents/QualityDocumentProperties";
-import {
- approveRequest,
- canApproveRequest,
- canCancelRequest,
- getLatestApprovalRequestForDocument,
- getTagsList,
- isApprovalRequired,
- rejectRequest
-} from "~/modules/shared";
+import { getTagsList } from "~/modules/shared";
import { getDatabaseClient } from "~/services/database.server";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsx
index db1854c566..0a5d8955a3 100644
--- a/apps/erp/app/routes/x+/quality-document+/update.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx
@@ -1,12 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
-import { trigger } from "@carbon/jobs";
-import { getLogger } from "@carbon/logger";
-import { NotificationEvent } from "@carbon/notifications";
-import type { SupabaseClient } from "@supabase/supabase-js";
-import type { ActionFunctionArgs } from "react-router";
-import { qualityDocumentStatus } from "~/modules/quality/quality.models";
import {
canApproveRequest,
createApprovalRequest,
@@ -15,7 +9,13 @@ import {
getLatestApprovalRequestForDocument,
hasPendingApproval,
isApprovalRequired
-} from "~/modules/shared";
+} from "@carbon/ee/approvals.server";
+import { trigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
+import { NotificationEvent } from "@carbon/notifications";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { ActionFunctionArgs } from "react-router";
+import { qualityDocumentStatus } from "~/modules/quality/quality.models";
const logger = getLogger("erp", "update");
diff --git a/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx b/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx
index b78b0b6b6b..602bb5dd1f 100644
--- a/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx
+++ b/apps/erp/app/routes/x+/resources+/work-centers.rules.assign.$workCenterId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { assignStorageRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { assignStorageRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
create: "resources"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx b/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx
index 2f0989c2d9..3b04e835a1 100644
--- a/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx
+++ b/apps/erp/app/routes/x+/resources+/work-centers.rules.unassign.$workCenterId.$ruleId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { unassignStorageRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { unassignStorageRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "resources"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -28,7 +28,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const result = await unassignStorageRule(client, {
targetType: "workCenter",
targetId: workCenterId,
- ruleId
+ ruleId,
+ companyId
});
if (result.error) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.$id.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.$id.tsx
index 7fb6b52327..2f5a950677 100644
--- a/apps/erp/app/routes/x+/sales+/customer-portals.$id.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-portals.$id.tsx
@@ -1,13 +1,14 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertCustomerPortal } from "@carbon/ee/customer-portals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import { customerPortalValidator } from "~/modules/sales";
-import CustomerPortalForm from "~/modules/sales/ui/CustomerPortals/CustomerPortalForm";
-import { getCustomerPortal, upsertExternalLink } from "~/modules/shared";
+import CustomerPortalForm from "~/modules/sales/ui/CustomerPortals/CustomerPortalForm.ee";
+import { getCustomerPortal } from "~/modules/shared";
import { path } from "~/utils/path";
@@ -43,7 +44,7 @@ export async function action({ request }: ActionFunctionArgs) {
update: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -63,7 +64,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { id, customerId } = validation.data;
if (!id) throw new Error("id not found");
- const updateCustomerPortal = await upsertExternalLink(client, {
+ const updateCustomerPortal = await upsertCustomerPortal(client, companyId, {
id,
documentType: "Customer",
documentId: customerId,
diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx
index a89bfe05c0..a7b2e9add3 100644
--- a/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx
@@ -1,12 +1,13 @@
import { error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { deleteCustomerPortal } from "@carbon/ee/customer-portals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { useLingui } from "@lingui/react/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteCustomerPortal, getCustomerPortal } from "~/modules/shared";
+import { getCustomerPortal } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -36,7 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -54,7 +55,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { error: deleteCustomerPortalError } = await deleteCustomerPortal(
client,
- id
+ id,
+ companyId
);
if (deleteCustomerPortalError) {
const errorMessage =
diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.new.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.new.tsx
index 9cf58c8385..6f1f4a05cb 100644
--- a/apps/erp/app/routes/x+/sales+/customer-portals.new.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-portals.new.tsx
@@ -1,13 +1,13 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertCustomerPortal } from "@carbon/ee/customer-portals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useNavigate } from "react-router";
import { customerPortalValidator } from "~/modules/sales";
-import CustomerPortalForm from "~/modules/sales/ui/CustomerPortals/CustomerPortalForm";
-import { upsertExternalLink } from "~/modules/shared";
+import CustomerPortalForm from "~/modules/sales/ui/CustomerPortals/CustomerPortalForm.ee";
import { getParams, path, requestReferrer } from "~/utils/path";
@@ -25,7 +25,7 @@ export async function action({ request }: ActionFunctionArgs) {
create: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -46,11 +46,10 @@ export async function action({ request }: ActionFunctionArgs) {
const { customerId } = validation.data;
- const insertCustomerPortal = await upsertExternalLink(client, {
+ const insertCustomerPortal = await upsertCustomerPortal(client, companyId, {
documentType: "Customer",
documentId: customerId,
- customerId,
- companyId
+ customerId
});
if (insertCustomerPortal.error) {
diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx
index 7fef845cae..8548120c04 100644
--- a/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx
+++ b/apps/erp/app/routes/x+/sales+/sales-rules.$id.delete.tsx
@@ -1,11 +1,12 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { deleteEnforcementRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteEnforcementRule, getEnforcementRule } from "~/modules/shared";
+import { getEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -30,7 +31,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx
index 301149c43b..26434f1921 100644
--- a/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/sales+/sales-rules.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertEnforcementRule } from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
import type { SalesRuleSurface } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -9,7 +10,7 @@ import { data, redirect, useLoaderData, useNavigate } from "react-router";
import type { z } from "zod";
import { type salesRuleSeverities, salesRuleValidator } from "~/modules/sales";
import { SalesRuleForm } from "~/modules/sales/ui/SalesRules";
-import { getEnforcementRule, upsertEnforcementRule } from "~/modules/shared";
+import { getEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -29,7 +30,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx
index 3786fa0844..81efec208c 100644
--- a/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx
+++ b/apps/erp/app/routes/x+/sales+/sales-rules.assign.$itemId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { assignSalesRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { assignSalesRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx
index 25cdeb9fe0..30dc4cbefa 100644
--- a/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx
+++ b/apps/erp/app/routes/x+/sales+/sales-rules.new.tsx
@@ -1,13 +1,13 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertEnforcementRule } from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useNavigate } from "react-router";
import { salesRuleValidator } from "~/modules/sales";
import { SalesRuleForm } from "~/modules/sales/ui/SalesRules";
-import { upsertEnforcementRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -21,7 +21,7 @@ export async function action({ request }: ActionFunctionArgs) {
create: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx
index 4aa2707aad..d9bf1bcf36 100644
--- a/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx
+++ b/apps/erp/app/routes/x+/sales+/sales-rules.unassign.$itemId.$ruleId.tsx
@@ -1,8 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
-import { unassignSalesRule } from "@carbon/ee/rules";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { unassignSalesRule } from "@carbon/ee/rules.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -13,7 +13,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "sales"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/accounting.tsx b/apps/erp/app/routes/x+/settings+/accounting.tsx
index faf8eb3f01..d0a237b3c9 100644
--- a/apps/erp/app/routes/x+/settings+/accounting.tsx
+++ b/apps/erp/app/routes/x+/settings+/accounting.tsx
@@ -30,7 +30,6 @@ import {
Number as NumberInput,
Submit
} from "~/components/Form";
-import SettingsSectionHeader from "~/components/SettingsSectionHeader";
import { useFlags } from "~/hooks";
import { getDefaultAccounts } from "~/modules/accounting";
import {
@@ -238,10 +237,6 @@ export default function AccountingSettingsRoute() {
<Trans>Accounting</Trans>
</Heading>
- <SettingsSectionHeader>
- <Trans>Ledger</Trans>
- </SettingsSectionHeader>
-
<Card>
<CardHeader>
<CardTitle>
@@ -292,10 +287,6 @@ export default function AccountingSettingsRoute() {
</CardContent>
</Card>
- <SettingsSectionHeader>
- <Trans>Currency</Trans>
- </SettingsSectionHeader>
-
<Card>
<CardHeader>
<HStack className="justify-between items-center">
@@ -321,10 +312,6 @@ export default function AccountingSettingsRoute() {
</CardHeader>
</Card>
- <SettingsSectionHeader>
- <Trans>Assets</Trans>
- </SettingsSectionHeader>
-
<ValidatedForm
className="w-full"
validator={taxDepreciationSettingsValidator}
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx b/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
index bf25ce275c..d9f00ab470 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.$id.tsx
@@ -1,13 +1,14 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertApiKey } from "@carbon/ee/api-keys.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect, useNavigate, useParams } from "react-router";
import { useRouteData } from "~/hooks";
import type { ApiKey } from "~/modules/settings";
-import { ApiKeyForm, apiKeyValidator, upsertApiKey } from "~/modules/settings";
+import { ApiKeyForm, apiKeyValidator } from "~/modules/settings";
import { invalidateApiKeyCache } from "~/modules/settings/settings.server";
import { getParams, path } from "~/utils/path";
@@ -17,7 +18,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "users"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx
index b11cd89f8b..db9e657402 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.delete.$id.tsx
@@ -1,14 +1,14 @@
import { error, success } from "@carbon/auth";
import { bustApiKeyCache, requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { deleteApiKey } from "@carbon/ee/api-keys.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { useLingui } from "@lingui/react/macro";
import type { ActionFunctionArgs } from "react-router";
import { redirect, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
import { useRouteData } from "~/hooks";
import type { ApiKey } from "~/modules/settings";
-import { deleteApiKey } from "~/modules/settings";
import { invalidateApiKeyCache } from "~/modules/settings/settings.server";
import { getParams, path } from "~/utils/path";
@@ -17,7 +17,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "users"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.new.tsx b/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
index 28a57c32c0..057d5732b6 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.new.tsx
@@ -1,13 +1,14 @@
import { assertIsPost, error } from "@carbon/auth";
import { hashApiKey, requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { upsertApiKey } from "@carbon/ee/api-keys.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import { nanoid } from "nanoid";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, useNavigate } from "react-router";
import { useRouteData } from "~/hooks";
-import { ApiKeyForm, apiKeyValidator, upsertApiKey } from "~/modules/settings";
+import { ApiKeyForm, apiKeyValidator } from "~/modules/settings";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -24,7 +25,7 @@ export async function action({ request }: ActionFunctionArgs) {
update: "users"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
index f5d86b7e92..84764271de 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
@@ -1,9 +1,10 @@
import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { deleteApprovalRule } from "@carbon/ee/approvals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { deleteApprovalRule } from "~/modules/shared";
import { getParams, path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -12,6 +13,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.settings,
+ feature: "APPROVAL_RULES"
+ });
+
const { id } = params;
if (!id) throw new Error("Rule ID is required");
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
index 8905d80d11..d8490bc1ad 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
@@ -2,17 +2,18 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { approvalRuleValidator } from "@carbon/ee/approvals";
+import {
+ getApprovalRuleById,
+ getApprovalRules,
+ upsertApprovalRule
+} from "@carbon/ee/approvals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import { useUrlParams } from "~/hooks";
import { ApprovalRuleForm } from "~/modules/settings";
-import {
- approvalRuleValidator,
- getApprovalRuleById,
- getApprovalRules,
- upsertApprovalRule
-} from "~/modules/shared";
import { getParams, path } from "~/utils/path";
@@ -22,6 +23,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.settings,
+ feature: "APPROVAL_RULES"
+ });
+
const { id } = params;
if (!id) throw new Error("Rule ID is required");
@@ -49,11 +58,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "settings",
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.settings,
+ feature: "APPROVAL_RULES"
+ });
+
const serviceRole = getCarbonServiceRole();
const { id } = params;
if (!id) throw new Error("Rule ID is required");
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
index d7f5f740eb..1b27be7ee1 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
@@ -2,23 +2,32 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import {
+ type ApprovalDocumentType,
+ approvalRuleValidator
+} from "@carbon/ee/approvals";
+import { upsertApprovalRule } from "@carbon/ee/approvals.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import { ApprovalRuleForm } from "~/modules/settings";
-import {
- type ApprovalDocumentType,
- approvalRuleValidator,
- upsertApprovalRule
-} from "~/modules/shared";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "settings",
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.settings,
+ feature: "APPROVAL_RULES"
+ });
+
const url = new URL(request.url);
const typeParam = url.searchParams.get("type");
const documentType: ApprovalDocumentType | null =
@@ -37,11 +46,19 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "settings",
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.settings,
+ feature: "APPROVAL_RULES"
+ });
+
const serviceRole = getCarbonServiceRole();
const formData = await request.formData();
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.tsx
index c4fecfe9f6..51ef6bff76 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.tsx
@@ -2,11 +2,12 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { getApprovalRules } from "@carbon/ee/approvals.server";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
-import { ApprovalRules } from "~/modules/settings";
-import { getApprovalRules } from "~/modules/shared";
+import { usePlanGate } from "~/hooks/usePlanGate";
+import { ApprovalRules, ApprovalRulesUpgradeOverlay } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -76,6 +77,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function ApprovalSettingsRoute() {
const { poRules, qdRules, supplierRules } = useLoaderData<typeof loader>();
+ const { isGated } = usePlanGate({ feature: "APPROVAL_RULES" });
+
+ if (isGated) {
+ return <ApprovalRulesUpgradeOverlay />;
+ }
return (
<>
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 6a921c8728..3c76e1db9a 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -60,6 +60,7 @@ import {
totalScopeRows
} from "~/modules/settings";
import {
+ canManageBackups,
dismissCompanyExportFailure,
finalizeCompanyRestore,
getCompanyBackups,
@@ -82,7 +83,6 @@ import {
RestoreIncludeChoice,
RestoreReviewRow
} from "~/modules/settings/ui/Backups";
-import { canAccessBackups } from "~/utils/backups";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -148,19 +148,14 @@ async function clearStaleExportFailure(
}
}
-function requireBackupAccess(email: string | null) {
- // Internal-only in real deployments while multi-tenant hardening is pending;
- // open to everyone on a local dev stack.
- if (!canAccessBackups(email)) {
- throw redirect(path.to.settings);
- }
-}
-
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
update: "settings"
});
- requireBackupAccess(email);
+ // Business/Enterprise feature, plus an internal/local-dev escape hatch.
+ if (!(await canManageBackups(client, companyId, email))) {
+ throw redirect(path.to.settings);
+ }
const [backupsList, restoreRuns, exportRun] = await Promise.all([
getCompanyBackups(client, companyId),
@@ -184,7 +179,9 @@ export async function action({ request }: ActionFunctionArgs) {
update: "settings"
}
);
- requireBackupAccess(email);
+ if (!(await canManageBackups(client, companyId, email))) {
+ throw redirect(path.to.settings);
+ }
const formData = await request.formData();
const intent = formData.get("intent");
diff --git a/apps/erp/app/routes/x+/settings+/people.tsx b/apps/erp/app/routes/x+/settings+/people.tsx
index 5693dd6bfb..e55637bb5c 100644
--- a/apps/erp/app/routes/x+/settings+/people.tsx
+++ b/apps/erp/app/routes/x+/settings+/people.tsx
@@ -1,6 +1,8 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { updateConsoleSetting } from "@carbon/ee/console.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import {
Badge,
Button,
@@ -27,14 +29,11 @@ import {
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
-
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData } from "react-router";
-import {
- getCompanySettings,
- updateConsoleSetting,
- updateTimeCardSetting
-} from "~/modules/settings";
+import { UpgradeOverlayUpgradeButton } from "~/components/UpgradeOverlay";
+import { usePlanGate } from "~/hooks/usePlanGate";
+import { getCompanySettings, updateTimeCardSetting } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -77,6 +76,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (intent === "console") {
+ // Enterprise: console (kiosk) mode is gated. `companyHasFeature` blocks the
+ // Community edition outright and applies the plan check on Cloud.
+ const hasConsole = await companyHasFeature(client, companyId, {
+ feature: "PERMISSIONS"
+ });
+ if (!hasConsole) {
+ return {
+ success: false,
+ message: "Console mode requires the Business plan"
+ };
+ }
+
const update = await updateConsoleSetting(
client,
companyId,
@@ -114,6 +125,8 @@ export async function action({ request }: ActionFunctionArgs) {
export default function PeopleSettingsRoute() {
const { companySettings } = useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
+ // Enterprise: console (kiosk) mode is gated to the Business plan.
+ const { isGated: consoleGated } = usePlanGate({ feature: "PERMISSIONS" });
const [showPinModal, setShowPinModal] = useState(false);
const [generatedPin, setGeneratedPin] = useState<string | null>(null);
@@ -193,7 +206,9 @@ export default function PeopleSettingsRoute() {
</HStack>
<span className="text-sm text-muted-foreground">
- {(companySettings as any).consoleEnabled ? (
+ {consoleGated ? (
+ <Trans>Available on the Business plan</Trans>
+ ) : (companySettings as any).consoleEnabled ? (
<Trans>
Operators can use shared workstations with PIN
authentication.
@@ -203,11 +218,15 @@ export default function PeopleSettingsRoute() {
)}
</span>
</VStack>
- <Switch
- checked={(companySettings as any).consoleEnabled ?? false}
- onCheckedChange={handleConsoleToggle}
- disabled={isToggling}
- />
+ {consoleGated ? (
+ <UpgradeOverlayUpgradeButton />
+ ) : (
+ <Switch
+ checked={(companySettings as any).consoleEnabled ?? false}
+ onCheckedChange={handleConsoleToggle}
+ disabled={isToggling}
+ />
+ )}
</HStack>
</CardContent>
</Card>
diff --git a/apps/erp/app/routes/x+/settings+/security.tsx b/apps/erp/app/routes/x+/settings+/security.tsx
index a3d88ba3d5..694f0946df 100644
--- a/apps/erp/app/routes/x+/settings+/security.tsx
+++ b/apps/erp/app/routes/x+/settings+/security.tsx
@@ -7,7 +7,7 @@ import {
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import {
getSamlSpUrls,
getSsoConnection,
@@ -15,6 +15,7 @@ import {
getTxtRecord,
isSsoEnabled
} from "@carbon/ee/sso.server";
+import { updateRequireMfaSetting } from "@carbon/ee/two-factor.server";
import { ValidatedForm } from "@carbon/form";
import {
Button,
@@ -50,11 +51,7 @@ import { UpgradeOverlaySection } from "~/components/UpgradeOverlay";
import { usePermissions } from "~/hooks";
import { usePlanGate } from "~/hooks/usePlanGate";
import { useSettings } from "~/hooks/useSettings";
-import {
- ssoConnectionValidator,
- ssoDomainValidator,
- updateRequireMfaSetting
-} from "~/modules/settings";
+import { ssoConnectionValidator, ssoDomainValidator } from "~/modules/settings";
import { sendMfaRequiredEmails } from "~/services/mfa-email.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -156,7 +153,7 @@ export async function action({ request }: ActionFunctionArgs) {
const requireMfa = formData.get("enabled") === "true";
if (requireMfa) {
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
@@ -434,16 +431,6 @@ export default function Security() {
</p>
</div>
- <div className="flex flex-col gap-1 w-full">
- <Heading size="h3">
- <Trans>MFA</Trans>
- </Heading>
- <p className="text-sm text-muted-foreground text-pretty max-w-xl">
- <Trans>
- Require a second factor when members sign in to this company.
- </Trans>
- </p>
- </div>
{mfaGated ? (
<UpgradeOverlaySection
icon={<LuShieldCheck className="size-6 text-muted-foreground" />}
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx b/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx
index 7e05faadf5..2f48d6c24a 100644
--- a/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx
@@ -1,15 +1,12 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertWebhook } from "@carbon/ee/webhooks.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
-import {
- getWebhook,
- upsertWebhook,
- webhookValidator
-} from "~/modules/settings";
+import { getWebhook, webhookValidator } from "~/modules/settings";
import { WebhookForm } from "~/modules/settings/ui/Webhooks";
import { getParams, path } from "~/utils/path";
@@ -40,7 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
view: "settings"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx
index 70116329e5..0b1ade2b91 100644
--- a/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx
@@ -1,12 +1,13 @@
import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { deleteWebhook } from "@carbon/ee/webhooks.server";
import { useLingui } from "@lingui/react/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteWebhook, getWebhook } from "~/modules/settings";
+import { getWebhook } from "~/modules/settings";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "users"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.new.tsx b/apps/erp/app/routes/x+/settings+/webhooks.new.tsx
index 42cc50ae45..c121219c30 100644
--- a/apps/erp/app/routes/x+/settings+/webhooks.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/webhooks.new.tsx
@@ -1,11 +1,12 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { requirePlan } from "@carbon/ee/plan.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { upsertWebhook } from "@carbon/ee/webhooks.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useNavigate } from "react-router";
-import { upsertWebhook, webhookValidator } from "~/modules/settings";
+import { webhookValidator } from "~/modules/settings";
import { WebhookForm } from "~/modules/settings/ui/Webhooks";
import { getParams, path } from "~/utils/path";
@@ -23,7 +24,7 @@ export async function action({ request }: ActionFunctionArgs) {
view: "settings"
});
- await requirePlan({
+ await requireFeature({
request,
client,
companyId,
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
index 9de4eea760..2983720b51 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
@@ -2,14 +2,6 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import { trigger } from "@carbon/jobs";
-import { getLogger } from "@carbon/logger";
-import { NotificationEvent } from "@carbon/notifications";
-import { datetime } from "@carbon/utils";
-import type { ActionFunctionArgs } from "react-router";
-import { redirect } from "react-router";
-import { supplierApprovalDecisionValidator } from "~/modules/purchasing";
import {
approveRequest,
canApproveRequest,
@@ -19,7 +11,15 @@ import {
getLatestApprovalRequestForDocument,
hasPendingApproval,
rejectRequest
-} from "~/modules/shared";
+} from "@carbon/ee/approvals.server";
+import { validationError, validator } from "@carbon/form";
+import { trigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
+import { NotificationEvent } from "@carbon/notifications";
+import { datetime } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { supplierApprovalDecisionValidator } from "~/modules/purchasing";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.tsx
index 4d4eb2e6d2..ee20c42690 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.tsx
@@ -7,11 +7,11 @@ import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect } from "react-router";
import {
getSupplier,
- getSupplierApprovalContext,
getSupplierContacts,
getSupplierLocations,
getSupplierTax
} from "~/modules/purchasing";
+import { getSupplierApprovalContext } from "~/modules/purchasing/purchasing.server";
import SupplierHeader from "~/modules/purchasing/ui/Supplier/SupplierHeader";
import SupplierSidebar from "~/modules/purchasing/ui/Supplier/SupplierSidebar";
import { getTagsList } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
index daa0df8fe7..db9bb13a38 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -11,7 +12,6 @@ import {
getSupplierQuote,
selectedLinesValidator
} from "~/modules/purchasing";
-import { isApprovalRequired } from "~/modules/shared";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
index b7f208cb20..ffd0c1d120 100644
--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import { batchTrigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
@@ -13,10 +14,18 @@ import { getParams, path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const validation = await validator(bulkPermissionsValidator).validate(
await request.formData()
);
diff --git a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx
index 4b3dbc467b..178443900b 100644
--- a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx
+++ b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx
@@ -1,6 +1,12 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import {
+ makeCompanyPermissionsFromEmployeeType,
+ upsertEmployeeType,
+ upsertEmployeeTypePermissions
+} from "@carbon/ee/permissions.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type {
ActionFunctionArgs,
@@ -13,11 +19,8 @@ import {
employeeTypePermissionsValidator,
employeeTypeValidator,
getEmployeeType,
- getPermissionsByEmployeeType,
- upsertEmployeeType,
- upsertEmployeeTypePermissions
+ getPermissionsByEmployeeType
} from "~/modules/users";
-import { makeCompanyPermissionsFromEmployeeType } from "~/modules/users/users.server";
import { path } from "~/utils/path";
import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";
@@ -27,6 +30,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
role: "employee"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const { employeeTypeId } = params;
if (!employeeTypeId) throw notFound("employeeTypeId not found");
@@ -50,6 +61,14 @@ export async function action({ request }: ActionFunctionArgs) {
update: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const validation = await validator(employeeTypeValidator).validate(
await request.formData()
);
diff --git a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx
index e5b183a88a..e6569aa482 100644
--- a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx
+++ b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx
@@ -1,6 +1,8 @@
import { error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { deleteEmployeeType } from "@carbon/ee/permissions.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { useLingui } from "@lingui/react/macro";
import type {
ActionFunctionArgs,
@@ -9,15 +11,24 @@ import type {
} from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteEmployeeType, getEmployeeType } from "~/modules/users";
+import { getEmployeeType } from "~/modules/users";
import { path } from "~/utils/path";
import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
role: "employee"
});
+
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const { employeeTypeId } = params;
if (!employeeTypeId) throw notFound("EmployeeTypeId not found");
@@ -38,10 +49,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export async function action({ request, params }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
delete: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const { employeeTypeId } = params;
if (!employeeTypeId) {
throw redirect(
@@ -52,7 +71,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { error: deleteTypeError } = await deleteEmployeeType(
client,
- employeeTypeId
+ employeeTypeId,
+ companyId
);
if (deleteTypeError) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/users+/employee-types.new.tsx b/apps/erp/app/routes/x+/users+/employee-types.new.tsx
index b84f9440db..c70500d12d 100644
--- a/apps/erp/app/routes/x+/users+/employee-types.new.tsx
+++ b/apps/erp/app/routes/x+/users+/employee-types.new.tsx
@@ -1,6 +1,12 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import {
+ insertEmployeeType,
+ makeEmptyPermissionsFromModules,
+ upsertEmployeeTypePermissions
+} from "@carbon/ee/permissions.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import type {
ActionFunctionArgs,
@@ -13,19 +19,24 @@ import {
EmployeeTypeForm,
employeeTypePermissionsValidator,
employeeTypeValidator,
- getModules,
- insertEmployeeType,
- upsertEmployeeTypePermissions
+ getModules
} from "~/modules/users";
-import { makeEmptyPermissionsFromModules } from "~/modules/users/users.server";
import { path } from "~/utils/path";
import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
create: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const modules = await getModules(client);
if (modules.error || modules.data === null) {
throw redirect(
@@ -45,6 +56,14 @@ export async function action({ request }: ActionFunctionArgs) {
create: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const validation = await validator(employeeTypeValidator).validate(
await request.formData()
);
diff --git a/apps/erp/app/routes/x+/users+/employee-types.tsx b/apps/erp/app/routes/x+/users+/employee-types.tsx
index e284bc7160..afa1da2aac 100644
--- a/apps/erp/app/routes/x+/users+/employee-types.tsx
+++ b/apps/erp/app/routes/x+/users+/employee-types.tsx
@@ -3,7 +3,12 @@ import { VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, useLoaderData } from "react-router";
-import { EmployeeTypesTable, getEmployeeTypes } from "~/modules/users";
+import { usePlanGate } from "~/hooks/usePlanGate";
+import {
+ EmployeeTypesTable,
+ EmployeeTypesUpgradeOverlay,
+ getEmployeeTypes
+} from "~/modules/users";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -41,6 +46,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function EmployeeTypesRoute() {
const { data, count } = useLoaderData<typeof loader>();
+ const { isGated } = usePlanGate({ feature: "PERMISSIONS" });
+
+ if (isGated) {
+ return <EmployeeTypesUpgradeOverlay />;
+ }
return (
<VStack spacing={0} className="h-full">
diff --git a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx
index df98396fc0..7d6144a4f4 100644
--- a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx
+++ b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx
@@ -3,13 +3,32 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import type { Json } from "@carbon/database";
+import {
+ makeCompanyPermissionsFromClaims,
+ makeCompanyPermissionsFromEmployeeType,
+ updateEmployee
+} from "@carbon/ee/permissions.server";
+import { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
+import {
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ VStack
+} from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { LuShield } from "react-icons/lu";
import type {
ActionFunctionArgs,
ClientActionFunctionArgs,
LoaderFunctionArgs
} from "react-router";
-import { data, redirect, useLoaderData } from "react-router";
+import { data, redirect, useLoaderData, useNavigate } from "react-router";
+import { UpgradeOverlayUpgradeButton } from "~/components/UpgradeOverlay";
+import { usePlanGate } from "~/hooks/usePlanGate";
import type { CompanyPermission } from "~/modules/users";
import {
EmployeePermissionsForm,
@@ -19,15 +38,49 @@ import {
getPermissionsByEmployeeType,
userPermissionsValidator
} from "~/modules/users";
-import {
- getClaims,
- makeCompanyPermissionsFromClaims,
- makeCompanyPermissionsFromEmployeeType,
- updateEmployee
-} from "~/modules/users/users.server";
+import { getClaims } from "~/modules/users/users.server";
import { path } from "~/utils/path";
import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";
+// The per-user permissions editor is a modal over the accounts list; when the
+// company isn't entitled we show the upgrade prompt IN that modal (not a
+// full-page overlay), so closing it returns to the accounts list — which stays
+// fully usable (inviting people is a Community feature).
+function PermissionsUpgradeModal() {
+ const navigate = useNavigate();
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) navigate(-1);
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>User Permissions</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4} className="items-center text-center py-6">
+ <div className="flex items-center justify-center rounded-full bg-muted size-12">
+ <LuShield className="size-6 text-muted-foreground" />
+ </div>
+ <p className="text-sm text-muted-foreground max-w-sm">
+ <Trans>
+ Grant each user fine-grained, per-module permissions instead of
+ giving everyone full access.
+ </Trans>
+ </p>
+ <UpgradeOverlayUpgradeButton />
+ </VStack>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+}
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { companyId } = await requirePermissions(request, {
view: "users",
@@ -38,6 +91,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!employeeId) throw notFound("employeeId not found");
const client = getCarbonServiceRole();
+
const [rawClaims, employee, employeeTypes] = await Promise.all([
getClaims(client, employeeId, companyId),
getEmployee(client, employeeId, companyId),
@@ -103,6 +157,14 @@ export async function action({ request }: ActionFunctionArgs) {
update: "users"
});
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo: path.to.employeeAccounts,
+ feature: "PERMISSIONS"
+ });
+
const validation = await validator(employeeValidator).validate(
await request.formData()
);
@@ -150,6 +212,11 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
export default function UsersEmployeeRoute() {
const { permissions, employee, employeeTypes, employeeTypePermissions } =
useLoaderData<typeof loader>();
+ const { isGated } = usePlanGate({ feature: "PERMISSIONS" });
+
+ if (isGated) {
+ return <PermissionsUpgradeModal />;
+ }
const initialValues = {
id: employee?.id || "",
diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsx
index 55077724b0..3b95ee7190 100644
--- a/apps/erp/app/routes/x+/users+/employees.new.tsx
+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx
@@ -8,6 +8,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { InviteEmail } from "@carbon/documents/email";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";
import { validationError, validator } from "@carbon/form";
import { sendEmail } from "@carbon/lib/email.server";
@@ -79,6 +80,26 @@ export async function action({ request }: ActionFunctionArgs) {
usPersonAttestation
} = validation.data;
+ // Community / Starter ships "everyone is an admin": authoring roles is gated,
+ // so an invited user always receives the seeded Admin employee type,
+ // regardless of what the (hidden) form control submitted. `companyHasFeature`
+ // blocks the Community edition outright and applies the plan check on Cloud.
+ let effectiveEmployeeType = employeeType;
+ const canAuthorRoles = await companyHasFeature(client, companyId, {
+ feature: "PERMISSIONS"
+ });
+ if (!canAuthorRoles) {
+ const adminType = await client
+ .from("employeeType")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("systemType", "Admin")
+ .maybeSingle();
+ if (adminType.data?.id) {
+ effectiveEmployeeType = adminType.data.id;
+ }
+ }
+
// Controlled environments require the inviter to attest the invitee is a
// U.S. person (22 CFR 120.62) before the invite can be created.
if (CONTROLLED_ENVIRONMENT && !usPersonAttestation) {
@@ -107,7 +128,7 @@ export async function action({ request }: ActionFunctionArgs) {
email: email.toLowerCase(),
firstName,
lastName,
- employeeType,
+ employeeType: effectiveEmployeeType,
locationId,
companyId,
createdBy: userId,
diff --git a/apps/erp/app/utils/backups.ts b/apps/erp/app/utils/backups.ts
index 45779dbef4..86853d8836 100644
--- a/apps/erp/app/utils/backups.ts
+++ b/apps/erp/app/utils/backups.ts
@@ -2,10 +2,12 @@ import { IS_LOCAL_DEV } from "@carbon/auth";
import { isInternalEmail } from "@carbon/utils";
/**
- * Backups/restores stay internal-only in real deployments while the
- * multi-tenant caveats are unhardened, but any user can exercise them on a
- * local dev stack. Shared by the route gates, the backup API loaders, and the
- * settings nav so they can never diverge.
+ * The internal-staff / local-dev escape hatch for backups. Backups are a
+ * Business/Enterprise feature — the authoritative gate is
+ * `canManageBackups` (`~/modules/settings/backups.server`), which is
+ * `canAccessBackups(email) || companyHasFeature(BACKUPS)`. This helper stays a
+ * pure, browser-safe predicate (no plan/DB read) so it can back Demo Data — which
+ * remains internal-only — and be the escape hatch inside `canManageBackups`.
*/
export function canAccessBackups(email: string | null | undefined): boolean {
return IS_LOCAL_DEV || isInternalEmail(email);
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index f9f4e2fb7a..b0bf53cd60 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1802,6 +1802,7 @@ export const path = {
postJournalEntry: (id: string) =>
generatePath(`${x}/journal-entry/${id}/post`),
priceOverride: (id: string) => generatePath(`${x}/sales/price-list/${id}`),
+ pricing: "https://carbon.ms/pricing",
pricingRule: (id: string) => generatePath(`${x}/sales/pricing-rules/${id}`),
printingSettings: `${x}/settings/printing`,
printingSettingsJobs: `${x}/settings/printing/jobs`,
diff --git a/apps/erp/test/mcp-tool-metadata.test.ts b/apps/erp/test/mcp-tool-metadata.test.ts
index 611ae9eacc..bfa5ec40fb 100644
--- a/apps/erp/test/mcp-tool-metadata.test.ts
+++ b/apps/erp/test/mcp-tool-metadata.test.ts
@@ -258,18 +258,21 @@ describe("mcp tool-metadata generator", () => {
// Array<{...}> generics publish as typed arrays, same as the `[]` suffix.
it("resolves Array<T> generic params to typed arrays", () => {
- const forecasts = props(get("production_upsertDemandForecasts")).forecasts;
- expect(forecasts?.type).toBe("array");
- expect(Object.keys(forecasts?.items?.properties ?? {})).toContain("itemId");
+ const sourceTools = props(get("production_maxToolQuantityByItem")).sourceTools;
+ expect(sourceTools?.type).toBe("array");
+ expect(Object.keys(sourceTools?.items?.properties ?? {})).toContain("itemId");
});
// A bare type alias declared in the module's own sources (service file,
// types.ts, models, or shared) resolves; Partial<{...}> drops required.
+ // `diffMethod(input: DiffMethodInput)` — DiffMethodInput is a named type
+ // alias declared in items.service.ts, so it must resolve to real properties
+ // rather than an opaque {}.
it("resolves module-local type aliases and Partial wrappers", () => {
- const rule = props(get("shared_upsertApprovalRule")).rule;
- const ruleBranches = rule?.anyOf ?? [rule];
+ const input = props(get("items_diffMethod")).input;
+ const inputBranches = input?.anyOf ?? [input];
expect(
- Object.keys(ruleBranches[0]?.properties ?? {}).length
+ Object.keys(inputBranches[0]?.properties ?? {}).length
).toBeGreaterThan(0);
// updateAbility takes an optional `name` and an optional cadence, so the
diff --git a/apps/erp/test/mcp-tool-permissions.test.ts b/apps/erp/test/mcp-tool-permissions.test.ts
index 8425af3d51..9626c3b647 100644
--- a/apps/erp/test/mcp-tool-permissions.test.ts
+++ b/apps/erp/test/mcp-tool-permissions.test.ts
@@ -18,12 +18,10 @@ const allTools = metadata.tools as Tool[];
// PERMISSION_OVERRIDES in scripts/lib/service-metadata.ts — route-verified
// exceptions that win over the derivation rules. Pinned exactly below and
-// excluded from the rule-based assertions.
-const OVERRIDDEN = new Set([
- "settings_getApiKeys",
- "settings_upsertApiKey",
- "settings_deleteApiKey"
-]);
+// excluded from the rule-based assertions. The API-key WRITES (upsert/delete)
+// moved to @carbon/ee/api-keys.server behind requireEntitlement, so they are no
+// longer MCP tools — only the read (getApiKeys) remains and keeps the override.
+const OVERRIDDEN = new Set(["settings_getApiKeys"]);
const tools = allTools.filter((t) => !OVERRIDDEN.has(t.name));
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 2ab5d38fa7..ec66772ef8 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -79,6 +79,7 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
currentUrl,
nextUrl,
formMethod,
+ formAction,
defaultShouldRevalidate
}) => {
if (
@@ -89,6 +90,17 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
return true;
}
+ // Console mode + pin-in/out live in this shell loader (via userMiddleware).
+ // Those actions set cookies, so the shell MUST re-run for the change to show —
+ // without this, the overlay/console state only updated on a full page refresh.
+ if (
+ formAction === path.to.consolePinIn ||
+ formAction === path.to.consolePinOut ||
+ formAction === path.to.consoleToggle
+ ) {
+ return true;
+ }
+
// This loader is the app shell: 9 queries plus an auth round-trip. Without
// this it re-ran on every filter, sort and page click, none of which can
// change anything it returns.
diff --git a/apps/mes/app/routes/x+/console.pin-in.tsx b/apps/mes/app/routes/x+/console.pin-in.tsx
index 1f146b6e79..457e95e601 100644
--- a/apps/mes/app/routes/x+/console.pin-in.tsx
+++ b/apps/mes/app/routes/x+/console.pin-in.tsx
@@ -2,9 +2,8 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { ActionFunctionArgs } from "react-router";
-import { data, redirect } from "react-router";
+import { data } from "react-router";
import { setConsolePinIn } from "~/services/console.server";
-import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -62,14 +61,20 @@ export async function action({ request }: ActionFunctionArgs) {
return data({ error: "Incorrect PIN" }, { status: 400 });
}
- throw redirect(path.to.authenticatedRoot, {
- headers: {
- "Set-Cookie": setConsolePinIn(companyId, {
- userId,
- name,
- avatarUrl,
- pinnedAt: Date.now()
- })
+ // Return data (not a redirect) so the caller's fetcher revalidates the shell
+ // loader — the `_layout` shouldRevalidate has an explicit case for this
+ // action, and a redirect would drop the form context it matches on.
+ return data(
+ { success: true },
+ {
+ headers: {
+ "Set-Cookie": setConsolePinIn(companyId, {
+ userId,
+ name,
+ avatarUrl,
+ pinnedAt: Date.now()
+ })
+ }
}
- });
+ );
}
diff --git a/apps/mes/app/routes/x+/console.pin-out.tsx b/apps/mes/app/routes/x+/console.pin-out.tsx
index f236dc5b8d..bd170f14b3 100644
--- a/apps/mes/app/routes/x+/console.pin-out.tsx
+++ b/apps/mes/app/routes/x+/console.pin-out.tsx
@@ -1,17 +1,22 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { ActionFunctionArgs } from "react-router";
-import { redirect } from "react-router";
+import { data } from "react-router";
import { clearConsolePinIn } from "~/services/console.server";
-import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId } = await requirePermissions(request, {});
- throw redirect(path.to.authenticatedRoot, {
- headers: {
- "Set-Cookie": clearConsolePinIn(companyId)
+ // Return data (not a redirect) so the caller's fetcher revalidates the shell
+ // loader — the `_layout` shouldRevalidate has an explicit case for this
+ // action, and a redirect would drop the form context it matches on.
+ return data(
+ { success: true },
+ {
+ headers: {
+ "Set-Cookie": clearConsolePinIn(companyId)
+ }
}
- });
+ );
}
diff --git a/apps/mes/app/routes/x+/console.toggle.tsx b/apps/mes/app/routes/x+/console.toggle.tsx
index 2b047adfdb..dd83527cd4 100644
--- a/apps/mes/app/routes/x+/console.toggle.tsx
+++ b/apps/mes/app/routes/x+/console.toggle.tsx
@@ -2,9 +2,8 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { updateSessionConsole } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
-import { redirect } from "react-router";
+import { data } from "react-router";
import { clearConsolePinIn } from "~/services/console.server";
-import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -37,5 +36,9 @@ export async function action({ request }: ActionFunctionArgs) {
headers.append("Set-Cookie", clearConsolePinIn(companyId));
}
- throw redirect(path.to.authenticatedRoot, { headers });
+ // Return data (not a redirect) so the caller's fetcher auto-revalidates the
+ // layout loader and `consoleMode` flips — mirroring the dark-mode toggle in
+ // root.tsx. A fetcher redirect to the current route did not reliably refresh
+ // the loader, so toggling console mode appeared to do nothing.
+ return data({ success: true }, { headers });
}
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index ccbb10fc23..15614c0e23 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -1,6 +1,6 @@
# @carbon/ee
-Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero, QuickBooks Online, Rillet), plan gating, Slack, email, Jira, Linear, Onshape, the shared rules layer (storage + sales rules), the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)
+Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero, QuickBooks Online, Rillet), plan gating, RBAC authoring (permissions), Slack, email, Jira, Linear, Onshape, the shared rules layer (storage + sales rules), the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)
## Always
@@ -8,7 +8,7 @@ Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero
- MUST link external ids through `createMappingService()` and `externalIntegrationMapping`; do not add per-entity external-id columns.
- MUST register server lifecycle hooks in `src/hooks.server.ts`; integration config files are shared with browser bundles.
- MUST use the operation-specific helpers from `@carbon/ee/ramp.server` for Ramp state. `patchRampSettings`, `patchRampOAuthCredentials`, `patchRampRefreshedTokens`, `patchRampConnection`, `patchRampWebhook`, and `patchRampCursor` own disjoint paths and delegate to the atomic `patchIntegrationState()` RPC boundary.
-- MUST use `FEATURE_PLANS` for client and server plan gating. `companyHasPlan()` and `requirePlan()` intentionally allow non-Cloud editions and bypass-listed companies.
+- MUST use `FEATURE_PLANS` for client and server plan gating. `companyHasPlan()` and `requirePlan()` intentionally allow non-Cloud editions and bypass-listed companies. For features that must be BLOCKED on the **Community** edition (RBAC authoring/permissions, console mode, and the entitlement-gated feature writes), use `companyHasFeature`/`requireFeature`/`requireEntitlement` instead — they return false/throw on `Edition.Community` (Enterprise/Test still pass). See `.claude/rules/commercial-licensing.md`.
- MUST pass caller-created Supabase/Kysely clients into `runMrp()`, `runLocationSchedule()`, `runExpediteWhatIf()`, and other planning entry points.
## Ask First
@@ -60,10 +60,12 @@ pnpm --filter @carbon/ee typecheck
- **Tie-out remote reads**: `accounting/core/remote-journal.ts` `fetchRemoteJournalTotals()` — provider-agnostic debit-signed per-account journal totals for the reconciliation tie-out
- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)
- **Rillet contact import**: the `actions` entry in `src/rillet/config.tsx` posts to `/api/integrations/rillet/import-contacts`, which fires `rillet-import-contacts` (`@carbon/jobs`). It is the only on-demand PULL of master data — `buildRilletSyncConfig` still forces customer/vendor `push-to-accounting`, and the job enqueues `pull-from-accounting` ledger rows by hand. `RilletCustomerSyncer`/`RilletVendorSyncer` implement `mapToLocal`/`upsertLocal` for it and extend `RilletEntitySyncer`; the pull rejections now live in `RilletPushOnlyEntitySyncer` (item + every transaction syncer). Importing exists to write the mapping row: `upsertRemote` reads `getRemoteId(localId)` first, so a Carbon sales invoice for an imported customer PUTs the original Rillet customer instead of creating a duplicate
+- **Permissions** (`./permissions.server`, `src/permissions.server.ts`): the licensed RBAC-authoring logic, gated to Business via the `PERMISSIONS` feature. `updatePermissions` (builds/persists the flattened `userPermission.permissions` object + audit diff + claims-cache bust), `updateEmployee`, employee-type CRUD (`insert/upsert/deleteEmployeeType`, `upsertEmployeeTypePermissions`), and the translators (`makeEmptyPermissionsFromModules`, `makeCompanyPermissionsFromClaims`, `makeCompanyPermissionsFromEmployeeType`). This is the ONLY copy of `updatePermissions` — the `@carbon/jobs` `carbon/update-permissions` (bulk-edit) task imports it here. **Server-only.** The ERP authoring UI stays `.ee.tsx` in `apps/erp` (couples to `~/components/Form`); routes stay in the app and gate with `requireFeature({ feature: "PERMISSIONS" })`. The community invite primitives (`setUserPermissions`, `makePermissionsFromEmployeeType`) deliberately stay in the app's `users.server.ts`. Console/kiosk mode is a sibling: `./console.server` (`updateConsoleSetting`) provisions the protected "Console Operator" employee type + a PIN, gated by the same `PERMISSIONS` feature.
+- **Commercial entitlement pattern** (`./entitlements.server`, `./plan.server`, and the per-feature `.server` modules): `requireEntitlement(client, companyId, feature)` (throws `EntitlementError`) is embedded at the top of every commercial authoring function so the gate lives in commercial code, not a strippable open route. Feature bodies moved here with in-code gates: `./approvals` (approval rules), `./rules.server` (sales + storage rules), `./api-keys.server`, `./webhooks.server`, `./two-factor.server` (the `requireMfa` policy), `./forecast.server` (demand forecasts + projections), `./customer-portals.server`, plus permissions/console above. Runtime paths that must degrade (not throw) use `companyHasFeature` (e.g. email notifications, webhook delivery). Full rationale: `.claude/rules/commercial-licensing.md`.
- **Ramp state helpers**: `src/ramp/lib/service.ts` is a compatibility facade. Put connection/auth in `connection.ts`, coding masters in `chart-of-accounts.ts`/`cost-centers.ts`, parties in `suppliers.ts`, PO/bill transport in `spend.ts`, confirms in `sync-confirmation.ts`, remote webhook lifecycle in `webhooks.ts`, and metadata/Vault writes in `state.ts`; `@carbon/ee/ramp.server` remains stable
- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions
- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`
-- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./rules` (client-safe storage + sales rule services/UI), `./rules.server` (both evaluators), `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, etc.
+- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, etc.
## Cross-References
diff --git a/packages/ee/LICENSE b/packages/ee/LICENSE
new file mode 100644
index 0000000000..80cdd4806d
--- /dev/null
+++ b/packages/ee/LICENSE
@@ -0,0 +1,41 @@
+Carbon Commercial License
+
+Copyright (C) Carbon Manufacturing Systems Corporation ("Carbon")
+
+This license covers the Enterprise files: (a) every file in the packages/ee
+directory of Carbon's source code, including its subdirectories, and (b)
+every file anywhere in Carbon's source code whose file name contains
+".ee.", including any modified version of those files. The rest of Carbon
+is licensed under the GNU Affero General Public License, version 3 only, as
+described in the LICENSE file at the root of the repository.
+
+1. Viewing and sharing. You may view and download the Enterprise files. You
+ may copy and share them only in source code form, only as part of a copy
+ of Carbon's source code, and only with this license and all copyright
+ notices included.
+
+2. Use requires a commercial license. You may not use the Enterprise files
+ in any other way, including running, testing, developing with, or
+ modifying them, unless you have a valid commercial license from Carbon
+ that covers them. A commercial license can be a Carbon Commercial
+ License Agreement (CCLA), an Enterprise Subscription Agreement (ESA), a
+ partner agreement, or any other commercial agreement with Carbon,
+ whether signed, purchased online, or accepted by click-through. Your use
+ must stay within what that agreement allows.
+
+3. Your agreement controls. If this license and your commercial agreement
+ with Carbon conflict, your commercial agreement controls.
+
+4. No other rights. Carbon keeps all rights in the Enterprise files that
+ this license does not expressly grant. This license does not give you
+ any right to use the name "Carbon," Carbon's logos, or any other Carbon
+ trademark.
+
+5. No warranty. Except as your commercial agreement with Carbon says
+ otherwise, THE ENTERPRISE FILES ARE PROVIDED "AS IS," WITHOUT WARRANTY
+ OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
+ NONINFRINGEMENT. IN NO EVENT SHALL CARBON OR ANY CONTRIBUTOR BE LIABLE
+ FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION
+ WITH THE ENTERPRISE FILES OR THE USE OF OR OTHER DEALINGS IN THEM.
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 88422c38db..644e89ec80 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -5,6 +5,13 @@
"exports": {
".": "./src/index.ts",
"./accounting": "./src/accounting/index.ts",
+ "./api-keys.server": "./src/api-keys.server.ts",
+ "./approvals": "./src/approvals/index.ts",
+ "./approvals.server": "./src/approvals/service.ts",
+ "./console.server": "./src/console.server.ts",
+ "./customer-portals.server": "./src/customer-portals.server.ts",
+ "./entitlements.server": "./src/entitlements.server.ts",
+ "./forecast.server": "./src/forecast.server.ts",
"./planning": "./src/planning/index.ts",
"./integrations/secrets": "./src/integrations/secrets.ts",
"./action-task-entity": "./src/lib/actionTaskEntity.ts",
@@ -17,6 +24,7 @@
"./notifications": "./src/notifications/index.ts",
"./onshape": "./src/onshape/lib/index.ts",
"./paperless-parts": "./src/paperless-parts/lib/index.ts",
+ "./permissions.server": "./src/permissions.server.ts",
"./plan": "./src/plan.ts",
"./plan.server": "./src/plan.server.ts",
"./slack.server": "./src/slack.server.ts",
@@ -28,7 +36,9 @@
"./ramp/hooks.server": "./src/ramp/hooks.server.ts",
"./rillet/hooks.server": "./src/rillet/hooks.server.ts",
"./xero/hooks.server": "./src/xero/hooks.server.ts",
- "./stripe-connect.server": "./src/stripe-connect/payment.server.ts"
+ "./stripe-connect.server": "./src/stripe-connect/payment.server.ts",
+ "./two-factor.server": "./src/two-factor.server.ts",
+ "./webhooks.server": "./src/webhooks.server.ts"
},
"private": true,
"scripts": {
diff --git a/packages/ee/src/api-keys.server.ts b/packages/ee/src/api-keys.server.ts
new file mode 100644
index 0000000000..3ebccdb588
--- /dev/null
+++ b/packages/ee/src/api-keys.server.ts
@@ -0,0 +1,139 @@
+import type { Database } from "@carbon/database";
+import { sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Business) API-key AUTHORING — creating, editing, and deleting a
+ * company's public-API keys, gated to the Business plan via the `API_KEYS`
+ * feature. The runtime VERIFICATION path (`@carbon/auth`
+ * `api-key.server.ts` / the `api+/v1+` authenticator) is a separate concern and
+ * is NOT gated here — an already-issued key keeps authenticating regardless of
+ * plan.
+ *
+ * The key is generated and hashed in the open route action (server-only:
+ * `hashApiKey` from `@carbon/auth/auth.server` + `nanoid`); this function only
+ * receives the already-computed `rawKey`/`keyHash`/`keyPreview` and stores the
+ * hash, so no crypto crosses the package boundary.
+ *
+ * The entitlement LOCK lives INSIDE this commercial function (see
+ * `entitlements.server`) so it cannot be stripped from open-licensed app code.
+ */
+
+// Minimal input shape — the validator's `Omit<…, "id" | "scopes" | "expiresAt">`
+// leaves only `name` (redefined here so `@carbon/ee` never imports `~/`).
+type ApiKeyInput = { name: string };
+
+export async function upsertApiKey(
+ client: SupabaseClient<Database>,
+ apiKey:
+ | (ApiKeyInput & {
+ createdBy: string;
+ companyId: string;
+ scopes: Record<string, string[]>;
+ expiresAt?: string;
+ rawKey: string;
+ keyHash: string;
+ keyPreview: string;
+ })
+ | (ApiKeyInput & {
+ id: string;
+ scopes: Record<string, string[]>;
+ expiresAt?: string;
+ })
+) {
+ if ("createdBy" in apiKey) {
+ await requireEntitlement(client, apiKey.companyId, "API_KEYS");
+ // Create: store the hash, return the raw key (caller generates both)
+ // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
+ const {
+ scopes,
+ expiresAt,
+ rawKey,
+ keyHash,
+ rateLimit: _rl,
+ rateLimitWindow: _rlw,
+ ...rest
+ } = apiKey as any;
+
+ const result = await client
+ .from("apiKey")
+ .insert(
+ sanitize({
+ ...rest,
+ keyHash,
+ scopes: scopes as any,
+ expiresAt: expiresAt || null
+ }) as any
+ )
+ .select("id")
+ .single();
+
+ if (result.error) {
+ return { data: null, error: result.error };
+ }
+
+ // Return the raw key (shown to user once, never stored)
+ return { data: { key: rawKey, id: result.data.id }, error: null };
+ }
+
+ // The update input carries no companyId — read it from the row so the
+ // entitlement check (the lock) can run before the write.
+ const existing = await client
+ .from("apiKey")
+ .select("companyId")
+ .eq("id", apiKey.id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "API key not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "API_KEYS");
+
+ // Update: update name, scopes, expiration (never the key itself)
+ // Strip rateLimit/rateLimitWindow — these are platform-controlled, not user-configurable
+ const {
+ scopes,
+ expiresAt,
+ rateLimit: _rl,
+ rateLimitWindow: _rlw,
+ ...rest
+ } = apiKey as any;
+ return client
+ .from("apiKey")
+ .update(
+ sanitize({
+ ...rest,
+ scopes: scopes as any,
+ expiresAt: expiresAt || null
+ }) as any
+ )
+ .eq("id", apiKey.id);
+}
+
+export async function deleteApiKey(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ // The input carries no companyId — read it from the row so the entitlement
+ // check (the lock) can run before the delete.
+ const existing = await client
+ .from("apiKey")
+ .select("companyId")
+ .eq("id", id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "API key not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "API_KEYS");
+ return client.from("apiKey").delete().eq("id", id);
+}
diff --git a/packages/ee/src/approvals/index.ts b/packages/ee/src/approvals/index.ts
new file mode 100644
index 0000000000..f6417604cb
--- /dev/null
+++ b/packages/ee/src/approvals/index.ts
@@ -0,0 +1,2 @@
+export * from "./models";
+export type * from "./types";
diff --git a/packages/ee/src/approvals/models.ts b/packages/ee/src/approvals/models.ts
new file mode 100644
index 0000000000..14f3730adc
--- /dev/null
+++ b/packages/ee/src/approvals/models.ts
@@ -0,0 +1,70 @@
+import type { Database } from "@carbon/database";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const approvalDecisionValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ decision: z.enum(["Approved", "Rejected"], {
+ error: "Decision is required"
+ }),
+ decisionNotes: zfd.text(z.string().optional())
+});
+
+export const approvalDocumentType = [
+ "purchaseOrder",
+ "qualityDocument",
+ "supplier"
+] as const;
+
+export type ApprovalDocumentType =
+ Database["public"]["Enums"]["approvalDocumentType"];
+
+export const approvalDocumentTypeLabel: Record<ApprovalDocumentType, string> = {
+ purchaseOrder: "Purchase Order",
+ qualityDocument: "Quality Document",
+ supplier: "Supplier"
+};
+
+export const approvalDocumentTypesWithAmounts: ApprovalDocumentType[] = [
+ "purchaseOrder"
+];
+
+export const approvalFiltersValidator = z.object({
+ documentType: z.enum(approvalDocumentType, {
+ error: "Document type is required"
+ }),
+ status: zfd.text(z.string().optional()),
+ dateFrom: zfd.text(z.string().optional()),
+ dateTo: zfd.text(z.string().optional())
+});
+
+export const approvalRequestValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ documentType: z.enum(approvalDocumentType, {
+ error: "Document type is required"
+ }),
+ documentId: zfd.text(
+ z.string().min(1, { message: "Document ID is required" })
+ ),
+ approverGroupIds: zfd.repeatableOfType(z.string()).optional()
+});
+
+export const approvalRuleValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ documentType: z.enum(approvalDocumentType, {
+ error: "Document type is required"
+ }),
+ approverGroupIds: z.array(
+ z.string().min(1, { message: "Invalid selection" })
+ ),
+ defaultApproverId: zfd.text(z.string().optional()),
+ lowerBoundAmount: zfd.numeric(z.number().gt(0).default(0)).optional(),
+ enabled: zfd.checkbox()
+});
+
+export const approvalStatusType = [
+ "Pending",
+ "Approved",
+ "Rejected",
+ "Cancelled"
+] as const;
diff --git a/packages/ee/src/approvals/service.ts b/packages/ee/src/approvals/service.ts
new file mode 100644
index 0000000000..ffd435e101
--- /dev/null
+++ b/packages/ee/src/approvals/service.ts
@@ -0,0 +1,939 @@
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { trackWorkEvent } from "@carbon/lib/telemetry";
+import { getLogger } from "@carbon/logger";
+import { getPurchaseOrderStatus, sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "../entitlements.server";
+import { companyHasFeature } from "../plan.server";
+import type { approvalDocumentType } from "./models";
+import type {
+ ApprovalFilters,
+ ApprovalRequestForApproveCheck,
+ ApprovalRequestForCancelCheck,
+ ApprovalRequestForViewCheck,
+ ApprovalRule,
+ CreateApprovalRequestInput,
+ UpsertApprovalRuleInput
+} from "./types";
+
+type GenericQueryFilters = {
+ limit?: number;
+ offset?: number;
+ sorts?: string[];
+ filters?: { column: string; operator: string; value: string }[];
+};
+
+const logger = getLogger("ee", "approvals");
+
+export async function approveRequest(
+ db: Kysely<KyselyDatabase>,
+ id: string,
+ userId: string,
+ notes?: string
+) {
+ // Pre-flight check: verify approval request exists and is pending
+ const approvalRequest = await db
+ .selectFrom("approvalRequest")
+ .select(["id", "status", "documentType", "documentId", "companyId"])
+ .where("id", "=", id)
+ .executeTakeFirst();
+
+ if (!approvalRequest) {
+ return { error: { message: "Approval request not found" }, data: null };
+ }
+
+ if (approvalRequest.status !== "Pending") {
+ return {
+ error: { message: "Approval request is not pending" },
+ data: null
+ };
+ }
+
+ const { documentType, documentId } = approvalRequest;
+ const now = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. Update approval request to "Approved"
+ const updatedApproval = await trx
+ .updateTable("approvalRequest")
+ .set({
+ status: "Approved",
+ decisionBy: userId,
+ decisionAt: now,
+ decisionNotes: notes || null,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", id)
+ .returning(["id", "documentType", "documentId"])
+ .executeTakeFirstOrThrow();
+
+ // 2. Update document status based on type
+ if (documentType === "purchaseOrder") {
+ // Fetch PO lines to calculate new status
+ const lines = await trx
+ .selectFrom("purchaseOrderLine")
+ .select([
+ "purchaseOrderLineType",
+ "invoicedComplete",
+ "receivedComplete"
+ ])
+ .where("purchaseOrderId", "=", documentId)
+ .execute();
+
+ const { status: calculatedStatus } = getPurchaseOrderStatus(lines);
+
+ // Update PO status (only if currently "Needs Approval")
+ const poUpdate = await trx
+ .updateTable("purchaseOrder")
+ .set({
+ status: calculatedStatus,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .where("status", "=", "Needs Approval")
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!poUpdate) {
+ throw new Error(
+ "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
+ );
+ }
+ } else if (documentType === "qualityDocument") {
+ const qdUpdate = await trx
+ .updateTable("qualityDocument")
+ .set({
+ status: "Active",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!qdUpdate) {
+ throw new Error("Failed to update quality document status");
+ }
+ } else if (documentType === "supplier") {
+ const supplierUpdate = await trx
+ .updateTable("supplier")
+ .set({
+ supplierStatus: "Active",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!supplierUpdate) {
+ throw new Error("Failed to update supplier status");
+ }
+ }
+
+ return updatedApproval;
+ });
+
+ // After the transaction, so a rollback emits nothing. The order became
+ // real here, not on the finalize route — that one stopped at the gate.
+ // Without this, every order a customer routes through an approval
+ // threshold is missing from "POs issued", and the shops that configure
+ // approval thresholds are the larger ones.
+ if (documentType === "purchaseOrder") {
+ trackWorkEvent(
+ "purchase_order_finalized",
+ {
+ companyId: approvalRequest.companyId,
+ userId,
+ purchaseOrderId: documentId,
+ stage: "committed"
+ },
+ { discriminator: "committed" }
+ );
+ }
+
+ return { data: result, error: null };
+ } catch (error) {
+ // Transaction automatically rolled back on error
+ return {
+ error: {
+ message:
+ error instanceof Error ? error.message : "Failed to process approval"
+ },
+ data: null
+ };
+ }
+}
+
+export async function canApproveRequest(
+ client: SupabaseClient<Database>,
+ approvalRequest: ApprovalRequestForApproveCheck,
+ userId: string
+): Promise<boolean> {
+ const rules = await getApprovalRulesForApprover(
+ client,
+ approvalRequest.documentType,
+ approvalRequest.companyId
+ );
+
+ if (!rules.data || rules.data.length === 0) {
+ return false;
+ }
+
+ // Authority flows upward only. Find the tier that matches this request's
+ // amount; a user may approve at that tier or any HIGHER tier, but never
+ // from a lower one (a $1k approver must not approve a $1M order).
+ // Amount-less document types (quality, supplier) match the base tier
+ // (lowerBoundAmount 0), so every rule qualifies and behavior is unchanged.
+ const matched = await getApprovalRuleByAmount(
+ client,
+ approvalRequest.documentType,
+ approvalRequest.companyId,
+ approvalRequest.amount ?? undefined
+ );
+ const tierFloor = matched.data?.lowerBoundAmount ?? 0;
+
+ const userGroups = await client.rpc("groups_for_user", { uid: userId });
+ const userGroupIds = userGroups.data || [];
+
+ return rules.data
+ .filter((rule) => (rule.lowerBoundAmount ?? 0) >= tierFloor)
+ .some((rule) => {
+ if (rule.defaultApproverId === userId) {
+ return true;
+ }
+
+ const approverGroupIds = rule.approverGroupIds;
+ if (!approverGroupIds || approverGroupIds.length === 0) {
+ return false;
+ }
+
+ // Direct individual approver
+ if (approverGroupIds.includes(userId)) {
+ return true;
+ }
+
+ // Member of an approver group
+ return approverGroupIds.some((groupId) => userGroupIds.includes(groupId));
+ });
+}
+
+/**
+ * Checks if a user can approve a request based on the specific rule matching the amount.
+ * This is the original approval check logic - user must be on the rule that matches the amount.
+ * Used for "Assigned to Me" lists.
+ */
+export async function canApproveRequestInWindow(
+ client: SupabaseClient<Database>,
+ approvalRequest: ApprovalRequestForApproveCheck,
+ userId: string
+): Promise<boolean> {
+ const rule = await getApprovalRuleByAmount(
+ client,
+ approvalRequest.documentType,
+ approvalRequest.companyId,
+ approvalRequest.amount ?? undefined
+ );
+
+ if (!rule.data) {
+ return false;
+ }
+
+ if (rule.data.defaultApproverId === userId) {
+ return true;
+ }
+
+ const approverGroupIds = rule.data.approverGroupIds;
+ if (!approverGroupIds || approverGroupIds.length === 0) {
+ return false;
+ }
+
+ // Check if user ID is directly in approverGroupIds (for individual approvers)
+ if (approverGroupIds.includes(userId)) {
+ return true;
+ }
+
+ // Check if user belongs to any of the approver groups
+ const userGroups = await client.rpc("groups_for_user", { uid: userId });
+ const userGroupIds = userGroups.data || [];
+ return approverGroupIds.some((groupId) => userGroupIds.includes(groupId));
+}
+
+export function canCancelRequest(
+ approvalRequest: ApprovalRequestForCancelCheck,
+ userId: string
+): boolean {
+ return (
+ approvalRequest.requestedBy === userId &&
+ approvalRequest.status === "Pending"
+ );
+}
+
+export async function cancelApprovalRequest(
+ client: SupabaseClient<Database>,
+ id: string,
+ userId: string
+) {
+ const existing = await client
+ .from("approvalRequest")
+ .select("id, status, requestedBy")
+ .eq("id", id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return { error: { message: "Approval request not found" }, data: null };
+ }
+
+ if (existing.data.status !== "Pending") {
+ return {
+ error: { message: "Approval request is not pending" },
+ data: null
+ };
+ }
+
+ if (existing.data.requestedBy !== userId) {
+ return {
+ error: { message: "Only the requester can cancel an approval request" },
+ data: null
+ };
+ }
+
+ return client
+ .from("approvalRequest")
+ .update({
+ status: "Cancelled",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", id)
+ .select("id")
+ .single();
+}
+
+export async function canViewApprovalRequest(
+ client: SupabaseClient<Database>,
+ approvalRequest: ApprovalRequestForViewCheck,
+ userId: string
+): Promise<boolean> {
+ if (approvalRequest.requestedBy === userId) {
+ return true;
+ }
+
+ return canApproveRequest(
+ client,
+ {
+ amount: approvalRequest.amount,
+ documentType: approvalRequest.documentType,
+ companyId: approvalRequest.companyId
+ },
+ userId
+ );
+}
+
+export async function createApprovalRequest(
+ client: SupabaseClient<Database>,
+ request: CreateApprovalRequestInput & { amount?: number }
+) {
+ return client
+ .from("approvalRequest")
+ .insert([
+ {
+ documentType: request.documentType,
+ documentId: request.documentId,
+ requestedBy: request.requestedBy,
+ amount: request.amount ?? null,
+ companyId: request.companyId,
+ createdBy: request.createdBy
+ }
+ ])
+ .select("id")
+ .single();
+}
+
+export async function deleteApprovalRule(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ await requireEntitlement(client, companyId, "APPROVAL_RULES");
+ return client
+ .from("approvalRule")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+}
+
+export async function getApprovalById(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ const baseRequest = await client
+ .from("approvalRequest")
+ .select("*")
+ .eq("id", id)
+ .single();
+
+ if (baseRequest.error || !baseRequest.data) {
+ return baseRequest;
+ }
+
+ const viewData = await client
+ .from("approvalRequests")
+ .select("documentReadableId, documentDescription")
+ .eq("id", id)
+ .single();
+
+ return {
+ data: {
+ ...baseRequest.data,
+ documentReadableId: viewData.data?.documentReadableId ?? null,
+ documentDescription: viewData.data?.documentDescription ?? null
+ },
+ error: null
+ };
+}
+
+export async function getApprovalRequestsByDocument(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ documentId: string
+) {
+ return client
+ .from("approvalRequests")
+ .select("*")
+ .eq("documentType", documentType)
+ .eq("documentId", documentId)
+ .order("requestedAt", { ascending: false });
+}
+
+export async function getApprovalRuleByAmount(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ companyId: string,
+ amount?: number
+) {
+ if (
+ !(await companyHasFeature(client, companyId, { feature: "APPROVAL_RULES" }))
+ ) {
+ return { data: null, error: null };
+ }
+
+ let query = client
+ .from("approvalRule")
+ .select("*")
+ .eq("documentType", documentType)
+ .eq("companyId", companyId)
+ .eq("enabled", true);
+
+ if (amount !== undefined && amount !== null) {
+ // The matching tier is the highest one whose floor is at or below the
+ // amount; the next tier's floor is where its coverage ends.
+ query = query.lte("lowerBoundAmount", amount);
+ } else {
+ query = query.eq("lowerBoundAmount", 0);
+ }
+
+ return query
+ .order("lowerBoundAmount", { ascending: false })
+ .order("id", { ascending: true })
+ .limit(1)
+ .maybeSingle();
+}
+
+export async function getApproverUserIdsForRule(
+ client: SupabaseClient<Database>,
+ rule: Pick<ApprovalRule, "approverGroupIds" | "defaultApproverId">
+): Promise<string[]> {
+ const groupIds = rule.approverGroupIds?.filter(Boolean) ?? [];
+ const defaultId = rule.defaultApproverId ?? null;
+
+ const fromGroups =
+ groupIds.length > 0
+ ? await client.rpc("users_for_groups", { groups: groupIds })
+ : { data: [] as string[], error: null };
+
+ if (fromGroups.error) {
+ logger.error(
+ "getApproverUserIdsForRule: users_for_groups failed",
+ fromGroups.error
+ );
+ return defaultId ? [defaultId] : [];
+ }
+
+ const ids = Array.isArray(fromGroups.data)
+ ? (fromGroups.data as string[])
+ : [];
+ const combined = defaultId
+ ? [...new Set([...ids, defaultId])]
+ : [...new Set(ids)];
+ return combined;
+}
+
+/**
+ * "Notified of spend" cascade resolver. When a tiered approval lands at
+ * a high tier, approvers of every enabled rule with a strictly lower
+ * `lowerBoundAmount` get pinged — visibility into spend that bypassed
+ * their tier. Returns deduped user IDs.
+ */
+export async function getLowerTierApproverUserIds(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ companyId: string,
+ amount: number | null | undefined
+): Promise<string[]> {
+ if (amount == null) return [];
+
+ const matched = await getApprovalRuleByAmount(
+ client,
+ documentType,
+ companyId,
+ amount
+ );
+ if (!matched.data) return [];
+
+ const lowerRules = await client
+ .from("approvalRule")
+ .select("approverGroupIds, defaultApproverId")
+ .eq("documentType", documentType)
+ .eq("companyId", companyId)
+ .eq("enabled", true)
+ .lt("lowerBoundAmount", matched.data.lowerBoundAmount ?? 0);
+
+ if (lowerRules.error || !lowerRules.data?.length) return [];
+
+ const expanded = await Promise.all(
+ lowerRules.data.map((rule) => getApproverUserIdsForRule(client, rule))
+ );
+ return [...new Set(expanded.flat())];
+}
+
+export async function getApprovalRuleById(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("approvalRule")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function getApprovalRules(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client.from("approvalRule").select("*").eq("companyId", companyId);
+}
+
+export async function getApprovalRulesForApprover(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ companyId: string
+) {
+ return client
+ .from("approvalRule")
+ .select("*")
+ .eq("documentType", documentType)
+ .eq("companyId", companyId)
+ .eq("enabled", true)
+ .order("lowerBoundAmount", { ascending: false });
+}
+
+export async function getApprovalsForUser(
+ client: SupabaseClient<Database>,
+ userId: string,
+ companyId: string,
+ args?: GenericQueryFilters & ApprovalFilters
+) {
+ let query = client
+ .from("approvalRequest")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId)
+ .eq("requestedBy", userId);
+
+ if (args?.documentType) {
+ query = query.eq("documentType", args.documentType);
+ }
+
+ if (args?.status) {
+ query = query.eq("status", args.status);
+ }
+
+ if (args?.dateFrom) {
+ query = query.gte("requestedAt", args.dateFrom);
+ }
+ if (args?.dateTo) {
+ query = query.lte("requestedAt", args.dateTo);
+ }
+
+ const requestedByUserBase = await query;
+
+ // Get readable fields from view for requestedByUser
+ const requestedByUser = await Promise.all(
+ (requestedByUserBase.data || []).map(async (approval) => {
+ const viewData = await client
+ .from("approvalRequests")
+ .select("documentReadableId, documentDescription")
+ .eq("id", approval.id)
+ .single();
+
+ return {
+ ...approval,
+ documentReadableId: viewData.data?.documentReadableId ?? null,
+ documentDescription: viewData.data?.documentDescription ?? null
+ };
+ })
+ );
+
+ let pendingQuery = client
+ .from("approvalRequest")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("status", "Pending")
+ .neq("requestedBy", userId);
+
+ if (args?.documentType) {
+ pendingQuery = pendingQuery.eq("documentType", args.documentType);
+ }
+
+ if (args?.dateFrom) {
+ pendingQuery = pendingQuery.gte("requestedAt", args.dateFrom);
+ }
+ if (args?.dateTo) {
+ pendingQuery = pendingQuery.lte("requestedAt", args.dateTo);
+ }
+
+ const allPending = await pendingQuery;
+
+ const pendingWithReadableFields = await Promise.all(
+ (allPending.data || []).map(async (approval) => {
+ const viewData = await client
+ .from("approvalRequests")
+ .select("documentReadableId, documentDescription")
+ .eq("id", approval.id)
+ .single();
+
+ return {
+ ...approval,
+ documentReadableId: viewData.data?.documentReadableId ?? null,
+ documentDescription: viewData.data?.documentDescription ?? null
+ };
+ })
+ );
+
+ const canApprovePromises = pendingWithReadableFields.map(async (approval) => {
+ const canApprove = await canApproveRequest(
+ client,
+ {
+ amount: approval.amount,
+ documentType: approval.documentType,
+ companyId: approval.companyId
+ },
+ userId
+ );
+ return canApprove ? approval : null;
+ });
+
+ const approvableByUser = (await Promise.all(canApprovePromises)).filter(
+ (approval): approval is NonNullable<typeof approval> => approval !== null
+ );
+
+ const allApprovals = [...requestedByUser, ...approvableByUser];
+
+ let filtered = allApprovals;
+ if (args?.status && args.status !== "Pending") {
+ filtered = allApprovals.filter((a) => a.status === args.status);
+ }
+
+ filtered.sort((a, b) => {
+ const aDate = new Date(a.requestedAt).getTime();
+ const bDate = new Date(b.requestedAt).getTime();
+ return bDate - aDate;
+ });
+
+ if (args?.limit) {
+ const offset = args.offset || 0;
+ filtered = filtered.slice(offset, offset + args.limit);
+ }
+
+ return {
+ data: filtered,
+ count: requestedByUserBase.count ?? allApprovals.length,
+ error: null
+ };
+}
+
+export async function getLatestApprovalRequestForDocument(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ documentId: string
+) {
+ const baseRequest = await client
+ .from("approvalRequest")
+ .select("*")
+ .eq("documentType", documentType)
+ .eq("documentId", documentId)
+ .eq("status", "Pending")
+ .order("requestedAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ if (baseRequest.error || !baseRequest.data) {
+ return baseRequest;
+ }
+
+ const viewData = await client
+ .from("approvalRequests")
+ .select("documentReadableId, documentDescription")
+ .eq("id", baseRequest.data.id)
+ .single();
+
+ return {
+ data: {
+ ...baseRequest.data,
+ documentReadableId: viewData.data?.documentReadableId ?? null,
+ documentDescription: viewData.data?.documentDescription ?? null
+ },
+ error: null
+ };
+}
+
+export async function getPendingApprovalsForApprover(
+ client: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+) {
+ const allPending = await client
+ .from("approvalRequest")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("status", "Pending")
+ .order("requestedAt", { ascending: false });
+
+ if (allPending.error || !allPending.data) {
+ return allPending;
+ }
+
+ const pendingWithReadableFields = await Promise.all(
+ allPending.data.map(async (approval) => {
+ const viewData = await client
+ .from("approvalRequests")
+ .select("documentReadableId, documentDescription")
+ .eq("id", approval.id)
+ .single();
+
+ return {
+ ...approval,
+ documentReadableId: viewData.data?.documentReadableId ?? null,
+ documentDescription: viewData.data?.documentDescription ?? null
+ };
+ })
+ );
+
+ // Use canApproveRequestInWindow to only show requests within user's specific
+ // approval window. That check relies on the amount-matched rule, which
+ // getApprovalRuleByAmount suppresses when APPROVAL_RULES is not entitled — so
+ // a company that configured rules and then downgraded would lose every
+ // in-flight pending request from this queue even though the document detail
+ // route (canApproveRequest, which does not degrade) can still approve them.
+ // Fall back to canApproveRequest when the feature is unavailable so existing
+ // approvals stay discoverable; entitled companies keep the exact window check.
+ const approvalRulesEnabled = await companyHasFeature(client, companyId, {
+ feature: "APPROVAL_RULES"
+ });
+ const canApprovePromises = pendingWithReadableFields.map(async (approval) => {
+ const approvalCheck = {
+ amount: approval.amount,
+ documentType: approval.documentType,
+ companyId: approval.companyId
+ };
+ const canApprove = approvalRulesEnabled
+ ? await canApproveRequestInWindow(client, approvalCheck, userId)
+ : await canApproveRequest(client, approvalCheck, userId);
+ return canApprove ? approval : null;
+ });
+
+ const approvableByUser = (await Promise.all(canApprovePromises)).filter(
+ (approval): approval is NonNullable<typeof approval> => approval !== null
+ );
+
+ return {
+ data: approvableByUser,
+ error: null
+ };
+}
+
+export async function hasPendingApproval(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ documentId: string
+): Promise<boolean> {
+ const result = await client
+ .from("approvalRequest")
+ .select("id")
+ .eq("documentType", documentType)
+ .eq("documentId", documentId)
+ .eq("status", "Pending")
+ .limit(1);
+
+ return (result.data?.length ?? 0) > 0;
+}
+
+export async function isApprovalRequired(
+ client: SupabaseClient<Database>,
+ documentType: (typeof approvalDocumentType)[number],
+ companyId: string,
+ amount?: number
+): Promise<boolean> {
+ const config = await getApprovalRuleByAmount(
+ client,
+ documentType,
+ companyId,
+ amount
+ );
+
+ if (!config.data) {
+ return false;
+ }
+
+ return config.data.enabled;
+}
+
+export async function rejectRequest(
+ db: Kysely<KyselyDatabase>,
+ id: string,
+ userId: string,
+ notes?: string
+) {
+ // Pre-flight check: verify approval request exists and is pending
+ const approvalRequest = await db
+ .selectFrom("approvalRequest")
+ .select(["id", "status", "documentType", "documentId"])
+ .where("id", "=", id)
+ .executeTakeFirst();
+
+ if (!approvalRequest) {
+ return { error: { message: "Approval request not found" }, data: null };
+ }
+
+ if (approvalRequest.status !== "Pending") {
+ return {
+ error: { message: "Approval request is not pending" },
+ data: null
+ };
+ }
+
+ const { documentType, documentId } = approvalRequest;
+ const now = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. Update approval request to "Rejected"
+ const updatedApproval = await trx
+ .updateTable("approvalRequest")
+ .set({
+ status: "Rejected",
+ decisionBy: userId,
+ decisionAt: now,
+ decisionNotes: notes || null,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", id)
+ .returning(["id", "documentType", "documentId"])
+ .executeTakeFirstOrThrow();
+
+ // 2. Update document status based on type
+ if (documentType === "purchaseOrder") {
+ const poUpdate = await trx
+ .updateTable("purchaseOrder")
+ .set({
+ status: "Rejected",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .where("status", "=", "Needs Approval")
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!poUpdate) {
+ throw new Error(
+ "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
+ );
+ }
+ }
+ // Note: qualityDocument rejection doesn't change status (stays Draft)
+
+ if (documentType === "supplier") {
+ const supplierUpdate = await trx
+ .updateTable("supplier")
+ .set({
+ supplierStatus: "Rejected",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!supplierUpdate) {
+ throw new Error("Failed to update supplier status");
+ }
+ }
+
+ return updatedApproval;
+ });
+
+ return { data: result, error: null };
+ } catch (error) {
+ // Transaction automatically rolled back on error
+ return {
+ error: {
+ message:
+ error instanceof Error ? error.message : "Failed to process rejection"
+ },
+ data: null
+ };
+ }
+}
+
+export async function upsertApprovalRule(
+ client: SupabaseClient<Database>,
+ rule: UpsertApprovalRuleInput
+) {
+ if ("id" in rule) {
+ const existing = await client
+ .from("approvalRule")
+ .select("companyId")
+ .eq("id", rule.id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "Rule not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "APPROVAL_RULES");
+
+ return client
+ .from("approvalRule")
+ .update(sanitize(rule))
+ .eq("id", rule.id)
+ .eq("companyId", existing.data.companyId)
+ .select("id")
+ .single();
+ }
+
+ await requireEntitlement(client, rule.companyId, "APPROVAL_RULES");
+
+ return client.from("approvalRule").insert([rule]).select("id").single();
+}
diff --git a/packages/ee/src/approvals/types.ts b/packages/ee/src/approvals/types.ts
new file mode 100644
index 0000000000..5a612d3951
--- /dev/null
+++ b/packages/ee/src/approvals/types.ts
@@ -0,0 +1,68 @@
+import type { Database } from "@carbon/database";
+import type { z } from "zod";
+import type {
+ ApprovalDocumentType,
+ approvalRequestValidator,
+ approvalRuleValidator
+} from "./models";
+
+// Derived straight from the DB types (NOT from `ReturnType<service>`) so this
+// client-safe barrel never pulls the server-only `service.ts` (which imports
+// `.server` modules) into the client graph. `getApprovalRuleByAmount` is a
+// `select("*")` on `approvalRule`; `getApprovalRequestsByDocument` a `select("*")`
+// on the `approvalRequests` view — so these are exactly those row shapes.
+
+export type ApprovalFilters = {
+ documentType?: ApprovalDocumentType | null;
+ status?: ApprovalStatus | null;
+ dateFrom?: string | null;
+ dateTo?: string | null;
+};
+
+export type ApprovalRequest =
+ Database["public"]["Views"]["approvalRequests"]["Row"];
+
+export type ApprovalHistory = ApprovalRequest[];
+
+export type ApprovalRequestForApproveCheck = {
+ amount: number | null;
+ documentType: ApprovalDocumentType;
+ companyId: string;
+};
+
+export type ApprovalRequestForCancelCheck = {
+ requestedBy: string;
+ status: string;
+};
+
+export type ApprovalRequestForViewCheck = {
+ requestedBy: string;
+ amount: number | null;
+ documentType: ApprovalDocumentType;
+ companyId: string;
+};
+
+export type ApprovalRule = Database["public"]["Tables"]["approvalRule"]["Row"];
+
+export type ApprovalDecision = "Approved" | "Rejected";
+
+export type ApprovalStatus = Database["public"]["Enums"]["approvalStatus"];
+
+export type CreateApprovalRequestInput = Omit<
+ z.infer<typeof approvalRequestValidator>,
+ "id"
+> & {
+ companyId: string;
+ requestedBy: string;
+ createdBy: string;
+};
+
+export type UpsertApprovalRuleInput =
+ | (Omit<z.infer<typeof approvalRuleValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof approvalRuleValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ });
diff --git a/packages/ee/src/console.server.ts b/packages/ee/src/console.server.ts
new file mode 100644
index 0000000000..789446b6a9
--- /dev/null
+++ b/packages/ee/src/console.server.ts
@@ -0,0 +1,132 @@
+import { randomInt } from "node:crypto";
+import type { Database } from "@carbon/database";
+import { sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Enterprise) console / kiosk mode. Enabling it provisions the
+ * protected "Console Operator" employee type (MES-only permissions) and a PIN
+ * for the enabling user — role provisioning, gated to the Business plan via the
+ * `PERMISSIONS` feature. The console settings route
+ * (`apps/erp/.../x+/settings+/people.tsx`) blocks this for Community/Starter
+ * before calling it; the `.server` file is server-only and the `@carbon/ee`
+ * package boundary carries the commercial license (see root LICENSE).
+ */
+export async function updateConsoleSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ consoleEnabled: boolean,
+ userId?: string
+) {
+ await requireEntitlement(client, companyId, "PERMISSIONS");
+ const update = await client
+ .from("companySettings")
+ .update(sanitize({ consoleEnabled }) as any)
+ .eq("id", companyId);
+
+ // When enabling, create "Console Operator" employee type if it doesn't exist
+ if (consoleEnabled) {
+ const existing = await client
+ .from("employeeType")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("systemType", "Console Operator")
+ .maybeSingle();
+
+ if (!existing.data) {
+ const newType = await client
+ .from("employeeType")
+ .insert({
+ name: "Console Operator",
+ companyId,
+ protected: true,
+ systemType: "Console Operator"
+ })
+ .select("id")
+ .single();
+
+ // Create default permissions for the Console Operator type.
+ // Only grant what's needed for MES operations — not ERP modules.
+ if (newType.data) {
+ const mesModules = [
+ {
+ module: "Production",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ {
+ module: "Inventory",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ {
+ module: "Resources",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ },
+ {
+ module: "Items",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ },
+ {
+ module: "Quality",
+ create: true,
+ update: true,
+ delete: false,
+ view: true
+ },
+ {
+ module: "People",
+ create: false,
+ update: false,
+ delete: false,
+ view: true
+ }
+ ];
+
+ const permissions = mesModules.map((m) => ({
+ employeeTypeId: newType.data.id,
+ module: m.module as "Accounting",
+ create: m.create ? [companyId] : [],
+ update: m.update ? [companyId] : [],
+ delete: m.delete ? [companyId] : [],
+ view: m.view ? [companyId] : []
+ }));
+
+ await client.from("employeeTypePermission").insert(permissions);
+ }
+ }
+
+ // Auto-generate a PIN for the enabling user if they don't have one
+ let generatedPin: string | null = null;
+ if (userId) {
+ const userEmployee = await client
+ .from("employee")
+ .select("id, pin" as any)
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (userEmployee.data && !(userEmployee.data as any).pin) {
+ generatedPin = randomInt(1000, 10000).toString();
+ await client
+ .from("employee")
+ .update({ pin: generatedPin } as any)
+ .eq("id", userId)
+ .eq("companyId", companyId);
+ }
+ }
+ }
+
+ return update;
+}
diff --git a/packages/ee/src/customer-portals.server.ts b/packages/ee/src/customer-portals.server.ts
new file mode 100644
index 0000000000..890ac9c9b6
--- /dev/null
+++ b/packages/ee/src/customer-portals.server.ts
@@ -0,0 +1,67 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial customer-portal AUTHORING — creating, editing, and deleting a
+ * company's customer portals, gated via the `CUSTOMER_PORTALS` feature. A
+ * customer portal is an `externalLink` row with `documentType: "Customer"`.
+ *
+ * These functions are DEDICATED to customer portals and do NOT touch the shared
+ * `upsertExternalLink` in `shared.service.ts`, which ALSO mints quote / RFQ /
+ * supplier-quote share links for community users — gating that shared function
+ * would break quote finalization. The public share page and the portal reads
+ * (`getCustomerPortals` / `getCustomerPortal`) DEGRADE via `companyHasFeature`
+ * and stay in the community module; only the write body is commercial.
+ *
+ * The entitlement LOCK lives INSIDE these commercial functions (see
+ * `entitlements.server`) so it cannot be stripped from open-licensed app code.
+ * Keeping the delete here also removes it as an ungated `shared_deleteCustomerPortal`
+ * MCP tool — an ungated MCP write path would otherwise route around the gate.
+ */
+
+export async function upsertCustomerPortal(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ portal:
+ | Omit<Database["public"]["Tables"]["externalLink"]["Insert"], "companyId">
+ | (Database["public"]["Tables"]["externalLink"]["Update"] & {
+ id: string;
+ })
+) {
+ await requireEntitlement(client, companyId, "CUSTOMER_PORTALS");
+
+ if ("id" in portal && portal.id) {
+ return client
+ .from("externalLink")
+ .update({ ...portal, documentType: "Customer" })
+ .eq("id", portal.id)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("externalLink")
+ .insert({
+ ...portal,
+ documentType: "Customer",
+ companyId
+ } as Database["public"]["Tables"]["externalLink"]["Insert"])
+ .select("id")
+ .single();
+}
+
+export async function deleteCustomerPortal(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ await requireEntitlement(client, companyId, "CUSTOMER_PORTALS");
+
+ return client
+ .from("externalLink")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+}
diff --git a/packages/ee/src/entitlements.server.ts b/packages/ee/src/entitlements.server.ts
new file mode 100644
index 0000000000..7887c671f3
--- /dev/null
+++ b/packages/ee/src/entitlements.server.ts
@@ -0,0 +1,50 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { Feature } from "./plan";
+import { companyHasFeature } from "./plan.server";
+
+/**
+ * The commercial-feature LOCK. Call `requireEntitlement` at the top of every
+ * commercial (`packages/ee`) feature function whose execution should require a
+ * license — role authoring, approval rules, console mode, etc.
+ *
+ * Why this lives in `@carbon/ee` and not in an app route: the entitlement
+ * decision must sit on the COMMERCIAL side of the license boundary. A gate in
+ * open (community-licensed) app code is a deletable `if` — removing it is not a
+ * license breach and routes around the paywall. A gate inside `@carbon/ee` can
+ * only be stripped by editing commercial code, which is a breach, and the
+ * feature body it guards is commercial too, so there is nothing to route around.
+ * (Same design as Twenty CRM's in-service `hasFeatureOrThrow` checks.)
+ *
+ * `companyHasFeature` is the single source of truth for "is this company
+ * entitled" — Community edition is blocked, Enterprise/Test self-hosted pass,
+ * Cloud is plan-based. It is also the ONE place the future license-key server
+ * plugs in (a signed, server-bound validity token), so every feature inherits
+ * that enforcement without touching a call site.
+ *
+ * Use `requireEntitlement` (throws) at AUTHORING entry points. Use the boolean
+ * `companyHasFeature` directly on RUNTIME paths that must DEGRADE rather than
+ * throw when a company is not entitled (e.g. "no approval rule applies" instead
+ * of crashing document creation).
+ *
+ * The open route may ALSO call `requireFeature` (`plan.server`) for a friendly
+ * upgrade redirect — that is UX only; this is the enforcement.
+ */
+export class EntitlementError extends Error {
+ readonly feature: Feature;
+
+ constructor(feature: Feature, message?: string) {
+ super(message ?? `${feature} requires an upgraded plan`);
+ this.name = "EntitlementError";
+ this.feature = feature;
+ }
+}
+
+export async function requireEntitlement(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ feature: Feature
+): Promise<void> {
+ if (await companyHasFeature(client, companyId, { feature })) return;
+ throw new EntitlementError(feature);
+}
diff --git a/packages/ee/src/forecast.server.ts b/packages/ee/src/forecast.server.ts
new file mode 100644
index 0000000000..3ca10dc2bf
--- /dev/null
+++ b/packages/ee/src/forecast.server.ts
@@ -0,0 +1,199 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Business) demand-forecast AUTHORING — upserting and deleting a
+ * company's `demandForecast` AND `demandProjection` rows, gated to the Business
+ * plan via the `FORECAST` feature. The MRP consumer (`planning/mrp/mrp.ts`) that
+ * READS forecasts is a separate concern and is not gated here.
+ *
+ * The entitlement LOCK lives INSIDE these commercial functions (see
+ * `entitlements.server`) so it cannot be stripped from open-licensed app code.
+ * Moving them out of the community `production.service.ts` also removes them as
+ * ungated `production_upsert*` / `production_delete*` MCP tools — an ungated MCP
+ * write path would otherwise route around the gate.
+ *
+ * The input shapes are declared inline (they carry no `~/` validator), so
+ * `@carbon/ee` never imports app code.
+ */
+
+export async function upsertDemandForecasts(
+ client: SupabaseClient<Database>,
+ forecasts: Array<{
+ itemId: string;
+ locationId: string;
+ periodId: string;
+ forecastQuantity: number;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }>
+) {
+ // Source companyId from the payload so the entitlement check (the lock) can
+ // run before any write. An empty batch writes nothing and needs no gate.
+ const companyId = forecasts[0]?.companyId;
+ if (companyId) {
+ await requireEntitlement(client, companyId, "FORECAST");
+ }
+
+ // Delete existing forecasts with 0 quantity, upsert others
+ const toDelete = forecasts.filter((f) => f.forecastQuantity === 0);
+ const toUpsert = forecasts.filter((f) => f.forecastQuantity > 0);
+
+ const promises = [];
+
+ if (toDelete.length > 0) {
+ for (const forecast of toDelete) {
+ promises.push(
+ client
+ .from("demandForecast")
+ .delete()
+ .eq("itemId", forecast.itemId)
+ .eq("locationId", forecast.locationId)
+ .eq("periodId", forecast.periodId)
+ .eq("companyId", forecast.companyId)
+ );
+ }
+ }
+
+ if (toUpsert.length > 0) {
+ promises.push(
+ client.from("demandForecast").upsert(
+ toUpsert.map((f) => ({
+ ...f,
+ updatedBy: f.updatedBy ?? f.createdBy ?? "system",
+ updatedAt: new Date().toISOString()
+ })),
+ {
+ onConflict: "itemId,locationId,periodId,companyId"
+ }
+ )
+ );
+ }
+
+ const results = await Promise.all(promises);
+ const hasError = results.some((r) => r.error);
+
+ return {
+ data: hasError ? null : toUpsert,
+ error: hasError ? results.find((r) => r.error)?.error : null
+ };
+}
+
+export async function deleteDemandForecasts(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ futurePeriodIds: string[];
+ }
+) {
+ const { itemId, locationId, companyId, futurePeriodIds } = params;
+
+ await requireEntitlement(client, companyId, "FORECAST");
+
+ const result = await client
+ .from("demandForecast")
+ .delete()
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", futurePeriodIds);
+
+ return {
+ data: result.data,
+ error: result.error
+ };
+}
+
+export async function upsertDemandProjections(
+ client: SupabaseClient<Database>,
+ forecasts: Array<{
+ itemId: string;
+ locationId: string;
+ periodId: string;
+ forecastQuantity: number;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }>
+) {
+ // Source companyId from the payload so the entitlement check (the lock) can
+ // run before any write. An empty batch writes nothing and needs no gate.
+ const companyId = forecasts[0]?.companyId;
+ if (companyId) {
+ await requireEntitlement(client, companyId, "FORECAST");
+ }
+
+ // Delete existing forecasts with 0 quantity, upsert others
+ const toDelete = forecasts.filter((f) => f.forecastQuantity === 0);
+ const toUpsert = forecasts.filter((f) => f.forecastQuantity > 0);
+
+ const promises = [];
+
+ if (toDelete.length > 0) {
+ for (const forecast of toDelete) {
+ promises.push(
+ client
+ .from("demandProjection")
+ .delete()
+ .eq("itemId", forecast.itemId)
+ .eq("locationId", forecast.locationId)
+ .eq("periodId", forecast.periodId)
+ .eq("companyId", forecast.companyId)
+ );
+ }
+ }
+
+ if (toUpsert.length > 0) {
+ promises.push(
+ client.from("demandProjection").upsert(
+ toUpsert.map((f) => ({
+ ...f,
+ updatedBy: f.updatedBy ?? f.createdBy ?? "system",
+ updatedAt: new Date().toISOString()
+ })),
+ {
+ onConflict: "itemId,locationId,periodId,companyId"
+ }
+ )
+ );
+ }
+
+ const results = await Promise.all(promises);
+ const hasError = results.some((r) => r.error);
+
+ return {
+ data: hasError ? null : toUpsert,
+ error: hasError ? results.find((r) => r.error)?.error : null
+ };
+}
+
+export async function deleteDemandProjections(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ futurePeriodIds: string[];
+ }
+) {
+ const { itemId, locationId, companyId, futurePeriodIds } = params;
+
+ await requireEntitlement(client, companyId, "FORECAST");
+
+ const result = await client
+ .from("demandProjection")
+ .delete()
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", futurePeriodIds);
+
+ return {
+ data: result.data,
+ error: result.error
+ };
+}
diff --git a/packages/ee/src/permissions.server.ts b/packages/ee/src/permissions.server.ts
new file mode 100644
index 0000000000..8439b0ac8a
--- /dev/null
+++ b/packages/ee/src/permissions.server.ts
@@ -0,0 +1,478 @@
+import type { Result } from "@carbon/auth";
+import { error, getClaims, getPermissionCacheKey, success } from "@carbon/auth";
+import { logPermissionChange } from "@carbon/auth/auth-events.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database, Json } from "@carbon/database";
+import { redis } from "@carbon/kv";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Enterprise) RBAC authoring — the single, licensed source of truth
+ * for creating/editing employee types, editing an individual user's permissions,
+ * and building the flattened `userPermission.permissions` object. Gated to the
+ * Business plan via the `PERMISSIONS` feature (`@carbon/ee/plan`); Community ships
+ * an "everyone is an admin" experience so none of this is reachable there.
+ *
+ * Consumed on the server by the ERP authoring routes AND by the `@carbon/jobs`
+ * bulk-edit task (`carbon/update-permissions`), which previously carried its own
+ * drifting copy of `updatePermissions` — this is now the only copy.
+ *
+ * The low-level community primitives (`setUserPermissions`,
+ * `makePermissionsFromEmployeeType`) stay in the ERP `users.server.ts`: they are
+ * shared plumbing the invite flow depends on, not authoring.
+ */
+
+export type CompanyPermission = {
+ view: boolean;
+ create: boolean;
+ update: boolean;
+ delete: boolean;
+};
+
+export type Permission = {
+ view: string[];
+ create: string[];
+ update: string[];
+ delete: string[];
+};
+
+type ModuleName = { name: string | null };
+
+type EmployeeTypePermissionRow = {
+ view: string[];
+ create: string[];
+ update: string[];
+ delete: string[];
+ module: string | null;
+};
+
+// Uppercase the first letter only (mirrors the ERP `~/utils/string` capitalize),
+// which `@carbon/ee` cannot import.
+function capitalize(words: string) {
+ const [first, ...otherLetters] = words;
+ return [first?.toLocaleUpperCase() ?? "", ...otherLetters].join("");
+}
+
+function isClaimPermission(key: string, value: unknown) {
+ const action = key.split("_")[1];
+ return (
+ action !== undefined &&
+ ["view", "create", "update", "delete"].includes(action) &&
+ Array.isArray(value)
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Employee-type CRUD
+// ---------------------------------------------------------------------------
+
+export async function deleteEmployeeType(
+ client: SupabaseClient<Database>,
+ employeeTypeId: string,
+ companyId: string
+) {
+ await requireEntitlement(client, companyId, "PERMISSIONS");
+ return client
+ .from("employeeType")
+ .delete()
+ .eq("id", employeeTypeId)
+ .eq("companyId", companyId)
+ .eq("protected", false);
+}
+
+export async function insertEmployeeType(
+ client: SupabaseClient<Database>,
+ employeeType: { name: string; companyId: string }
+) {
+ await requireEntitlement(client, employeeType.companyId, "PERMISSIONS");
+ return client
+ .from("employeeType")
+ .insert([employeeType])
+ .select("id")
+ .single();
+}
+
+export async function upsertEmployeeType(
+ client: SupabaseClient<Database>,
+ employeeType:
+ | { name: string; companyId: string }
+ | { id: string; name: string }
+) {
+ if ("id" in employeeType) {
+ // The update input carries no companyId — read it from the row so the
+ // entitlement check (the lock) can run before the write.
+ const existing = await client
+ .from("employeeType")
+ .select("companyId")
+ .eq("id", employeeType.id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "Employee type not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "PERMISSIONS");
+
+ return client
+ .from("employeeType")
+ .update(employeeType)
+ .eq("id", employeeType.id)
+ .eq("companyId", existing.data.companyId)
+ .select("id")
+ .single();
+ }
+
+ await requireEntitlement(client, employeeType.companyId, "PERMISSIONS");
+ return client
+ .from("employeeType")
+ .insert([employeeType])
+ .select("id")
+ .single();
+}
+
+export async function upsertEmployeeTypePermissions(
+ client: SupabaseClient<Database>,
+ employeeTypeId: string,
+ companyId: string,
+ permissions: { name: string; permission: CompanyPermission }[]
+) {
+ await requireEntitlement(client, companyId, "PERMISSIONS");
+ const employeeTypePermissions = permissions.map(({ name, permission }) => ({
+ employeeTypeId,
+ module: capitalize(name) as "Accounting",
+ view: permission.view ? [companyId] : [],
+ create: permission.create ? [companyId] : [],
+ update: permission.update ? [companyId] : [],
+ delete: permission.delete ? [companyId] : []
+ }));
+
+ return client.from("employeeTypePermission").upsert(employeeTypePermissions);
+}
+
+// ---------------------------------------------------------------------------
+// Permission-object translators (claims / employee-type / UI grid shapes)
+// ---------------------------------------------------------------------------
+
+export function makeEmptyPermissionsFromModules(data: ModuleName[]) {
+ return data.reduce<
+ Record<string, { name: string; permission: CompanyPermission }>
+ >((acc, m) => {
+ if (m.name && m.name !== "Messaging") {
+ acc[m.name] = {
+ name: m.name.toLowerCase(),
+ permission: {
+ view: false,
+ create: false,
+ update: false,
+ delete: false
+ }
+ };
+ }
+ return acc;
+ }, {});
+}
+
+export function makeCompanyPermissionsFromClaims(
+ claims: Json[] | null,
+ companyId: string
+) {
+ if (typeof claims !== "object" || claims === null) return null;
+ const permissions: Record<string, CompanyPermission> = {};
+ let role: string | null = null;
+
+ Object.entries(claims).forEach(([key, value]) => {
+ // `isClaimPermission` guarantees `value` is a string[] and `key` has an
+ // action segment, so `module` is present and the array branch is the only one.
+ if (!isClaimPermission(key, value) || !Array.isArray(value)) return;
+ const [module, action] = key.split("_");
+ if (module === undefined) return;
+
+ const perm = permissions[module] ?? {
+ view: false,
+ create: false,
+ update: false,
+ delete: false
+ };
+
+ if (action === "view") perm.view = value.includes(companyId);
+ else if (action === "create") perm.create = value.includes(companyId);
+ else if (action === "update") perm.update = value.includes(companyId);
+ else if (action === "delete") perm.delete = value.includes(companyId);
+
+ permissions[module] = perm;
+ });
+
+ if ("role" in claims) {
+ role = claims.role as string;
+ }
+
+ if ("items" in permissions) {
+ delete permissions.items;
+ }
+
+ if ("messaging" in permissions) {
+ delete permissions.messaging;
+ }
+
+ return { permissions, role };
+}
+
+export function makeCompanyPermissionsFromEmployeeType(
+ data: EmployeeTypePermissionRow[],
+ companyId: string
+) {
+ const result: Record<
+ string,
+ { name: string; permission: CompanyPermission }
+ > = {};
+ if (!data) return result;
+ data.forEach((permission) => {
+ if (!permission.module) {
+ throw new Error(
+ `Module is missing for permission ${JSON.stringify(permission)}`
+ );
+ } else {
+ result[permission.module] = {
+ name: permission.module.toLowerCase(),
+ permission: {
+ view: permission.view.includes(companyId),
+ create: permission.create.includes(companyId),
+ update: permission.update.includes(companyId),
+ delete: permission.delete.includes(companyId)
+ }
+ };
+ }
+ });
+
+ if ("items" in result) {
+ delete result.items;
+ }
+
+ if ("Messaging" in result) {
+ delete result.Messaging;
+ }
+
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// The write path — builds and persists the flattened permission object
+// ---------------------------------------------------------------------------
+
+export async function updateEmployee(
+ client: SupabaseClient<Database>,
+ {
+ id,
+ employeeType,
+ permissions,
+ companyId,
+ actorId,
+ ip
+ }: {
+ id: string;
+ employeeType: string;
+ permissions: Record<string, CompanyPermission>;
+ companyId: string;
+ actorId?: string;
+ ip?: string;
+ }
+): Promise<Result> {
+ await requireEntitlement(client, companyId, "PERMISSIONS");
+ const updateEmployeeEmployeeType = await client
+ .from("employee")
+ .upsert([{ id, companyId, employeeTypeId: employeeType }]);
+
+ if (updateEmployeeEmployeeType.error)
+ return error(updateEmployeeEmployeeType.error, "Failed to update employee");
+
+ return updatePermissions(client, {
+ id,
+ permissions,
+ companyId,
+ actorId,
+ ip
+ });
+}
+
+export async function updatePermissions(
+ client: SupabaseClient<Database>,
+ {
+ id,
+ permissions,
+ companyId,
+ addOnly = false,
+ actorId,
+ ip
+ }: {
+ id: string;
+ permissions: Record<string, CompanyPermission>;
+ companyId: string;
+ addOnly?: boolean;
+ actorId?: string;
+ ip?: string;
+ }
+): Promise<Result> {
+ await requireEntitlement(client, companyId, "PERMISSIONS");
+ const claimsAdmin = await client.rpc("is_claims_admin", {
+ company: companyId
+ });
+ if (claimsAdmin.error)
+ return error(claimsAdmin.error, "Failed to check claims admin");
+ if (claimsAdmin.data === true) {
+ const claims = await getClaims(client, id);
+
+ if (claims.error) return error(claims.error, "Failed to get claims");
+
+ const updatedPermissions = (
+ typeof claims.data !== "object" ||
+ Array.isArray(claims.data) ||
+ claims.data === null
+ ? {}
+ : claims.data
+ ) as Record<string, string[]>;
+ delete updatedPermissions.role;
+
+ // Snapshot the effective grant set BEFORE the in-place mutation below, so
+ // the audit event carries an honest before/after diff (NIST 3.3.1/3.3.2).
+ const beforePermissions = structuredClone(updatedPermissions);
+
+ // add any missing claims to the current claims
+ Object.keys(permissions).forEach((name) => {
+ const module = name.toLowerCase();
+ if (!(`${module}_view` in updatedPermissions)) {
+ updatedPermissions[`${module}_view`] = [];
+ }
+ if (!(`${module}_create` in updatedPermissions)) {
+ updatedPermissions[`${module}_create`] = [];
+ }
+ if (!(`${module}_update` in updatedPermissions)) {
+ updatedPermissions[`${module}_update`] = [];
+ }
+ if (!(`${module}_delete` in updatedPermissions)) {
+ updatedPermissions[`${module}_delete`] = [];
+ }
+ });
+
+ if (addOnly) {
+ Object.entries(permissions).forEach(([name, permission]) => {
+ const module = name.toLowerCase();
+ if (
+ permission.view &&
+ !updatedPermissions[`${module}_view`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_view`]!.push(companyId);
+ }
+ if (
+ permission.create &&
+ !updatedPermissions[`${module}_create`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_create`]!.push(companyId);
+ }
+ if (
+ permission.update &&
+ !updatedPermissions[`${module}_update`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_update`]!.push(companyId);
+ }
+ if (
+ permission.delete &&
+ !updatedPermissions[`${module}_delete`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_delete`]!.push(companyId);
+ }
+ });
+ } else {
+ Object.entries(permissions).forEach(([name, permission]) => {
+ const module = name.toLowerCase();
+ if (permission.view) {
+ if (!updatedPermissions[`${module}_view`]?.includes(companyId)) {
+ updatedPermissions[`${module}_view`] = [
+ ...(updatedPermissions[`${module}_view`] ?? []),
+ companyId
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_view`] = (
+ updatedPermissions[`${module}_view`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.create) {
+ if (!updatedPermissions[`${module}_create`]?.includes(companyId)) {
+ updatedPermissions[`${module}_create`] = [
+ ...(updatedPermissions[`${module}_create`] ?? []),
+ companyId
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_create`] = (
+ updatedPermissions[`${module}_create`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.update) {
+ if (!updatedPermissions[`${module}_update`]?.includes(companyId)) {
+ updatedPermissions[`${module}_update`] = [
+ ...(updatedPermissions[`${module}_update`] ?? []),
+ companyId
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_update`] = (
+ updatedPermissions[`${module}_update`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.delete) {
+ if (!updatedPermissions[`${module}_delete`]?.includes(companyId)) {
+ updatedPermissions[`${module}_delete`] = [
+ ...(updatedPermissions[`${module}_delete`] ?? []),
+ companyId
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_delete`] = (
+ updatedPermissions[`${module}_delete`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+ });
+ }
+
+ // The "0" global-company wildcard is retired (NIST 800-171 3.1.5). Strip it
+ // from every array so it can never be persisted to the authoritative table.
+ for (const key of Object.keys(updatedPermissions)) {
+ const value = updatedPermissions[key];
+ if (Array.isArray(value)) {
+ updatedPermissions[key] = value.filter((c: string) => c !== "0");
+ }
+ }
+
+ const permissionsUpdate = await getCarbonServiceRole()
+ .from("userPermission")
+ .update({ permissions: updatedPermissions })
+ .eq("id", id);
+ if (permissionsUpdate.error)
+ return error(permissionsUpdate.error, "Failed to update claims");
+
+ await redis.del(getPermissionCacheKey(id));
+
+ // Audit the change (NIST 800-171 3.3.1/3.3.2): actor, target, before/after.
+ logPermissionChange({
+ actor: actorId,
+ targetUserId: id,
+ companyId,
+ ip,
+ before: beforePermissions,
+ after: updatedPermissions,
+ reason: addOnly ? "bulk-add" : "bulk-edit"
+ });
+
+ return success("Permissions updated");
+ }
+
+ return error(null, "You do not have permission to update permissions");
+}
diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.ts
index 06e48e22a2..d6c9b2ba0c 100644
--- a/packages/ee/src/plan.server.ts
+++ b/packages/ee/src/plan.server.ts
@@ -129,3 +129,46 @@ export async function requirePlan({
);
}
}
+
+/**
+ * Like `companyHasPlan`, but the **Community** edition is ALWAYS gated: it has no
+ * license, so a plan-gated feature is off regardless of the (absent) plan row.
+ * Enterprise/Test self-hosted PASS; Cloud is plan-based; bypass/carbon-owned as
+ * in `companyHasPlan`.
+ *
+ * Use this (not `companyHasPlan`/`requirePlan`) for features that must be BLOCKED
+ * on Community — RBAC authoring, console/kiosk mode — rather than merely paywalled
+ * on Cloud. `companyHasPlan` deliberately returns true for every non-Cloud edition
+ * (a self-hosted feature toggle), which is wrong for these.
+ */
+export async function companyHasFeature(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ spec: GateSpec
+): Promise<boolean> {
+ if (CarbonEdition === Edition.Community) return false;
+ return companyHasPlan(client, companyId, spec);
+}
+
+/** Throws a redirect with flash when `companyHasFeature` is false. */
+export async function requireFeature({
+ request,
+ client,
+ companyId,
+ redirectTo,
+ message,
+ ...spec
+}: RequirePlanArgs): Promise<void> {
+ if (await companyHasFeature(client, companyId, spec as GateSpec)) return;
+
+ throw redirect(
+ redirectTo,
+ await flash(
+ request,
+ error(
+ null,
+ message ?? defaultUpgradeMessage(resolveRequirement(spec as GateSpec))
+ )
+ )
+ );
+}
diff --git a/packages/ee/src/plan.ts b/packages/ee/src/plan.ts
index f5bbf14087..35ef5a746e 100644
--- a/packages/ee/src/plan.ts
+++ b/packages/ee/src/plan.ts
@@ -8,6 +8,10 @@ import type { IntegrationID } from "./index";
export const FEATURE_PLANS = {
API_KEYS: [Plan.Business, Plan.Partner],
WEBHOOKS: [Plan.Business, Plan.Partner],
+ // The MCP server (POST /api/mcp) — machine/agent access to the ERP tools.
+ // Off on Community/Starter; enforced at the single route choke point via
+ // companyHasFeature, covering both the OAuth-connector and carbon-key paths.
+ MCP: [Plan.Business, Plan.Partner],
INTEGRATIONS: [Plan.Business, Plan.Partner],
SALES_RULES: [Plan.Business, Plan.Partner],
AUDIT_LOG: [Plan.Business, Plan.Partner],
@@ -17,7 +21,16 @@ export const FEATURE_PLANS = {
AI_AGENT: [Plan.Business, Plan.Partner],
WORKFLOWS: [Plan.Business, Plan.Partner],
FORECAST: [Plan.Business, Plan.Partner],
- TWO_FACTOR: [Plan.Business, Plan.Partner]
+ TWO_FACTOR: [Plan.Business, Plan.Partner],
+ // Authoring RBAC — creating/editing employee types, editing an individual
+ // user's permissions, and console (kiosk) mode. Community ships an
+ // "everyone is an admin" experience: you can add users but not author roles
+ // or modify permissions.
+ PERMISSIONS: [Plan.Business, Plan.Partner],
+ // Tiered document-approval rules (POs by amount, quality docs, suppliers).
+ APPROVAL_RULES: [Plan.Business, Plan.Partner],
+ // Company backup / restore (self-service export + restore of company data).
+ BACKUPS: [Plan.Business, Plan.Partner]
} as const satisfies Record<string, Plan[]>;
export type Feature = keyof typeof FEATURE_PLANS;
diff --git a/packages/ee/src/rules/sales/invoice-shipto.test.ts b/packages/ee/src/rules/sales/invoice-shipto.test.ts
index 25ef93765c..c40d395405 100644
--- a/packages/ee/src/rules/sales/invoice-shipto.test.ts
+++ b/packages/ee/src/rules/sales/invoice-shipto.test.ts
@@ -14,7 +14,7 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("../../plan.server", () => ({
- companyHasPlan: async () => true
+ companyHasFeature: async () => true
}));
import { evaluateSalesRulesForSalesDocument } from "./server";
diff --git a/packages/ee/src/rules/sales/server.ts b/packages/ee/src/rules/sales/server.ts
index a2fa56cbce..ade11d87c0 100644
--- a/packages/ee/src/rules/sales/server.ts
+++ b/packages/ee/src/rules/sales/server.ts
@@ -17,7 +17,7 @@ import {
type Violation
} from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { companyHasPlan } from "../../plan.server";
+import { companyHasFeature } from "../../plan.server";
import { itemPostingGroupIdFromEmbed } from "../storage/context";
import {
buildConditionValueResolver,
@@ -45,7 +45,7 @@ export const isSalesRulesEnabledForCompany = (
client: Client,
companyId: string
): Promise<boolean> =>
- companyHasPlan(client, companyId, { feature: "SALES_RULES" });
+ companyHasFeature(client, companyId, { feature: "SALES_RULES" });
// ---------------------------------------------------------------------------
// Per-line evaluator — single entry point the sales line actions call
diff --git a/packages/ee/src/rules/sales/service.ts b/packages/ee/src/rules/sales/service.ts
index 1bcc1912c0..8a2105dc37 100644
--- a/packages/ee/src/rules/sales/service.ts
+++ b/packages/ee/src/rules/sales/service.ts
@@ -289,47 +289,7 @@ export async function getSalesRulesList(
);
}
-export async function assignSalesRule(
- client: SupabaseClient<Database>,
- args: { itemId: string; ruleId: string; companyId: string; createdBy: string }
-) {
- // Preflight: rule must exist in this company. Without this, callers could
- // insert a foreign rule id; the evaluator filters defensively but the
- // orphan row still inflates assignment counts.
- const ruleRes = await client
- .from("enforcementRule")
- .select("id")
- .eq("id", args.ruleId)
- .eq("companyId", args.companyId)
- .eq("family", "sales")
- .single();
- if (ruleRes.error || !ruleRes.data) {
- return {
- data: null,
- error: ruleRes.error ?? new Error("Rule not found")
- };
- }
-
- return client
- .from("enforcementRuleItemAssignment")
- .insert({
- itemId: args.itemId,
- ruleId: args.ruleId,
- companyId: args.companyId,
- createdBy: args.createdBy
- })
- .select("itemId, ruleId")
- .single();
-}
-
-export async function unassignSalesRule(
- client: SupabaseClient<Database>,
- args: { itemId: string; ruleId: string; companyId: string }
-) {
- return client
- .from("enforcementRuleItemAssignment")
- .delete()
- .eq("itemId", args.itemId)
- .eq("ruleId", args.ruleId)
- .eq("companyId", args.companyId);
-}
+// `assignSalesRule` / `unassignSalesRule` (authoring writes) moved to
+// `../service.server.ts` (`@carbon/ee/rules.server`) — they embed
+// `requireEntitlement("SALES_RULES")` and so are server-only, which must not
+// reach the client-safe `@carbon/ee/rules` barrel this file feeds.
diff --git a/packages/ee/src/rules/server.ts b/packages/ee/src/rules/server.ts
index 1a47834a99..eea6f4c6e6 100644
--- a/packages/ee/src/rules/server.ts
+++ b/packages/ee/src/rules/server.ts
@@ -14,6 +14,19 @@ export {
resolveSalesOrderShipTo,
type SalesDocumentType
} from "./sales/server";
+// Enforcement-rule AUTHORING writes for both families (server-only; embed
+// `requireEntitlement`). Kept out of the client-safe `@carbon/ee/rules` barrel.
+export {
+ assignSalesRule,
+ assignStorageRule,
+ deleteEnforcementRule,
+ type EnforcementRuleFamily,
+ type EnforcementRuleInsert,
+ type EnforcementRuleUpdate,
+ unassignSalesRule,
+ unassignStorageRule,
+ upsertEnforcementRule
+} from "./service.server";
export {
dedupeViolations,
type EvaluateLinesForSurfaceArgs,
diff --git a/packages/ee/src/rules/service.server.ts b/packages/ee/src/rules/service.server.ts
new file mode 100644
index 0000000000..fdd2a7b85b
--- /dev/null
+++ b/packages/ee/src/rules/service.server.ts
@@ -0,0 +1,284 @@
+// Server-only enforcement-rule AUTHORING (storage + sales families).
+//
+// The commercial LOCK for both rule families: every write here calls
+// `requireEntitlement` before touching the DB, so the gate sits on the
+// commercial side of the license boundary and cannot be stripped from open
+// route code. Community edition → blocked (`STORAGE_RULES` / `SALES_RULES`).
+//
+// This file is server-only (`requireEntitlement` → `entitlements.server` →
+// `plan.server`) and is therefore reached ONLY through `@carbon/ee/rules.server`
+// (`./server.ts`), never the client-safe `@carbon/ee/rules` barrel. The
+// client-safe cross-app QUERIES stay in `./sales/service.ts` / `./storage/service.ts`.
+
+import type { Database, Json } from "@carbon/database";
+import type { ConditionAst, Severity, TargetType } from "@carbon/utils";
+import { datetime, sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "../entitlements.server";
+import type { Feature } from "../plan";
+
+// -----------------------------------------------------------------------------
+// Enforcement Rules (storage + sales families)
+// -----------------------------------------------------------------------------
+// Both rule families live in ONE `enforcementRule` table discriminated by
+// `family`. The admin CRUD is written once here; callers pass their family
+// explicitly. The `family` discriminator also chooses the commercial feature to
+// require — sales → `SALES_RULES`, storage → `STORAGE_RULES`.
+
+export type EnforcementRuleFamily =
+ Database["public"]["Enums"]["enforcementRuleFamily"];
+
+const featureForFamily = (family: EnforcementRuleFamily): Feature =>
+ family === "sales" ? "SALES_RULES" : "STORAGE_RULES";
+
+/** Item-scoping columns shared by both families (empty arrays = every item). */
+type RuleItemFilterFields = {
+ filteredItemTypes?: string[];
+ filteredItemGroupIds?: string[];
+ filteredItemMatchAll?: boolean;
+};
+
+/**
+ * Storage-family-only shape. The DB pins sales rows to `targetType: 'item'` /
+ * `appliesToAll: false` via the `enforcementRule_sales_shape` CHECK, so these
+ * stay optional here and simply go unset for sales.
+ */
+type RuleTargetFields = {
+ targetType?: Database["public"]["Enums"]["enforcementRuleTargetType"];
+ appliesToAll?: boolean;
+};
+
+type RuleSurfaces = Database["public"]["Enums"]["enforcementRuleSurface"][];
+
+export type EnforcementRuleInsert = RuleItemFilterFields &
+ RuleTargetFields & {
+ name: string;
+ description?: string | null;
+ message: string;
+ severity: Severity;
+ conditionAst: ConditionAst;
+ surfaces: RuleSurfaces;
+ active: boolean;
+ createdBy: string;
+ customFields?: Json;
+ };
+
+export type EnforcementRuleUpdate = RuleItemFilterFields &
+ RuleTargetFields & {
+ id: string;
+ name: string;
+ description?: string | null;
+ message: string;
+ severity: Severity;
+ conditionAst: ConditionAst;
+ surfaces: RuleSurfaces;
+ active: boolean;
+ updatedBy: string;
+ customFields?: Json;
+ };
+
+export async function upsertEnforcementRule(
+ client: SupabaseClient<Database>,
+ family: EnforcementRuleFamily,
+ companyId: string,
+ rule: EnforcementRuleInsert | EnforcementRuleUpdate
+) {
+ await requireEntitlement(client, companyId, featureForFamily(family));
+
+ if ("createdBy" in rule) {
+ return client
+ .from("enforcementRule")
+ .insert({
+ ...rule,
+ companyId,
+ family,
+ conditionAst: rule.conditionAst as unknown as Json
+ })
+ .select("id")
+ .single();
+ }
+ return client
+ .from("enforcementRule")
+ .update({
+ ...sanitize(rule),
+ conditionAst: rule.conditionAst as unknown as Json,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", rule.id)
+ .eq("family", family)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+}
+
+export async function deleteEnforcementRule(
+ client: SupabaseClient<Database>,
+ family: EnforcementRuleFamily,
+ id: string,
+ companyId: string
+) {
+ await requireEntitlement(client, companyId, featureForFamily(family));
+
+ return client
+ .from("enforcementRule")
+ .delete()
+ .eq("id", id)
+ .eq("family", family)
+ .eq("companyId", companyId);
+}
+
+// -----------------------------------------------------------------------------
+// Sales-rule item assignments (SALES_RULES)
+// -----------------------------------------------------------------------------
+
+export async function assignSalesRule(
+ client: SupabaseClient<Database>,
+ args: { itemId: string; ruleId: string; companyId: string; createdBy: string }
+) {
+ await requireEntitlement(client, args.companyId, "SALES_RULES");
+
+ // Preflight: rule must exist in this company. Without this, callers could
+ // insert a foreign rule id; the evaluator filters defensively but the
+ // orphan row still inflates assignment counts.
+ const ruleRes = await client
+ .from("enforcementRule")
+ .select("id")
+ .eq("id", args.ruleId)
+ .eq("companyId", args.companyId)
+ .eq("family", "sales")
+ .single();
+ if (ruleRes.error || !ruleRes.data) {
+ return {
+ data: null,
+ error: ruleRes.error ?? new Error("Rule not found")
+ };
+ }
+
+ return client
+ .from("enforcementRuleItemAssignment")
+ .insert({
+ itemId: args.itemId,
+ ruleId: args.ruleId,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ })
+ .select("itemId, ruleId")
+ .single();
+}
+
+export async function unassignSalesRule(
+ client: SupabaseClient<Database>,
+ args: { itemId: string; ruleId: string; companyId: string }
+) {
+ await requireEntitlement(client, args.companyId, "SALES_RULES");
+
+ return client
+ .from("enforcementRuleItemAssignment")
+ .delete()
+ .eq("itemId", args.itemId)
+ .eq("ruleId", args.ruleId)
+ .eq("companyId", args.companyId);
+}
+
+// -----------------------------------------------------------------------------
+// Storage-rule target assignments (STORAGE_RULES)
+// -----------------------------------------------------------------------------
+
+const assignmentTableFor = (
+ targetType: TargetType
+): "enforcementRuleItemAssignment" | "enforcementRuleWorkCenterAssignment" => {
+ switch (targetType) {
+ case "item":
+ return "enforcementRuleItemAssignment";
+ case "workCenter":
+ return "enforcementRuleWorkCenterAssignment";
+ }
+};
+
+const targetIdColumnFor = (
+ targetType: TargetType
+): "itemId" | "workCenterId" => {
+ switch (targetType) {
+ case "item":
+ return "itemId";
+ case "workCenter":
+ return "workCenterId";
+ }
+};
+
+export async function assignStorageRule(
+ client: SupabaseClient<Database>,
+ args: {
+ targetType: TargetType;
+ targetId: string;
+ ruleId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ await requireEntitlement(client, args.companyId, "STORAGE_RULES");
+
+ const table = assignmentTableFor(args.targetType);
+ const idCol = targetIdColumnFor(args.targetType);
+
+ // Preflight: rule must exist in this company, belong to the storage family,
+ // and its targetType must match the assignment table. Without this, callers
+ // could pin a sales rule (or a work-center rule) through the item-assignment
+ // table; the evaluator filters defensively but the orphan row still inflates
+ // getRuleAssignmentCounts.
+ const ruleRes = await client
+ .from("enforcementRule")
+ .select("id, targetType")
+ .eq("id", args.ruleId)
+ .eq("companyId", args.companyId)
+ .eq("family", "storage")
+ .single();
+ if (ruleRes.error || !ruleRes.data) {
+ return {
+ data: null,
+ error: ruleRes.error ?? new Error("Rule not found")
+ };
+ }
+ if (ruleRes.data.targetType !== args.targetType) {
+ return {
+ data: null,
+ error: new Error(
+ `Rule targetType "${ruleRes.data.targetType}" does not match "${args.targetType}"`
+ )
+ };
+ }
+
+ return (client as SupabaseClient<Database>)
+ .from(table)
+ .insert({
+ [idCol]: args.targetId,
+ ruleId: args.ruleId,
+ companyId: args.companyId,
+ createdBy: args.userId
+ } as never)
+ .select(`${idCol}, ruleId`)
+ .single();
+}
+
+export async function unassignStorageRule(
+ client: SupabaseClient<Database>,
+ // `companyId` added over the original arg shape purely to scope the
+ // entitlement check — the delete query itself is unchanged (RLS-scoped).
+ args: {
+ targetType: TargetType;
+ targetId: string;
+ ruleId: string;
+ companyId: string;
+ }
+) {
+ await requireEntitlement(client, args.companyId, "STORAGE_RULES");
+
+ const table = assignmentTableFor(args.targetType);
+ const idCol = targetIdColumnFor(args.targetType);
+
+ return (client as SupabaseClient<Database>)
+ .from(table)
+ .delete()
+ .eq(idCol, args.targetId)
+ .eq("ruleId", args.ruleId);
+}
diff --git a/packages/ee/src/rules/storage/server.ts b/packages/ee/src/rules/storage/server.ts
index 5acd961a85..1eea5335a4 100644
--- a/packages/ee/src/rules/storage/server.ts
+++ b/packages/ee/src/rules/storage/server.ts
@@ -21,7 +21,7 @@ import {
type Violation
} from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { companyHasPlan } from "../../plan.server";
+import { companyHasFeature } from "../../plan.server";
import { dedupeViolations, isBlocked } from "../violations";
import {
buildLineContext,
@@ -47,7 +47,7 @@ export const isStorageRulesEnabledForCompany = (
client: Client,
companyId: string
): Promise<boolean> =>
- companyHasPlan(client, companyId, { feature: "STORAGE_RULES" });
+ companyHasFeature(client, companyId, { feature: "STORAGE_RULES" });
// ---------------------------------------------------------------------------
// Block decision
diff --git a/packages/ee/src/rules/storage/service.ts b/packages/ee/src/rules/storage/service.ts
index 4ce8ae94b5..87abee02ff 100644
--- a/packages/ee/src/rules/storage/service.ts
+++ b/packages/ee/src/rules/storage/service.ts
@@ -432,68 +432,7 @@ export async function getStorageRulesList(
);
}
-export async function assignStorageRule(
- client: SupabaseClient<Database>,
- args: {
- targetType: TargetType;
- targetId: string;
- ruleId: string;
- companyId: string;
- userId: string;
- }
-) {
- const table = assignmentTableFor(args.targetType);
- const idCol = targetIdColumnFor(args.targetType);
-
- // Preflight: rule must exist in this company, belong to the storage family,
- // and its targetType must match the assignment table. Without this, callers
- // could pin a sales rule (or a work-center rule) through the item-assignment
- // table; the evaluator filters defensively but the orphan row still inflates
- // getRuleAssignmentCounts.
- const ruleRes = await client
- .from("enforcementRule")
- .select("id, targetType")
- .eq("id", args.ruleId)
- .eq("companyId", args.companyId)
- .eq("family", "storage")
- .single();
- if (ruleRes.error || !ruleRes.data) {
- return {
- data: null,
- error: ruleRes.error ?? new Error("Rule not found")
- };
- }
- if (ruleRes.data.targetType !== args.targetType) {
- return {
- data: null,
- error: new Error(
- `Rule targetType "${ruleRes.data.targetType}" does not match "${args.targetType}"`
- )
- };
- }
-
- return (client as SupabaseClient<Database>)
- .from(table)
- .insert({
- [idCol]: args.targetId,
- ruleId: args.ruleId,
- companyId: args.companyId,
- createdBy: args.userId
- } as never)
- .select(`${idCol}, ruleId`)
- .single();
-}
-
-export async function unassignStorageRule(
- client: SupabaseClient<Database>,
- args: { targetType: TargetType; targetId: string; ruleId: string }
-) {
- const table = assignmentTableFor(args.targetType);
- const idCol = targetIdColumnFor(args.targetType);
-
- return (client as SupabaseClient<Database>)
- .from(table)
- .delete()
- .eq(idCol, args.targetId)
- .eq("ruleId", args.ruleId);
-}
+// `assignStorageRule` / `unassignStorageRule` (authoring writes) moved to
+// `../service.server.ts` (`@carbon/ee/rules.server`) — they embed
+// `requireEntitlement("STORAGE_RULES")` and so are server-only, which must not
+// reach the client-safe `@carbon/ee/rules` barrel this file feeds.
diff --git a/packages/ee/src/two-factor.server.ts b/packages/ee/src/two-factor.server.ts
new file mode 100644
index 0000000000..fa1d78c934
--- /dev/null
+++ b/packages/ee/src/two-factor.server.ts
@@ -0,0 +1,28 @@
+import type { Database } from "@carbon/database";
+import { sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Business) company-wide two-factor policy. Setting
+ * `companySettings.requireMfa = true` forces every member to enrol an
+ * authenticator before they can open the company — gated to the Business plan
+ * via the `TWO_FACTOR` feature.
+ *
+ * Only ENABLING is gated: a downgraded company can still turn the policy OFF so
+ * it is never locked out of its own account. MFA enrolment itself (Supabase
+ * GoTrue) is unaffected; this governs only the company-wide REQUIREMENT.
+ */
+export async function updateRequireMfaSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ requireMfa: boolean
+) {
+ if (requireMfa) {
+ await requireEntitlement(client, companyId, "TWO_FACTOR");
+ }
+ return client
+ .from("companySettings")
+ .update(sanitize({ requireMfa }))
+ .eq("id", companyId);
+}
diff --git a/packages/ee/src/webhooks.server.ts b/packages/ee/src/webhooks.server.ts
new file mode 100644
index 0000000000..0860d5f5f6
--- /dev/null
+++ b/packages/ee/src/webhooks.server.ts
@@ -0,0 +1,100 @@
+import type { Database } from "@carbon/database";
+import { sanitize } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * Commercial (Business) webhook AUTHORING — creating, editing, deleting, and
+ * bulk-deactivating a company's outbound webhook subscriptions, gated to the
+ * Business plan via the `WEBHOOKS` feature. The runtime DELIVERY path (the
+ * `@carbon/jobs` `event-handler-webhook` inngest function) is a separate
+ * concern; it degrades to a no-op for an unentitled company rather than being
+ * gated here.
+ *
+ * The entitlement LOCK lives INSIDE these commercial functions (see
+ * `entitlements.server`) so it cannot be stripped from open-licensed app code.
+ *
+ * The input shape is redefined locally so `@carbon/ee` never imports the app's
+ * `~/modules/settings` `webhookValidator`.
+ */
+
+// Minimal input shape — mirrors `webhookValidator` (`~/modules/settings`) minus
+// the optional `id`, redefined here so `@carbon/ee` never imports `~/`.
+type WebhookInput = {
+ name: string;
+ table: string;
+ url: string;
+ onInsert: boolean;
+ onUpdate: boolean;
+ onDelete: boolean;
+ active: boolean;
+};
+
+export async function upsertWebhook(
+ client: SupabaseClient<Database>,
+ webhook:
+ | (WebhookInput & {
+ createdBy: string;
+ companyId: string;
+ })
+ | (WebhookInput & {
+ id: string;
+ })
+) {
+ if ("createdBy" in webhook) {
+ await requireEntitlement(client, webhook.companyId, "WEBHOOKS");
+ return client.from("webhook").insert(webhook).select("id").single();
+ }
+
+ // The update input carries no companyId — read it from the row so the
+ // entitlement check (the lock) can run before the write.
+ const existing = await client
+ .from("webhook")
+ .select("companyId")
+ .eq("id", webhook.id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "Webhook not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "WEBHOOKS");
+ return client.from("webhook").update(sanitize(webhook)).eq("id", webhook.id);
+}
+
+export async function deleteWebhook(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ // The input carries no companyId — read it from the row so the entitlement
+ // check (the lock) can run before the delete.
+ const existing = await client
+ .from("webhook")
+ .select("companyId")
+ .eq("id", id)
+ .single();
+
+ if (existing.error || !existing.data) {
+ return {
+ data: null,
+ error: existing.error || { message: "Webhook not found" }
+ };
+ }
+
+ await requireEntitlement(client, existing.data.companyId, "WEBHOOKS");
+ return client.from("webhook").delete().eq("id", id);
+}
+
+export async function deactivateWebhooks(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ await requireEntitlement(client, companyId, "WEBHOOKS");
+ return client
+ .from("webhook")
+ .update({ active: false })
+ .eq("companyId", companyId);
+}
diff --git a/packages/jobs/src/inngest/functions/events/webhook.ts b/packages/jobs/src/inngest/functions/events/webhook.ts
index a3e3408a34..0a2a3240d2 100644
--- a/packages/jobs/src/inngest/functions/events/webhook.ts
+++ b/packages/jobs/src/inngest/functions/events/webhook.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import axios from "axios";
import { inngest } from "../../client.ts";
import { toWebhookBody, webhookPayloadSchema } from "./webhook-body.ts";
@@ -28,6 +29,23 @@ export const webhookFunction = inngest.createFunction(
);
const webhookId = payload.config.webhookId;
+ // Commercial feature gate — WEBHOOKS is a Business/entitled feature. An
+ // unentitled company keeps its subscriptions but delivery degrades to a
+ // no-op (mirrors the EMAIL_NOTIFICATIONS gate in notify.ts). Do NOT throw:
+ // a throw would retry and count as a delivery failure.
+ const entitled = await step.run("check-webhook-plan", () =>
+ companyHasFeature(getCarbonServiceRole(), payload.companyId, {
+ feature: "WEBHOOKS"
+ })
+ );
+
+ if (!entitled) {
+ console.warn(
+ `WEBHOOKS not enabled for company ${payload.companyId}; skipping webhook delivery`
+ );
+ return;
+ }
+
await step.run("send-webhook", async () => {
// Never log payload.url — the docs tell customers to treat the URL itself
// as the secret (an unguessable token in the path or query), since Carbon
diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.ts
index ebdd0a44bc..4e435321f3 100644
--- a/packages/jobs/src/inngest/functions/notifications/notify.ts
+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts
@@ -4,7 +4,7 @@ import {
type CompanyIntegration,
notifyTaskAssigned
} from "@carbon/ee/notifications";
-import { companyHasPlan } from "@carbon/ee/plan.server";
+import { companyHasFeature } from "@carbon/ee/plan.server";
import { getSlackUserIdByCarbonId } from "@carbon/ee/slack.server";
import { ERP_URL } from "@carbon/env";
import type { Events } from "@carbon/lib/events";
@@ -534,7 +534,7 @@ export const notifyFunction = inngest.createFunction(
const emailAllowed =
wantsEmail &&
(await step.run("check-email-plan", () =>
- companyHasPlan(client, payload.companyId, {
+ companyHasFeature(client, payload.companyId, {
feature: "EMAIL_NOTIFICATIONS"
})
));
diff --git a/packages/jobs/src/inngest/functions/tasks/update-permissions.ts b/packages/jobs/src/inngest/functions/tasks/update-permissions.ts
index efeed869c7..265b118200 100644
--- a/packages/jobs/src/inngest/functions/tasks/update-permissions.ts
+++ b/packages/jobs/src/inngest/functions/tasks/update-permissions.ts
@@ -1,12 +1,11 @@
-import type { Result } from "@carbon/auth";
-import { error, getClaims, getPermissionCacheKey, success } from "@carbon/auth";
-import { logPermissionChange } from "@carbon/auth/auth-events.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { Database } from "@carbon/database";
-import { redis } from "@carbon/kv";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import { updatePermissions } from "@carbon/ee/permissions.server";
import { inngest } from "../../client";
+// `updatePermissions` (the flattened-permission-object builder) is the licensed
+// authoring logic and lives once in `@carbon/ee/permissions.server`. This task
+// is just the durable wrapper for the bulk-edit path; it used to carry its own
+// drifting copy.
export const updatePermissionsFunction = inngest.createFunction(
{ id: "update-permissions", retries: 3 },
{ event: "carbon/update-permissions" },
@@ -33,180 +32,3 @@ export const updatePermissionsFunction = inngest.createFunction(
return result;
}
);
-
-export async function updatePermissions(
- client: SupabaseClient<Database>,
- {
- id,
- permissions,
- companyId,
- addOnly = false,
- actorId,
- ip
- }: {
- id: string;
- addOnly: boolean;
- permissions: Record<
- string,
- { view: boolean; create: boolean; update: boolean; delete: boolean }
- >;
- companyId: string;
- actorId?: string;
- ip?: string;
- }
-): Promise<Result> {
- if (await client.rpc("is_claims_admin", { company: companyId })) {
- const claims = await getClaims(client, id);
-
- if (claims.error) return error(claims.error, "Failed to get claims");
-
- const updatedPermissions = (
- typeof claims.data !== "object" ||
- Array.isArray(claims.data) ||
- claims.data === null
- ? {}
- : claims.data
- ) as Record<string, string[]>;
- delete updatedPermissions.role;
-
- // Snapshot the effective grant set BEFORE mutation — `updatedPermissions`
- // is the same object reference we mutate in place below, so this must be a
- // deep copy taken now to produce an honest before/after audit diff.
- const beforePermissions = structuredClone(updatedPermissions);
-
- // add any missing claims to the current claims
- Object.keys(permissions).forEach((name) => {
- const module = name.toLowerCase();
- if (!(`${module}_view` in updatedPermissions)) {
- updatedPermissions[`${module}_view`] = [];
- }
- if (!(`${module}_create` in updatedPermissions)) {
- updatedPermissions[`${module}_create`] = [];
- }
- if (!(`${module}_update` in updatedPermissions)) {
- updatedPermissions[`${module}_update`] = [];
- }
- if (!(`${module}_delete` in updatedPermissions)) {
- updatedPermissions[`${module}_delete`] = [];
- }
- });
-
- if (addOnly) {
- Object.entries(permissions).forEach(([name, permission]) => {
- const module = name.toLowerCase();
- if (
- permission.view &&
- !updatedPermissions[`${module}_view`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_view`]!.push(companyId);
- }
- if (
- permission.create &&
- !updatedPermissions[`${module}_create`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_create`]!.push(companyId);
- }
- if (
- permission.update &&
- !updatedPermissions[`${module}_update`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_update`]!.push(companyId);
- }
- if (
- permission.delete &&
- !updatedPermissions[`${module}_delete`]?.includes(companyId)
- ) {
- updatedPermissions[`${module}_delete`]!.push(companyId);
- }
- });
- } else {
- Object.entries(permissions).forEach(([name, permission]) => {
- const module = name.toLowerCase();
- if (permission.view) {
- if (!updatedPermissions[`${module}_view`]?.includes(companyId)) {
- updatedPermissions[`${module}_view`] = [
- ...(updatedPermissions[`${module}_view`] ?? []),
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_view`] = (
- updatedPermissions[`${module}_view`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.create) {
- if (!updatedPermissions[`${module}_create`]?.includes(companyId)) {
- updatedPermissions[`${module}_create`] = [
- ...(updatedPermissions[`${module}_create`] ?? []),
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_create`] = (
- updatedPermissions[`${module}_create`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.update) {
- if (!updatedPermissions[`${module}_update`]?.includes(companyId)) {
- updatedPermissions[`${module}_update`] = [
- ...(updatedPermissions[`${module}_update`] ?? []),
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_update`] = (
- updatedPermissions[`${module}_update`] as string[]
- ).filter((c: string) => c !== companyId);
- }
-
- if (permission.delete) {
- if (!updatedPermissions[`${module}_delete`]?.includes(companyId)) {
- updatedPermissions[`${module}_delete`] = [
- ...(updatedPermissions[`${module}_delete`] ?? []),
- companyId
- ];
- }
- } else {
- updatedPermissions[`${module}_delete`] = (
- updatedPermissions[`${module}_delete`] as string[]
- ).filter((c: string) => c !== companyId);
- }
- });
- }
-
- // The "0" global-company wildcard is retired (NIST 800-171 3.1.5). Strip it
- // from every array so it can never be persisted to the authoritative table.
- for (const key of Object.keys(updatedPermissions)) {
- const value = updatedPermissions[key];
- if (Array.isArray(value)) {
- updatedPermissions[key] = value.filter((c: string) => c !== "0");
- }
- }
-
- const permissionsUpdate = await getCarbonServiceRole()
- .from("userPermission")
- .update({ permissions: updatedPermissions })
- .eq("id", id);
- if (permissionsUpdate.error)
- return error(permissionsUpdate.error, "Failed to update claims");
-
- await redis.del(getPermissionCacheKey(id));
-
- // Audit the change (NIST 800-171 3.3.1/3.3.2): actor, target, before/after.
- logPermissionChange({
- actor: actorId,
- targetUserId: id,
- companyId,
- ip,
- before: beforePermissions,
- after: updatedPermissions,
- reason: addOnly ? "bulk-add" : "bulk-edit"
- });
-
- return success("Permissions updated");
- } else {
- return error(null, "You do not have permission to update permissions");
- }
-}
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 74f64b97f6..c25532cf3c 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Verfügbar nach {0}"
msgid "Available hours"
msgstr "Verfügbare Stunden"
+msgid "Available on the Business plan"
+msgstr "Im Business-Plan verfügbar"
+
msgid "Avatar url"
msgstr "Avatar-URL"
@@ -5384,6 +5387,9 @@ msgstr "Latente Steuerverpflichtung (Standard)"
msgid "Define a manufacturing operation first."
msgstr "Definieren Sie zuerst einen Fertigungsarbeitsgang."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Definieren Sie benutzerdefinierte Rollen mit granularen, modulspezifischen Berechtigungen und weisen Sie diese Ihrem Team zu."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definieren Sie mehrstufige BOMs und Arbeitsganglisten (Fertigungsmethoden)"
@@ -8225,6 +8231,9 @@ msgstr "Klassen"
msgid "Grades"
msgstr "Sorten"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Gewähren Sie jedem Benutzer granulare, modulspezifische Berechtigungen, anstatt jedem vollständigen Zugriff zu geben."
+
msgid "Grants Ability"
msgstr "Verleiht Qualifikation"
@@ -9500,9 +9509,6 @@ msgstr "Leer lassen für exakte Übereinstimmung"
msgid "Leave this page"
msgstr "Diese Seite verlassen"
-msgid "Ledger"
-msgstr "Hauptbuch"
-
msgid "Left item"
msgstr "Linkes Element"
@@ -10308,9 +10314,6 @@ msgstr "Metrische Einheiten sind deaktiviert"
msgid "Metric units are enabled"
msgstr "Metrische Einheiten sind aktiviert"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Konvention für Mitte des Monats / Quartal / Halbjahr, die den Abzug im ersten Jahr bestimmt."
@@ -14155,9 +14158,6 @@ msgstr "Wunschtermin"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Erfordert einen 6-stelligen Code aus einer Authentifikator-App beim Anmelden."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Zweiten Faktor anfordern, wenn sich Mitglieder bei diesem Unternehmen anmelden."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Erfordert einen zugewiesenen Werker, bevor der Planer Arbeiten an einem Standort platziert. Wenn aktiviert, erhalten unbesetzte Arbeitsplätze keine Arbeiten und ein Arbeitsgang ohne bemannte Abdeckung wird als nicht planbar angezeigt. Lichter-aus (24×7) Arbeitsplätze sind ausgenommen."
@@ -14179,6 +14179,9 @@ msgstr "Abgleich erforderlich"
msgid "Require SAML SSO"
msgstr "SAML SSO erforderlich"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Erfordern Sie mehrstufige Genehmigungen für Bestellungen, Qualitätsdokumente und Lieferanten basierend auf Schwellenwertbeträgen und Genehmigungsgruppen."
+
msgid "Require two-factor authentication"
msgstr "Zwei-Faktor-Authentifizierung erforderlich"
@@ -18832,6 +18835,9 @@ msgstr "Upgrade"
msgid "Upgrade to Business"
msgstr "Upgrade to Business"
+msgid "Upgrade to Enterprise"
+msgstr "Zu Enterprise upgraden"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Upgraden Sie, um {0} Regeln freizuschalten"
@@ -18949,6 +18955,9 @@ msgstr "Nutzungsdauer (Monate)"
msgid "User"
msgstr "Benutzer"
+msgid "User Permissions"
+msgstr "Benutzerberechtigungen"
+
msgid "User roles"
msgstr "Benutzerrollen"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 68af2e8159..f2a709e6b2 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Available after {0}"
msgid "Available hours"
msgstr "Available hours"
+msgid "Available on the Business plan"
+msgstr "Available on the Business plan"
+
msgid "Avatar url"
msgstr "Avatar url"
@@ -5384,6 +5387,9 @@ msgstr "Deferred Tax Liability (default)"
msgid "Define a manufacturing operation first."
msgstr "Define a manufacturing operation first."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Define multi-level BOMs and Bill of Process (make methods)"
@@ -8225,6 +8231,9 @@ msgstr "grades"
msgid "Grades"
msgstr "Grades"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+
msgid "Grants Ability"
msgstr "Grants Ability"
@@ -9500,9 +9509,6 @@ msgstr "Leave empty for exact match"
msgid "Leave this page"
msgstr "Leave this page"
-msgid "Ledger"
-msgstr "Ledger"
-
msgid "Left item"
msgstr "Left item"
@@ -10308,9 +10314,6 @@ msgstr "Metric units are disabled"
msgid "Metric units are enabled"
msgstr "Metric units are enabled"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
@@ -14155,9 +14158,6 @@ msgstr "Requested Date"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Require a 6-digit code from an authenticator app when signing in."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Require a second factor when members sign in to this company."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
@@ -14179,6 +14179,9 @@ msgstr "Require Match"
msgid "Require SAML SSO"
msgstr "Require SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+
msgid "Require two-factor authentication"
msgstr "Require two-factor authentication"
@@ -18832,6 +18835,9 @@ msgstr "Upgrade"
msgid "Upgrade to Business"
msgstr "Upgrade to Business"
+msgid "Upgrade to Enterprise"
+msgstr "Upgrade to Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Upgrade to unlock {0} rules"
@@ -18949,6 +18955,9 @@ msgstr "Useful Life (Months)"
msgid "User"
msgstr "User"
+msgid "User Permissions"
+msgstr "User Permissions"
+
msgid "User roles"
msgstr "User roles"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index aa784f5545..aae0b07f8f 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Disponible después de {0}"
msgid "Available hours"
msgstr "Horas disponibles"
+msgid "Available on the Business plan"
+msgstr "Disponible en el plan Business"
+
msgid "Avatar url"
msgstr "URL del avatar"
@@ -5384,6 +5387,9 @@ msgstr "Pasivo por impuesto diferido (predeterminado)"
msgid "Define a manufacturing operation first."
msgstr "Primero define una operación de manufactura."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Define roles personalizados con permisos granulares por módulo y asígnalos a tu equipo."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Define BOM multinivel y lista de operaciones (métodos de fabricación)"
@@ -8225,6 +8231,9 @@ msgstr "grados"
msgid "Grades"
msgstr "Grados"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Otorga a cada usuario permisos granulares por módulo en lugar de dar acceso completo a todos."
+
msgid "Grants Ability"
msgstr "Otorga Habilidad"
@@ -9500,9 +9509,6 @@ msgstr "Dejar vacío para coincidencia exacta"
msgid "Leave this page"
msgstr "Salir de esta página"
-msgid "Ledger"
-msgstr "Libro mayor"
-
msgid "Left item"
msgstr "Elemento izquierdo"
@@ -10308,9 +10314,6 @@ msgstr "Las unidades métricas están deshabilitadas"
msgid "Metric units are enabled"
msgstr "Las unidades métricas están habilitadas"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Convención de mitad de mes / mitad de trimestre / mitad de año que determina la deducción del primer año."
@@ -14155,9 +14158,6 @@ msgstr "Fecha Solicitada"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Requerir un código de 6 dígitos de una aplicación de autenticación al iniciar sesión."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Requerir un segundo factor cuando los miembros inician sesión en esta empresa."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Requerir un operario asignado antes de que el programador coloque trabajo en una ubicación. Cuando está activado, los centros de trabajo sin personal no reciben trabajo y una operación sin cobertura de personal se muestra como no programable. Los centros de trabajo automáticos (24×7) están exentos."
@@ -14179,6 +14179,9 @@ msgstr "Requiere Coincidencia"
msgid "Require SAML SSO"
msgstr "Requerir SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Requiere aprobación escalonada en órdenes de compra, documentos de calidad y proveedores según umbrales de monto y grupos de aprobadores."
+
msgid "Require two-factor authentication"
msgstr "Requerir autenticación de dos factores"
@@ -18832,6 +18835,9 @@ msgstr "Actualizar"
msgid "Upgrade to Business"
msgstr "Actualizar a Business"
+msgid "Upgrade to Enterprise"
+msgstr "Actualizar a Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Actualizar para desbloquear reglas de {0}"
@@ -18949,6 +18955,9 @@ msgstr "Vida Útil (Meses)"
msgid "User"
msgstr "Usuario"
+msgid "User Permissions"
+msgstr "Permisos de Usuario"
+
msgid "User roles"
msgstr "Roles de usuario"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 126fc379b7..6c6d6a747a 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Disponible après {0}"
msgid "Available hours"
msgstr "Heures disponibles"
+msgid "Available on the Business plan"
+msgstr "Disponible sur le plan Business"
+
msgid "Avatar url"
msgstr "URL de l'avatar"
@@ -5384,6 +5387,9 @@ msgstr "Passif d'Impôt Différé (par défaut)"
msgid "Define a manufacturing operation first."
msgstr "Définir d'abord une opération de production."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Définir des rôles personnalisés avec des autorisations granulaires par module et les attribuer à votre équipe."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Définir des BOM multi-niveaux et des Listes des opérations (méthodes de fabrication)"
@@ -8225,6 +8231,9 @@ msgstr "grades"
msgid "Grades"
msgstr "Grades"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Accorder à chaque utilisateur des autorisations granulaires par module au lieu de donner un accès complet à tous."
+
msgid "Grants Ability"
msgstr "Accorde une compétence"
@@ -9500,9 +9509,6 @@ msgstr "Laisser vide pour une correspondance exacte"
msgid "Leave this page"
msgstr "Quitter cette page"
-msgid "Ledger"
-msgstr "Grand livre"
-
msgid "Left item"
msgstr "Élément de gauche"
@@ -10308,9 +10314,6 @@ msgstr "Les unités métriques sont désactivées"
msgid "Metric units are enabled"
msgstr "Les unités métriques sont activées"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Convention de mi-mois / mi-trimestre / mi-année qui détermine la déduction de première année."
@@ -14155,9 +14158,6 @@ msgstr "Date demandée"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Exiger un code à 6 chiffres d'une application d'authentification lors de la connexion."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Exiger un second facteur quand les membres se connectent à cette société."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Exiger un opérateur assigné avant que le planificateur ne place le travail sur un site. Lorsque c'est activé, les postes de travail non dotés en personnel ne reçoivent pas de travail et une opération sans couverture en main-d'œuvre s'affiche comme non planifiable. Les postes de travail sans interruption (24×7) sont exemptés."
@@ -14179,6 +14179,9 @@ msgstr "Correspondance obligatoire"
msgid "Require SAML SSO"
msgstr "Exiger SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Exiger une approbation étagée sur les bons de commande, les documents de qualité et les fournisseurs en fonction des seuils de montant et des groupes d'approbateurs."
+
msgid "Require two-factor authentication"
msgstr "Exiger l'authentification à deux facteurs"
@@ -18832,6 +18835,9 @@ msgstr "Mettre à niveau"
msgid "Upgrade to Business"
msgstr "Passer à Business"
+msgid "Upgrade to Enterprise"
+msgstr "Mettre à niveau vers Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Passer à la version supérieure pour déverrouiller les règles {0}"
@@ -18949,6 +18955,9 @@ msgstr "Durée d'utilité (Mois)"
msgid "User"
msgstr "Utilisateur"
+msgid "User Permissions"
+msgstr "Autorisations utilisateur"
+
msgid "User roles"
msgstr "Rôles utilisateur"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index cd1f3292ce..7cf07f55d7 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -2798,6 +2798,9 @@ msgstr "{0} के बाद उपलब्ध"
msgid "Available hours"
msgstr "उपलब्ध घंटे"
+msgid "Available on the Business plan"
+msgstr "बिज़नेस प्लान पर उपलब्ध"
+
msgid "Avatar url"
msgstr "अवतार url"
@@ -5384,6 +5387,9 @@ msgstr "आस्थगित कर देयता (डिफ़ॉल्ट)"
msgid "Define a manufacturing operation first."
msgstr "पहले एक विनिर्माण ऑपरेशन को परिभाषित करें।"
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "अपनी टीम को असाइन करने के लिए बारीक-दानेदार, प्रति-मॉड्यूल अनुमतियों के साथ कस्टम भूमिकाएं परिभाषित करें।"
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "बहु-स्तरीय BOMs और प्रक्रिया सूची (निर्माण विधि) को परिभाषित करें"
@@ -8225,6 +8231,9 @@ msgstr "ग्रेड"
msgid "Grades"
msgstr "ग्रेड"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "सभी को पूर्ण पहुंच देने के बजाय प्रत्येक उपयोगकर्ता को बारीक-दानेदार, प्रति-मॉड्यूल अनुमतियां प्रदान करें।"
+
msgid "Grants Ability"
msgstr "कौशल प्रदान करता है"
@@ -9500,9 +9509,6 @@ msgstr "सटीक मिलान के लिए खाली छोड़
msgid "Leave this page"
msgstr "इस पृष्ठ को छोड़ें"
-msgid "Ledger"
-msgstr "बहीखाता"
-
msgid "Left item"
msgstr "बाईं ओर की वस्तु"
@@ -10308,9 +10314,6 @@ msgstr "मीट्रिक इकाइयाँ अक्षम हैं"
msgid "Metric units are enabled"
msgstr "मीट्रिक इकाइयाँ सक्षम हैं"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "मध्य-महीना / मध्य-त्रैमासिक / आधा-वर्ष सम्मेलन जो पहले वर्ष की कटौती निर्धारित करता है।"
@@ -14155,9 +14158,6 @@ msgstr "अनुरोधित तिथि"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "साइन इन करते समय ऑथेंटिकेटर ऐप से 6-अंकीय कोड की आवश्यकता है।"
-msgid "Require a second factor when members sign in to this company."
-msgstr "जब सदस्य इस कंपनी में साइन इन करते हैं तो एक दूसरे कारक की आवश्यकता है।"
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "शेड्यूलर किसी स्थान पर काम रखने से पहले एक असाइन किया गया ऑपरेटर आवश्यक करें। जब सक्षम हो, तो अनस्टाफ्ड वर्क सेंटर को कोई काम नहीं मिलते और कोई मानव कवरेज के बिना एक ऑपरेशन गैर-शेड्यूल करने योग्य दिखाई देता है। लाइट-आउट (24×7) वर्क सेंटर छूट प्राप्त हैं।"
@@ -14179,6 +14179,9 @@ msgstr "मिलान आवश्यक है"
msgid "Require SAML SSO"
msgstr "SAML SSO आवश्यक करें"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "राशि की सीमा और अनुमोदनकर्ता समूहों के आधार पर क्रय आदेशों, गुणवत्ता दस्तावेज़ों और आपूर्तिकर्ताओं पर स्तरीय अनुमोदन की आवश्यकता है।"
+
msgid "Require two-factor authentication"
msgstr "दो-कारक प्रमाणीकरण की आवश्यकता"
@@ -18832,6 +18835,9 @@ msgstr "अपग्रेड करें"
msgid "Upgrade to Business"
msgstr "बिजनेस में अपग्रेड करें"
+msgid "Upgrade to Enterprise"
+msgstr "एंटरप्राइज़ में अपग्रेड करें"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "{0} नियमों को अनलॉक करने के लिए अपग्रेड करें"
@@ -18949,6 +18955,9 @@ msgstr "उपयोगी जीवन (महीने)"
msgid "User"
msgstr "उपयोगकर्ता"
+msgid "User Permissions"
+msgstr "उपयोगकर्ता अनुमतियां"
+
msgid "User roles"
msgstr "उपयोगकर्ता भूमिकाएं"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 00feca9bf8..09ee510a6f 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Disponibile dopo {0}"
msgid "Available hours"
msgstr "Ore disponibili"
+msgid "Available on the Business plan"
+msgstr "Disponibile nel piano Business"
+
msgid "Avatar url"
msgstr "URL avatar"
@@ -5384,6 +5387,9 @@ msgstr "Imposte differite passive (predefinito)"
msgid "Define a manufacturing operation first."
msgstr "Definisci prima un'operazione di produzione."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Definisci ruoli personalizzati con autorizzazioni granulari per modulo e assegnali al tuo team."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definire BOM multilivello e Lista delle operazioni (metodi di produzione)"
@@ -8225,6 +8231,9 @@ msgstr "gradi"
msgid "Grades"
msgstr "Gradi"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Concedi a ogni utente autorizzazioni granulari per modulo invece di dare l'accesso completo a tutti."
+
msgid "Grants Ability"
msgstr "Assegna Competenza"
@@ -9500,9 +9509,6 @@ msgstr "Lascia vuoto per una corrispondenza esatta"
msgid "Leave this page"
msgstr "Lascia questa pagina"
-msgid "Ledger"
-msgstr "Libro mastro"
-
msgid "Left item"
msgstr "Elemento sinistro"
@@ -10308,9 +10314,6 @@ msgstr "Le unità metriche sono disabilitate"
msgid "Metric units are enabled"
msgstr "Le unità metriche sono abilitate"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Convenzione di metà mese / metà trimestre / metà anno che determina la detrazione del primo anno."
@@ -14155,9 +14158,6 @@ msgstr "Data Richiesta"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Richiedi un codice a 6 cifre dall'app autenticatore al momento dell'accesso."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Richiedi un secondo fattore quando i membri accedono a questa Azienda."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Richiedi un operatore assegnato prima che lo scheduler assegni il lavoro a un'ubicazione. Quando attivato, i centri di lavoro non staffati non ricevono lavoro e un'operazione senza copertura di manodopera appare come non programmabile. I centri di lavoro lights-out (24×7) sono esentati."
@@ -14179,6 +14179,9 @@ msgstr "Richiedi Corrispondenza"
msgid "Require SAML SSO"
msgstr "Richiedi SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Richiedi approvazione per livelli su ordini di acquisto, documenti di qualità e fornitori in base a soglie di importo e gruppi di approvatori."
+
msgid "Require two-factor authentication"
msgstr "Richiedi autenticazione a due fattori"
@@ -18832,6 +18835,9 @@ msgstr "Aggiorna"
msgid "Upgrade to Business"
msgstr "Passa a Business"
+msgid "Upgrade to Enterprise"
+msgstr "Passa a Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Esegui l'upgrade per sbloccare le regole {0}"
@@ -18949,6 +18955,9 @@ msgstr "Vita Utile (Mesi)"
msgid "User"
msgstr "Utente"
+msgid "User Permissions"
+msgstr "Autorizzazioni utente"
+
msgid "User roles"
msgstr "Ruoli utente"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index c45083d0f9..b6bac44fb3 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -2798,6 +2798,9 @@ msgstr "{0}の後に利用可能"
msgid "Available hours"
msgstr "利用可能時間"
+msgid "Available on the Business plan"
+msgstr "ビジネスプランで利用可能"
+
msgid "Avatar url"
msgstr "アバターURL"
@@ -5384,6 +5387,9 @@ msgstr "繰延税金負債(デフォルト)"
msgid "Define a manufacturing operation first."
msgstr "最初に製造作業を定義します。"
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "細粒度で、モジュール単位の権限を持つカスタムロールを定義して、チームに割り当てます。"
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "多階層BOMおよび工程表(製造方法)を定義"
@@ -8225,6 +8231,9 @@ msgstr "グレード"
msgid "Grades"
msgstr "等級"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "全員にフルアクセスを付与するのではなく、各ユーザーに細粒度で、モジュール単位の権限を付与します。"
+
msgid "Grants Ability"
msgstr "スキルを付与"
@@ -9500,9 +9509,6 @@ msgstr "正確な一致のために空のままにしてください"
msgid "Leave this page"
msgstr "このページを離れる"
-msgid "Ledger"
-msgstr "元帳"
-
msgid "Left item"
msgstr "左側の項目"
@@ -10308,9 +10314,6 @@ msgstr "メートル法の単位は無効です"
msgid "Metric units are enabled"
msgstr "メートル法単位が有効です"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "初年度控除を決定する中月/四半期中/半年の慣例。"
@@ -14155,9 +14158,6 @@ msgstr "希望納期"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "サインイン時に認証器アプリから6桁のコードが必要です。"
-msgid "Require a second factor when members sign in to this company."
-msgstr "メンバーがこの会社にサインインする際に、セカンドファクタを必須にする。"
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "スケジューラがある拠点に作業を配置する前に、割当済の作業者を必要とします。オンの場合、スタッフなしの作業区は作業を取得せず、配置された人員がいない工程はスケジュール不可として表示されます。ライトアウト(24×7)作業区は除外されます。"
@@ -14179,6 +14179,9 @@ msgstr "照合が必須"
msgid "Require SAML SSO"
msgstr "SAML SSOを必須にする"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "金額閾値と承認者グループに基づいて、発注書、品質ドキュメント、および仕入先に対する段階的な承認を要求します。"
+
msgid "Require two-factor authentication"
msgstr "二要素認証が必要です"
@@ -18832,6 +18835,9 @@ msgstr "アップグレード"
msgid "Upgrade to Business"
msgstr "ビジネスプランにアップグレード"
+msgid "Upgrade to Enterprise"
+msgstr "エンタープライズにアップグレード"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "{0}ルールのロックを解除するにはアップグレード"
@@ -18949,6 +18955,9 @@ msgstr "耐用年数(月)"
msgid "User"
msgstr "ユーザー"
+msgid "User Permissions"
+msgstr "ユーザー権限"
+
msgid "User roles"
msgstr "ユーザーロール"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 05695794ae..754b774301 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -2798,6 +2798,9 @@ msgstr "{0} 이후 가용"
msgid "Available hours"
msgstr "가용 시간"
+msgid "Available on the Business plan"
+msgstr "Business 플랜에서 사용 가능"
+
msgid "Avatar url"
msgstr "아바타 URL"
@@ -5384,6 +5387,9 @@ msgstr "이연법인세부채(기본값)"
msgid "Define a manufacturing operation first."
msgstr "먼저 제조 공정작업을 정의하세요."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "모듈별 세밀한 권한으로 사용자 정의 역할을 정의하고 팀에 할당합니다."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "다단계 BOM 및 공정 목록(생산 방법) 정의"
@@ -8225,6 +8231,9 @@ msgstr "등급"
msgid "Grades"
msgstr "등급"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "모든 사용자에게 전체 접근 권한을 부여하는 대신 각 사용자에게 모듈별 세밀한 권한을 부여합니다."
+
msgid "Grants Ability"
msgstr "역량 부여"
@@ -9500,9 +9509,6 @@ msgstr "정확히 일치시키려면 비워두세요"
msgid "Leave this page"
msgstr "이 페이지 나가기"
-msgid "Ledger"
-msgstr "원장"
-
msgid "Left item"
msgstr "왼쪽 품목"
@@ -10308,9 +10314,6 @@ msgstr "미터법 단위가 비활성화됨"
msgid "Metric units are enabled"
msgstr "미터법 단위가 활성화됨"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "1차년도 공제액을 결정하는 월중/분기중/반기 컨벤션입니다."
@@ -14155,9 +14158,6 @@ msgstr "요청일"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "로그인 시 인증 앱의 6자리 코드를 입력하세요."
-msgid "Require a second factor when members sign in to this company."
-msgstr "회사에 로그인할 때 구성원들이 두 번째 인증 요소를 사용하도록 요구"
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "스케줄러가 사업장에 작업을 배치하기 전에 할당된 작업자를 요구하세요. 활성화되면 인력이 부족한 작업장은 작업을 받지 않으며 배치된 작업자가 없는 공정은 일정을 잡을 수 없는 것으로 표시됩니다. 조명 없는(24×7) 작업장은 제외됩니다."
@@ -14179,6 +14179,9 @@ msgstr "필수 일치"
msgid "Require SAML SSO"
msgstr "SAML SSO 필수"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "금액 한계 및 승인자 그룹을 기준으로 발주서, 품질 문서, 공급업체에 대한 단계별 승인을 요구합니다."
+
msgid "Require two-factor authentication"
msgstr "2단계 인증 필수"
@@ -18832,6 +18835,9 @@ msgstr "업그레이드"
msgid "Upgrade to Business"
msgstr "비즈니스로 업그레이드"
+msgid "Upgrade to Enterprise"
+msgstr "Enterprise로 업그레이드"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "{0}개의 규칙을 사용하려면 업그레이드하세요"
@@ -18949,6 +18955,9 @@ msgstr "내용연수(개월)"
msgid "User"
msgstr "사용자"
+msgid "User Permissions"
+msgstr "사용자 권한"
+
msgid "User roles"
msgstr "사용자 역할"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index d22bd50af6..b6dff12938 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Dostępne po {0}"
msgid "Available hours"
msgstr "Dostępne godziny"
+msgid "Available on the Business plan"
+msgstr "Dostępne w planie Business"
+
msgid "Avatar url"
msgstr "URL avatara"
@@ -5384,6 +5387,9 @@ msgstr "Odroczone Zobowiązania Podatkowe (domyślne)"
msgid "Define a manufacturing operation first."
msgstr "Najpierw zdefiniuj operację produkcyjną."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Utwórz niestandardowe role z precyzyjnymi uprawnieniami dla każdego modułu i przypisz je swoim pracownikom."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Zdefiniuj wielopoziomowe BOM i listy operacji (metody produkcji)"
@@ -8225,6 +8231,9 @@ msgstr "stopnie"
msgid "Grades"
msgstr "Gatunki"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Przydzielaj każdemu użytkownikowi szczegółowe uprawnienia dla każdego modułu zamiast udzielać wszystkim pełnego dostępu."
+
msgid "Grants Ability"
msgstr "Przyznaje Umiejętność"
@@ -9500,9 +9509,6 @@ msgstr "Pozostaw puste dla dokładnego dopasowania"
msgid "Leave this page"
msgstr "Opuść tę stronę"
-msgid "Ledger"
-msgstr "Księga główna"
-
msgid "Left item"
msgstr "Element po lewej stronie"
@@ -10308,9 +10314,6 @@ msgstr "Jednostki metryczne są wyłączone"
msgid "Metric units are enabled"
msgstr "Jednostki metryczne są włączone"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Konwencja połowy miesiąca / połowy kwartału / połowy roku, która określa potrącenie w pierwszym roku."
@@ -14155,9 +14158,6 @@ msgstr "Data żądana"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Wymagaj 6-cyfrowego kodu z aplikacji Authenticator przy logowaniu."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Wymagaj drugiego czynnika podczas logowania członków do tej firmy."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Wymagaj przypisanego operatora, zanim harmonogram umieści pracę w lokalizacji. Gdy włączone, stanowiska robocze bez obsady nie otrzymują pracy, a operacja bez pokrycia obsługą personelu wyświetla się jako nieplanowalna. Stanowiska robocze bez oświetlenia (24×7) są zwolnione."
@@ -14179,6 +14179,9 @@ msgstr "Wymaga dopasowania"
msgid "Require SAML SSO"
msgstr "Wymagaj SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Wymagaj wielopoziomowego zatwierdzenia zamówień zakupu, dokumentów jakości i dostawców na podstawie limitów kwot i grup zatwierdzających."
+
msgid "Require two-factor authentication"
msgstr "Wymagaj uwierzytelniania dwuskładnikowego"
@@ -18832,6 +18835,9 @@ msgstr "Uaktualnij"
msgid "Upgrade to Business"
msgstr "Uaktualnij do Business"
+msgid "Upgrade to Enterprise"
+msgstr "Uaktualnij do Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Uaktualnij, aby odblokować reguły {0}"
@@ -18949,6 +18955,9 @@ msgstr "Okres użytkowania (Miesiące)"
msgid "User"
msgstr "Użytkownik"
+msgid "User Permissions"
+msgstr "Uprawnienia użytkownika"
+
msgid "User roles"
msgstr "Role użytkownika"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index a06c91f5f6..a4342f5729 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Disponível após {0}"
msgid "Available hours"
msgstr "Horas Disponíveis"
+msgid "Available on the Business plan"
+msgstr "Disponível no plano Business"
+
msgid "Avatar url"
msgstr "URL do avatar"
@@ -5384,6 +5387,9 @@ msgstr "Passivo de imposto diferido (padrão)"
msgid "Define a manufacturing operation first."
msgstr "Defina primeiro uma operação de manufatura."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Defina funções personalizadas com permissões granulares por módulo e atribua-as à sua equipe."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Definir BOMs multinível e Lista de operações (métodos de fabricação)"
@@ -8225,6 +8231,9 @@ msgstr "classificações"
msgid "Grades"
msgstr "Graus"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Conceda a cada usuário permissões granulares por módulo em vez de dar acesso completo a todos."
+
msgid "Grants Ability"
msgstr "Concede Habilidade"
@@ -9500,9 +9509,6 @@ msgstr "Deixe vazio para correspondência exata"
msgid "Leave this page"
msgstr "Sair desta página"
-msgid "Ledger"
-msgstr "Livro razão"
-
msgid "Left item"
msgstr "Item esquerdo"
@@ -10308,9 +10314,6 @@ msgstr "Unidades métricas desativadas"
msgid "Metric units are enabled"
msgstr "Unidades métricas ativadas"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Convenção de meio de mês / meio de trimestre / meio de ano que determina a dedução do primeiro ano."
@@ -14155,9 +14158,6 @@ msgstr "Data Solicitada"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Exigir um código de 6 dígitos de uma aplicação autenticadora ao iniciar sessão."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Exigir um segundo fator quando membros fazem login nesta empresa."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Exigir um operador atribuído antes que o programador coloque trabalho em um local. Quando ativado, centros de trabalho sem pessoal não recebem trabalho e uma operação sem cobertura de pessoal aparece como improgramável. Centros de trabalho lights-out (24×7) são isentos."
@@ -14179,6 +14179,9 @@ msgstr "Exigir Correspondência"
msgid "Require SAML SSO"
msgstr "Exigir SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Exija aprovação em camadas em pedidos de compra, documentos de qualidade e fornecedores com base em limites de valor e grupos de aprovadores."
+
msgid "Require two-factor authentication"
msgstr "Requerer autenticação de dois fatores"
@@ -18832,6 +18835,9 @@ msgstr "Atualizar"
msgid "Upgrade to Business"
msgstr "Atualizar para Business"
+msgid "Upgrade to Enterprise"
+msgstr "Faça upgrade para Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Atualize para desbloquear regras de {0}"
@@ -18949,6 +18955,9 @@ msgstr "Vida Útil (Meses)"
msgid "User"
msgstr "Usuário"
+msgid "User Permissions"
+msgstr "Permissões de Usuário"
+
msgid "User roles"
msgstr "Funções do usuário"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 583581fff9..f7a74b5e4d 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -2798,6 +2798,9 @@ msgstr "Доступно после {0}"
msgid "Available hours"
msgstr "Доступные часы"
+msgid "Available on the Business plan"
+msgstr "Доступно в плане Business"
+
msgid "Avatar url"
msgstr "URL аватара"
@@ -5384,6 +5387,9 @@ msgstr "Отложенное налоговое обязательство (по
msgid "Define a manufacturing operation first."
msgstr "Сначала определите производственную операцию."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Определить пользовательские роли с детальными правами доступа по модулям и назначить их сотрудникам."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Определите многоуровневые BOM и перечни операций (методы производства)"
@@ -8225,6 +8231,9 @@ msgstr "сорта"
msgid "Grades"
msgstr "Сорта"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Предоставить каждому пользователю детальные права доступа по модулям вместо предоставления полного доступа всем."
+
msgid "Grants Ability"
msgstr "Предоставляет Навык"
@@ -9500,9 +9509,6 @@ msgstr "Оставьте пустым для точного совпадения
msgid "Leave this page"
msgstr "Покинуть эту страницу"
-msgid "Ledger"
-msgstr "Главная книга"
-
msgid "Left item"
msgstr "Левый элемент"
@@ -10308,9 +10314,6 @@ msgstr "Метрические единицы отключены"
msgid "Metric units are enabled"
msgstr "Метрические единицы включены"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Условие середины месяца / середины квартала / половины года, определяющее вычет первого года."
@@ -14155,9 +14158,6 @@ msgstr "Запрошенная дата"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Требовать 6-значный код из приложения-аутентификатора при входе."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Требовать второй фактор при входе сотрудников в эту организацию."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Требовать назначенного оператора перед размещением планировщиком работ на площадке. Когда включено, рабочие центры без персонала не получают работу, а операция без назначенного оператора отображается как невозможная для планирования. Круглосуточные (24×7) рабочие центры освобождены от этого требования."
@@ -14179,6 +14179,9 @@ msgstr "Требовать совпадение"
msgid "Require SAML SSO"
msgstr "Требовать SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Требовать многоуровневого одобрения заказов поставщикам, документов качества и поставщиков на основе пороговых сумм и групп утверждающих."
+
msgid "Require two-factor authentication"
msgstr "Требовать двухфакторную аутентификацию"
@@ -18832,6 +18835,9 @@ msgstr "Обновить"
msgid "Upgrade to Business"
msgstr "Перейти на Business"
+msgid "Upgrade to Enterprise"
+msgstr "Обновить до Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Обновитесь, чтобы разблокировать правила {0}"
@@ -18949,6 +18955,9 @@ msgstr "Срок полезного использования (месяцы)"
msgid "User"
msgstr "Пользователь"
+msgid "User Permissions"
+msgstr "Права доступа пользователя"
+
msgid "User roles"
msgstr "Роли пользователей"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 03abe88ea0..2b900f66ce 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -2798,6 +2798,9 @@ msgstr "{0}'den sonra kullanılabilir"
msgid "Available hours"
msgstr "Kullanılabilir saatler"
+msgid "Available on the Business plan"
+msgstr "Business planında kullanılabilir"
+
msgid "Avatar url"
msgstr "Avatar URL'si"
@@ -5384,6 +5387,9 @@ msgstr "Ertelenen Vergi Yükümlülüğü (varsayılan)"
msgid "Define a manufacturing operation first."
msgstr "Önce bir üretim işlemini tanımlayın."
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "Özel roller tanımlayın ve bunları modüle özel, ayrıntılı izinlerle takımınıza atayın."
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "Çok seviyeli BOM'lar ve Operasyon listesi (üretim yöntemleri) tanımlayın"
@@ -8225,6 +8231,9 @@ msgstr "sınıflar"
msgid "Grades"
msgstr "Dereceler"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "Her kullanıcıya modüle özel, ayrıntılı izinler verin, herkes için tam erişim vermek yerine."
+
msgid "Grants Ability"
msgstr "Yetkinlik Verir"
@@ -9500,9 +9509,6 @@ msgstr "Tam eşleşme için boş bırakın"
msgid "Leave this page"
msgstr "Bu sayfadan ayrıl"
-msgid "Ledger"
-msgstr "Büyük Defter"
-
msgid "Left item"
msgstr "Sol öğe"
@@ -10308,9 +10314,6 @@ msgstr "Metrik birimleri devre dışı"
msgid "Metric units are enabled"
msgstr "Metrik birimler etkinleştirilmiş"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "Ay ortası / çeyrek ortası / yarı yıl kuralı, ilk yıl kesintisini belirler."
@@ -14155,9 +14158,6 @@ msgstr "Talep Edilen Tarih"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "Oturum açarken kimlik doğrulayıcı uygulamasından 6 haneli kod isteyini."
-msgid "Require a second factor when members sign in to this company."
-msgstr "Bu şirkete giriş yaparken üyelerin ikinci bir faktör kullanmasını zorunlu tutun."
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "Çizelgeleme sistemi bir lokasyon'da iş yerleştirmeden önce atanmış bir operatör gerekli kılın. Etkinleştirildiğinde, personel olmayan iş merkezleri iş almaz ve uygun personel olmayan bir operasyon zamanlanmaz olarak görünür. Tam otomasyonlu (24×7) iş merkezleri muaftır."
@@ -14179,6 +14179,9 @@ msgstr "Eşleştirme Gerekli"
msgid "Require SAML SSO"
msgstr "SAML SSO Gerekli"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "Satın alma siparişleri, kalite belgeler ve tedarikçiler için tutar eşikleri ve onaylayan gruplarına göre katmanlı imzayı talep edin."
+
msgid "Require two-factor authentication"
msgstr "İki faktörlü kimlik doğrulamayı gerektir"
@@ -18832,6 +18835,9 @@ msgstr "Yükselt"
msgid "Upgrade to Business"
msgstr "İşletmeye Yükselt"
+msgid "Upgrade to Enterprise"
+msgstr "Enterprise'a yükselt"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "Üniforma kurallarını açmak için yükseltin"
@@ -18949,6 +18955,9 @@ msgstr "Faydalı Ömür (Aylar)"
msgid "User"
msgstr "Kullanıcı"
+msgid "User Permissions"
+msgstr "Kullanıcı İzinleri"
+
msgid "User roles"
msgstr "Kullanıcı rolleri"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index de980e99fd..c280d2a296 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -2798,6 +2798,9 @@ msgstr "在{0}之后可用"
msgid "Available hours"
msgstr "可用小时数"
+msgid "Available on the Business plan"
+msgstr "在商业计划中可用"
+
msgid "Avatar url"
msgstr "头像网址"
@@ -5384,6 +5387,9 @@ msgstr "递延所得税负债(默认)"
msgid "Define a manufacturing operation first."
msgstr "首先定义制造操作。"
+msgid "Define custom roles with fine-grained, per-module permissions and assign them to your team."
+msgstr "定义具有细粒度、按模块权限的自定义角色,并将其分配给您的团队。"
+
msgid "Define multi-level BOMs and Bill of Process (make methods)"
msgstr "定义多级BOM和工序清单(制造方法)"
@@ -8225,6 +8231,9 @@ msgstr "等级"
msgid "Grades"
msgstr "等级"
+msgid "Grant each user fine-grained, per-module permissions instead of giving everyone full access."
+msgstr "向每个用户授予细粒度、按模块权限,而不是给予所有人完全访问权。"
+
msgid "Grants Ability"
msgstr "授予能力"
@@ -9500,9 +9509,6 @@ msgstr "留空以精确匹配"
msgid "Leave this page"
msgstr "离开此页面"
-msgid "Ledger"
-msgstr "总账"
-
msgid "Left item"
msgstr "左项"
@@ -10308,9 +10314,6 @@ msgstr "公制单位已禁用"
msgid "Metric units are enabled"
msgstr "公制单位已启用"
-msgid "MFA"
-msgstr "MFA"
-
msgid "Mid-month / mid-quarter / half-year convention that determines the first-year deduction."
msgstr "决定首年扣除的月中/季中/半年约定俗成的方法。"
@@ -14155,9 +14158,6 @@ msgstr "要求日期"
msgid "Require a 6-digit code from an authenticator app when signing in."
msgstr "登录时需要来自身份验证器应用的 6 位数字代码。"
-msgid "Require a second factor when members sign in to this company."
-msgstr "成员登录此公司时需要第二因素验证"
-
msgid "Require an assigned operator before the scheduler places work at a location. When on, unstaffed work centers get no work and an operation with no manned coverage shows as unschedulable. Lights-out (24×7) work centers are exempt."
msgstr "排程前需要已分配的操作员才能在地点安排工作。启用时,无人工作中心不会分配工作,且无人工覆盖的工序显示为无法排程。熄灯(24×7)工作中心豁免。"
@@ -14179,6 +14179,9 @@ msgstr "必需匹配"
msgid "Require SAML SSO"
msgstr "需要 SAML SSO"
+msgid "Require tiered sign-off on purchase orders, quality documents, and suppliers based on amount thresholds and approver groups."
+msgstr "根据金额阈值和批准人组,对采购订单、质量文档和供应商要求分级批准。"
+
msgid "Require two-factor authentication"
msgstr "需要双因素认证"
@@ -18832,6 +18835,9 @@ msgstr "升级"
msgid "Upgrade to Business"
msgstr "升级到商业版"
+msgid "Upgrade to Enterprise"
+msgstr "升级到 Enterprise"
+
#. placeholder {0}: targetCopy.noun
msgid "Upgrade to unlock {0} rules"
msgstr "升级以解锁 {0} 规则"
@@ -18949,6 +18955,9 @@ msgstr "使用年限(月)"
msgid "User"
msgstr "用户"
+msgid "User Permissions"
+msgstr "用户权限"
+
msgid "User roles"
msgstr "用户角色"
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index c7df1cb1cf..256f75ec0b 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -122,13 +122,13 @@ const PERMISSION_MODULE_MAP: Record<string, string | null> = {
// module than their service module (spot-checked against the real routes). Keep
// this hand-curated list small and grounded — each entry needs a verified route.
const PERMISSION_OVERRIDES: Record<string, ToolPermission> = {
- // API-key management is an admin capability: every route in the family —
- // x+/settings+/api-keys.tsx (list loader), api-keys.new.tsx, api-keys.$id.tsx,
- // api-keys.delete.$id.tsx — gates on { update: "users" }, not "settings".
- // Deriving "settings" would let a settings-scoped key mint new API keys.
+ // API-key management is an admin capability: the list loader
+ // (x+/settings+/api-keys.tsx) gates on { update: "users" }, not "settings" —
+ // deriving "settings" would let a settings-scoped key read the key family.
+ // The WRITES (upsert/delete) moved to @carbon/ee/api-keys.server behind
+ // requireEntitlement, so they are no longer scanned as MCP tools; only the
+ // read remains here.
settings_getApiKeys: { module: "users", actions: ["update"] },
- settings_upsertApiKey: { module: "users", actions: ["update"] },
- settings_deleteApiKey: { module: "users", actions: ["update"] },
};
// ---------------------------------------------------------------------------