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.

fix(security): scope tenant records and harden reported security issues (#1734)

Brad Barbin9ddb3bc29584
diff --git a/.ai/lessons.md b/.ai/lessons.md
index e1f31d1dfa..5eafc72e55 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2296,3 +2296,23 @@ function as `anon` and as another company's user, not by reading the catalog. Ed
**Applies to:** every `CREATE FUNCTION` in `packages/database/supabase/migrations/**`,
`packages/database/supabase/functions/*/index.ts`; enforced by the
`public-definer-function-authorizes-caller` invariant and `supabase/tests/rpc-privileges.test.sql`.
+
+## `CREATE OR REPLACE VIEW` without `WITH (...)` silently drops `security_invoker`
+
+**Context:** `openJobMaterialLines` served every company's open job material lines to the anon
+key (reported against production, 2026-09-26). The clause had been added, audited back in, and
+then dropped by four separate migrations that recreated the view from an older copy.
+
+**Problem:** `CREATE OR REPLACE VIEW` REPLACES the view's options with whatever the statement
+states, so a recreation that omits `WITH (security_invoker = true)` turns an invoker view back
+into an owner-rights one. Owner rights bypass RLS on every table underneath, and every `public`
+view is a PostgREST endpoint. Nothing failed: the app filters by `companyId` itself, so every
+screen still looked right.
+
+**Rule:** Every `CREATE [OR REPLACE] VIEW` states `security_invoker` — copy a view's definition
+from its NEWEST migration, and re-check the `WITH` clause when you do. Test a view the way an
+attacker reads it: `SET LOCAL ROLE anon; SELECT count(*) FROM "view";` must be 0. Join on
+`companyId` too, so a view is tenant-consistent on its own.
+
+**Applies to:** `packages/database/supabase/migrations/**`; enforced by the
+`no-view-without-invoker` conformance check and the `view-without-security-invoker` invariant.
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index 0d9fbec0d5..b1bde130b2 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -216,6 +216,19 @@ querying), and every route entry point checks it too — login buttons, the
`REFRESH_ACCESS_TOKEN_THRESHOLD` (10 min) of expiry via `refreshAccessToken`.
- `destroyAuthSession` clears auth + company-id cookies, redirects to login.
`updateCompanySession` / `updateSessionConsole` switch active company / console mode.
+- **Console pin-in** (`@carbon/auth/console-pin.server`): which operator is pinned in
+ at a console terminal lives in the `console-pin-<companyId>` cookie, SIGNED with
+ `SESSION_SECRET` and bound to the company and the terminal's session user
+ (`setConsolePinIn` / `clearConsolePinIn`). `resolveConsolePinIn` re-validates it on
+ every request — the operator must still be an active employee of the company and
+ `companySettings.consoleEnabled` still on — and is memoized per read request. PINs
+ are bcrypt hashes in `employeePin` (no API-role access; `set_employee_pin` /
+ `verify_employee_pin` over the server's Kysely connection, via
+ `@carbon/ee/console.server`). MES pin-in (`x+/console.pin-in.tsx`) consumes the
+ per-operator `AccountLockout` attempt and the per-terminal `Ratelimit` token BEFORE
+ verifying (refunding both on a non-guess), so a parallel burst cannot outrun the
+ limits. `companySettings.consoleEnabled` is server-only: a trigger refuses API-role
+ writes, and it only moves through `updateConsoleSetting` (`requireEntitlement`).
## MFA / TOTP (`mfa.server.ts`)
@@ -321,6 +334,11 @@ the gate used in every loader/action. Two paths:
- Returns `{ client, companyId, companyGroupId, email, userId, sessionUserId,
consoleMode }`. `bypassRls: true` + employee role returns a service-role client;
otherwise a Bearer-authed `getCarbon(accessToken)` client (RLS enforced).
+ - `consoleMode` is `authSession.console === companyId`. In console mode `userId`
+ is the pinned operator from `resolveConsolePinIn` (falling back to the session
+ user when nobody valid is pinned in); `sessionUserId` is always the account the
+ terminal is signed in with. Gate terminal-level actions (entering console mode)
+ on `sessionUserId`, never `userId`.
Claims cache must be invalidated when permissions change — `users.server.ts` deactivate
flows call `redis.del(getPermissionCacheKey(userId))`.
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 8dadb51fc5..49863a7e61 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -86,7 +86,10 @@ both use it; `company-backup.ts` re-exports it), exported to app code as
data; `companyGroupId` = config shared across a company group (chart of
accounts, currencies, dimensions).
- Skip/scope sets: `SECRET_TABLES` (`apiKey`, `apiKeyRateLimit`,
- `companyIntegration`, `webhook`, `oauthClient`, `oauthToken` — never travel;
+ `companyIntegration`, `employeePin`, `webhook`, `oauthClient`, `oauthToken` — never travel;
+ `employeePin` holds console-PIN bcrypt hashes, a credential for a 4-digit PIN, and
+ stays in place on restore alongside `employee` (`IN_PLACE_SKIPPED_TABLES`), which is
+ never wiped, so its (employee, company) FK has nothing to orphan it from;
`apiKeyRateLimit` is here because its NOT-NULL `apiKeyId` references the stripped
secret `apiKey`, so exporting it alone would dangle every row on restore — and
it's UNLOGGED operational counters, not user data), `STRUCTURAL_TABLES` (`company` —
diff --git a/.claude/rules/conventions-services.md b/.claude/rules/conventions-services.md
index 85f611b6c7..80ea236a21 100644
--- a/.claude/rules/conventions-services.md
+++ b/.claude/rules/conventions-services.md
@@ -155,24 +155,34 @@ Kysely **bypasses RLS** and **throws on rollback** (the route try/catches it). S
```typescript
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { updateSortOrder } from "../shared/sort-order";
// real: updateQuoteLineOrder in sales.service.ts
export async function updateQuoteLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ quoteId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("quoteLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "quoteLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "quoteId", id: quoteId },
+ updates
});
}
```
+Because Kysely bypasses RLS, a Kysely service **always** scopes by `companyId` — and by the
+parent document id when the row ids come from the request — in the SQL itself. Never a per-row
+query in a loop: `updateSortOrder` (`modules/shared/sort-order.ts`) is one
+`UPDATE … FROM (VALUES …)` that throws, rolling back, if any id falls outside that scope. Name
+the tenant params `companyId` / `userId` so the API dispatcher injects them from the auth
+context rather than the body.
+
A single write is already atomic — don't reach for a transaction.
**Never construct the Kysely client (or a `pg` pool) inside the service.** The service
@@ -204,7 +214,7 @@ route-wiring example is in [database-patterns.md](database-patterns.md#transacti
| Create-or-update | `upsertCustomer(client, data)` | client |
| Insert-only | `insertCustomerContact(client, data)` | client |
| Delete | `deleteCustomer(client, id)` | client |
-| Multi-row / reorder | `updateQuoteLineOrder(db, updates)` | `Kysely<KyselyDatabase>` |
+| Multi-row / reorder | `updateQuoteLineOrder(db, companyId, userId, quoteId, updates)` | `Kysely<KyselyDatabase>` |
## Checklist
diff --git a/.claude/rules/database-migration-patterns.md b/.claude/rules/database-migration-patterns.md
index 661183376a..15698925ae 100644
--- a/.claude/rules/database-migration-patterns.md
+++ b/.claude/rules/database-migration-patterns.md
@@ -131,6 +131,13 @@ FROM "entityName" e
LEFT JOIN "user" u ON u."id" = e."createdBy";
```
+`CREATE OR REPLACE VIEW` replaces the view's options, so recreating a view without the `WITH`
+clause silently turns it back into an owner-rights view that bypasses RLS for every PostgREST
+caller, anon included (`openJobMaterialLines`, fixed in `20260926093417`). The
+`no-view-without-invoker` check (`@carbon/checks`) fails any `CREATE VIEW` that does not state
+`security_invoker`; the `view-without-security-invoker` invariant checks the live catalog.
+Materialized views cannot run as the caller — revoke SELECT from `anon, authenticated` instead.
+
## Triggers
There is **no generic boilerplate trigger** to add per table. Triggers in this codebase are
diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.md
index 0888e8dbcd..44e2532683 100644
--- a/.claude/rules/database-patterns.md
+++ b/.claude/rules/database-patterns.md
@@ -154,28 +154,47 @@ every write inside it, and rolls everything back on any error.
### Service function example
`Kysely<KyselyDatabase>` is the first arg by convention. The route passes `getDatabaseClient()`.
-Real precedents: `items.service.ts → upsertPickMethodWithShelfLife`,
-`update<Entity>LineOrder` functions across purchasing, sales, invoicing services.
+Real precedents: `items.service.ts → upsertPickMethodWithShelfLife`, and the drag-sort
+reorders (`update<Entity>LineOrder` in purchasing/sales/invoicing,
+`updateAssemblyInstructionStep{,Material}Order`, `updateChangeNoticeActionOrder`), which are
+thin wrappers over ONE shared helper, `updateSortOrder` in
+`apps/erp/app/modules/shared/sort-order.ts`. Reuse it for any new reorder — never write a
+per-row UPDATE loop.
```typescript
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { updateSortOrder } from "../shared/sort-order";
export async function updatePurchaseOrderLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ purchaseOrderId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("purchaseOrderLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "purchaseOrderLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "purchaseOrderId", id: purchaseOrderId },
+ updates
});
}
```
+`updateSortOrder` issues a single `UPDATE t … FROM (VALUES …) v(id, sortOrder) WHERE t.id = v.id
+AND t."companyId" = $ AND t.<parent> = $ RETURNING t.id` inside a transaction and throws (rolling
+back) when fewer rows come back than were sent — an id from another company, another document,
+or a missing row aborts the whole reorder. A row one hop from the document uses
+`parent: { column, via: { table, column, id } }` (assembly step materials → step → instruction).
+It is deliberately NOT in a `*.service.ts`, so the generic "reorder any table" function never
+becomes an API/MCP tool. Its compiled SQL is pinned by `shared/sort-order.test.ts`.
+
+Keep `companyId`/`userId` as positional params named exactly that: the API dispatcher
+(`api+/v1+/lib/dispatch.server.ts`) fills them from the authenticated context, never the body.
+The parent document id is an ordinary payload param.
+
### Route handler example
```typescript
@@ -183,10 +202,17 @@ import { getDatabaseClient } from "~/services/database.server";
import { updatePurchaseOrderLineOrder } from "~/modules/purchasing";
export async function action({ request, params }: ActionFunctionArgs) {
- const { userId } = await requirePermissions(request, { update: "purchasing" });
+ const { companyId, userId } = await requirePermissions(request, { update: "purchasing" });
+ if (!params.orderId) throw new Error("Could not find orderId");
// ... build `updates` from formData ...
try {
- await updatePurchaseOrderLineOrder(getDatabaseClient(), updates);
+ await updatePurchaseOrderLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.orderId, // the URL's document — every row must belong to it
+ updates
+ );
} catch (err) {
return data(
{ success: false },
@@ -200,11 +226,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
### Key notes
- Kysely **throws** on rollback — use `try/catch`, not the `{ error }` return pattern.
-- Kysely **does not apply RLS**. Authorize at the route with `requirePermissions` before calling it;
- when in doubt, scope queries by `companyId` inside the transaction.
+- Kysely **does not apply RLS**, so authorization is two layers and both are required:
+ `requirePermissions` at the route proves the caller may act in the company, and the service
+ **always** scopes every statement by `companyId` — plus the parent document id whenever the row
+ ids come from the request body. The route cannot enforce the second: it never sees which rows
+ the ids name, so an unscoped service lets any route reorder/edit any row in the company.
+ The `no-unscoped-kysely-write` check (`@carbon/checks`) fails any `updateTable`/`deleteFrom`
+ in ERP modules/routes, MES or `packages/jobs` whose statement has no `.where("companyId", …)`.
+ A link table with no `companyId` column (`jobMaterialStep`, `jobOperationToolStep`) is scoped
+ through its parent: `.where("jobOperationStepId", "in", (eb) => eb.selectFrom("jobOperationStep")
+ .select("id").where("id", "in", ids).where("companyId", "=", companyId))`.
+- Never query inside a loop — one set-based statement (`UPDATE … FROM (VALUES …)`, `.in()`, a
+ join) per logical write.
- Single writes are already atomic — don't reach for a transaction.
-- Kysely auto-quotes reserved column names (e.g. `order`), so `.set({ order: sortOrder })` is safe.
-- Kysely uses a connection pool and the Postgres role — enforce auth at the route, not in the service.
+- Kysely auto-quotes reserved column names (e.g. `order`), so `.set({ order: sortOrder })` is
+ safe; in raw `sql`, use `sql.ref(column)`.
## RLS / permission model
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.md
index 127ff8884d..b58255b4d6 100644
--- a/.claude/rules/environment-configuration.md
+++ b/.claude/rules/environment-configuration.md
@@ -101,10 +101,17 @@ exchange/token refresh), Slack (`SLACK_BOT_TOKEN`, `SLACK_CLIENT_ID`,
plus webhook/redirect/state secrets), `EXCHANGE_RATES_API_KEY`,
`GOOGLE_PLACES_API_KEY`, AI keys `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`.
-Ramp intentionally has no separate `RAMP_STATE_SECRET`. `issueOAuthState()` stores a
-random nonce plus `{integrationId,userId,companyId,expiresAt}` in a signed HttpOnly
-cookie backed by `SESSION_SECRET`; `consumeOAuthState()` validates all fields and
-destroys the cookie on every attempt. Managed deployment propagates both Ramp OAuth
+Ramp intentionally has no separate `RAMP_STATE_SECRET`. `issueOAuthState()` /
+`issueOAuthStates()` store a random nonce plus `{integrationId,userId,companyId,expiresAt}`
+per integration (keyed by `integrationId`, 1 h lifetime, a still-fresh one is reused) in
+one signed HttpOnly cookie backed by `SESSION_SECRET`; pass the request so other
+integrations' pending states survive. `consumeOAuthState()` validates all fields and
+removes that integration's entry on every attempt (the cookie is destroyed once empty).
+The integrations page loader issues one for every integration with an `oauth` config
+(Ramp, Xero, QuickBooks, Jira — IntegrationCard puts it on the authorize URL), Onshape's
+`api+/integrations.onshape.install.ts` issues its own, and each callback consumes it.
+Slack binds its state separately (`SLACK_STATE_SECRET`, `@slack/oauth` state store,
+checked against the caller's company and user). Managed deployment propagates both Ramp OAuth
vars through `ci/src/deploy.ts` → `sst.config.ts` → the ERP service only.
**Analytics / config** — `POSTHOG_API_HOST`, `POSTHOG_PROJECT_PUBLIC_KEY`
diff --git a/.claude/rules/jira-integration.md b/.claude/rules/jira-integration.md
index 3a78a93f1e..38eb32989a 100644
--- a/.claude/rules/jira-integration.md
+++ b/.claude/rules/jira-integration.md
@@ -23,7 +23,11 @@ Code lives in `packages/ee/src/jira/`. Two export subpaths (see `packages/ee/pac
category "Project Management", `active: !!JIRA_CLIENT_ID`). Registered in
`packages/ee/src/index.ts` `integrations[]`. OAuth scopes: `read:jira-user`,
`read:jira-work`, `write:jira-work`, `offline_access`. Also renders the
- `SetupInstructions` (webhook URL + which events to subscribe).
+ `SetupInstructions` (webhook URL + which events to subscribe + the "Secret" field).
+ One setting: `webhookSigningSecret` (optional, `type: "secret"`, vaulted via
+ `SECRET_KEYS.jira`; an empty field keeps the stored value). The drawer is only
+ reachable after the OAuth install, so its Update button never installs Jira
+ without credentials.
- `lib/client.ts` — `JiraClient` (singleton via `getJiraClient()`). REST calls go to
`https://api.atlassian.com/ex/jira/{cloudId}/rest/api/3{path}`. `getAuthHeaders()`
refreshes the access token when within a 5-min expiry buffer and persists the new
@@ -77,10 +81,31 @@ this reason.
assignable users filtered to Carbon employees.
- `integrations.jira.issue.sync-notes.ts` — POST pushes Tiptap notes → ADF onto the
linked issue's description (no-op if the task isn't linked).
-- `webhook.jira.$companyId.ts` — inbound webhook. Validates the company's `jira`
- integration is active, parses with `syncIssueFromJiraSchema` (`@carbon/jobs`), then
+- `webhook.jira.$companyId.ts` — inbound webhook. Reads the raw body once, validates
+ the company's `jira` integration is active, verifies the signature (below), parses
+ with `syncIssueFromJiraSchema` (`@carbon/jobs`), then
`trigger("sync-issue-from-jira", ...)`.
+## Webhook signing (opt-in)
+
+The webhook is created BY HAND as a Jira admin webhook, so a signature cannot be
+required without breaking existing installs. The route reads the secret with
+`getWebhookSigningSecret(serviceRole, companyId, "jira", row)`
+(`@carbon/ee/integrations/secrets`; a vault read failure → 500, fail-closed).
+
+- Secret set → `verifyJiraWebhook` (`packages/ee/src/jira/lib/webhook.ts`, exported
+ from `@carbon/ee/jira.server`): `X-Hub-Signature` must be `sha256=<hex HMAC-SHA256
+ of the RAW body keyed by the secret>` (only the `sha256` method is accepted;
+ constant-time, length-checked, non-hex rejected). Failure → logged `warning` with a
+ `reason` + 401, before parsing or triggering. Scheme per
+ https://developer.atlassian.com/cloud/jira/platform/webhooks/ ("Secure admin
+ webhooks"). Jira sends no signed timestamp, so there is no replay window; the job
+ re-fetches the issue, so a replay only re-applies Jira's current state.
+- No secret → accepted as before, with one `warning` per delivery that it is unsigned.
+- Shared HMAC compare: `verifyHmacSha256Signature`
+ (`packages/ee/src/integrations/webhook-signature.ts`).
+- Tests: `webhook.jira.$companyId.test.ts`.
+
## Inbound webhook job (Inngest, NOT Trigger.dev)
`packages/jobs/src/inngest/functions/integrations/jira.ts` — `jiraSyncFunction`
diff --git a/.claude/rules/linear-integration.md b/.claude/rules/linear-integration.md
index c352aca277..2db84f6350 100644
--- a/.claude/rules/linear-integration.md
+++ b/.claude/rules/linear-integration.md
@@ -17,9 +17,12 @@ type, not just `action`.
## Pieces
- **Config:** `packages/ee/src/linear/config.tsx` — `defineIntegration` (id `"linear"`,
- category "Project Management", `active: true`). One setting `apiKey` (required; zod
- must start with `lin_api`). Renders setup instructions + webhook URL
- `/api/webhook/linear/{companyId}`.
+ category "Project Management", `active: true`). Settings: `apiKey` (required; zod
+ must start with `lin_api`) and `webhookSigningSecret` (optional). Both are
+ `type: "secret"` — vaulted via `SECRET_KEYS.linear` in
+ `packages/ee/src/integrations/secrets.ts`, never in the plaintext `metadata`
+ column; an empty field keeps the stored value. Renders setup instructions + webhook
+ URL `/api/webhook/linear/{companyId}` + where Linear shows the signing secret.
- **Client:** `packages/ee/src/linear/lib/client.ts` — `LinearClient` over the Linear
GraphQL API (`https://api.linear.app/graphql`, axios). Singleton `getLinearClient()`.
Every method takes `companyId` first; auth header is the raw `apiKey` read from the
@@ -51,9 +54,29 @@ actionId)` looks up by **`entityId`** (the action id, despite the name) and pars
## Inbound: Linear → Carbon (webhook → Inngest, NOT trigger.dev)
-- Route `apps/erp/app/routes/api+/webhook.linear.$companyId.ts`: checks the integration
- exists + is active, parses `syncIssueFromLinearSchema`, then
- `trigger("sync-issue-from-linear", payload)`.
+- Route `apps/erp/app/routes/api+/webhook.linear.$companyId.ts`: reads the raw body
+ once, checks the integration exists + is active, verifies the signature (below),
+ parses `syncIssueFromLinearSchema`, then `trigger("sync-issue-from-linear", payload)`.
+- **Signing is OPT-IN.** Customers create the webhook by hand in Linear, so
+ requiring a signature would break every install made before it existed. The route
+ reads the secret with `getWebhookSigningSecret(serviceRole, companyId, "linear", row)`
+ (`@carbon/ee/integrations/secrets`; throws when the vault is unreadable → the route
+ returns 500, fail-closed, because "no secret" and "unreadable" are indistinguishable).
+ - Secret set → `verifyLinearWebhook` (`packages/ee/src/linear/lib/webhook.ts`,
+ exported from `@carbon/ee/linear.server`): `Linear-Signature` must be the hex
+ HMAC-SHA256 of the RAW body keyed by the secret (constant-time, length-checked,
+ non-hex rejected), AND the body's `webhookTimestamp` (UNIX ms) must be within
+ `LINEAR_WEBHOOK_TOLERANCE_MS` (60 s) of now. Any failure → logged `warning` with a
+ `reason` + 401, before parsing or triggering. Scheme per
+ https://linear.app/developers/webhooks ("Securing webhooks").
+ - No secret → accepted as before, with one `warning` per delivery that it is unsigned.
+ - There is no "clear" for the secret (an empty secret field keeps the vaulted value).
+ - The HMAC compare is shared: `verifyHmacSha256Signature`
+ (`packages/ee/src/integrations/webhook-signature.ts`), also used by Jira and Ramp.
+ - Tests: `webhook.linear.$companyId.test.ts` (stubs only the service-role client,
+ the clock and `trigger`).
+ - The settings action's "a credential is required" install check ignores
+ `WEBHOOK_SIGNING_SECRET_KEY`, so a signing secret alone never satisfies it.
- Webhook body schema is **minimal**: `event.data = { id, assigneeId? }` only (type
`"Issue"`, action `"update"`) — `packages/jobs/src/schemas.ts`
`syncIssueFromLinearSchema`. The full issue is re-fetched, never trusted from the payload.
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index c0301f2136..418ff6267e 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -278,9 +278,20 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate
addressed on its own pass. When a payload param is an **array** of rows,
`enrichWithAuthContext` stamps `createdBy` into each element (insert only) —
the top-level stamp never reached inside, so a NOT NULL `createdBy` on the row
- table (e.g. `quoteLinePrice`) used to fail. Only `createdBy` is injected per
- element; `companyId`/`updatedBy` are left to the service, since element keys
- spread straight into an INSERT.
+ table (e.g. `quoteLinePrice`) used to fail. `createdBy` is the only key ever
+ ADDED to an element (element keys spread straight into an INSERT). But an
+ identity key the CALLER supplied — `createdBy`, `updatedBy`, `companyId`,
+ `companyGroupId` — is always OVERWRITTEN with the authenticated value, in
+ top-level array elements, in objects nested one level inside an object
+ payload (`{ itemUpdate: {...} }`), and in array elements one level down
+ (`{ lines: [...] }`), on every operation including reads (where it can only
+ narrow to the caller's own company). `userId` is deliberately NOT
+ overwritten inside rows — there it is usually data (the assigned employee).
+ Anything deeper (an array inside a nested object) is NOT reached, so a
+ service must not spread such a structure into a write. Pinned by
+ `dispatch-parity.test.ts` h, h3, h3b, h4. A Kysely service takes
+ `companyId`/`userId` as POSITIONAL params so they always come from context
+ (h2 — `updateQuoteLineOrder(db, companyId, userId, quoteId, updates)`).
- Blocked tools (`lib/mcp-blocked-tools.ts`, `MCP_BLOCKED_TOOL_NAMES`) are
rejected in `call_tool`, in `callOperation`, and (belt-and-braces) in the
`gate()` middleware — though the primary gate is that the generator excludes
diff --git a/.claude/rules/workflow-edge-function.md b/.claude/rules/workflow-edge-function.md
index 6082ad9e99..95b36785cd 100644
--- a/.claude/rules/workflow-edge-function.md
+++ b/.claude/rules/workflow-edge-function.md
@@ -183,7 +183,24 @@ was is what produced the cross-tenant write in
`companyId`; it proves nothing about the RECORD IDS in the body, which usually come
straight from the URL. When the invocation is service-role, RLS is not there to
catch the mismatch either. So a function that takes a record id must re-read that
-record under `companyId` itself and 404 on a miss — `schedule` does this for `jobId`.
+record under `companyId` itself and 404 on a miss.
+
+The pattern is `functions/lib/company-records.ts`:
+
+- **Ids the function only writes as references** (a ledger's `locationId`, an
+ activity's `trackedEntityId`, a caller-chosen `purchaseOrderId`) — call
+ `assertCompanyRecords(db, table, ids, companyId, label)` once per table, right
+ after `requirePermissions`. It ignores null/undefined/duplicate ids (optional
+ fields stay optional), runs one query, and throws `RecordNotFoundError`. A table
+ must be on its `CompanyScopedTable` allow-list; add it there.
+- **The document the function acts on** (the receipt being posted, the invoice being
+ voided) — scope the EXISTING header read with `.eq("companyId", companyId)` and
+ `.maybeSingle()`, and 404 on a miss. Do not add a second pre-check query.
+- **Any other "X not found" miss** — throw `RecordNotFoundError`, not `Error`.
+
+`RecordNotFoundError` carries `status = 404`, and `errorResponse` (`lib/response.ts`)
+uses a numeric 4xx/5xx `err.status` over the status the catch block passes, so a
+catch block needs no `instanceof RecordNotFoundError` mapping.
## 6. Local dev
diff --git a/.claude/rules/xero-webhooks.md b/.claude/rules/xero-webhooks.md
index 98e675e30b..ce73a47bbf 100644
--- a/.claude/rules/xero-webhooks.md
+++ b/.claude/rules/xero-webhooks.md
@@ -23,32 +23,42 @@ because it uses `crypto` for HMAC.
1. `const payloadText = await request.text()` — read the **raw** body first; signature
verification must hash the raw bytes, not re-serialized JSON.
-2. **Intent-to-receive short-circuit**: if `XERO_WEBHOOK_SECRET` is set and the body is
- empty / `"{}"`, return `200` with an empty body immediately. This is how Xero's
- "Intent to Receive" validation handshake passes.
-3. **Signature check**: read the `x-xero-signature` header. Missing → `401`
- `{ success: false, error: "Missing signature" }`. Present → `verifySignature()`.
-4. `JSON.parse` the body (parse failure → `401`), then validate with `WebhookSchema`
+2. **Fail closed when unconfigured**: if `XERO_WEBHOOK_SECRET` is unset, log an error
+ and return `401` `{ success: false, error: "Webhook secret not configured" }` before
+ anything else — without the key a Xero delivery cannot be told from anyone else's,
+ and every event queues a sync job.
+3. **Intent-to-receive short-circuit**: if the body is empty / `"{}"`, return `200`
+ with an empty body.
+4. **Signature check**: read the `x-xero-signature` header. Missing → `401`
+ `{ success: false, error: "Missing signature" }`. Mismatch → `401`
+ `{ success: false, error: "Invalid signature" }` (see `verifySignature` below).
+5. `JSON.parse` the body (parse failure → `401`), then validate with `WebhookSchema`
(zod). Invalid shape → `401`.
-5. Group events by `tenantId`. Per tenant: `getAccountingIntegration(serviceRole,
+6. Group events by `tenantId`. Per tenant: `getAccountingIntegration(serviceRole,
tenantId, ProviderID.XERO)` to resolve the `companyId`; missing → record an error and
- `continue`. Then `getProviderIntegration(...)` to build a live `XeroProvider`.
-6. For each event, **fetch the entity from Xero** to refine its type, build
+ `continue`. **Tenant binding**: the resolved row is trusted only when its OWN stored
+ tenant (`getStoredTenantId` → `parseStoredCredentials(...).providerMetadata.tenantId`)
+ equals the event's `tenantId` — `getAccountingIntegration` also matches on
+ `companyId`, so an event naming a company id instead of a tenant would otherwise
+ resolve that company. A mismatch records the same "Tenant ID not found in
+ integrations" error and `continue`s. Then `getProviderIntegration(...)` builds a
+ live `XeroProvider`.
+7. For each event, **fetch the entity from Xero** to refine its type, build
`AccountingEntity[]`, and if non-empty fire one background job per tenant via
`trigger("sync-external-accounting", payload)`.
-7. Return a plain object summary `{ success, jobsTriggered, jobs, errors?, timestamp }`
+8. Return a plain object summary `{ success, jobsTriggered, jobs, errors?, timestamp }`
(HTTP 200). `success` is `errors.length === 0`.
## Signature verification (`verifySignature`)
-- HMAC **SHA-256** of the raw `payloadText` keyed by `XERO_WEBHOOK_SECRET`, digest
- **base64**, compared to the header via `crypto.timingSafeEqual`.
-- **Fail-open when unconfigured**: if `XERO_WEBHOOK_SECRET` is unset, `verifySignature`
- logs a warning and *returns the payload string* (truthy) — and the whole verification
- block in `action` is skipped anyway (`if (XERO_WEBHOOK_SECRET)`). So with no secret set,
- every request is processed unverified. The env var is declared optional
+- `verifySignature(payload, header, secret)` returns a boolean: HMAC **SHA-256** of the
+ raw `payloadText` keyed by `XERO_WEBHOOK_SECRET`, digest **base64**, compared to the
+ header via `crypto.timingSafeEqual` (unequal lengths are a mismatch, not a throw).
+- **Fail-closed when unconfigured**: the action returns `401` before verification when
+ `XERO_WEBHOOK_SECRET` is unset (step 2). The env var is still declared optional
(`getEnv("XERO_WEBHOOK_SECRET", { isRequired: false, isSecret: true })` in
- `packages/env/src/index.ts`).
+ `packages/env/src/index.ts`) so an instance without Xero boots; it just cannot
+ receive Xero webhooks.
## Event payload (`WebhookSchema`)
@@ -94,11 +104,14 @@ downstream syncer architecture see `accounting-sync-handlers.md`.
## Gotchas
-- Verification is **fail-open**: no `XERO_WEBHOOK_SECRET` = all requests trusted.
+- Verification is **fail-closed**: no `XERO_WEBHOOK_SECRET` = every delivery is `401`.
- Validation/parse failures return **401** (not 400) — only the intent handshake and the
fully-processed case return 200.
- The route fans out extra synchronous Xero GETs per event before responding.
-- `getAccountingIntegration` matches the tenant via `companyId` OR
- `metadata->credentials->>tenantId`, so the webhook's `tenantId` resolves the company.
+- `getAccountingIntegration` resolves by `companyId` first, then by the stored tenant
+ (`metadata->credentials->>tenantId` or `metadata->credentials->providerMetadata->>tenantId`,
+ each a separate parameterised `.eq()`; more than one company on one tenant resolves
+ to nothing). Because a company-id match also succeeds, the route re-checks the
+ resolved row's own tenant against the event (step 6).
- Only `CONTACT` and `INVOICE` categories are accepted by the schema; any other category
fails zod validation → 401.
diff --git a/apps/erp/app/components/Form/PdfExtractor.tsx b/apps/erp/app/components/Form/PdfExtractor.tsx
index b8fb8b3cfb..ef91d87daf 100644
--- a/apps/erp/app/components/Form/PdfExtractor.tsx
+++ b/apps/erp/app/components/Form/PdfExtractor.tsx
@@ -1,4 +1,4 @@
-import { storage } from "@carbon/files";
+import { safeStorageFileName, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { Spinner, useCarbon } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -87,7 +87,9 @@ export function PdfExtractor({
setUploadFailed(false);
setUploadedFileName(file.name);
setUploading(true);
- const storagePath = `${company.id}/extractions/${Date.now()}_${file.name}`;
+ // The key is internal (the user sees file.name above); drop the characters
+ // a storage key can't hold so a "#" never shortens it.
+ const storagePath = `${company.id}/extractions/${Date.now()}_${safeStorageFileName(file.name) ?? "document.pdf"}`;
const { error } = await storage(supabase)
.company(company.id)
diff --git a/apps/erp/app/hooks/useFileUpload.ts b/apps/erp/app/hooks/useFileUpload.ts
index 58f63b4e2b..f3f1d6559e 100644
--- a/apps/erp/app/hooks/useFileUpload.ts
+++ b/apps/erp/app/hooks/useFileUpload.ts
@@ -1,5 +1,9 @@
import { useCarbon } from "@carbon/auth";
-import { getCompanyPrivateBucket, storage } from "@carbon/files";
+import {
+ getCompanyPrivateBucket,
+ safeStorageFileName,
+ storage
+} from "@carbon/files";
import {
DuplicateFileNameError,
MediaUploader,
@@ -65,11 +69,37 @@ export function useFileUpload(options: FileUploadOptions = {}) {
return;
}
+ // Storage keys can't hold `?`, `#` or `%` — the first two end the key
+ // there, silently shortening the name. Rename up front (before HEIC
+ // conversion, which marks the files it produces) and say so, so the
+ // stored key, the document record and what the user sees all agree.
+ const nameable: File[] = [];
+ for (const file of files) {
+ const name = safeStorageFileName(file.name);
+ if (!name) {
+ toast.error(t`Can't upload a file named ${file.name}`);
+ onError?.(file);
+ continue;
+ }
+ if (name !== file.name) {
+ toast.info(t`${file.name} will be saved as ${name}`);
+ nameable.push(
+ new File([file], name, {
+ type: file.type,
+ lastModified: file.lastModified
+ })
+ );
+ continue;
+ }
+ nameable.push(file);
+ }
+ if (nameable.length === 0) return;
+
setIsUploading(true);
try {
let prepared: File[];
try {
- prepared = await uploader.prepareForUpload(files);
+ prepared = await uploader.prepareForUpload(nameable);
} catch (error) {
toast.error(
error instanceof DuplicateFileNameError
diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.ts
index 83977d3efe..4702ef586f 100644
--- a/apps/erp/app/modules/accounting/accounting.server.ts
+++ b/apps/erp/app/modules/accounting/accounting.server.ts
@@ -600,6 +600,7 @@ export async function postDepreciationRun(
.updateTable("depreciationRunLine")
.set({ journalId: journal.id })
.where("id", "=", line.id)
+ .where("companyId", "=", companyId)
.execute();
const newAccumulated = Number(asset.accumulatedDepreciation) + amount;
@@ -628,6 +629,7 @@ export async function postDepreciationRun(
.updateTable("fixedAsset")
.set(assetUpdate)
.where("id", "=", line.fixedAssetId)
+ .where("companyId", "=", companyId)
.execute();
}
@@ -799,6 +801,7 @@ export async function postDepreciationRun(
postedBy: userId
})
.where("id", "=", depreciationRunId)
+ .where("companyId", "=", companyId)
.execute();
});
}
diff --git a/apps/erp/app/modules/agent/kb/docs/building/architecture.md b/apps/erp/app/modules/agent/kb/docs/building/architecture.md
index 64e05705b1..56dc286ee3 100644
--- a/apps/erp/app/modules/agent/kb/docs/building/architecture.md
+++ b/apps/erp/app/modules/agent/kb/docs/building/architecture.md
@@ -396,19 +396,29 @@ so it can open a real transaction. This is the answer to the "three inserts aren
atomic" problem from [Part 2](#part-2-follow-one-click-all-the-way-down):
```ts
-return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("quoteLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+// updateSortOrder (apps/erp/app/modules/shared/sort-order.ts), which every
+// drag-to-reorder route uses: one UPDATE for all the rows, inside a transaction.
+await db.transaction().execute(async (trx) => {
+ const { rows } = await sql<{ id: string }>`
+ UPDATE "quoteLine" AS t SET "sortOrder" = v."sortOrder", …
+ FROM (VALUES ${values}) AS v("id", "sortOrder")
+ WHERE t."id" = v."id"
+ AND t."companyId" = ${companyId}
+ AND t."quoteId" = ${quoteId}
+ RETURNING t."id"`.execute(trx);
+ // A row from another company or another quote matched nothing. Throwing
+ // here rolls back the rows that did match: all or nothing.
+ if (rows.length !== updates.length) throw new Error("…");
});
```
-Three warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it
-in `try/catch`. It applies **no** RLS, so authorize before you call it. And the pool it
+Four warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it
+in `try/catch`. It applies **no** RLS, so authorize before you call it, and then scope
+**every** statement yourself: `companyId` always, plus the parent document's id whenever
+the row ids come from the request. Without the parent filter, a request sent through one
+quote's URL could reorder the lines of any other quote in the company, including one
+that is already closed. Write one statement for the whole set rather than a query per row
+inside a loop. And the pool it
draws from is small (edge functions ask for exactly one connection,
`getConnectionPool(1)`): if code inside a transaction reaches for a second connection from
the same pool, that second request queues behind a transaction that cannot finish until it
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
index b7c73f45f7..f7f98c1f38 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/company-settings.md
@@ -29,7 +29,7 @@ Company membership is per-user: one login can hold several companies and switch
- **accountingEnabled**: Master switch for the ledger. When off, operations complete without posting journal entries.
- **timeCardEnabled**: Turns on shop-floor time cards.
- - **consoleEnabled**: Enables the support/impersonation console.
+ - **consoleEnabled**: Enables MES console (shared-station) mode, where operators pin in with a 4-digit PIN. Business plan; toggled from **Settings → People** by someone with `settings_update`, and only through that screen — the API refuses a direct write to this column. See `docs/reference/mes`.
- **requireMfa**: Everyone needs an authenticator app to open this company. Edited from **Settings → System → Security**; locked on in controlled (ITAR) deployments. See `docs/reference/two-factor`.
- **useMetric**: Whether material units default to metric.
- **materialGeneratedIds**: Whether new materials get an auto-generated readable id.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/mes.md b/apps/erp/app/modules/agent/kb/docs/reference/mes.md
index a236de65a4..8cdda1e5a8 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/mes.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/mes.md
@@ -14,9 +14,9 @@ Once in, the operator sets their context. If the company has more than one locat
### Console (shared-station) mode
-A single tablet bolted to a work center can't ask every operator to log in and out all shift. **Console mode** turns that station into a shared kiosk. It's gated by the `consoleEnabled` company setting, and when on, the sidebar exposes a **"Console Mode"** toggle.
+A single tablet bolted to a work center can't ask every operator to log in and out all shift. **Console mode** turns that station into a shared kiosk. It's gated by the `consoleEnabled` company setting (Business plan), and when on, the sidebar exposes a **"Console Mode"** toggle. Switching a station INTO console mode takes `settings_update` on the account the station is signed in with; switching it back out is open to anyone, so a station is never stuck.
-In console mode an operator identifies themselves with a **4-digit PIN**, not a full login. The station prompts to enter a PIN for the named operator, checks it, and attributes the work to that person. Two things stop cold when the PIN is wrong or missing: the station shows **"Incorrect PIN"**, or **"No PIN set. Please set a PIN in your account settings."** if the person never configured one.
+In console mode an operator identifies themselves with a **4-digit PIN**, not a full login. PINs are generated by Carbon and handed out by an admin — shown once when an operator is created or a PIN is reset, and stored only as a hash (see `docs/reference/permissions`). The station prompts to enter a PIN for the named operator, checks it, and attributes the work to that person. Three things stop it: **"Incorrect PIN"**, **"Too many incorrect PINs. Please wait a few minutes and try again."** after repeated wrong guesses, or **"No PIN set. Ask an admin to set a console PIN for you."** if the person has none yet.
A shared station is meant to hand off. **"Switch Operator"** re-prompts for a PIN so the next person takes over, and **"Pin Out"** clears the current operator. Ending the shift also pins out automatically. The PIN identifies *who did the work*; it is not a substitute for the person's real account.
@@ -128,8 +128,11 @@ The exact blocks operators hit on the floor, and what unblocks each.
### "Incorrect PIN"
In console mode the 4-digit PIN entered for the named operator didn't match. Re-enter it, or use **"Switch Operator"** to pick the right person. The PIN identifies who did the work; it is not the person's login password.
-### "No PIN set. Please set a PIN in your account settings."
-The named operator has never configured a console PIN, so console mode can't attribute work to them. They set one in their account settings (in the ERP), then the station can pin them in.
+### "Too many incorrect PINs. Please wait a few minutes and try again."
+Five wrong PINs for one person within 15 minutes lock that person's pin-in, from every station, for a minute at first (doubling on repeat offenses, up to an hour). A station is also capped at 30 wrong PINs in 15 minutes across all operators — and stations signed in with the same account share that cap. Wait, then enter the right PIN.
+
+### "No PIN set. Ask an admin to set a console PIN for you."
+The named person has no console PIN, so console mode can't attribute work to them. PINs aren't chosen on the floor: an admin generates one in the ERP — **Reset PIN** under **Settings → Users → Operators** for an operator, or **Set Console PIN** on the **Accounts** list for anyone else (that one also needs `settings_update`). Then the station can pin them in.
### "This picking list is closed. Reopen it from the ERP to continue."
The picking list is already `Completed` or `Cancelled`, which locks it — the floor can't pick, unpick, short, or scan against a closed list. Reopening it requires an inventory permission the MES doesn't hold; a user reopens it from the ERP.
@@ -141,7 +144,7 @@ The picking list is already `Completed` or `Cancelled`, which locks it — the f
A time card was left open for twelve hours or more. Choose **"I'm Still Working"** to keep the shift open, or **"Set Clock Out"** to close it. Time cards are labor/presence time for payroll — separate from the per-operation production events that drive job costing.
### The Console Mode toggle or the time card isn't there
-Both are company-setting gated. **"Console Mode"** only appears when `consoleEnabled` is on; the **"Clock In"/"Clock Out"** time card (and the 12-hour prompt) only appear when `timeCardEnabled` is on. If a floor needs either, an admin enables it in company settings.
+Both are company-setting gated. **"Console Mode"** only appears when `consoleEnabled` is on and the plan includes it, and then only to an account with `settings_update` (or on a station already in console mode, so it can leave); the **"Clock In"/"Clock Out"** time card (and the 12-hour prompt) only appear when `timeCardEnabled` is on. If a floor needs either, an admin enables it in company settings.
### I can't drag a card to reschedule on the floor
The MES **"Schedule"** board is display and filter only — it never reschedules. Rebalancing the plan (moving an operation to another work center, or shifting a job's dates) happens on the `docs/reference/scheduling`, where a planner owns the sequence.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/permissions.md b/apps/erp/app/modules/agent/kb/docs/reference/permissions.md
index 99eb4f419c..14914f9897 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/permissions.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/permissions.md
@@ -67,7 +67,7 @@ An invite is a company-scoped record keyed by email, and it carries the permissi
Not everyone who needs to touch Carbon has an email inbox. A machinist on the floor signs in to the `docs/reference/mes` with a **4-digit PIN** on a shared station tablet, not a magic link. These are **console operators**, and they're a distinct kind of account.
-Add one under **Settings → Users → Operators** (visible only when console mode is enabled for the company) with a name, a location, and a 4-digit PIN (`apps/erp/app/modules/users/users.models.ts:31`). Carbon creates a lightweight account with no email login and assigns it the **Console Operator** employee type automatically. On the shop floor the operator taps their name and enters the PIN, which Carbon checks against the account before starting their session (`apps/mes/app/routes/x+/console.pin-in.tsx:61`). You can reset an operator's PIN at any time from the same screen.
+Add one under **Settings → Users → Operators** (visible only when console mode is enabled for the company) with a name and a location. Carbon creates a lightweight account with no email login, assigns it the **Console Operator** employee type automatically, and generates a 4-digit PIN that is shown once, when the operator is created — Carbon stores only a hash of it, so copy it then. On the shop floor the operator taps their name and enters the PIN, which Carbon checks before starting their session. If a PIN is lost, reset it from the same screen to generate a new one; the old PIN stops working immediately. Resetting an operator's PIN takes `users_update`; setting a console PIN for any other employee (from the **Accounts** list) also takes `settings_update`.
When a PIN account needs real ERP access, convert it: give it an email and a full employee type, and Carbon promotes the same person to a normal invited user without losing their history (`apps/erp/app/modules/users/users.server.ts:905`). Their old floor activity stays attached to the one identity.
@@ -86,11 +86,11 @@ Access gates, PIN accounts, and why a permission change didn't take.
### "Incorrect PIN"
The 4-digit PIN entered on the shop-floor station doesn't match the operator's account. Re-enter it, or reset the operator's PIN from **Settings → Users → Operators**.
-### "No PIN set. Please set a PIN in your account settings."
-The operator account being signed into has no PIN on record. Set one for that operator from the Operators screen before they can sign in on the floor.
+### "Too many incorrect PINs. Please wait a few minutes and try again."
+Five wrong PINs for one person within 15 minutes lock that person's pin-in for a while, from every station; the lock lasts a minute at first and doubles on repeat offenses. A single station is also capped at 30 wrong PINs in 15 minutes across everyone, and stations signed in with the same login share that cap. Wait it out — a correct PIN afterwards clears the person's count.
-### "PIN must be 4 digits"
-Creating or resetting an operator rejects anything that isn't exactly four digits. Enter a 4-digit numeric PIN.
+### "No PIN set. Ask an admin to set a console PIN for you."
+The person has no PIN on record, and PINs are never chosen on the floor: an admin generates one. For an operator, use **Reset PIN** on **Settings → Users → Operators** (needs `users_update`). For any other employee, use **Set Console PIN** on the **Accounts** list, which also needs `settings_update`, because a PIN lets whoever holds it act as that person on the floor.
### "Group members are required"
A bulk action — bulk permission edit, group edit, deactivate, resend/revoke invite — was submitted with no users selected. Select at least one user first.
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index 56dbf793e3..af519c59bc 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -980,7 +980,8 @@
"Maintenance dispatch",
"Troubleshooting",
"\"Incorrect PIN\"",
- "\"No PIN set. Please set a PIN in your account settings.\"",
+ "\"Too many incorrect PINs. Please wait a few minutes and try again.\"",
+ "\"No PIN set. Ask an admin to set a console PIN for you.\"",
"\"This picking list is closed. Reopen it from the ERP to continue.\"",
"Finish is blocked or warns (\"Insufficient quantity\" / \"Steps are missing\")",
"\"Forgot to Clock Out?\"",
@@ -1128,8 +1129,8 @@
"Where each piece lives",
"Troubleshooting",
"\"Incorrect PIN\"",
- "\"No PIN set. Please set a PIN in your account settings.\"",
- "\"PIN must be 4 digits\"",
+ "\"Too many incorrect PINs. Please wait a few minutes and try again.\"",
+ "\"No PIN set. Ask an admin to set a console PIN for you.\"",
"\"Group members are required\"",
"A user can sign in but sees nothing / can't open a module",
"Editing an employee type didn't change existing people's access",
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 01d4b3f23a..3ca06deb65 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -502,9 +502,17 @@ export async function getKanbans(
export async function getKanban(
client: SupabaseClient<Database>,
- kanbanId: string
+ kanbanId: string,
+ companyId: string
) {
- return client.from("kanbans").select("*").eq("id", kanbanId).single();
+ // Scoped by company, not left to RLS: a user in several companies can read
+ // every one of their companies' kanbans, and a scan acts in the ACTIVE one.
+ return client
+ .from("kanbans")
+ .select("*")
+ .eq("id", kanbanId)
+ .eq("companyId", companyId)
+ .single();
}
export async function getStockTransfer(
@@ -2952,6 +2960,7 @@ export async function setPickingListLineTrackedEntity(
quantity?: number;
unpick?: boolean;
userId: string;
+ companyId: string;
}
) {
const lineResult = await client
@@ -2960,6 +2969,9 @@ export async function setPickingListLineTrackedEntity(
"*, pickingList(locationId, companyId, status), item(itemTrackingType)"
)
.eq("id", args.pickingListLineId)
+ // Callers pass the service role: the company scope is the tenant boundary,
+ // and the edge function below acts in args.companyId, never the row's.
+ .eq("companyId", args.companyId)
.single();
if (lineResult.error || !lineResult.data) {
@@ -3011,7 +3023,7 @@ export async function setPickingListLineTrackedEntity(
trackedEntityId: args.trackedEntityId,
locationId: pickingList.locationId,
userId: args.userId,
- companyId: pickingList.companyId
+ companyId: args.companyId
};
if (!args.unpick) {
body.fromStorageUnitId = args.fromStorageUnitId ?? null;
@@ -3146,6 +3158,7 @@ export async function cancelOpenPickingListsForJob(
"in",
lines.map((line) => line.id)
)
+ .where("companyId", "=", args.companyId)
.execute();
const pickingListIds = Array.from(
@@ -3939,6 +3952,7 @@ export async function pickPickingListLine(
quantity: number;
markShort?: boolean;
userId: string;
+ companyId: string;
}
) {
const lineResult = await client
@@ -3947,6 +3961,9 @@ export async function pickPickingListLine(
"*, pickingList(locationId, companyId, status), item(itemTrackingType)"
)
.eq("id", args.pickingListLineId)
+ // Callers pass the service role: the company scope is the tenant boundary,
+ // and the edge function below acts in args.companyId, never the row's.
+ .eq("companyId", args.companyId)
.single();
if (lineResult.error || !lineResult.data) {
@@ -4006,7 +4023,7 @@ export async function pickPickingListLine(
quantity: delta,
locationId: pickingList.locationId,
userId: args.userId,
- companyId: pickingList.companyId
+ companyId: args.companyId
}
: {
type: "unpickInventory",
@@ -4015,7 +4032,7 @@ export async function pickPickingListLine(
quantity: -delta,
locationId: pickingList.locationId,
userId: args.userId,
- companyId: pickingList.companyId
+ companyId: args.companyId
};
const result = await client.functions.invoke("post-picking", { body });
@@ -4041,7 +4058,8 @@ export async function pickPickingListLine(
updatedBy: args.userId,
updatedAt: new Date().toISOString()
})
- .eq("id", line.id);
+ .eq("id", line.id)
+ .eq("companyId", args.companyId);
if (update.error) {
return { data: null, error: update.error };
}
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 20aadfddbc..5d897c5f75 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -40,6 +40,7 @@ import {
getCustomerPayment,
getCustomerShipping
} from "../sales/sales.service";
+import { updateSortOrder } from "../shared/sort-order";
import type {
CardTransactionStatusType,
CardTransactionType,
@@ -978,16 +979,18 @@ export async function upsertPurchaseInvoiceLine(
export async function updatePurchaseInvoiceLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ invoiceId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("purchaseInvoiceLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "purchaseInvoiceLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "invoiceId", id: invoiceId },
+ updates
});
}
@@ -1354,16 +1357,18 @@ export async function upsertSalesInvoiceLine(
export async function updateSalesInvoiceLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ invoiceId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("salesInvoiceLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "salesInvoiceLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "invoiceId", id: invoiceId },
+ updates
});
}
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 958fa32fe4..abdff380c9 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -35,6 +35,7 @@ import {
type SourcingType,
type SupplierPriceMap
} from "../shared";
+import { updateSortOrder } from "../shared/sort-order";
import {
type ChangeNoticeChangeType,
type ChangeNoticeError,
@@ -2896,6 +2897,7 @@ export async function upsertPickMethodWithShelfLife(
defaultStorageUnitId?: string | null;
sortMethod?: (typeof pickMethodSortMethods)[number];
customFields?: Json;
+ companyId: string;
userId: string;
shelfLife: {
mode?: (typeof shelfLifeModes)[number];
@@ -2909,6 +2911,18 @@ export async function upsertPickMethodWithShelfLife(
const updatedAt = datetime.timestamp();
return db.transaction().execute(async (trx) => {
+ // Kysely bypasses RLS and itemId comes from the URL, so prove the item is
+ // this company's before any write — every statement below is also scoped.
+ const item = await trx
+ .selectFrom("item")
+ .select("id")
+ .where("id", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!item) {
+ throw new Error(`Item ${args.itemId} not found`);
+ }
+
await trx
.updateTable("pickMethod")
.set({
@@ -2922,6 +2936,7 @@ export async function upsertPickMethodWithShelfLife(
})
.where("itemId", "=", args.itemId)
.where("locationId", "=", args.locationId)
+ .where("companyId", "=", args.companyId)
.execute();
const { mode, days, triggerProcessId, triggerTiming, calculateFromBom } =
@@ -2935,6 +2950,7 @@ export async function upsertPickMethodWithShelfLife(
await trx
.deleteFrom("itemShelfLife")
.where("itemId", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
.execute();
return;
}
@@ -2957,6 +2973,7 @@ export async function upsertPickMethodWithShelfLife(
.innerJoin("activeMakeMethods as amm", "amm.id", "mo.makeMethodId")
.select("mo.processId")
.where("amm.itemId", "=", args.itemId)
+ .where("amm.companyId", "=", args.companyId)
.where("mo.processId", "is not", null)
.execute();
const allowed = new Set(
@@ -2975,6 +2992,7 @@ export async function upsertPickMethodWithShelfLife(
.selectFrom("itemShelfLife")
.select("itemId")
.where("itemId", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
.executeTakeFirst();
if (existing) {
@@ -2990,20 +3008,11 @@ export async function upsertPickMethodWithShelfLife(
updatedAt
})
.where("itemId", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
.execute();
return;
}
- const itemRow = await trx
- .selectFrom("item")
- .select("companyId")
- .where("id", "=", args.itemId)
- .executeTakeFirstOrThrow();
-
- if (!itemRow.companyId) {
- throw new Error(`Item ${args.itemId} has no companyId`);
- }
-
await trx
.insertInto("itemShelfLife")
.values({
@@ -3013,7 +3022,7 @@ export async function upsertPickMethodWithShelfLife(
triggerProcessId: normalizedTriggerProcess,
triggerTiming: normalizedTriggerTiming,
calculateFromBom: normalizedCalcFromBom,
- companyId: itemRow.companyId,
+ companyId: args.companyId,
createdBy: args.userId
})
.execute();
@@ -3192,10 +3201,22 @@ export async function updateItemMethodAndSourcing(
const updatedAt = datetime.timestamp();
+ // An explicit allow-list, never a spread: `itemUpdate` reaches this from the
+ // API with whatever keys the caller sent, and Kysely bypasses RLS — a spread
+ // would let `{ companyId }` (or any other column) through to the UPDATE.
+ const { replenishmentSystem, defaultMethodType, sourcingType } =
+ args.itemUpdate;
+
return db.transaction().execute(async (trx) => {
await trx
.updateTable("item")
- .set({ ...args.itemUpdate, updatedBy: args.userId, updatedAt })
+ .set({
+ ...(replenishmentSystem !== undefined && { replenishmentSystem }),
+ ...(defaultMethodType !== undefined && { defaultMethodType }),
+ ...(sourcingType !== undefined && { sourcingType }),
+ updatedBy: args.userId,
+ updatedAt
+ })
.where("id", "in", args.itemIds)
.where("companyId", "=", args.companyId)
.execute();
@@ -7188,28 +7209,20 @@ export async function deleteChangeNoticeAction(
return client.from("changeOrderActionTask").delete().eq("id", id);
}
-// Bulk reorder (drag-sort) — a multi-row write, so Kysely (route passes
-// getDatabaseClient()). Kysely bypasses RLS and the ids come from the request
-// body, so every update is scoped to the owning change notice + company.
export async function updateChangeNoticeActionOrder(
db: Kysely<KyselyDatabase>,
- args: {
- changeNoticeId: string;
- companyId: string;
- updates: { id: string; sortOrder: number; updatedBy: string }[];
- }
+ companyId: string,
+ userId: string,
+ changeNoticeId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- const { changeNoticeId, companyId, updates } = args;
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("changeOrderActionTask")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .where("changeOrderId", "=", changeNoticeId)
- .where("companyId", "=", companyId)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "changeOrderActionTask",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "changeOrderId", id: changeNoticeId },
+ updates
});
}
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index d6a46a62b0..b4ccd21e12 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -615,18 +615,93 @@ export async function updateEmployeeJob(
// so a caller that omits it (the API/MCP tool leaves it optional) would
// otherwise wipe a set location. Never write a falsy locationId — drop it
// from the payload so the existing value is preserved.
- const updatePayload = sanitize(employeeJob);
- if (!updatePayload.locationId) {
- delete (updatePayload as { locationId?: unknown }).locationId;
- }
+ const sanitized = sanitize(employeeJob);
+ // An explicit allow-list, never the caller's object: the API passes
+ // `employeeJob` through with whatever keys were sent, and a spread into
+ // Kysely's `.set()` (no RLS) would reach any column — `companyId` included.
+ const updatePayload = {
+ title: sanitized.title,
+ startDate: sanitized.startDate,
+ ...(sanitized.locationId ? { locationId: sanitized.locationId } : {}),
+ shiftId: sanitized.shiftId,
+ departmentId: sanitized.departmentId,
+ managerId: sanitized.managerId,
+ ...("customFields" in sanitized
+ ? { customFields: sanitized.customFields }
+ : {}),
+ updatedBy: sanitized.updatedBy
+ };
+
+ const { companyId } = employeeJob;
await db.transaction().execute(async (trx) => {
- await trx
+ // Kysely bypasses RLS and every id below comes from the caller, so each
+ // one is re-read under companyId: the single-column FKs would accept a
+ // location, shift, department or manager from any company.
+ const [employee, location, shift, department, manager] =
+ await Promise.all([
+ trx
+ .selectFrom("employee")
+ .select("id")
+ .where("id", "=", employeeId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ updatePayload.locationId
+ ? trx
+ .selectFrom("location")
+ .select("id")
+ .where("id", "=", updatePayload.locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ employeeJob.shiftId
+ ? trx
+ .selectFrom("shift")
+ .select("id")
+ .where("id", "=", employeeJob.shiftId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ employeeJob.departmentId
+ ? trx
+ .selectFrom("department")
+ .select("id")
+ .where("id", "=", employeeJob.departmentId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ employeeJob.managerId
+ ? trx
+ .selectFrom("employee")
+ .select("id")
+ .where("id", "=", employeeJob.managerId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null
+ ]);
+ if (!employee) throw new Error("Employee not found");
+ if (updatePayload.locationId && !location) {
+ throw new Error("Location not found");
+ }
+ if (employeeJob.shiftId && !shift) throw new Error("Shift not found");
+ if (employeeJob.departmentId && !department) {
+ throw new Error("Department not found");
+ }
+ if (employeeJob.managerId && !manager) {
+ throw new Error("Manager not found");
+ }
+
+ const updated = await trx
.updateTable("employeeJob")
.set(updatePayload)
.where("id", "=", employeeId)
- .where("companyId", "=", employeeJob.companyId)
- .execute();
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ // No row means the employee is not in this company — stop before the
+ // employeeShift insert below writes a row for a foreign user id.
+ if (Number(updated.numUpdatedRows) === 0) {
+ throw new Error("Employee not found");
+ }
// The scheduler reads shift assignments from employeeShift (see
// getEmployeeShiftWindows in the schedule engine), NOT from
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 1d947440bb..832bd9d389 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -54,6 +54,7 @@ import type {
operationToolValidator
} from "../shared";
import { normalizeOperationSourceIds } from "../shared";
+import { updateSortOrder } from "../shared/sort-order";
import {
listBalloons,
listInspectionFeatures,
@@ -90,6 +91,7 @@ import {
cameraSchema,
fastenerSchema,
getAssemblyModelState,
+ isJobLocked,
isJobOrderStatusHidden,
JOB_LOCKED_STATUSES,
JOB_SUPPLY_STATUS_PRIORITY,
@@ -2729,6 +2731,7 @@ export async function runMRP(
export async function updateJobBatchNumber(
client: SupabaseClient<Database>,
+ companyId: string,
trackedEntityId: string,
value: string | null
) {
@@ -2738,6 +2741,7 @@ export async function updateJobBatchNumber(
readableId: value
})
.eq("id", trackedEntityId)
+ .eq("companyId", companyId)
.select("id, readableId");
}
@@ -3734,15 +3738,27 @@ export async function upsertJobMaterial(
| (z.infer<typeof jobMaterialValidator> & {
jobId: string;
jobOperationId?: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
) {
if ("updatedBy" in jobMaterial) {
+ // A material never moves between jobs, make methods or tenants — strip the
+ // parent columns so an update cannot re-parent the row, and scope it to
+ // the caller's company (callers may pass a service-role client).
+ const {
+ id,
+ companyId,
+ jobId: _jobId,
+ jobMakeMethodId: _jobMakeMethodId,
+ ...update
+ } = jobMaterial;
return client
.from("jobMaterial")
- .update(sanitize(jobMaterial))
- .eq("id", jobMaterial.id)
+ .update(sanitize(update))
+ .eq("id", id)
+ .eq("companyId", companyId)
.select("id, methodType")
.single();
}
@@ -3771,10 +3787,20 @@ export async function upsertJobOperation(
) {
const normalized = normalizeOperationSourceIds(jobOperation);
if ("updatedBy" in normalized) {
+ // An operation never moves between jobs, make methods or tenants — strip
+ // the parent columns so an update cannot re-parent the row.
+ const {
+ id,
+ companyId,
+ jobId: _jobId,
+ jobMakeMethodId: _jobMakeMethodId,
+ ...update
+ } = normalized;
return client
.from("jobOperation")
- .update(sanitize(normalized))
- .eq("id", normalized.id)
+ .update(sanitize(update))
+ .eq("id", id)
+ .eq("companyId", companyId)
.select("id")
.single();
}
@@ -5191,7 +5217,7 @@ export async function getActiveEmployeeAbilities(
* `employeeShift`. The same ladder the boards' shift filter displays through,
* so a row a filtered board shows is always a row its mutations can reach.
*/
-function whereEffectiveShift(shiftId: string) {
+function whereEffectiveShift(shiftId: string, companyId: string) {
return (eb: ExpressionBuilder<KyselyDatabase, "peopleAssignment">) =>
eb.or([
eb("shiftId", "=", shiftId),
@@ -5204,11 +5230,78 @@ function whereEffectiveShift(shiftId: string) {
.selectFrom("employeeShift")
.select("employeeId")
.where("shiftId", "=", shiftId)
+ .where("companyId", "=", companyId)
)
])
]);
}
+/**
+ * The people-board mutations write caller-supplied ids through Kysely (no
+ * RLS), and the API dispatcher reaches them without the board route's own
+ * check, so every referenced row must belong to `companyId` — the employee
+ * as an employee of the company. One query per table; absent refs are skipped.
+ * Throws, like the Kysely callers it guards.
+ */
+async function requirePeopleBoardRefs(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ refs: {
+ employeeId?: string;
+ locationId?: string;
+ shiftId?: string | null;
+ workCenterIds?: string[];
+ }
+) {
+ const workCenterIds = [...new Set(refs.workCenterIds ?? [])];
+ const [employee, location, shift, workCenters] = await Promise.all([
+ refs.employeeId
+ ? db
+ .selectFrom("employee")
+ .select("id")
+ .where("id", "=", refs.employeeId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ refs.locationId
+ ? db
+ .selectFrom("location")
+ .select("id")
+ .where("id", "=", refs.locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ refs.shiftId
+ ? db
+ .selectFrom("shift")
+ .select("id")
+ .where("id", "=", refs.shiftId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ workCenterIds.length > 0
+ ? db
+ .selectFrom("workCenter")
+ .select("id")
+ .where("id", "in", workCenterIds)
+ .where("companyId", "=", companyId)
+ .execute()
+ : []
+ ]);
+ if (
+ (refs.employeeId && !employee) ||
+ (refs.locationId && !location) ||
+ (refs.shiftId && !shift) ||
+ workCenters.length !== workCenterIds.length
+ ) {
+ logger.error("People board reference is not in the caller's company", {
+ companyId,
+ refs
+ });
+ throw new Error("Not found");
+ }
+}
+
/**
* Move-semantics upsert: one magnet per person per date/shift — any existing
* assignment for the person on that date/shift is replaced.
@@ -5228,6 +5321,12 @@ export async function upsertPeopleAssignment(
createdBy: string;
}
) {
+ await requirePeopleBoardRefs(db, assignment.companyId, {
+ employeeId: assignment.employeeId,
+ locationId: assignment.locationId,
+ shiftId: assignment.shiftId,
+ workCenterIds: [assignment.workCenterId]
+ });
if (assignment.hours !== undefined) {
// remainder assignment: ADD hours at this station without touching the
// person's other stations; same-station rows merge their hours
@@ -5240,7 +5339,9 @@ export async function upsertPeopleAssignment(
.where("date", "=", assignment.date)
.where("workCenterId", "=", assignment.workCenterId);
existing = assignment.shiftId
- ? existing.where(whereEffectiveShift(assignment.shiftId))
+ ? existing.where(
+ whereEffectiveShift(assignment.shiftId, assignment.companyId)
+ )
: existing.where("shiftId", "is", null);
const row = await existing.executeTakeFirst();
if (row) {
@@ -5286,7 +5387,9 @@ export async function upsertPeopleAssignment(
.where("employeeId", "=", assignment.employeeId)
.where("date", "=", assignment.date);
existing = assignment.shiftId
- ? existing.where(whereEffectiveShift(assignment.shiftId))
+ ? existing.where(
+ whereEffectiveShift(assignment.shiftId, assignment.companyId)
+ )
: existing.where("shiftId", "is", null);
// moving stations keeps the person's authorized overtime for that day
const carriedOvertime = (await existing.executeTakeFirst())?.overtimeHours;
@@ -5298,7 +5401,7 @@ export async function upsertPeopleAssignment(
.where("employeeId", "=", assignment.employeeId)
.where("date", "=", assignment.date);
del = assignment.shiftId
- ? del.where(whereEffectiveShift(assignment.shiftId))
+ ? del.where(whereEffectiveShift(assignment.shiftId, assignment.companyId))
: del.where("shiftId", "is", null);
await del.execute();
return trx
@@ -5374,6 +5477,9 @@ export async function movePeopleAssignment(
db: Kysely<KyselyDatabase>,
args: { id: string; companyId: string; workCenterId: string }
) {
+ await requirePeopleBoardRefs(db, args.companyId, {
+ workCenterIds: [args.workCenterId]
+ });
return db.transaction().execute(async (trx) => {
const source = await trx
.selectFrom("peopleAssignment")
@@ -5391,6 +5497,7 @@ export async function movePeopleAssignment(
.selectFrom("employeeShift")
.select("shiftId")
.where("employeeId", "=", source.employeeId)
+ .where("companyId", "=", args.companyId)
.executeTakeFirst()
)?.shiftId ??
null;
@@ -5402,7 +5509,7 @@ export async function movePeopleAssignment(
.where("date", "=", source.date)
.where("workCenterId", "=", args.workCenterId);
targetQuery = effectiveShiftId
- ? targetQuery.where(whereEffectiveShift(effectiveShiftId))
+ ? targetQuery.where(whereEffectiveShift(effectiveShiftId, args.companyId))
: targetQuery.where("shiftId", "is", null);
const target = await targetQuery.executeTakeFirst();
@@ -5448,6 +5555,8 @@ export async function movePeopleAssignment(
*/
export async function setPeopleDay(
db: Kysely<KyselyDatabase>,
+ /** the authenticated user — filled by the caller, never the payload */
+ userId: string,
args: {
companyId: string;
locationId: string;
@@ -5466,9 +5575,14 @@ export async function setPeopleDay(
workCenterId: string;
hours: number | null;
}[];
- createdBy: string;
}
) {
+ await requirePeopleBoardRefs(db, args.companyId, {
+ employeeId: args.employeeId,
+ locationId: args.locationId,
+ shiftId: args.shiftId,
+ workCenterIds: args.rows.map((row) => row.workCenterId)
+ });
return db.transaction().execute(async (trx) => {
// location-scoped: the rows this reconciliation may DELETE must be limited
// to the board the edit was made on
@@ -5480,7 +5594,9 @@ export async function setPeopleDay(
.where("employeeId", "=", args.employeeId)
.where("date", "=", args.date);
if (args.shiftId) {
- existingQuery = existingQuery.where(whereEffectiveShift(args.shiftId));
+ existingQuery = existingQuery.where(
+ whereEffectiveShift(args.shiftId, args.companyId)
+ );
}
const existing = await existingQuery.execute();
const existingByStation = new Map(
@@ -5497,7 +5613,7 @@ export async function setPeopleDay(
hours: row.hours,
overtimeHours: args.overtimeHours,
note: args.note,
- updatedBy: args.createdBy,
+ updatedBy: userId,
updatedAt: new Date().toISOString()
})
.where("id", "=", id)
@@ -5516,7 +5632,7 @@ export async function setPeopleDay(
hours: row.hours,
overtimeHours: args.overtimeHours,
note: args.note,
- createdBy: args.createdBy
+ createdBy: userId
})
.execute();
}
@@ -5597,7 +5713,7 @@ export async function setPeopleOvertimeBulk(
? query.where("date", ">=", args.date).where("date", "<=", args.toDate)
: query.where("date", "=", args.date);
if (args.shiftId) {
- query = query.where(whereEffectiveShift(args.shiftId));
+ query = query.where(whereEffectiveShift(args.shiftId, args.companyId));
}
if (args.departmentId) {
const departmentId = args.departmentId;
@@ -5651,7 +5767,9 @@ async function copyPeopleDayInTransaction(
.where("locationId", "=", args.locationId)
.where("date", "=", args.fromDate);
if (args.shiftId) {
- sourceQuery = sourceQuery.where(whereEffectiveShift(args.shiftId));
+ sourceQuery = sourceQuery.where(
+ whereEffectiveShift(args.shiftId, args.companyId)
+ );
}
const source = await sourceQuery.execute();
@@ -5718,6 +5836,8 @@ const toIsoDate = (value: unknown) => {
*/
export async function assignPeopleWeek(
db: Kysely<KyselyDatabase>,
+ /** the authenticated user — filled by the caller, never the payload */
+ userId: string,
args: {
companyId: string;
locationId: string;
@@ -5725,9 +5845,14 @@ export async function assignPeopleWeek(
workCenterId: string;
weekStart: string;
shiftId: string | null;
- createdBy: string;
}
) {
+ await requirePeopleBoardRefs(db, args.companyId, {
+ employeeId: args.employeeId,
+ locationId: args.locationId,
+ shiftId: args.shiftId,
+ workCenterIds: [args.workCenterId]
+ });
return db.transaction().execute(async (trx) => {
// working days: the chosen shift's weekdays → the person's own shift's
// weekdays → Mon–Fri
@@ -5762,6 +5887,7 @@ export async function assignPeopleWeek(
"shift.sunday"
])
.where("employeeShift.employeeId", "=", args.employeeId)
+ .where("employeeShift.companyId", "=", args.companyId)
.where("shift.companyId", "=", args.companyId)
.executeTakeFirst();
}
@@ -5814,7 +5940,7 @@ export async function assignPeopleWeek(
employeeId: args.employeeId,
date,
shiftId: args.shiftId,
- createdBy: args.createdBy
+ createdBy: userId
});
}
if (rows.length > 0) {
@@ -5847,7 +5973,7 @@ export async function unassignPeopleWeek(
.where("date", ">=", args.weekStart)
.where("date", "<=", addIsoDays(args.weekStart, 6));
if (args.shiftId) {
- query = query.where(whereEffectiveShift(args.shiftId));
+ query = query.where(whereEffectiveShift(args.shiftId, args.companyId));
}
return query.execute();
}
@@ -5868,6 +5994,9 @@ export async function movePeopleWeek(
shiftId: string | null;
}
) {
+ await requirePeopleBoardRefs(db, args.companyId, {
+ workCenterIds: [args.workCenterId]
+ });
const weekEnd = addIsoDays(args.weekStart, 6);
return db.transaction().execute(async (trx) => {
let sourceQuery = trx
@@ -5879,7 +6008,9 @@ export async function movePeopleWeek(
.where("date", ">=", args.weekStart)
.where("date", "<=", weekEnd);
if (args.shiftId) {
- sourceQuery = sourceQuery.where(whereEffectiveShift(args.shiftId));
+ sourceQuery = sourceQuery.where(
+ whereEffectiveShift(args.shiftId, args.companyId)
+ );
}
const source = await sourceQuery.execute();
@@ -5961,6 +6092,8 @@ export async function copyPeopleWeek(
*/
export async function setPeopleAbsenceRange(
db: Kysely<KyselyDatabase>,
+ /** the authenticated user — filled by the caller, never the payload */
+ userId: string,
args: {
companyId: string;
employeeId: string;
@@ -5968,9 +6101,12 @@ export async function setPeopleAbsenceRange(
toDate: string;
shiftId: string | null;
note?: string;
- createdBy: string;
}
) {
+ await requirePeopleBoardRefs(db, args.companyId, {
+ employeeId: args.employeeId,
+ shiftId: args.shiftId
+ });
return db.transaction().execute(async (trx) => {
const existing = await trx
.selectFrom("peopleAbsence")
@@ -6003,7 +6139,7 @@ export async function setPeopleAbsenceRange(
date,
shiftId: args.shiftId,
note: args.note ?? null,
- createdBy: args.createdBy
+ createdBy: userId
});
}
if (rows.length > 0) {
@@ -7467,16 +7603,18 @@ export async function updateAssemblyInstructionStepStatus(
export async function updateAssemblyInstructionStepOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ assemblyInstructionId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("assemblyInstructionStep")
- .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "assemblyInstructionStep",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "assemblyInstructionId", id: assemblyInstructionId },
+ updates
});
}
@@ -7702,16 +7840,27 @@ async function getNextStepMaterialSortOrder(
export async function updateAssemblyInstructionStepMaterialOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ assemblyInstructionId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("assemblyInstructionStepMaterial")
- .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "assemblyInstructionStepMaterial",
+ column: "sortOrder",
+ companyId,
+ userId,
+ // A material hangs off a step, so it is scoped to the instruction
+ // through that step.
+ parent: {
+ column: "stepId",
+ via: {
+ table: "assemblyInstructionStep",
+ column: "assemblyInstructionId",
+ id: assemblyInstructionId
+ }
+ },
+ updates
});
}
@@ -8560,6 +8709,25 @@ export async function syncAssemblyInstructionToOperation(
const slideTable = "jobOperationStepSlide" as const;
return db.transaction().execute(async (trx) => {
+ // The operation id comes from the caller and every write below is keyed on
+ // it, so it must belong to this company — and, since the API reaches this
+ // without the route's check, its job must not be locked.
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .innerJoin("job", (join) =>
+ join
+ .onRef("job.id", "=", "jobOperation.jobId")
+ .onRef("job.companyId", "=", "jobOperation.companyId")
+ )
+ .select(["jobOperation.id", "job.status"])
+ .where("jobOperation.id", "=", operationId)
+ .where("jobOperation.companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!operation) throw new Error("Operation not found");
+ if (isJobLocked(operation.status)) {
+ throw new Error("This job is locked — steps can't be synced to it");
+ }
+
const instruction = await trx
.selectFrom("assemblyInstruction")
.select(["id", "itemId", "modelUploadId"])
@@ -8811,7 +8979,14 @@ export async function syncAssemblyInstructionToOperation(
// Refresh part links on the synced steps only (hand-authored steps keep theirs).
await trx
.deleteFrom("jobMaterialStep")
- .where("jobOperationStepId", "in", syncedTargetIds)
+ // No companyId column — scope through the step it links to.
+ .where("jobOperationStepId", "in", (eb) =>
+ eb
+ .selectFrom("jobOperationStep")
+ .select("id")
+ .where("id", "in", syncedTargetIds)
+ .where("companyId", "=", companyId)
+ )
.execute();
if (linkPairs.length > 0) {
await trx
@@ -8833,6 +9008,7 @@ export async function syncAssemblyInstructionToOperation(
await trx
.deleteFrom(slideTable)
.where("stepId", "in", syncedTargetIds)
+ .where("companyId", "=", companyId)
.execute();
const slideRows: {
stepId: string;
@@ -8921,13 +9097,21 @@ export async function syncAssemblyInstructionToOperation(
.updateTable("jobOperationTool")
.set({ quantity, updatedBy: userId, updatedAt: now })
.where("id", "=", existingId)
+ .where("companyId", "=", companyId)
.execute();
}
}
}
await trx
.deleteFrom("jobOperationToolStep")
- .where("jobOperationStepId", "in", syncedTargetIds)
+ // No companyId column — scope through the step it links to.
+ .where("jobOperationStepId", "in", (eb) =>
+ eb
+ .selectFrom("jobOperationStep")
+ .select("id")
+ .where("id", "in", syncedTargetIds)
+ .where("companyId", "=", companyId)
+ )
.execute();
const toolLinkRows = buildAssemblyToolStepLinks(
sourceSteps,
@@ -8990,10 +9174,13 @@ export async function generateAssemblyStepsFromPlan(
mode?: "generate" | "regenerate";
}
): Promise<GenerateStepsResult> {
+ // The route calls this with the service role (bypassRls) and a URL id, so
+ // every read and write is scoped to the caller's company.
const instruction = await client
.from("assemblyInstruction")
.select("id, modelUploadId, modelUpload(graphPath)")
.eq("id", args.assemblyInstructionId)
+ .eq("companyId", args.companyId)
.single();
if (instruction.error || !instruction.data.modelUploadId) {
return { ok: false, reason: "no-model" };
@@ -9003,7 +9190,8 @@ export async function generateAssemblyStepsFromPlan(
const existing = await client
.from("assemblyInstructionStep")
.select("id, planConfidence, status")
- .eq("assemblyInstructionId", args.assemblyInstructionId);
+ .eq("assemblyInstructionId", args.assemblyInstructionId)
+ .eq("companyId", args.companyId);
if ((existing.data ?? []).length > 0) {
if (args.mode !== "regenerate") {
return { ok: false, reason: "steps-exist", modelUploadId };
@@ -9024,7 +9212,8 @@ export async function generateAssemblyStepsFromPlan(
const removed = await client
.from("assemblyInstructionStep")
.delete()
- .eq("assemblyInstructionId", args.assemblyInstructionId);
+ .eq("assemblyInstructionId", args.assemblyInstructionId)
+ .eq("companyId", args.companyId);
if (removed.error) {
return { ok: false, reason: "error", message: removed.error.message };
}
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index a3cea8ffc8..dc9d223620 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -29,6 +29,7 @@ import {
} from "../accounting/accounting.service";
import type { PurchaseInvoice } from "../invoicing/types";
import { upsertExternalLink } from "../shared/shared.service";
+import { updateSortOrder } from "../shared/sort-order";
import type {
purchaseOrderDeliveryValidator,
purchaseOrderLineValidator,
@@ -582,15 +583,17 @@ export async function getSupplier(
export async function getSupplierContact(
client: SupabaseClient<Database>,
- supplierContactId: string
+ supplierContactId: string,
+ companyId?: string
) {
- return client
+ let query = client
.from("supplierContact")
.select(
"*, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, notes)"
)
- .eq("id", supplierContactId)
- .single();
+ .eq("id", supplierContactId);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.single();
}
export async function getSupplierContacts(
@@ -1927,16 +1930,18 @@ export async function upsertPurchaseOrderLine(
export async function updatePurchaseOrderLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ purchaseOrderId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("purchaseOrderLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "purchaseOrderLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "purchaseOrderId", id: purchaseOrderId },
+ updates
});
}
@@ -2475,16 +2480,18 @@ export async function upsertSupplierQuoteLine(
export async function updateSupplierQuoteLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ supplierQuoteId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("supplierQuoteLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "supplierQuoteLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "supplierQuoteId", id: supplierQuoteId },
+ updates
});
}
@@ -2792,16 +2799,18 @@ export async function upsertPurchasingRFQLine(
export async function updatePurchasingRFQLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ purchasingRfqId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("purchasingRfqLine")
- .set({ order: sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "purchasingRfqLine",
+ column: "order",
+ companyId,
+ userId,
+ parent: { column: "purchasingRfqId", id: purchasingRfqId },
+ updates
});
}
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index d56d1dc0f3..379533e9de 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -1767,16 +1767,20 @@ export async function insertIssue(
}
if (jobOperationId) {
+ // Callers pass the service role, so every lookup keyed on a caller id is
+ // scoped: a foreign id matches nothing and no link is written.
const jobOperation = await client
.from("jobOperation")
.select("*")
.eq("id", jobOperationId)
+ .eq("companyId", input.companyId)
.single();
if (jobOperation?.data) {
const job = await client
.from("job")
.select("*")
.eq("id", jobOperation.data.jobId)
+ .eq("companyId", input.companyId)
.single();
if (job.data) {
const jobOperationInsert = await client
@@ -1821,6 +1825,7 @@ export async function insertIssue(
.from("salesOrderLine")
.select("*, salesOrder(salesOrderId)")
.eq("id", salesOrderLineId)
+ .eq("companyId", input.companyId)
.single();
if (salesOrderLine.data) {
const salesOrderLineInsert = await client
@@ -1848,6 +1853,7 @@ export async function insertIssue(
.from("supplierProcess")
.select("*")
.eq("id", operationSupplierProcessId)
+ .eq("companyId", input.companyId)
.single();
if (operationSupplierProcess.data) {
diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.ts
index cd15299ce4..96350eb13e 100644
--- a/apps/erp/app/modules/sales/sales.server.ts
+++ b/apps/erp/app/modules/sales/sales.server.ts
@@ -194,25 +194,38 @@ export async function duplicatePriceOverrides(
* written here.
*/
export async function saveQuoteLineWithPrices(args: {
+ companyId: string;
+ quoteId: string;
lineId: string;
line: Record<string, unknown>;
removedQuantities: number[];
priceRows: Record<string, unknown>[];
}): Promise<void> {
- const { lineId, line, removedQuantities, priceRows } = args;
+ const { companyId, quoteId, lineId, line, removedQuantities, priceRows } =
+ args;
const db = getDatabaseClient();
await db.transaction().execute(async (trx) => {
- await trx
+ // Kysely bypasses RLS and lineId/quoteId come from the URL: the line must
+ // belong to this company AND to the quote whose lock state the route
+ // checked, or nothing is written. The form's own quoteId is overridden so
+ // a line can't be re-parented onto another document.
+ const result = await trx
.updateTable("quoteLine")
- .set(line as never)
+ .set({ ...line, quoteId } as never)
.where("id", "=", lineId)
- .execute();
+ .where("quoteId", "=", quoteId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (Number(result.numUpdatedRows) === 0) {
+ throw new Error(`Quote line ${lineId} not found`);
+ }
if (removedQuantities.length > 0) {
await trx
.deleteFrom("quoteLinePrice")
.where("quoteLineId", "=", lineId)
+ .where("companyId", "=", companyId)
.where("quantity", "in", removedQuantities)
.execute();
}
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index cb2c2ff294..7219350684 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -39,6 +39,7 @@ import {
resolveBuyUnitCost,
upsertExternalLink
} from "../shared/shared.service";
+import { updateSortOrder } from "../shared/sort-order";
import type {
customerAccountingValidator,
customerBankAccountValidator,
@@ -2828,6 +2829,44 @@ export async function upsertCustomerItemPriceOverride(
};
}
+ // Kysely bypasses RLS and the dispatcher reaches this with caller-supplied
+ // ids, so the item and the customer (or customer type) must belong to this
+ // company before either is written onto the override.
+ const [item, customer, customerType] = await Promise.all([
+ db
+ .selectFrom("item")
+ .select("id")
+ .where("id", "=", data.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ data.customerId
+ ? db
+ .selectFrom("customer")
+ .select("id")
+ .where("id", "=", data.customerId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ data.customerTypeId
+ ? db
+ .selectFrom("customerType")
+ .select("id")
+ .where("id", "=", data.customerTypeId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null
+ ]);
+ if (
+ !item ||
+ (data.customerId && !customer) ||
+ (data.customerTypeId && !customerType)
+ ) {
+ return {
+ data: null,
+ error: { message: "Item, customer or customer type not found" }
+ };
+ }
+
const sortedBreaks = [...data.breaks].sort((a, b) => a.quantity - b.quantity);
const parentFields = {
@@ -3993,16 +4032,18 @@ export async function upsertQuoteLine(
export async function updateQuoteLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ quoteId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("quoteLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "quoteLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "quoteId", id: quoteId },
+ updates
});
}
@@ -4093,6 +4134,7 @@ async function rewriteQuoteLinePrices(
.selectFrom("quoteLine")
.select("unitPricePrecision")
.where("id", "=", lineId)
+ .where("quoteId", "=", quoteId)
.where("companyId", "=", companyId)
.executeTakeFirst();
@@ -4820,37 +4862,56 @@ export async function resolvePurchaseToOrderPrices(
export async function recalculateQuoteLinePrices(
client: SupabaseClient<Database>,
+ companyId: string,
quoteId: string,
quoteLineId: string,
userId: string
) {
- // 1. Fetch existing price rows
- const existingPrices = await client
- .from("quoteLinePrice")
- .select("*")
- .eq("quoteLineId", quoteLineId);
-
- if (existingPrices.error) return { error: existingPrices.error };
- if (!existingPrices.data?.length) return { error: null };
-
- // 2. Fetch line precision and company + customer context for engine pipe-through
+ // Callers pass a service-role client and URL ids: the line must belong to
+ // this quote AND this company before any price row is read or rewritten.
const [lineResult, quoteResult] = await Promise.all([
client
.from("quoteLine")
.select("itemId, unitPricePrecision")
.eq("id", quoteLineId)
- .single(),
+ .eq("quoteId", quoteId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("quote")
- .select("companyId, customerId")
+ .select("customerId")
.eq("id", quoteId)
- .single()
+ .eq("companyId", companyId)
+ .maybeSingle()
]);
- const precision = lineResult.data?.unitPricePrecision ?? 2;
- const itemId = lineResult.data?.itemId ?? undefined;
- const companyId = quoteResult.data?.companyId;
- const customerId = quoteResult.data?.customerId ?? undefined;
+ if (lineResult.error) return { error: lineResult.error };
+ if (quoteResult.error) return { error: quoteResult.error };
+ if (!lineResult.data || !quoteResult.data) {
+ logger.error("Quote line not found for price recalculation", {
+ companyId,
+ quoteId,
+ quoteLineId
+ });
+ return {
+ error: { message: "Quote line not found" } as PostgrestError
+ };
+ }
+
+ // 1. Fetch existing price rows
+ const existingPrices = await client
+ .from("quoteLinePrice")
+ .select("*")
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId);
+
+ if (existingPrices.error) return { error: existingPrices.error };
+ if (!existingPrices.data?.length) return { error: null };
+
+ // 2. Line precision and customer context for engine pipe-through
+ const precision = lineResult.data.unitPricePrecision ?? 2;
+ const itemId = lineResult.data.itemId ?? undefined;
+ const customerId = quoteResult.data.customerId ?? undefined;
// Fetch default markups to use as fallback for legacy rows without categoryMarkups
let defaultMarkups: Record<string, number> = {};
@@ -4947,6 +5008,7 @@ export async function recalculateQuoteLinePrices(
updatedBy: userId
})
.eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId)
.eq("quantity", row.quantity);
if (updateResult.error) {
@@ -5033,15 +5095,28 @@ export async function upsertQuoteMaterial(
quoteId: string;
quoteLineId: string;
quoteOperationId?: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
) {
if ("updatedBy" in quoteMaterial) {
+ // A material never moves between quotes, lines, make methods or tenants —
+ // strip the parent columns so an update cannot re-parent the row, and
+ // scope it to the caller's company (callers may pass a service-role client).
+ const {
+ id,
+ companyId,
+ quoteId: _quoteId,
+ quoteLineId: _quoteLineId,
+ quoteMakeMethodId: _quoteMakeMethodId,
+ ...update
+ } = quoteMaterial;
return client
.from("quoteMaterial")
- .update(sanitize(quoteMaterial))
- .eq("id", quoteMaterial.id)
+ .update(sanitize(update))
+ .eq("id", id)
+ .eq("companyId", companyId)
.select("id, methodType")
.single();
}
@@ -5138,6 +5213,7 @@ export async function upsertQuoteOperation(
id: string;
quoteId: string;
quoteLineId: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -5149,10 +5225,21 @@ export async function upsertQuoteOperation(
.select("id")
.single();
}
+ // An operation never moves between quotes, lines, make methods or tenants —
+ // strip the parent columns so an update cannot re-parent the row.
+ const {
+ id,
+ companyId,
+ quoteId: _quoteId,
+ quoteLineId: _quoteLineId,
+ quoteMakeMethodId: _quoteMakeMethodId,
+ ...update
+ } = operation;
return client
.from("quoteOperation")
- .update(sanitize(normalizeOperationSourceIds(operation)))
- .eq("id", operation.id)
+ .update(sanitize(normalizeOperationSourceIds(update)))
+ .eq("id", id)
+ .eq("companyId", companyId)
.select("id")
.single();
}
@@ -5969,16 +6056,18 @@ export async function upsertSalesOrderLine(
export async function updateSalesOrderLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ salesOrderId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("salesOrderLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "salesOrderLine",
+ column: "sortOrder",
+ companyId,
+ userId,
+ parent: { column: "salesOrderId", id: salesOrderId },
+ updates
});
}
@@ -6034,6 +6123,76 @@ export async function insertSalesRFQ(
data: { id: string; rfqId: string } | null;
error: PostgrestError | null;
}> {
+ // Kysely bypasses RLS and the dispatcher reaches this with caller-supplied
+ // ids: the customer, its contacts and location, the location and the sales
+ // person must all belong to this company (the contacts and location to this
+ // customer) before any of them is written onto the RFQ.
+ const { companyId, customerId } = input;
+ const contactIds = [
+ ...new Set(
+ [input.customerContactId, input.customerEngineeringContactId].filter(
+ (id): id is string => !!id
+ )
+ )
+ ];
+ const [customer, contacts, customerLocation, location, salesPerson] =
+ await Promise.all([
+ db
+ .selectFrom("customer")
+ .select("id")
+ .where("id", "=", customerId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ contactIds.length > 0
+ ? db
+ .selectFrom("customerContact")
+ .select("id")
+ .where("id", "in", contactIds)
+ .where("customerId", "=", customerId)
+ .where("companyId", "=", companyId)
+ .execute()
+ : [],
+ input.customerLocationId
+ ? db
+ .selectFrom("customerLocation")
+ .select("id")
+ .where("id", "=", input.customerLocationId)
+ .where("customerId", "=", customerId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ input.locationId
+ ? db
+ .selectFrom("location")
+ .select("id")
+ .where("id", "=", input.locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null,
+ input.salesPersonId
+ ? db
+ .selectFrom("employee")
+ .select("id")
+ .where("id", "=", input.salesPersonId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : null
+ ]);
+ if (
+ !customer ||
+ contacts.length !== contactIds.length ||
+ (input.customerLocationId && !customerLocation) ||
+ (input.locationId && !location) ||
+ (input.salesPersonId && !salesPerson)
+ ) {
+ return {
+ data: null,
+ error: {
+ message: "Customer, contact, location or sales person not found"
+ } as PostgrestError
+ };
+ }
+
let rfqId: string;
if (input.rfqId) {
rfqId = input.rfqId;
@@ -6276,16 +6435,18 @@ export async function upsertSalesRFQLine(
export async function updateSalesRFQLineOrder(
db: Kysely<KyselyDatabase>,
- updates: { id: string; sortOrder: number; updatedBy: string }[]
+ companyId: string,
+ userId: string,
+ salesRfqId: string,
+ updates: { id: string; sortOrder: number }[]
) {
- return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("salesRfqLine")
- .set({ order: sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+ return updateSortOrder(db, {
+ table: "salesRfqLine",
+ column: "order",
+ companyId,
+ userId,
+ parent: { column: "salesRfqId", id: salesRfqId },
+ updates
});
}
diff --git a/apps/erp/app/modules/settings/integration-errors.ts b/apps/erp/app/modules/settings/integration-errors.ts
index 6655de095f..32870d124a 100644
--- a/apps/erp/app/modules/settings/integration-errors.ts
+++ b/apps/erp/app/modules/settings/integration-errors.ts
@@ -58,6 +58,10 @@ export const integrationErrors = {
title: msg`Onshape denied the connection`,
description: msg`The authorization was refused in Onshape. Try connecting again.`
},
+ "invalid-state": {
+ title: msg`The Onshape connection expired`,
+ description: msg`Return to Integrations and connect Onshape again.`
+ },
"invalid-response": {
title: msg`Onshape didn't return an authorization code`,
description: msg`The response from Onshape was missing required parameters. Try connecting again.`
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index d387d57c48..84b24f879a 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -28,13 +28,13 @@ import { sanitize } from "~/utils/supabase";
import type {
accountsPayableBillingAddressValidator,
accountsReceivableBillingAddressValidator,
- companyValidator,
itemSerialSequenceValidator,
kanbanOutputTypes,
purchasePriceUpdateTimingTypes,
sequenceValidator,
subsidiaryValidator
} from "./settings.models";
+import { companyValidator } from "./settings.models";
const PUBLIC_STORAGE_URL_PREFIX = `${SUPABASE_URL}/storage/v1/object/public/public/`;
@@ -897,10 +897,18 @@ export async function updateCompanyWithBaseCurrencyChange(
updatedBy: string;
}
) {
+ // An explicit allow-list of the company form's fields, never the caller's
+ // object: Kysely bypasses RLS and the API passes `company` through with
+ // whatever keys were sent, so a spread would reach any column of the row.
+ const allowed = new Set<string>(Object.keys(companyValidator.shape));
+ const fields = Object.fromEntries(
+ Object.entries(sanitize(company)).filter(([key]) => allowed.has(key))
+ ) as Partial<z.infer<typeof companyValidator>>;
+
return db.transaction().execute(async (trx) => {
await trx
.updateTable("company")
- .set(sanitize(company))
+ .set({ ...fields, updatedBy: company.updatedBy })
.where("id", "=", companyId)
.execute();
await trx
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
index 964175d7ba..450b95b515 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
@@ -34,7 +34,6 @@ export function IntegrationCard({
const fetcher = useFetcher<{}>();
const navigate = useNavigate();
const routeData = useRouteData<{
- state: string;
oauthStates: Record<string, string>;
}>(path.to.integrations);
const { isGated } = usePlanGate({ feature: "INTEGRATIONS" });
@@ -43,10 +42,7 @@ export function IntegrationCard({
const handleInstall = async () => {
if ("oauth" in integration && integration.oauth) {
- const state =
- integration.id === "ramp"
- ? routeData?.oauthStates?.[integration.id]
- : routeData?.state;
+ const state = routeData?.oauthStates?.[integration.id];
const oauthUrl = buildIntegrationOAuthUrl(
integration.oauth,
state,
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index 841a5b0109..587d4e6c73 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -3,6 +3,7 @@ import { SalesOrderEmail } from "@carbon/documents/email";
import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
import type { CalendarDate } from "@internationalized/date";
import { startOfWeek } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
@@ -27,6 +28,8 @@ import { stripSpecialCharacters } from "~/utils/string";
import { upsertDocument } from "../documents/documents.service";
import type { CustomFieldsTableType } from "../settings";
+const logger = getLogger("erp", "shared");
+
export async function assign(
client: SupabaseClient<Database>,
args: {
@@ -412,7 +415,9 @@ export async function sendSalesOrderEmail(args: {
paymentTerms
] = await Promise.all([
getCompany(serviceRole, companyId),
- getCustomerContact(serviceRole, customerContactId),
+ // customerContactId comes from the form and the service role bypasses
+ // RLS — scope it so another company's contact is never read or emailed.
+ getCustomerContact(serviceRole, customerContactId, companyId),
getSalesOrder(serviceRole, salesOrderId),
getSalesOrderLines(serviceRole, salesOrderId),
getSalesOrderCustomerDetails(serviceRole, salesOrderId),
@@ -586,3 +591,58 @@ function toPlainPeriod(p: {
periodType: p.periodType
};
}
+
+type Tables = Database["public"]["Tables"];
+
+/**
+ * Every table with a string `id` and a `companyId` column. A nullable
+ * `companyId` (e.g. `item`) is fine: global rows never match `.eq("companyId")`.
+ */
+type CompanyScopedTable = {
+ [K in keyof Tables]: Tables[K]["Row"] extends {
+ id: string;
+ companyId: string | null;
+ }
+ ? K
+ : never;
+}[keyof Tables];
+
+/**
+ * Throws a 404 `Response` unless a row of `table` in `companyId` matches every
+ * column in `match` — e.g. `{ id: lineId, quoteId }` proves the line exists,
+ * belongs to the company AND hangs off that quote. One query.
+ *
+ * Record ids in a URL or form body prove nothing about tenancy:
+ * `requirePermissions` authorizes the CALLER for `companyId`, not the ids it
+ * sends. Most tables have single-column foreign keys, so a service-role or
+ * Kysely write happily accepts another company's row as a parent. Call this
+ * before any RLS-bypassing read or write keyed on a caller-supplied id.
+ */
+export async function requireCompanyRecord(
+ client: SupabaseClient<Database>,
+ table: CompanyScopedTable,
+ companyId: string,
+ match: { id: string } & Record<string, string>
+): Promise<void> {
+ // Every table in the union has `id` + `companyId`; the cast only narrows the
+ // union so supabase-js can type the builder.
+ const { data, error } = await client
+ .from(table as "quoteLine")
+ .select("id")
+ .match(match)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (error) {
+ logger.error(`Failed to verify ${table} for company`, {
+ companyId,
+ match,
+ error
+ });
+ throw new Response("Not found", { status: 404 });
+ }
+ if (!data) {
+ logger.error(`${table} not found for company`, { companyId, match });
+ throw new Response("Not found", { status: 404 });
+ }
+}
diff --git a/apps/erp/app/modules/shared/sort-order.test.ts b/apps/erp/app/modules/shared/sort-order.test.ts
new file mode 100644
index 0000000000..15e869e301
--- /dev/null
+++ b/apps/erp/app/modules/shared/sort-order.test.ts
@@ -0,0 +1,206 @@
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ type CompiledQuery,
+ type DatabaseConnection,
+ DummyDriver,
+ Kysely as KyselyClient,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ type QueryResult
+} from "kysely";
+import { describe, expect, it } from "vitest";
+import {
+ buildSortOrderUpdate,
+ parseSortOrderUpdates,
+ updateSortOrder
+} from "./sort-order";
+
+// The boundary here is the Postgres wire: a driver that records what Kysely
+// sends and answers with the rows the database would have returned. Everything
+// above it — SQL building, the transaction, the row-count check — runs real.
+class RecordingDriver extends DummyDriver {
+ readonly sent: string[] = [];
+ constructor(private readonly returnedIds: string[]) {
+ super();
+ }
+ override async acquireConnection(): Promise<DatabaseConnection> {
+ return {
+ executeQuery: async <R>(
+ query: CompiledQuery
+ ): Promise<QueryResult<R>> => {
+ this.sent.push(query.sql);
+ return { rows: this.returnedIds.map((id) => ({ id })) as R[] };
+ },
+ // biome-ignore lint/correctness/useYield: never streamed
+ streamQuery: async function* () {
+ throw new Error("not streamed");
+ }
+ };
+ }
+ override async beginTransaction() {
+ this.sent.push("BEGIN");
+ }
+ override async commitTransaction() {
+ this.sent.push("COMMIT");
+ }
+ override async rollbackTransaction() {
+ this.sent.push("ROLLBACK");
+ }
+}
+
+function database(returnedIds: string[] = []) {
+ const driver = new RecordingDriver(returnedIds);
+ const db = new KyselyClient<KyselyDatabase>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => driver,
+ createIntrospector: (k) => new PostgresIntrospector(k),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+ }) as unknown as Kysely<KyselyDatabase>;
+ return { db, driver };
+}
+
+const updates = [
+ { id: "ql1", sortOrder: 2 },
+ { id: "ql2", sortOrder: 1 }
+];
+
+describe("buildSortOrderUpdate", () => {
+ it("scopes one UPDATE … FROM (VALUES …) to the company and the parent document", () => {
+ const { db } = database();
+ const compiled = buildSortOrderUpdate({
+ table: "quoteLine",
+ column: "sortOrder",
+ companyId: "c1",
+ userId: "u1",
+ parent: { column: "quoteId", id: "q1" },
+ updates,
+ updatedAt: "2026-09-26T00:00:00.000Z"
+ }).compile(db);
+
+ expect(compiled.sql).toBe(
+ 'UPDATE "quoteLine" AS t SET "sortOrder" = v."sortOrder", "updatedBy" = $1, "updatedAt" = $2 FROM (VALUES ($3::text, $4::numeric), ($5::text, $6::numeric)) AS v("id", "sortOrder") WHERE t."id" = v."id" AND t."companyId" = $7 AND "t"."quoteId" = $8 RETURNING t."id"'
+ );
+ expect(compiled.parameters).toEqual([
+ "u1",
+ "2026-09-26T00:00:00.000Z",
+ "ql1",
+ 2,
+ "ql2",
+ 1,
+ "c1",
+ "q1"
+ ]);
+ });
+
+ it("writes an `order` sort column and scopes a one-hop parent through its table", () => {
+ const { db } = database();
+ const compiled = buildSortOrderUpdate({
+ table: "assemblyInstructionStepMaterial",
+ column: "sortOrder",
+ companyId: "c1",
+ userId: "u1",
+ parent: {
+ column: "stepId",
+ via: {
+ table: "assemblyInstructionStep",
+ column: "assemblyInstructionId",
+ id: "ai1"
+ }
+ },
+ updates: [{ id: "m1", sortOrder: 1 }],
+ updatedAt: "2026-09-26T00:00:00.000Z"
+ }).compile(db);
+
+ expect(compiled.sql).toContain(
+ 'AND "t"."stepId" IN (SELECT p."id" FROM "assemblyInstructionStep" AS p WHERE "p"."assemblyInstructionId" = $6 AND p."companyId" = $7)'
+ );
+ // The subquery is tenant-scoped too, with the same companyId.
+ expect(compiled.parameters.slice(4)).toEqual(["c1", "ai1", "c1"]);
+
+ const rfq = buildSortOrderUpdate({
+ table: "salesRfqLine",
+ column: "order",
+ companyId: "c1",
+ userId: "u1",
+ parent: { column: "salesRfqId", id: "rfq1" },
+ updates: [{ id: "l1", sortOrder: 1 }],
+ updatedAt: "2026-09-26T00:00:00.000Z"
+ }).compile(db);
+ expect(rfq.sql).toContain('UPDATE "salesRfqLine" AS t SET "order" = ');
+ expect(rfq.sql).toContain('AND "t"."salesRfqId" = $6');
+ });
+});
+
+describe("updateSortOrder", () => {
+ const args = {
+ table: "quoteLine" as const,
+ column: "sortOrder" as const,
+ companyId: "c1",
+ userId: "u1",
+ parent: { column: "quoteId" as const, id: "q1" },
+ updates
+ };
+
+ it("issues exactly one statement and commits when every row is on the document", async () => {
+ const { db, driver } = database(["ql1", "ql2"]);
+ await updateSortOrder(db, args);
+ expect(driver.sent).toHaveLength(3);
+ expect(driver.sent[0]).toBe("BEGIN");
+ expect(driver.sent[1]).toMatch(/^UPDATE "quoteLine" AS t /);
+ expect(driver.sent[2]).toBe("COMMIT");
+ });
+
+ it("rolls the whole reorder back when a row is outside the company or document", async () => {
+ // Postgres matched only one of the two ids — the other belongs to another
+ // quote (or company), so the predicates filtered it out.
+ const { db, driver } = database(["ql1"]);
+ await expect(updateSortOrder(db, args)).rejects.toThrow(
+ "quoteLine: 1 of 2 rows are not on this document"
+ );
+ expect(driver.sent).toEqual(["BEGIN", expect.any(String), "ROLLBACK"]);
+ });
+
+ it("refuses an empty parent id instead of issuing an unscoped update", async () => {
+ const { db, driver } = database(["ql1", "ql2"]);
+ await expect(
+ updateSortOrder(db, { ...args, parent: { column: "quoteId", id: "" } })
+ ).rejects.toThrow("quoteLine: missing parent id");
+ expect(driver.sent).toEqual([]);
+ });
+
+ it("sends nothing for an empty reorder", async () => {
+ const { db, driver } = database();
+ await updateSortOrder(db, { ...args, updates: [] });
+ expect(driver.sent).toEqual([]);
+ });
+});
+
+describe("parseSortOrderUpdates", () => {
+ const form = (updates?: string) => {
+ const formData = new FormData();
+ if (updates !== undefined) formData.set("updates", updates);
+ return formData;
+ };
+
+ it("reads the id → sort order map the drag-sort UI posts", () => {
+ expect(parseSortOrderUpdates(form('{"ql1":2,"ql2":"1.5"}'))).toEqual([
+ { id: "ql1", sortOrder: 2 },
+ { id: "ql2", sortOrder: 1.5 }
+ ]);
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["not JSON", "{ql1: 2"],
+ ["empty", "{}"],
+ ["NaN", '{"ql1":"abc"}'],
+ ["blank string (Number() would make it 0)", '{"ql1":""}'],
+ ["null", '{"ql1":null}'],
+ ["an array", "[1,2]"]
+ ])("rejects %s", (_label, updates) => {
+ expect(parseSortOrderUpdates(form(updates))).toBeNull();
+ });
+});
diff --git a/apps/erp/app/modules/shared/sort-order.ts b/apps/erp/app/modules/shared/sort-order.ts
new file mode 100644
index 0000000000..bc02dac156
--- /dev/null
+++ b/apps/erp/app/modules/shared/sort-order.ts
@@ -0,0 +1,172 @@
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { datetime } from "@carbon/utils";
+import { sql } from "kysely";
+import { z } from "zod";
+
+// Drag-sort persistence for every child list (document lines, assembly steps,
+// change-notice actions). Not a `*.service.ts` on purpose: a generic
+// "reorder any table" function must never be scanned into the API/MCP
+// manifest — the per-table wrappers in each module's service are the contract.
+//
+// Kysely bypasses RLS, and the ids come from the request body, so the
+// companyId AND parent-document predicates are the only thing stopping a
+// request made through one document's route from reordering another
+// document's rows. Both are mandatory arguments, not options.
+
+type PublicTables = Database["public"]["Tables"];
+type Row<T extends keyof PublicTables> = PublicTables[T]["Row"];
+
+type SortColumnName = "sortOrder" | "order";
+type RequiredColumns = "id" | "companyId" | "updatedBy" | "updatedAt";
+
+/** Columns of `T` holding a text value (ids, foreign keys). */
+type TextColumn<T extends keyof PublicTables> = {
+ [K in keyof Row<T>]: Row<T>[K] extends string | null ? K : never;
+}[keyof Row<T>] &
+ string;
+
+/** Tables with an `id` and a `companyId` — anything a parent can be. */
+export type TenantTable = {
+ [T in keyof PublicTables]: "id" | "companyId" extends keyof Row<T>
+ ? T
+ : never;
+}[keyof PublicTables];
+
+/** Tables a drag-sort can reorder: tenant key, audit columns and a sort column. */
+export type SortableTable = {
+ [T in keyof PublicTables]: RequiredColumns extends keyof Row<T>
+ ? [Extract<keyof Row<T>, SortColumnName>] extends [never]
+ ? never
+ : T
+ : never;
+}[keyof PublicTables];
+
+export type SortColumn<T extends SortableTable> = Extract<
+ keyof Row<T>,
+ SortColumnName
+>;
+
+export type ParentColumn<T extends keyof PublicTables> = Exclude<
+ TextColumn<T>,
+ RequiredColumns | "createdBy"
+>;
+
+/**
+ * How the rows are tied to the document whose route is reordering them.
+ * `id` when the row carries the parent's id itself (`quoteLine.quoteId`);
+ * `via` when it is one hop away (`assemblyInstructionStepMaterial.stepId` →
+ * `assemblyInstructionStep.assemblyInstructionId`).
+ */
+export type SortParent<T extends SortableTable, P extends TenantTable> =
+ | { column: ParentColumn<T>; id: string }
+ | {
+ column: ParentColumn<T>;
+ via: { table: P; column: ParentColumn<P>; id: string };
+ };
+
+export type UpdateSortOrderArgs<
+ T extends SortableTable,
+ P extends TenantTable = TenantTable
+> = {
+ table: T;
+ column: SortColumn<T>;
+ companyId: string;
+ userId: string;
+ parent: SortParent<T, P>;
+ updates: { id: string; sortOrder: number }[];
+};
+
+/**
+ * The single statement behind `updateSortOrder`, exported so its SQL can be
+ * pinned by compiling it (no database needed).
+ */
+export function buildSortOrderUpdate<
+ T extends SortableTable,
+ P extends TenantTable = TenantTable
+>(args: UpdateSortOrderArgs<T, P> & { updatedAt: string }) {
+ const { table, column, companyId, userId, parent, updates, updatedAt } = args;
+
+ const values = sql.join(
+ updates.map(
+ ({ id, sortOrder }) => sql`(${id}::text, ${sortOrder}::numeric)`
+ )
+ );
+
+ const parentPredicate =
+ "via" in parent
+ ? sql`${sql.ref(`t.${parent.column}`)} IN (SELECT p."id" FROM ${sql.table(parent.via.table)} AS p WHERE ${sql.ref(`p.${parent.via.column}`)} = ${parent.via.id} AND p."companyId" = ${companyId})`
+ : sql`${sql.ref(`t.${parent.column}`)} = ${parent.id}`;
+
+ return sql<{
+ id: string;
+ }>`UPDATE ${sql.table(table)} AS t SET ${sql.ref(column)} = v."sortOrder", "updatedBy" = ${userId}, "updatedAt" = ${updatedAt} FROM (VALUES ${values}) AS v("id", "sortOrder") WHERE t."id" = v."id" AND t."companyId" = ${companyId} AND ${parentPredicate} RETURNING t."id"`;
+}
+
+/**
+ * Persist a drag-sort in ONE `UPDATE … FROM (VALUES …)`, scoped to the company
+ * and the parent document. All-or-nothing: if any id is outside that scope (or
+ * missing, or repeated) fewer rows come back than were sent, and the
+ * transaction rolls the whole reorder back.
+ *
+ * Takes the Kysely handle as an argument — never builds one (see AGENTS.md:
+ * service files are browser-bundled). Throws; the route try/catches it.
+ */
+export async function updateSortOrder<
+ T extends SortableTable,
+ P extends TenantTable = TenantTable
+>(db: Kysely<KyselyDatabase>, args: UpdateSortOrderArgs<T, P>) {
+ if (args.updates.length === 0) return;
+
+ const parentId = "via" in args.parent ? args.parent.via.id : args.parent.id;
+ if (!parentId) throw new Error(`${args.table}: missing parent id`);
+
+ const query = buildSortOrderUpdate({
+ ...args,
+ updatedAt: datetime.timestamp()
+ });
+
+ await db.transaction().execute(async (trx) => {
+ const { rows } = await query.execute(trx);
+ if (rows.length !== args.updates.length) {
+ throw new Error(
+ `${args.table}: ${args.updates.length - rows.length} of ${args.updates.length} rows are not on this document`
+ );
+ }
+ });
+}
+
+// The drag-sort UI posts `updates` as a JSON map of row id → new sort order.
+// A value must be a real finite number (or a numeric string): `Number()` turns
+// garbage into NaN and "" into 0, and either would be written as a sort order.
+const sortOrderValue = z.union([
+ z.number(),
+ z.string().trim().min(1).pipe(z.coerce.number())
+]);
+const sortOrderUpdatesValidator = z
+ .record(z.string().min(1), sortOrderValue)
+ .refine((map) => Object.keys(map).length > 0);
+
+/**
+ * Parse a reorder route's `updates` form field. Returns null when it is
+ * missing, not JSON, empty, or carries a non-numeric sort order — the route
+ * flashes an error instead of writing anything.
+ */
+export function parseSortOrderUpdates(
+ formData: FormData
+): { id: string; sortOrder: number }[] | null {
+ const raw = formData.get("updates");
+ if (typeof raw !== "string" || !raw) return null;
+ let json: unknown;
+ try {
+ json = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ const parsed = sortOrderUpdatesValidator.safeParse(json);
+ if (!parsed.success) return null;
+ return Object.entries(parsed.data).map(([id, sortOrder]) => ({
+ id,
+ sortOrder
+ }));
+}
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
index eb299e3a7f..a9449d75c4 100644
--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -374,18 +374,24 @@ const EmployeesTable = memo(
<MenuIcon icon={<LuPencil />} />
<Trans>Edit Permissions</Trans>
</MenuItem>
- {settings.consoleEnabled && (
- <MenuItem
- onClick={() =>
- navigate(
- `${path.to.operatorResetPin(row.id!)}?${params.toString()}`
- )
- }
- >
- <MenuIcon icon={<LuShield />} />
- <Trans>Set Console PIN</Trans>
- </MenuItem>
- )}
+ {/* Resetting a PIN hands over that person's console identity:
+ console operators need users_update, anyone else also
+ settings_update (enforced again by the route). */}
+ {settings.consoleEnabled &&
+ permissions.can("update", "users") &&
+ (permissions.can("update", "settings") ||
+ row.email?.endsWith("@console.internal")) && (
+ <MenuItem
+ onClick={() =>
+ navigate(
+ `${path.to.operatorResetPin(row.id!)}?${params.toString()}`
+ )
+ }
+ >
+ <MenuIcon icon={<LuShield />} />
+ <Trans>Set Console PIN</Trans>
+ </MenuItem>
+ )}
<MenuItem
onClick={() =>
navigate(
diff --git a/apps/erp/app/modules/users/users.models.ts b/apps/erp/app/modules/users/users.models.ts
index 4a04dfc9ef..243ceba5f2 100644
--- a/apps/erp/app/modules/users/users.models.ts
+++ b/apps/erp/app/modules/users/users.models.ts
@@ -74,8 +74,7 @@ export const itarUserCertificationValidator = z.object({
export const createOperatorValidator = z.object({
firstName: z.string().min(1, { message: "First name is required" }),
lastName: z.string().min(1, { message: "Last name is required" }),
- locationId: z.string().min(1, { message: "Location is required" }),
- pin: z.string().regex(/^\d{4}$/, "PIN must be 4 digits")
+ locationId: z.string().min(1, { message: "Location is required" })
});
export const convertOperatorValidator = z.object({
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 348c58fcb6..31c15631b4 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -106,7 +106,12 @@ export async function acceptInvite(
};
}
- if (email && invite.data.email !== email) {
+ // GoTrue stores auth emails lower-cased, while an invite keeps the address
+ // as it was typed, so compare the normalized forms.
+ if (
+ email &&
+ invite.data.email.trim().toLowerCase() !== email.trim().toLowerCase()
+ ) {
throw new Error(
"Invite code does not match email. Please logout and try again."
);
@@ -339,13 +344,23 @@ export async function createCustomerAccount(
| { success: false; message: string }
| { success: true; code: string; userId: string; email: string }
> {
- const customerContact = await getCustomerContact(client, id);
+ // Both ids come from the form: the contact must be this company's and hang
+ // off the customer the account is being created for, or the account (and the
+ // contact's userId write below) would point at another tenant's rows.
+ const customerContact = await getCustomerContact(client, id, companyId);
if (
customerContact.error ||
customerContact.data === null ||
+ customerContact.data.customerId !== customerId ||
customerContact.data.contact === null ||
!customerContact.data.contact.email
) {
+ logger.error("Failed to get customer contact for the company", {
+ companyId,
+ customerContactId: id,
+ customerId,
+ error: customerContact.error
+ });
return { success: false, message: "Failed to get customer contact" };
}
@@ -468,6 +483,40 @@ export async function createEmployeeAccount(
| { success: false; message: string }
| { success: true; code: string; userId: string }
> {
+ // Both ids come from the invite form. The employee type's permission rows
+ // carry their own company ids, so a foreign type would put another
+ // company's grants into this invite; the location lands on employeeJob.
+ const [ownedEmployeeType, ownedLocation] = await Promise.all([
+ getCarbonServiceRole()
+ .from("employeeType")
+ .select("id")
+ .eq("id", employeeType)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ getCarbonServiceRole()
+ .from("location")
+ .select("id")
+ .eq("id", locationId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+ if (ownedEmployeeType.error || !ownedEmployeeType.data) {
+ logger.error("Invite employee type is not in the company", {
+ companyId,
+ employeeType,
+ error: ownedEmployeeType.error
+ });
+ return { success: false, message: "Employee type not found" };
+ }
+ if (ownedLocation.error || !ownedLocation.data) {
+ logger.error("Invite location is not in the company", {
+ companyId,
+ locationId,
+ error: ownedLocation.error
+ });
+ return { success: false, message: "Location not found" };
+ }
+
const employeeTypePermissions = await getPermissionsByEmployeeType(
client,
employeeType
@@ -599,13 +648,23 @@ export async function createSupplierAccount(
| { success: false; message: string }
| { success: true; code: string; userId: string; email: string }
> {
- const supplierContact = await getSupplierContact(client, id);
+ // Both ids come from the form: the contact must be this company's and hang
+ // off the supplier the account is being created for, or the account (and the
+ // contact's userId write below) would point at another tenant's rows.
+ const supplierContact = await getSupplierContact(client, id, companyId);
if (
supplierContact.error ||
supplierContact.data === null ||
+ supplierContact.data.supplierId !== supplierId ||
supplierContact.data.contact === null ||
!supplierContact.data.contact.email
) {
+ logger.error("Failed to get supplier contact for the company", {
+ companyId,
+ supplierContactId: id,
+ supplierId,
+ error: supplierContact.error
+ });
return { success: false, message: "Failed to get supplier contact" };
}
@@ -1040,6 +1099,41 @@ export async function convertConsoleOperatorToUser(
): Promise<{ success: false; message: string } | { success: true }> {
const serviceRole = getCarbonServiceRole();
+ // userId comes from the URL and every write below is service-role, so prove
+ // the operator is an employee of THIS company — otherwise another company's
+ // operator could be given an auth login under an email the caller chose —
+ // and that the employee type is this company's.
+ const [membership, targetEmployeeType] = await Promise.all([
+ serviceRole
+ .from("employee")
+ .select("id")
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ serviceRole
+ .from("employeeType")
+ .select("id")
+ .eq("id", employeeType)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+ if (membership.error || !membership.data) {
+ logger.error("Console operator is not an employee of the company", {
+ companyId,
+ userId,
+ error: membership.error
+ });
+ return { success: false, message: "User is not a console operator" };
+ }
+ if (targetEmployeeType.error || !targetEmployeeType.data) {
+ logger.error("Employee type is not in the company", {
+ companyId,
+ employeeType,
+ error: targetEmployeeType.error
+ });
+ return { success: false, message: "Employee type not found" };
+ }
+
// Verify the user is a console operator
// Note: isConsoleOperator field added by migration 20260319000000_console-mode.sql
const existingUser = await serviceRole
diff --git a/apps/erp/app/routes/_public+/callback.tsx b/apps/erp/app/routes/_public+/callback.tsx
index 4ae56c89be..67d7537de3 100644
--- a/apps/erp/app/routes/_public+/callback.tsx
+++ b/apps/erp/app/routes/_public+/callback.tsx
@@ -35,6 +35,7 @@ import {
} from "@carbon/ee/sso.server";
import { validator } from "@carbon/form";
import { AccountLockout, redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
import {
Alert,
AlertDescription,
@@ -57,6 +58,8 @@ import { getCompanies, getEmployeeCompanies } from "~/modules/settings";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "callback");
+
export async function loader({ request }: LoaderFunctionArgs) {
const authSession = await getAuthSession(request);
@@ -109,6 +112,21 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // `userId` is caller-supplied; the refresh token is the only proof of
+ // identity. Everything above (the company pick) and below (SSO
+ // classification, JIT cleanup) keys on `userId`, so refuse a form whose
+ // `userId` is not the token's own user.
+ if (authSession.userId !== userId) {
+ logger.error("Callback userId does not match the refresh token's user", {
+ userId,
+ tokenUserId: authSession.userId
+ });
+ return redirect(
+ path.to.root,
+ await flash(request, error(null, "Invalid refresh token"))
+ );
+ }
+
// ── SSO branch ─────────────────────────────────────────────────────────
// A SAML session is company-bound by its provider. Enforce the
// provider → company binding and the asserted email's registered domain
diff --git a/apps/erp/app/routes/_public+/unlock.tsx b/apps/erp/app/routes/_public+/unlock.tsx
index 94a6cb725c..5eccd306fa 100644
--- a/apps/erp/app/routes/_public+/unlock.tsx
+++ b/apps/erp/app/routes/_public+/unlock.tsx
@@ -282,6 +282,15 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // Absolute cap already passed → termination wins over lock, as in the loader
+ // and requireAuthSession. Both unlock paths below re-stamp createdAt (the
+ // passkey path directly, TOTP via makeAuthSession), so a POST here would
+ // otherwise revive a session past its absolute cap.
+ const lockedSession = await getAuthSession(request);
+ if (lockedSession && isSessionExpiredAbsolute(lockedSession)) {
+ throw await destroyAuthSession(request);
+ }
+
// Passkey unlock arrives as JSON (the credential assertion); TOTP unlock is a
// form POST. Branch on content type — the TOTP path below is unchanged.
const contentType = request.headers.get("content-type") ?? "";
diff --git a/apps/erp/app/routes/api+/integrations.jira.oauth.ts b/apps/erp/app/routes/api+/integrations.jira.oauth.ts
index a74ae39602..36389d94ce 100644
--- a/apps/erp/app/routes/api+/integrations.jira.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.jira.oauth.ts
@@ -1,5 +1,6 @@
import { getAppUrl } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { consumeOAuthState } from "@carbon/auth/oauth-state.server";
import { getIntegrationConfigById } from "@carbon/ee";
import {
exchangeCodeForTokens,
@@ -34,8 +35,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { data: params } = jiraAuthResponse;
- if (!params.state) {
- return data({ error: "Invalid state parameter" }, { status: 400 });
+ // The state must be the one the integrations page issued to THIS browser
+ // for this user and company (IntegrationCard puts it on the authorize URL).
+ // Without the check anyone could send a victim a callback URL carrying the
+ // attacker's own authorization code, linking the victim's company to the
+ // attacker's Jira account. Single-use: consumed whether it matches or not.
+ const consumedState = await consumeOAuthState(request, params.state, {
+ integrationId: "jira",
+ userId,
+ companyId
+ });
+
+ if (!consumedState.valid) {
+ logger.error("Invalid Jira OAuth state", { companyId, userId });
+ return data(
+ { error: "Invalid state parameter" },
+ { status: 400, headers: { "Set-Cookie": consumedState.cookie } }
+ );
}
try {
@@ -96,7 +112,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (createdJiraIntegration?.data?.metadata) {
// Redirect on the canonical public origin — `request.url`'s origin is the
// internal proxy address in dev, which would drop the session cookies.
- return redirect(`${getAppUrl()}${path.to.integrations}`);
+ return redirect(`${getAppUrl()}${path.to.integrations}`, {
+ headers: { "Set-Cookie": consumedState.cookie }
+ });
} else {
return data(
{ error: "Failed to save Jira integration" },
diff --git a/apps/erp/app/routes/api+/integrations.onshape.install.ts b/apps/erp/app/routes/api+/integrations.onshape.install.ts
index df80ca451b..9c6eef37fb 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.install.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.install.ts
@@ -1,16 +1,24 @@
import { ONSHAPE_CLIENT_ID, ONSHAPE_OAUTH_REDIRECT_URL } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { issueOAuthState } from "@carbon/auth/oauth-state.server";
+import { Onshape } from "@carbon/ee";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, {});
+ const { userId, companyId } = await requirePermissions(request, {});
if (!ONSHAPE_CLIENT_ID || !ONSHAPE_OAUTH_REDIRECT_URL) {
return data({ error: "Onshape OAuth not configured" }, { status: 500 });
}
- const state = crypto.randomUUID();
+ // Bound to this browser, user and company, and consumed by the callback —
+ // otherwise anyone could hand a victim a callback URL carrying their own
+ // Onshape code and link the victim's company to the attacker's account.
+ const { state, cookie } = await issueOAuthState(
+ { integrationId: Onshape.id, userId, companyId },
+ request
+ );
const params = new URLSearchParams({
client_id: ONSHAPE_CLIENT_ID,
@@ -31,5 +39,5 @@ export async function loader({ request }: LoaderFunctionArgs) {
const url = `https://oauth.onshape.com/oauth/authorize?${params}&scope=${scope}`;
- return { url };
+ return data({ url }, { headers: { "Set-Cookie": cookie } });
}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.oauth.ts b/apps/erp/app/routes/api+/integrations.onshape.oauth.ts
index d85a47d924..757455305f 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.oauth.ts
@@ -6,6 +6,7 @@ import {
} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { consumeOAuthState } from "@carbon/auth/oauth-state.server";
import { Onshape } from "@carbon/ee";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
@@ -42,10 +43,12 @@ function integrationsUrl(request: Request) {
*/
function connectionFailed(
request: Request,
- reason: IntegrationErrorCode<"onshape">
+ reason: IntegrationErrorCode<"onshape">,
+ stateCookie: string
) {
return redirect(
- `${integrationsUrl(request)}${integrationErrorSearch("onshape", reason)}`
+ `${integrationsUrl(request)}${integrationErrorSearch("onshape", reason)}`,
+ { headers: { "Set-Cookie": stateCookie } }
);
}
@@ -57,6 +60,21 @@ export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const searchParams = Object.fromEntries(url.searchParams.entries());
+ // The state must be the one install.ts issued to THIS browser for this user
+ // and company. Without the check anyone could send a victim a callback URL
+ // carrying the attacker's own Onshape code, linking the victim's company to
+ // the attacker's Onshape account. Single-use: consumed whether it matches or not.
+ const consumedState = await consumeOAuthState(
+ request,
+ url.searchParams.get("state") ?? "",
+ { integrationId: Onshape.id, userId, companyId }
+ );
+
+ if (!consumedState.valid) {
+ logger.error("Invalid Onshape OAuth state", { companyId, userId });
+ return connectionFailed(request, "invalid-state", consumedState.cookie);
+ }
+
// Onshape reports a refused authorization by redirecting here with `error` (and
// usually `error_description`) in place of `code` — e.g. `invalid_scope` when the
// OAuth application in the Onshape dev portal isn't granted a scope install.ts
@@ -74,7 +92,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
// instead of echoing Onshape's wording, which never says which scope is missing.
return connectionFailed(
request,
- searchParams.error === "invalid_scope" ? "write-permission" : "denied"
+ searchParams.error === "invalid_scope" ? "write-permission" : "denied",
+ consumedState.cookie
);
}
@@ -86,21 +105,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
logger.error("Invalid Onshape auth response", {
params: Object.keys(searchParams)
});
- return connectionFailed(request, "invalid-response");
+ return connectionFailed(request, "invalid-response", consumedState.cookie);
}
const { data: params } = authResponse;
- if (!params.state) {
- return connectionFailed(request, "invalid-response");
- }
-
if (
!ONSHAPE_CLIENT_ID ||
!ONSHAPE_CLIENT_SECRET ||
!ONSHAPE_OAUTH_REDIRECT_URL
) {
- return connectionFailed(request, "not-configured");
+ return connectionFailed(request, "not-configured", consumedState.cookie);
}
try {
@@ -123,14 +138,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
status: tokenResponse.status,
body: await tokenResponse.text()
});
- return connectionFailed(request, "token-exchange");
+ return connectionFailed(request, "token-exchange", consumedState.cookie);
}
const tokenData = await tokenResponse.json();
if (!tokenData.access_token) {
logger.error("Onshape token response had no access token");
- return connectionFailed(request, "token-exchange");
+ return connectionFailed(request, "token-exchange", consumedState.cookie);
}
const serviceRole = getCarbonServiceRole();
@@ -162,15 +177,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
// the integration settings save + ensureOnshapeReleaseWebhook), not on
// connect — asset sync is off by default, so there's nothing to subscribe
// to yet at this point.
- return redirect(integrationsUrl(request));
+ return redirect(integrationsUrl(request), {
+ headers: { "Set-Cookie": consumedState.cookie }
+ });
} else {
logger.error("Failed to save Onshape integration", {
createdIntegration
});
- return connectionFailed(request, "save-failed");
+ return connectionFailed(request, "save-failed", consumedState.cookie);
}
} catch (err) {
logger.error("Onshape OAuth Error", { error: err });
- return connectionFailed(request, "unexpected");
+ return connectionFailed(request, "unexpected", consumedState.cookie);
}
}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.sync.ts b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
index 31a36388f6..9cb12b1ca3 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.sync.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
@@ -70,7 +70,8 @@ export async function action({ request }: ActionFunctionArgs) {
.delete()
.eq("entityType", "item")
.eq("entityId", itemId)
- .eq("integration", "onshape");
+ .eq("integration", "onshape")
+ .eq("companyId", companyId);
await client.from("externalIntegrationMapping").insert({
entityType: "item",
diff --git a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts
index ba45c6cd45..f925d10d19 100644
--- a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts
@@ -4,6 +4,7 @@ import {
QUICKBOOKS_CLIENT_SECRET
} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { consumeOAuthState } from "@carbon/auth/oauth-state.server";
import { QuickBooks } from "@carbon/ee";
import {
DEFAULT_SYNC_CONFIG,
@@ -11,6 +12,7 @@ import {
ProviderID
} from "@carbon/ee/accounting";
import { quickbooksOnInstall } from "@carbon/ee/quickbooks/hooks.server";
+import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
@@ -21,6 +23,8 @@ export const config = {
runtime: "nodejs"
};
+const logger = getLogger("erp", "quickbooks", "oauth");
+
export async function loader({ request }: LoaderFunctionArgs) {
const { client, userId, companyId } = await requirePermissions(request, {
update: "settings"
@@ -37,9 +41,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { data: params } = quickBooksAuthResponse;
- // TODO: Verify state parameter
- if (!params.state) {
- return data({ error: "Invalid state parameter" }, { status: 400 });
+ // The state must be the one the integrations page issued to THIS browser
+ // for this user and company (IntegrationCard puts it on the authorize URL).
+ // Without the check anyone could send a victim a callback URL carrying the
+ // attacker's own authorization code, linking the victim's company to the
+ // attacker's QuickBooks account. Single-use: consumed whether it matches or not.
+ const consumedState = await consumeOAuthState(request, params.state, {
+ integrationId: QuickBooks.id,
+ userId,
+ companyId
+ });
+
+ if (!consumedState.valid) {
+ logger.error("Invalid QuickBooks OAuth state", { companyId, userId });
+ return data(
+ { error: "Invalid state parameter" },
+ { status: 400, headers: { "Set-Cookie": consumedState.cookie } }
+ );
}
if (!QUICKBOOKS_CLIENT_ID || !QUICKBOOKS_CLIENT_SECRET) {
@@ -107,7 +125,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (createdQuickBooksIntegration?.data?.metadata) {
// Canonical public origin — `request.url`'s origin is the internal proxy
// address in dev, which would drop the session cookies on redirect.
- return redirect(`${getAppUrl()}${path.to.integrations}`);
+ return redirect(`${getAppUrl()}${path.to.integrations}`, {
+ headers: { "Set-Cookie": consumedState.cookie }
+ });
} else {
return data(
{ error: "Failed to save QuickBooks integration" },
diff --git a/apps/erp/app/routes/api+/integrations.slack.interactive.ts b/apps/erp/app/routes/api+/integrations.slack.interactive.ts
index 01f5b3de80..32d2e055f5 100644
--- a/apps/erp/app/routes/api+/integrations.slack.interactive.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.interactive.ts
@@ -1,4 +1,5 @@
-import { ERP_URL } from "@carbon/auth";
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { ERP_URL, SLACK_SIGNING_SECRET } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import { resolveIntegrationSecrets } from "@carbon/ee";
@@ -20,6 +21,9 @@ import {
} from "~/modules/quality/quality.service";
import { path } from "~/utils/path";
+// nodejs runtime: the Slack signature check uses node:crypto.
+export const config = { runtime: "nodejs" };
+
const logger = getLogger("erp", "slack", "interactive");
const slackInteractivePayloadSchema = z.object({
@@ -54,10 +58,58 @@ const slackInteractivePayloadSchema = z.object({
callback_id: z.string().optional()
});
+const SLACK_SIGNATURE_VERSION = "v0";
+const SLACK_MAX_REQUEST_AGE_SECONDS = 5 * 60;
+
+/**
+ * Verifies Slack's `x-slack-signature` HMAC over the RAW body. The payload's
+ * `team.id` picks the company this request acts on with the service role, and a
+ * Slack team id is not a secret — without this check anyone could POST a forged
+ * payload and create issues in any company that has Slack connected.
+ */
+function isValidSlackSignature(request: Request, rawBody: string): boolean {
+ if (!SLACK_SIGNING_SECRET) return false;
+
+ const timestamp = request.headers.get("x-slack-request-timestamp");
+ const signature = request.headers.get("x-slack-signature");
+ if (!timestamp || !signature) return false;
+
+ const timestampSeconds = Number.parseInt(timestamp, 10);
+ if (
+ !Number.isFinite(timestampSeconds) ||
+ Math.abs(Date.now() / 1000 - timestampSeconds) >
+ SLACK_MAX_REQUEST_AGE_SECONDS
+ ) {
+ return false;
+ }
+
+ const expected = `${SLACK_SIGNATURE_VERSION}=${createHmac(
+ "sha256",
+ SLACK_SIGNING_SECRET
+ )
+ .update(`${SLACK_SIGNATURE_VERSION}:${timestamp}:${rawBody}`)
+ .digest("hex")}`;
+
+ const a = Buffer.from(signature);
+ const b = Buffer.from(expected);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
export async function action({ request }: ActionFunctionArgs) {
try {
- const formData = await request.formData();
- const payloadString = formData.get("payload") as string;
+ const rawBody = await request.text();
+
+ if (!isValidSlackSignature(request, rawBody)) {
+ logger.error(
+ "Rejected Slack interactive request with invalid signature",
+ {
+ hasSigningSecret: Boolean(SLACK_SIGNING_SECRET)
+ }
+ );
+ return data({ error: "Invalid signature" }, { status: 401 });
+ }
+
+ const payloadString = new URLSearchParams(rawBody).get("payload");
if (!payloadString) {
return data({ error: "Missing payload" }, { status: 400 });
diff --git a/apps/erp/app/routes/api+/integrations.xero.oauth.ts b/apps/erp/app/routes/api+/integrations.xero.oauth.ts
index df45bddd11..17ad717ecb 100644
--- a/apps/erp/app/routes/api+/integrations.xero.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.xero.oauth.ts
@@ -1,5 +1,6 @@
import { getAppUrl, XERO_CLIENT_ID, XERO_CLIENT_SECRET } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { consumeOAuthState } from "@carbon/auth/oauth-state.server";
import { Xero } from "@carbon/ee";
import {
DEFAULT_SYNC_CONFIG,
@@ -36,9 +37,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { data: params } = xeroAuthResponse;
- // TODO: Verify state parameter
- if (!params.state) {
- return data({ error: "Invalid state parameter" }, { status: 400 });
+ // The state must be the one the integrations page issued to THIS browser
+ // for this user and company (IntegrationCard puts it on the authorize URL).
+ // Without the check anyone could send a victim a callback URL carrying the
+ // attacker's own authorization code, linking the victim's company to the
+ // attacker's Xero account. Single-use: consumed whether it matches or not.
+ const consumedState = await consumeOAuthState(request, params.state, {
+ integrationId: Xero.id,
+ userId,
+ companyId
+ });
+
+ if (!consumedState.valid) {
+ logger.error("Invalid Xero OAuth state", { companyId, userId });
+ return data(
+ { error: "Invalid state parameter" },
+ { status: 400, headers: { "Set-Cookie": consumedState.cookie } }
+ );
}
if (!XERO_CLIENT_ID || !XERO_CLIENT_SECRET) {
@@ -196,7 +211,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (createdXeroIntegration?.data?.metadata) {
// Canonical public origin — `request.url`'s origin is the internal proxy
// address in dev, which would drop the session cookies on redirect.
- return redirect(`${getAppUrl()}${path.to.integrations}`);
+ return redirect(`${getAppUrl()}${path.to.integrations}`, {
+ headers: { "Set-Cookie": consumedState.cookie }
+ });
} else {
return data(
{ error: "Failed to save Xero integration" },
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 9ead82e99f..5e92248e4e 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -52,16 +52,7 @@ async function handleKanban({
userId: string;
id: string;
}): Promise<{ data: string; error: null } | { data: null; error: string }> {
- const kanban = await getKanban(client, id);
- if (
- kanban.data?.replenishmentSystem === "Make" &&
- kanban.data?.jobReadableId
- ) {
- return {
- data: path.to.api.kanbanCollision(id),
- error: null
- };
- }
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error || !kanban.data) {
return {
@@ -70,10 +61,10 @@ async function handleKanban({
};
}
- if (kanban.data.companyId !== companyId) {
+ if (kanban.data.replenishmentSystem === "Make" && kanban.data.jobReadableId) {
return {
- data: null,
- error: "Kanban is not active"
+ data: path.to.api.kanbanCollision(id),
+ error: null
};
}
@@ -439,7 +430,9 @@ async function handleKanban({
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, companyGroupId, userId } =
- await requirePermissions(request, {});
+ await requirePermissions(request, {
+ role: "employee"
+ });
const { id } = params;
if (!id) throw notFound("id not found");
diff --git a/apps/erp/app/routes/api+/kanban.collision.$id.tsx b/apps/erp/app/routes/api+/kanban.collision.$id.tsx
index d059d0fbe4..42a0b280d2 100644
--- a/apps/erp/app/routes/api+/kanban.collision.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.collision.$id.tsx
@@ -14,12 +14,14 @@ import {
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ role: "employee"
+ });
const { id } = params;
if (!id) throw notFound("id not found");
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (
kanban.data?.replenishmentSystem !== "Make" ||
!kanban.data?.jobReadableId
diff --git a/apps/erp/app/routes/api+/kanban.complete.$id.tsx b/apps/erp/app/routes/api+/kanban.complete.$id.tsx
index 141afe867a..ce6d3f7da1 100644
--- a/apps/erp/app/routes/api+/kanban.complete.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.complete.$id.tsx
@@ -17,7 +17,7 @@ async function handleKanbanComplete({
companyId: string;
id: string;
}): Promise<{ data: string; error: null } | { data: null; error: string }> {
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error) {
return {
data: null,
@@ -52,7 +52,9 @@ async function handleKanbanComplete({
}
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ role: "employee"
+ });
const { id } = params;
if (!id) throw notFound("id not found");
diff --git a/apps/erp/app/routes/api+/kanban.link.$id.tsx b/apps/erp/app/routes/api+/kanban.link.$id.tsx
index 2e905cf47f..dc57320ce5 100644
--- a/apps/erp/app/routes/api+/kanban.link.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.link.$id.tsx
@@ -7,12 +7,14 @@ import { getActiveJobOperationByJobId } from "~/modules/production";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ role: "employee"
+ });
const { id } = params;
if (!id) throw notFound("id not found");
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error) {
throw notFound("Kanban not found");
}
diff --git a/apps/erp/app/routes/api+/kanban.start.$id.tsx b/apps/erp/app/routes/api+/kanban.start.$id.tsx
index 6ed6670085..cb37d6fefc 100644
--- a/apps/erp/app/routes/api+/kanban.start.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.start.$id.tsx
@@ -20,7 +20,7 @@ async function handleKanbanStart({
companyId: string;
id: string;
}): Promise<{ data: string; error: null } | { data: null; error: string }> {
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error) {
return {
data: null,
@@ -66,7 +66,9 @@ async function handleKanbanStart({
}
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ role: "employee"
+ });
const { id } = params;
if (!id) throw notFound("id not found");
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 261ae0709c..814093f103 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
@@ -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":"acf68dbfa875","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"none","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},
@@ -303,7 +303,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":"acf68dbfa875","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"none","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},
@@ -354,11 +354,11 @@
{"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","paramCount":2,"schema":"8e0a48ddafaf","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","paramCount":15,"schema":"304bf354aa67","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
+ {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updatePurchaseInvoiceStatus","classification":"WRITE","paramCount":4,"schema":"f50dc1abbd65","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updateSalesInvoice","classification":"WRITE","paramCount":15,"schema":"71a9939b9245","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
+ {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_updateSalesInvoiceStatus","classification":"WRITE","paramCount":4,"schema":"be5f9d03d216","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},
{"name":"invoicing_upsertInvoiceSettlement","classification":"WRITE","paramCount":13,"schema":"aa171dfbfeb9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},
{"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"b19aa6b4c8f5","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},
@@ -408,7 +408,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":"acf68dbfa875","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"none","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},
@@ -598,7 +598,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":"df0f32d1fef7","injectAuth":"companyId","permission":"people:view","paginates":false},
+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"88a9d1fc3d35","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},
@@ -788,13 +788,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":"acf68dbfa875","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"none","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":"acf68dbfa875","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"8589eb1ea5aa","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"acf68dbfa875","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"ac83813d8c48","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId+userId","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+userId","permission":"production:update","paginates":false},
@@ -818,8 +818,8 @@
{"name":"production_unassignPeopleWeek","classification":"DESTRUCTIVE","paramCount":4,"schema":"06ead5d3d9ce","response":"9658926b2cd2","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_unreleaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"none","injectAuth":"companyId+userId","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","paramCount":2,"schema":"e43955681d7c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
- {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
- {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
+ {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","paramCount":2,"schema":"5a4d7dc208a5","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
+ {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":2,"schema":"5a4d7dc208a5","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","paramCount":2,"schema":"9291eed55a4a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyStepComponents","classification":"WRITE","paramCount":2,"schema":"d7ea6b1800f7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":3,"schema":"6665a9b53a17","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
@@ -876,7 +876,7 @@
{"name":"purchasing_closePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_confirmPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"purchasing:update","paginates":false},
{"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"03ce7e291c3c","response":"5cb338fa12e6","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},
- {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},
+ {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},
{"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"11b028f16d94","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},
{"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"a424256cbe29","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},
{"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},
@@ -980,12 +980,12 @@
{"name":"purchasing_updatePurchaseOrder","classification":"WRITE","paramCount":11,"schema":"f254c2222188","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},
- {"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
+ {"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"744101d1c67c","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderStatus","classification":"WRITE","paramCount":3,"schema":"da4b3835e841","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderStatusLegacy","classification":"WRITE","paramCount":2,"schema":"443b40ba5bdd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseReturnOrder","classification":"WRITE","paramCount":13,"schema":"65e2a245cbbe","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"f1f07b8e0c83","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
- {"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
+ {"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"3be259f3e887","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","paramCount":3,"schema":"8dc0490a9402","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierAccounting","classification":"WRITE","paramCount":2,"schema":"00634b037a3e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierContact","classification":"WRITE","paramCount":4,"schema":"f6b4a36788e6","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
@@ -993,7 +993,7 @@
{"name":"purchasing_updateSupplierPayment","classification":"WRITE","paramCount":6,"schema":"7c667f4542f3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierQuote","classification":"WRITE","paramCount":8,"schema":"64e0b2d29d98","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
- {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
+ {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"7bf10894875d","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierQuoteStatus","classification":"WRITE","paramCount":3,"schema":"a89efeaa1348","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierShipping","classification":"WRITE","paramCount":8,"schema":"ac0c2133e800","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updateSupplierTax","classification":"WRITE","paramCount":8,"schema":"9467cd226e93","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},
@@ -1206,7 +1206,7 @@
{"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_createPricingRule","classification":"WRITE","paramCount":15,"schema":"306872f9cb7b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_createReplacementSalesOrder","classification":"WRITE","paramCount":1,"schema":"f41daa12b05a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
- {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
+ {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
{"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","paramCount":1,"schema":"09e48c79fb16","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
{"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
{"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"3fd22b0165d4","response":"700b93baa3ef","injectAuth":"companyId","permission":"sales:delete","paginates":false},
@@ -1359,18 +1359,18 @@
{"name":"sales_updatePricingRule","classification":"WRITE","paramCount":2,"schema":"121160ebf01e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuote","classification":"WRITE","paramCount":17,"schema":"ad5fc3f2a158","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
- {"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
+ {"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"fce9a5d72ad3","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteLinePrecision","classification":"WRITE","paramCount":3,"schema":"90f52ec96806","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteStatus","classification":"WRITE","paramCount":3,"schema":"35467c4f9528","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrder","classification":"WRITE","paramCount":9,"schema":"d9b815fe7f4c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
- {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
+ {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"fc73ab432ad8","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderStatus","classification":"WRITE","paramCount":3,"schema":"ba9f86dc4f78","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesReturnOrder","classification":"WRITE","paramCount":13,"schema":"d2b0eab7a550","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQ","classification":"WRITE","paramCount":13,"schema":"29d3ed584bda","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
- {"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
+ {"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"7a17ee77c8c5","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQStatus","classification":"WRITE","paramCount":4,"schema":"987b1b266fe8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_upsertCustomer","classification":"WRITE","paramCount":11,"schema":"5f03a003004d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"2f6b498df5e9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
diff --git a/apps/erp/app/routes/api+/model.optimize-cancel.ts b/apps/erp/app/routes/api+/model.optimize-cancel.ts
index e7a0e3598b..9074b18db0 100644
--- a/apps/erp/app/routes/api+/model.optimize-cancel.ts
+++ b/apps/erp/app/routes/api+/model.optimize-cancel.ts
@@ -39,6 +39,7 @@ export async function action({ request }: ActionFunctionArgs) {
optimizeError: "Cancelled by user"
})
.eq("id", modelUploadId)
+ .eq("companyId", companyId)
.in("optimizeStatus", ["Queued", "Processing"])
.select("id");
diff --git a/apps/erp/app/routes/api+/model.reoptimize.ts b/apps/erp/app/routes/api+/model.reoptimize.ts
index 55e5a714cc..97a6bb23c0 100644
--- a/apps/erp/app/routes/api+/model.reoptimize.ts
+++ b/apps/erp/app/routes/api+/model.reoptimize.ts
@@ -40,7 +40,8 @@ export async function action({ request }: ActionFunctionArgs) {
await serviceRole
.from("modelUpload")
.update({ optimizeStatus: "Queued", optimizeError: null })
- .eq("id", modelUploadId);
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId);
}
await trigger("model-optimize", { modelUploadId, companyId, userId, force });
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index a2567b5776..a84713f12e 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -1,5 +1,6 @@
// import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { isUnsafeStoragePath } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
import { isAssemblerServiceHealthy } from "~/modules/production/production.server";
@@ -33,7 +34,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
// The path is client-supplied; never let it point outside this tenant's
// storage prefix or escape via traversal.
- if (!modelPath.startsWith(`${companyId}/`) || modelPath.includes("..")) {
+ if (
+ !modelPath.startsWith(`${companyId}/`) ||
+ isUnsafeStoragePath(modelPath)
+ ) {
throw new Error("Invalid model path");
}
diff --git a/apps/erp/app/routes/api+/mrp.ts b/apps/erp/app/routes/api+/mrp.ts
index bacb9d3102..5dd900d58d 100644
--- a/apps/erp/app/routes/api+/mrp.ts
+++ b/apps/erp/app/routes/api+/mrp.ts
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { ActionFunctionArgs } from "react-router";
import { runMRP } from "~/modules/production/production.service";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request }: ActionFunctionArgs) {
@@ -15,7 +16,17 @@ export async function action({ request }: ActionFunctionArgs) {
update: "inventory"
});
- const result = await runMRP(getCarbonServiceRole(), getDatabaseClient(), {
+ const serviceRole = getCarbonServiceRole();
+
+ // The location id comes from the query string and MRP runs with the service
+ // role + Kysely, so confirm it belongs to this company first.
+ if (locationId) {
+ await requireCompanyRecord(serviceRole, "location", companyId, {
+ id: locationId
+ });
+ }
+
+ const result = await runMRP(serviceRole, getDatabaseClient(), {
type: locationId ? "location" : "company",
id: locationId ?? companyId,
companyId,
diff --git a/apps/erp/app/routes/api+/purchase-invoice.$invoiceId.map-lines.ts b/apps/erp/app/routes/api+/purchase-invoice.$invoiceId.map-lines.ts
index 5cc01c4871..905f5c43ae 100644
--- a/apps/erp/app/routes/api+/purchase-invoice.$invoiceId.map-lines.ts
+++ b/apps/erp/app/routes/api+/purchase-invoice.$invoiceId.map-lines.ts
@@ -1,8 +1,11 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { resolveItemIdFromExtractedText, upsertPart } from "~/modules/items";
+const logger = getLogger("erp", "purchase-invoice-map-lines");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "invoicing"
@@ -63,8 +66,63 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!mappingsStr) return { success: false, error: "No mappings provided" };
const mappings = JSON.parse(mappingsStr);
+ if (!Array.isArray(mappings)) {
+ return { success: false, error: "Invalid mappings" };
+ }
const serviceRole = await getCarbonServiceRole();
+ // Every line id and chosen item id is caller-supplied. Prove each line
+ // belongs to this invoice in this company, and each item to this company,
+ // before any of them is written — otherwise a line could be pointed at
+ // another company's item.
+ const activeMappings = mappings.filter((map) => map?.action !== "ignore");
+ if (activeMappings.some((map) => typeof map?.lineId !== "string")) {
+ return { success: false, error: "Invalid mappings" };
+ }
+ const lineIds = [...new Set(activeMappings.map((map) => map.lineId))];
+ const itemIds = [
+ ...new Set(
+ activeMappings
+ .filter((map) => map.itemId)
+ .map((map) => String(map.itemId))
+ )
+ ];
+
+ if (lineIds.length > 0) {
+ const lines = await serviceRole
+ .from("purchaseInvoiceLine")
+ .select("id")
+ .eq("invoiceId", invoiceId)
+ .eq("companyId", companyId)
+ .in("id", lineIds);
+ if (lines.error || (lines.data?.length ?? 0) !== lineIds.length) {
+ logger.error("Invoice lines not found for mapping", {
+ companyId,
+ invoiceId,
+ lineIds,
+ error: lines.error
+ });
+ return { success: false, error: "Invoice line not found" };
+ }
+ }
+
+ if (itemIds.length > 0) {
+ const items = await serviceRole
+ .from("item")
+ .select("id")
+ .eq("companyId", companyId)
+ .in("id", itemIds);
+ if (items.error || (items.data?.length ?? 0) !== itemIds.length) {
+ logger.error("Items not found for invoice line mapping", {
+ companyId,
+ invoiceId,
+ itemIds,
+ error: items.error
+ });
+ return { success: false, error: "Item not found" };
+ }
+ }
+
for (const map of mappings) {
if (map.action === "ignore") continue;
diff --git a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
index 49511ff329..fb7aab45bf 100644
--- a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
@@ -167,12 +167,41 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
+ // The line ids are caller-supplied and every write below runs as the
+ // service role, while the share link only authorizes THIS quote. Prove
+ // each line belongs to it before touching any price row — otherwise one
+ // supplier's link could rewrite another quote's (or company's) prices.
+ const lineIds = [
+ ...new Set(priceRecordsToProcess.map(({ lineId }) => lineId))
+ ];
+ if (lineIds.length > 0) {
+ const ownedLines = await serviceRole
+ .from("supplierQuoteLine")
+ .select("id")
+ .eq("supplierQuoteId", quote.data.id)
+ .eq("companyId", quote.data.companyId)
+ .in("id", lineIds);
+ if (
+ ownedLines.error ||
+ (ownedLines.data?.length ?? 0) !== lineIds.length
+ ) {
+ logger.error("Digital quote lines do not belong to the quote", {
+ quoteId: quote.data.id,
+ companyId: quote.data.companyId,
+ lineIds,
+ error: ownedLines.error
+ });
+ return { success: false, message: "Invalid selected lines data" };
+ }
+ }
+
// Batch check which price records exist
const existingPriceChecks = await Promise.all(
priceRecordsToProcess.map(({ lineId, quantity }) =>
serviceRole
.from("supplierQuoteLinePrice")
.select("id")
+ .eq("supplierQuoteId", quote.data.id)
.eq("supplierQuoteLineId", lineId)
.eq("quantity", quantity)
.maybeSingle()
@@ -212,6 +241,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
updatedBy: quote.data.createdBy
})
+ .eq("supplierQuoteId", quote.data.id)
.eq("supplierQuoteLineId", lineId)
.eq("quantity", quantity)
);
diff --git a/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts b/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts
index 762fd32207..9c4be41817 100644
--- a/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts
+++ b/apps/erp/app/routes/api+/sales-rfq.$rfqId.map-lines.ts
@@ -1,7 +1,11 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { resolveItemIdFromExtractedText, upsertPart } from "~/modules/items";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
+
+const logger = getLogger("erp", "sales-rfq-map-lines");
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -63,8 +67,69 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!mappingsStr) return { success: false, error: "No mappings provided" };
const mappings = JSON.parse(mappingsStr);
+ if (!Array.isArray(mappings)) {
+ return { success: false, error: "Invalid mappings" };
+ }
const serviceRole = await getCarbonServiceRole();
+ // Every line, item and customer id is caller-supplied, and the
+ // customerPartToItem upsert runs as the service role keyed on
+ // (customerId, itemId) — a foreign pair would overwrite another company's
+ // mapping. Prove each id belongs to this company (lines to this RFQ) first.
+ const activeMappings = mappings.filter((map) => map?.action !== "ignore");
+ if (activeMappings.some((map) => typeof map?.lineId !== "string")) {
+ return { success: false, error: "Invalid mappings" };
+ }
+ const lineIds = [...new Set(activeMappings.map((map) => map.lineId))];
+ const itemIds = [
+ ...new Set(
+ activeMappings
+ .filter((map) => map.itemId)
+ .map((map) => String(map.itemId))
+ )
+ ];
+
+ if (lineIds.length > 0) {
+ const lines = await serviceRole
+ .from("salesRfqLine")
+ .select("id")
+ .eq("salesRfqId", rfqId)
+ .eq("companyId", companyId)
+ .in("id", lineIds);
+ if (lines.error || (lines.data?.length ?? 0) !== lineIds.length) {
+ logger.error("RFQ lines not found for mapping", {
+ companyId,
+ rfqId,
+ lineIds,
+ error: lines.error
+ });
+ return { success: false, error: "RFQ line not found" };
+ }
+ }
+
+ if (itemIds.length > 0) {
+ const items = await serviceRole
+ .from("item")
+ .select("id")
+ .eq("companyId", companyId)
+ .in("id", itemIds);
+ if (items.error || (items.data?.length ?? 0) !== itemIds.length) {
+ logger.error("Items not found for RFQ line mapping", {
+ companyId,
+ rfqId,
+ itemIds,
+ error: items.error
+ });
+ return { success: false, error: "Item not found" };
+ }
+ }
+
+ if (customerId) {
+ await requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: customerId
+ });
+ }
+
for (const map of mappings) {
if (map.action === "ignore") continue;
diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
index 8c6aadd4bb..32fafa4bab 100644
--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
@@ -4,7 +4,7 @@ import {
dedupeViolations,
evaluateSalesRulesForSalesDocument
} from "@carbon/ee/rules.server";
-import { storage } from "@carbon/files";
+import { safeStorageFileName, storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
@@ -88,6 +88,18 @@ export async function action(args: ActionFunctionArgs) {
const selectedLines = parseResult.data;
+ // Unauthenticated endpoint: the name becomes a storage key segment.
+ const uploadFileName =
+ file instanceof File ? safeStorageFileName(file.name) : null;
+ if (file instanceof File && !uploadFileName) {
+ logger.error("Rejected digital quote upload file name", {
+ quoteId: quote.data.id,
+ companyId: quote.data.companyId,
+ fileName: file.name
+ });
+ return { success: false, message: "Invalid file name" };
+ }
+
// Extract purchase order number from PDF filename if available
let purchaseOrderNumber = "";
if (file instanceof File && file.name.toLowerCase().endsWith(".pdf")) {
@@ -235,8 +247,8 @@ export async function action(args: ActionFunctionArgs) {
}
}
- if (file && file instanceof File) {
- const purchaseOrderDocumentPath = `${companySettings.data.id}/opportunity/${quote.data.opportunityId}/${file.name}`;
+ if (file && file instanceof File && uploadFileName) {
+ const purchaseOrderDocumentPath = `${quote.data.companyId}/opportunity/${quote.data.opportunityId}/${uploadFileName}`;
const fileUpload = await storage(serviceRole)
.company(quote.data.companyId)
diff --git a/apps/erp/app/routes/api+/schedule.ts b/apps/erp/app/routes/api+/schedule.ts
index bf545a865e..fd95ac6b74 100644
--- a/apps/erp/app/routes/api+/schedule.ts
+++ b/apps/erp/app/routes/api+/schedule.ts
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { runLocationSchedule } from "@carbon/planning";
import type { ActionFunctionArgs } from "react-router";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request }: ActionFunctionArgs) {
@@ -19,6 +20,12 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: false, error: "A location is required to regenerate" };
}
+ // The location id comes from the query string and the run below is
+ // privileged (Kysely + service role), so prove it is this company's first.
+ await requireCompanyRecord(getCarbonServiceRole(), "location", companyId, {
+ id: locationId
+ });
+
// Regenerate the whole location's forecast IN-PROCESS (Node) rather than
// round-tripping to the `schedule` edge function — no cold start, no HTTP hop.
// Awaited before we return, so the fetcher's revalidation reads fully-
diff --git a/apps/erp/app/routes/api+/settings.backup-upload.ts b/apps/erp/app/routes/api+/settings.backup-upload.ts
index 6bf33511e4..cdb94ba246 100644
--- a/apps/erp/app/routes/api+/settings.backup-upload.ts
+++ b/apps/erp/app/routes/api+/settings.backup-upload.ts
@@ -53,8 +53,17 @@ export async function action({ request }: ActionFunctionArgs) {
if (intent === "unpack") {
const path = formData.get("path");
- // Caller-supplied — only ever read back an archive staged for this company.
- if (typeof path !== "string" || !path.startsWith(`${companyId}/backups/`)) {
+ // Caller-supplied — only ever read back (and then remove) an archive
+ // staged for this company. Match the exact shape `sign` mints: a prefix
+ // check alone would admit `${companyId}/backups/../<other>/…`.
+ if (
+ typeof path !== "string" ||
+ !path.startsWith(`${companyId}/backups/`) ||
+ !/^[A-Za-z0-9_-]+\.tar\.gz$/.test(
+ path.slice(`${companyId}/backups/`.length)
+ )
+ ) {
+ logger.error("Rejected backup archive path", { companyId, path });
throw new Response("Invalid path", { status: 400 });
}
try {
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index ba681f702c..3031e97f39 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -16,6 +16,7 @@ const spies = vi.hoisted(() => ({
upsertJobMaterial: vi.fn(),
upsertMethodMaterial: vi.fn(),
upsertQuoteLinePrices: vi.fn(),
+ updateQuoteLineOrder: vi.fn(),
generateInventoryCountLines: vi.fn(),
upsertNotificationPreference: vi.fn(),
insertJob: vi.fn(),
@@ -65,6 +66,7 @@ vi.mock("~/modules/quality/quality.service", () => ({
vi.mock("~/modules/resources/resources.service", () => ({}));
vi.mock("~/modules/sales/sales.service", () => ({
upsertQuoteLinePrices: spies.upsertQuoteLinePrices,
+ updateQuoteLineOrder: spies.updateQuoteLineOrder,
insertSalesOrder: spies.insertSalesOrder
}));
vi.mock("~/modules/settings/settings.service", () => ({}));
@@ -145,6 +147,7 @@ const allSpies = [
spies.upsertJobMaterial,
spies.upsertMethodMaterial,
spies.upsertQuoteLinePrices,
+ spies.updateQuoteLineOrder,
spies.generateInventoryCountLines,
spies.upsertNotificationPreference,
spies.insertJob,
@@ -428,18 +431,145 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
expect("updatedBy" in rows[0]).toBe(false);
});
- it("h. array payload on an update passes through untouched", () => {
+ it("h. array payload on an update adds nothing, but overwrites caller-supplied identity keys", () => {
// No manifest op combines `_operation` with an array payload, so this pins the
// enrichment helper directly.
- const rows = [{ id: "p1", createdBy: "orig" }];
+ const rows = [
+ { id: "p1", sortOrder: 1 },
+ {
+ id: "p2",
+ createdBy: "forged",
+ updatedBy: "forged",
+ companyId: "other-company",
+ userId: "employee-7"
+ },
+ 42
+ ];
const out = enrichWithAuthContext(
rows,
ctx,
["companyId", "createdBy", "updatedBy"],
"update"
);
- expect(out).toBe(rows);
- expect(rows[0]).toEqual({ id: "p1", createdBy: "orig" });
+ expect(out).toEqual([
+ { id: "p1", sortOrder: 1 },
+ {
+ id: "p2",
+ createdBy: "u1",
+ updatedBy: "u1",
+ companyId: "c1",
+ // A row's userId is data (e.g. the assigned employee), never stamped.
+ userId: "employee-7"
+ },
+ 42
+ ]);
+ // The caller's array is not mutated.
+ expect(rows[1]).toMatchObject({ createdBy: "forged" });
+ });
+
+ it("h2. a Kysely reorder gets the AUTHENTICATED companyId/userId positionally, never the body's", async () => {
+ // The service's companyId predicate is the only tenant boundary on a Kysely
+ // write, so it must come from context even when the body forges one.
+ const r = await runDispatch(
+ "sales_updateQuoteLineOrder",
+ spies.updateQuoteLineOrder,
+ {
+ companyId: "other-company",
+ userId: "forged",
+ quoteId: "q1",
+ updates: [
+ { id: "ql1", sortOrder: 2, updatedBy: "forged" },
+ { id: "ql2", sortOrder: 1 }
+ ]
+ }
+ );
+ // The parent quote id is the caller's (the service scopes every row to it);
+ // the identity fields never are.
+ expect(r.calls).toEqual([
+ [
+ spies.FAKE_DB,
+ "c1",
+ "u1",
+ "q1",
+ [
+ { id: "ql1", sortOrder: 2, updatedBy: "u1" },
+ { id: "ql2", sortOrder: 1 }
+ ]
+ ]
+ ]);
+ });
+
+ it("h3. a tenant key the caller nested one level down is overwritten, never added", () => {
+ // A `db` service may spread a nested object into `.set()`
+ // (updateItemMethodAndSourcing spreads `itemUpdate`), so a nested companyId
+ // would move the caller's rows into another company.
+ const out = enrichWithAuthContext(
+ {
+ itemIds: ["i1"],
+ itemUpdate: { sourcingType: "Buy", companyId: "other-company" },
+ cascade: { methodType: "Buy" },
+ rows: [{ id: "r1", companyGroupId: "other-group" }, { id: "r2" }]
+ },
+ ctx,
+ ["companyId", "updatedBy", "userId"],
+ "update"
+ );
+ expect(out).toEqual({
+ itemIds: ["i1"],
+ itemUpdate: { sourcingType: "Buy", companyId: "c1" },
+ cascade: { methodType: "Buy" },
+ rows: [{ id: "r1", companyGroupId: "g1" }, { id: "r2" }],
+ companyId: "c1",
+ updatedBy: "u1",
+ userId: "u1"
+ });
+ });
+
+ it("h3b. nested audit keys follow the top-level array rule: overwritten when supplied, never added", () => {
+ const out = enrichWithAuthContext(
+ {
+ lines: [
+ { id: "l1", createdBy: "forged", updatedBy: "forged" },
+ { id: "l2" }
+ ],
+ header: { updatedBy: "forged", userId: "employee-7" },
+ plain: { note: "untouched" }
+ },
+ ctx,
+ ["companyId"],
+ "update"
+ );
+ expect(out).toEqual({
+ lines: [{ id: "l1", createdBy: "u1", updatedBy: "u1" }, { id: "l2" }],
+ // A nested userId is data (e.g. an assignee), exactly as in an array row.
+ header: { updatedBy: "u1", userId: "employee-7" },
+ plain: { note: "untouched" },
+ companyId: "c1"
+ });
+ });
+
+ it("h4. a READ tool's nested identity keys are overwritten harmlessly — the read can only narrow to the caller's own company", async () => {
+ const r = await runDispatch(
+ "accounting_getAccountLedger",
+ spies.getAccountLedger,
+ {
+ accountNumber: "1000",
+ scope: { companyId: "other-company" },
+ filters: [{ column: "accountNumber", operator: "eq", value: "1000" }]
+ }
+ );
+ expect(r.calls).toEqual([
+ [
+ spies.FAKE_CLIENT,
+ {
+ accountNumber: "1000",
+ scope: { companyId: "c1" },
+ // Rows with no identity key pass through unchanged — nothing added.
+ filters: [{ column: "accountNumber", operator: "eq", value: "1000" }],
+ companyId: "c1"
+ }
+ ]
+ ]);
});
it("i. a `db` service param receives the Kysely client from getDatabaseClient()", async () => {
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
index ac50e5dc2e..033b5cb94a 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
@@ -42,18 +42,32 @@ export function enrichWithAuthContext(
// Array payloads (e.g. the row list for upsertQuoteLinePrices) need per-element
// stamping — enrichment never reached inside them, so a NOT NULL createdBy on
- // the row table failed. Only createdBy is injected into elements (and only for
- // an insert): element keys are spread straight into an INSERT, so injecting
- // companyId/updatedBy could add a column the row table doesn't have. The
- // service owns companyId for these rows. createdBy is stamped AFTER the spread
- // so a caller can't forge audit attribution by supplying it in a row.
+ // the row table failed. Only createdBy is ADDED to elements (and only for an
+ // insert): element keys are spread straight into an INSERT, so adding
+ // companyId/updatedBy could add a column the row table doesn't have.
+ //
+ // But an identity key the CALLER put in a row is always OVERWRITTEN with the
+ // authenticated value, on every operation. The input schema preserves unknown
+ // keys, so without this a row could carry a forged createdBy/updatedBy (audit
+ // attribution) or a foreign companyId straight into a service that spreads it.
+ // Overwriting a key that is already present never changes the row's shape.
+ // userId is deliberately left alone: in a row it is usually data (the employee
+ // being assigned), not the caller.
if (Array.isArray(value)) {
- if (operation === "update" || !fields.includes("createdBy")) return value;
- return value.map((element) =>
- element && typeof element === "object" && !Array.isArray(element)
- ? { ...(element as Record<string, unknown>), createdBy: context.userId }
- : element
- );
+ const addCreatedBy = operation !== "update" && fields.includes("createdBy");
+ return value.map((element) => {
+ if (!element || typeof element !== "object" || Array.isArray(element)) {
+ return element;
+ }
+ const row: Record<string, unknown> = {
+ ...(element as Record<string, unknown>)
+ };
+ if (addCreatedBy || "createdBy" in row) row.createdBy = context.userId;
+ if ("updatedBy" in row) row.updatedBy = context.userId;
+ if ("companyId" in row) row.companyId = context.companyId;
+ if ("companyGroupId" in row) row.companyGroupId = context.companyGroupId;
+ return row;
+ });
}
const enriched: Record<string, unknown> = {
@@ -91,9 +105,57 @@ export function enrichWithAuthContext(
enriched.userId = context.userId;
}
+ // One level down, too. The input schema passes unknown keys through nested
+ // objects as well, and a service handed the superuser `db` may spread one
+ // straight into a Kysely `.set()` — `updateItemMethodAndSourcing` spreads
+ // `itemUpdate`, so `{ itemUpdate: { companyId: "<other>" } }` moved the
+ // caller's items into another company. The same rule as the array branch:
+ // only an identity key the caller PUT there is overwritten, never added —
+ // createdBy/updatedBy included, so a nested row cannot forge attribution
+ // any more than a top-level array element can. Nested arrays inside THOSE
+ // are not reached.
+ for (const [key, nested] of Object.entries(enriched)) {
+ if (Array.isArray(nested)) {
+ enriched[key] = nested.map((element) =>
+ overwriteIdentityKeys(element, context)
+ );
+ } else {
+ enriched[key] = overwriteIdentityKeys(nested, context);
+ }
+ }
+
return enriched;
}
+const IDENTITY_KEYS = [
+ "createdBy",
+ "updatedBy",
+ "companyId",
+ "companyGroupId"
+] as const;
+
+/** A copy of a plain object with any caller-supplied `createdBy` /
+ * `updatedBy` / `companyId` / `companyGroupId` replaced by the authenticated
+ * value (the same keys, and the same never-add rule, as the top-level array
+ * branch); anything else is returned as is. */
+function overwriteIdentityKeys(
+ value: unknown,
+ context: AuthStampContext
+): unknown {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return value;
+ }
+ if (!IDENTITY_KEYS.some((key) => key in value)) return value;
+ const row: Record<string, unknown> = {
+ ...(value as Record<string, unknown>)
+ };
+ if ("createdBy" in row) row.createdBy = context.userId;
+ if ("updatedBy" in row) row.updatedBy = context.userId;
+ if ("companyId" in row) row.companyId = context.companyId;
+ if ("companyGroupId" in row) row.companyGroupId = context.companyGroupId;
+ return row;
+}
+
// Pulls the MCP-only `_operation` flag out of the args, top level or nested.
// Returns every value it found so the caller can reject contradictory ones.
export function extractOperation(args: Record<string, any> | undefined): {
diff --git a/apps/erp/app/routes/api+/webhook.jira.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.jira.$companyId.test.ts
new file mode 100644
index 0000000000..095dd15de0
--- /dev/null
+++ b/apps/erp/app/routes/api+/webhook.jira.$companyId.test.ts
@@ -0,0 +1,123 @@
+import { createHmac } from "node:crypto";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// The DB boundary: `companyIntegration` row + the vault RPC that resolves its
+// secret bag. Everything between it and the route (getIntegration,
+// resolveIntegrationSecrets, the HMAC check) runs for real.
+const db = vi.hoisted(() => ({
+ row: null as Record<string, unknown> | null,
+ vault: {} as Record<string, unknown>
+}));
+// Env constants only: the real @carbon/auth barrel reaches Lingui macros that
+// only compile under Vite's lingui plugin.
+vi.mock("@carbon/auth", () => ({
+ SUPABASE_URL: "http://localhost",
+ JIRA_CLIENT_ID: "test",
+ JIRA_CLIENT_SECRET: "test"
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: () => {
+ const query = {
+ select: () => query,
+ eq: () => query,
+ maybeSingle: async () => ({ data: db.row, error: null })
+ };
+ return {
+ from: () => query,
+ rpc: async () => ({ data: db.vault, error: null })
+ };
+ }
+}));
+// The real payload schema (the @carbon/jobs barrel pulls in Lingui macros that
+// only compile under Vite's lingui plugin); `trigger` is the Inngest boundary.
+vi.mock("@carbon/jobs", async () => ({
+ syncIssueFromJiraSchema: (
+ await import("../../../../../packages/jobs/src/schemas")
+ ).syncIssueFromJiraSchema,
+ trigger: vi.fn()
+}));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })
+}));
+
+import { trigger } from "@carbon/jobs";
+import { action } from "./webhook.jira.$companyId";
+
+const SECRET = "jira-admin-webhook-secret";
+
+const body = JSON.stringify({
+ timestamp: 1_790_000_000_000,
+ webhookEvent: "jira:issue_updated",
+ issue: {
+ id: "10001",
+ key: "QA-1",
+ fields: { summary: "Fix the fixture" }
+ }
+});
+
+function sign(payload: string, secret = SECRET) {
+ return `sha256=${createHmac("sha256", secret).update(payload).digest("hex")}`;
+}
+
+function run(payload: string, signature?: string) {
+ const headers = new Headers({ "content-type": "application/json" });
+ if (signature !== undefined) headers.set("x-hub-signature", signature);
+ const request = new Request("http://localhost/api/webhook/jira/company-1", {
+ method: "POST",
+ body: payload,
+ headers
+ });
+ return action({ request, params: { companyId: "company-1" } } as never);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ db.row = { active: true, metadata: {}, secretRef: "secret-ref" };
+ db.vault = {
+ credentials: { accessToken: "at", refreshToken: "rt" },
+ webhookSigningSecret: SECRET
+ };
+});
+
+describe("Jira webhook with a signing secret", () => {
+ it("accepts a validly signed delivery and triggers the sync", async () => {
+ expect(await run(body, sign(body))).toEqual({ success: true });
+ expect(trigger).toHaveBeenCalledOnce();
+ expect(vi.mocked(trigger).mock.calls[0]?.[0]).toBe("sync-issue-from-jira");
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["signed with the wrong secret", sign(body, "wrong-secret")],
+ ["missing the sha256= prefix", sign(body).slice("sha256=".length)],
+ ["using an unsupported method", sign(body).replace("sha256=", "sha1=")],
+ ["an empty digest", "sha256="],
+ ["a valid digest with trailing junk", `${sign(body)}zz`]
+ ])("rejects a signature that is %s with 401", async (_label, signature) => {
+ const result = await run(body, signature);
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("rejects a signature over a different body", async () => {
+ const tampered = body.replace("QA-1", "QA-2");
+ const result = await run(tampered, sign(body));
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("fails closed with 500 when the vault cannot be read", async () => {
+ db.row = { active: true, metadata: {}, secretRef: null };
+ const result = await run(body, sign(body));
+ expect(result).toMatchObject({ init: { status: 500 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+});
+
+describe("Jira webhook without a signing secret", () => {
+ it("still accepts an unsigned delivery (existing installs)", async () => {
+ db.vault = { credentials: { accessToken: "at", refreshToken: "rt" } };
+ expect(await run(body)).toEqual({ success: true });
+ expect(trigger).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/erp/app/routes/api+/webhook.jira.$companyId.ts b/apps/erp/app/routes/api+/webhook.jira.$companyId.ts
index 83ad14df85..5e9770a614 100644
--- a/apps/erp/app/routes/api+/webhook.jira.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.jira.$companyId.ts
@@ -1,13 +1,19 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getWebhookSigningSecret } from "@carbon/ee/integrations/secrets";
+import { verifyJiraWebhook } from "@carbon/ee/jira.server";
import { syncIssueFromJiraSchema, trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
-import { getIntegration } from "../../modules/settings";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+// Needs node:crypto for the constant-time HMAC comparison in
+// verifyJiraWebhook.
+export const config = { runtime: "nodejs" };
const logger = getLogger("erp", "webhook-jira-companyid");
-export async function loader({ request, params }: LoaderFunctionArgs) {
+export async function loader({ params }: LoaderFunctionArgs) {
const { companyId } = params;
if (!companyId) {
return data({ success: false }, { status: 400 });
@@ -17,6 +23,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
success: true
};
}
+
+/**
+ * Receives the admin webhook a customer creates BY HAND in Jira (see the setup
+ * instructions in `@carbon/ee` `jira/config.tsx`). Signing is OPT-IN so
+ * installs made before it existed keep working: with a "Webhook Secret" saved
+ * on the integration, every delivery must carry a valid `X-Hub-Signature`;
+ * without one, deliveries are accepted as before and logged as unsigned.
+ */
export async function action({ request, params }: ActionFunctionArgs) {
const { companyId } = params;
@@ -24,11 +38,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
return data({ success: false }, { status: 400 });
}
+ // Raw body FIRST — the signature covers the exact bytes, not re-serialized
+ // JSON.
+ const body = await request.text();
+
const serviceRole = getCarbonServiceRole();
const integration = await getIntegration(serviceRole, "jira", companyId);
if (integration.error) {
+ logger.error("Jira webhook: integration query failed", {
+ companyId,
+ error: integration.error
+ });
return data(
{ success: false, error: "Integration query failed" },
{ status: 400 }
@@ -49,11 +71,55 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const body = await request.json();
+ // Fail closed when the vault is unreadable: "no secret configured" cannot be
+ // told apart from "secret unavailable", and only the former may skip the
+ // signature check.
+ let signingSecret: string | null;
+ try {
+ signingSecret = await getWebhookSigningSecret(
+ serviceRole,
+ companyId,
+ "jira",
+ integration.data
+ );
+ } catch (error) {
+ logger.error("Jira webhook: failed to resolve signing secret", {
+ companyId,
+ error
+ });
+ return data({ success: false }, { status: 500 });
+ }
+
+ if (signingSecret) {
+ const verification = verifyJiraWebhook({
+ signature: request.headers.get("x-hub-signature"),
+ body,
+ secret: signingSecret
+ });
+ if (!verification.ok) {
+ logger.warning("Jira webhook rejected", {
+ companyId,
+ reason: verification.reason
+ });
+ return data({ success: false }, { status: 401 });
+ }
+ } else {
+ logger.warning(
+ "Jira webhook is unsigned: add the webhook's secret to the Jira integration settings to verify deliveries",
+ { companyId }
+ );
+ }
+
+ let event: unknown;
+ try {
+ event = JSON.parse(body);
+ } catch {
+ return data({ success: false, error: "Invalid JSON" }, { status: 400 });
+ }
const parsed = syncIssueFromJiraSchema.safeParse({
companyId,
- event: body
+ event
});
if (!parsed.success) {
@@ -67,7 +133,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trigger("sync-issue-from-jira", parsed.data);
return { success: true };
} catch (err) {
- logger.error("Error", { error: err });
+ logger.error("Jira webhook: failed to trigger task", {
+ companyId,
+ error: err
+ });
return data({ success: false }, { status: 500 });
}
}
diff --git a/apps/erp/app/routes/api+/webhook.linear.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.linear.$companyId.test.ts
new file mode 100644
index 0000000000..e0d834480b
--- /dev/null
+++ b/apps/erp/app/routes/api+/webhook.linear.$companyId.test.ts
@@ -0,0 +1,162 @@
+import { createHmac } from "node:crypto";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// The DB boundary: `companyIntegration` row + the vault RPC that resolves its
+// secret bag. Everything between it and the route (getIntegration,
+// resolveIntegrationSecrets, the HMAC check) runs for real.
+const db = vi.hoisted(() => ({
+ row: null as Record<string, unknown> | null,
+ vault: {} as Record<string, unknown>
+}));
+// Env constants only: the real @carbon/auth barrel reaches Lingui macros that
+// only compile under Vite's lingui plugin.
+vi.mock("@carbon/auth", () => ({
+ SUPABASE_URL: "http://localhost",
+ JIRA_CLIENT_ID: "test",
+ JIRA_CLIENT_SECRET: "test"
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: () => {
+ const query = {
+ select: () => query,
+ eq: () => query,
+ maybeSingle: async () => ({ data: db.row, error: null })
+ };
+ return {
+ from: () => query,
+ rpc: async () => ({ data: db.vault, error: null })
+ };
+ }
+}));
+// The real payload schema (the @carbon/jobs barrel pulls in Lingui macros that
+// only compile under Vite's lingui plugin); `trigger` is the Inngest boundary.
+vi.mock("@carbon/jobs", async () => ({
+ syncIssueFromLinearSchema: (
+ await import("../../../../../packages/jobs/src/schemas")
+ ).syncIssueFromLinearSchema,
+ trigger: vi.fn()
+}));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })
+}));
+
+import { trigger } from "@carbon/jobs";
+import { action } from "./webhook.linear.$companyId";
+
+const SECRET = "lin_wh_test_signing_secret";
+const NOW = 1_790_000_000_000;
+
+function payload(webhookTimestamp = NOW) {
+ return JSON.stringify({
+ type: "Issue",
+ action: "update",
+ data: { id: "issue-1", assigneeId: "user-1" },
+ webhookTimestamp
+ });
+}
+
+function sign(body: string, secret = SECRET) {
+ return createHmac("sha256", secret).update(body).digest("hex");
+}
+
+function run(body: string, signature?: string) {
+ const headers = new Headers({ "content-type": "application/json" });
+ if (signature !== undefined) headers.set("linear-signature", signature);
+ const request = new Request("http://localhost/api/webhook/linear/company-1", {
+ method: "POST",
+ body,
+ headers
+ });
+ return action({ request, params: { companyId: "company-1" } } as never);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ db.row = { active: true, metadata: {}, secretRef: "secret-ref" };
+ db.vault = { apiKey: "lin_api_key", webhookSigningSecret: SECRET };
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("Linear webhook with a signing secret", () => {
+ it("accepts a validly signed, fresh delivery and triggers the sync", async () => {
+ const body = payload();
+ expect(await run(body, sign(body))).toEqual({ success: true });
+ expect(trigger).toHaveBeenCalledExactlyOnceWith("sync-issue-from-linear", {
+ companyId: "company-1",
+ event: {
+ type: "Issue",
+ action: "update",
+ data: { id: "issue-1", assigneeId: "user-1" }
+ }
+ });
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["signed with the wrong secret", sign(payload(), "wrong-secret")],
+ ["not hex", "not-a-signature"],
+ ["a valid digest with trailing junk", `${sign(payload())}zz`],
+ ["truncated", sign(payload()).slice(0, 32)]
+ ])("rejects a signature that is %s with 401", async (_label, signature) => {
+ const result = await run(payload(), signature);
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("rejects a signature over a different body", async () => {
+ const tampered = payload().replace("issue-1", "issue-2");
+ const result = await run(tampered, sign(payload()));
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["older than 60 s", NOW - 60_001],
+ ["more than 60 s in the future", NOW + 60_001]
+ ])("rejects a validly signed delivery %s (replay)", async (_label, ts) => {
+ const body = payload(ts);
+ const result = await run(body, sign(body));
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("rejects a validly signed delivery without webhookTimestamp", async () => {
+ const body = JSON.stringify({
+ type: "Issue",
+ action: "update",
+ data: { id: "issue-1" }
+ });
+ const result = await run(body, sign(body));
+ expect(result).toMatchObject({ init: { status: 401 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("fails closed with 500 when the vault cannot be read", async () => {
+ db.row = { active: true, metadata: {}, secretRef: null };
+ const body = payload();
+ const result = await run(body, sign(body));
+ expect(result).toMatchObject({ init: { status: 500 } });
+ expect(trigger).not.toHaveBeenCalled();
+ });
+});
+
+describe("Linear webhook without a signing secret", () => {
+ beforeEach(() => {
+ db.vault = { apiKey: "lin_api_key" };
+ });
+
+ it("still accepts an unsigned delivery (existing installs)", async () => {
+ expect(await run(payload())).toEqual({ success: true });
+ expect(trigger).toHaveBeenCalledOnce();
+ });
+
+ it("does not apply the replay window to unsigned deliveries", async () => {
+ expect(await run(payload(NOW - 3_600_000))).toEqual({ success: true });
+ expect(trigger).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/erp/app/routes/api+/webhook.linear.$companyId.ts b/apps/erp/app/routes/api+/webhook.linear.$companyId.ts
index 89110336be..288ec4e91f 100644
--- a/apps/erp/app/routes/api+/webhook.linear.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.linear.$companyId.ts
@@ -1,13 +1,19 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getWebhookSigningSecret } from "@carbon/ee/integrations/secrets";
+import { verifyLinearWebhook } from "@carbon/ee/linear.server";
import { syncIssueFromLinearSchema, trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
-import { getIntegration } from "../../modules/settings";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+// Needs node:crypto for the constant-time HMAC comparison in
+// verifyLinearWebhook.
+export const config = { runtime: "nodejs" };
const logger = getLogger("erp", "webhook-linear-companyid");
-export async function loader({ request, params }: LoaderFunctionArgs) {
+export async function loader({ params }: LoaderFunctionArgs) {
const { companyId } = params;
if (!companyId) {
return data({ success: false }, { status: 400 });
@@ -18,6 +24,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
};
}
+/**
+ * Receives the webhook a customer creates BY HAND in Linear (see the setup
+ * instructions in `@carbon/ee` `linear/config.tsx`). Signing is OPT-IN so
+ * installs made before it existed keep working: with a "Webhook Signing
+ * Secret" saved on the integration, every delivery must carry a valid
+ * `Linear-Signature` and a fresh `webhookTimestamp`; without one, deliveries
+ * are accepted as before and logged as unsigned.
+ */
export async function action({ request, params }: ActionFunctionArgs) {
const { companyId } = params;
@@ -25,11 +39,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
return data({ success: false }, { status: 400 });
}
+ // Raw body FIRST — the signature covers the exact bytes, not re-serialized
+ // JSON.
+ const body = await request.text();
+
const serviceRole = getCarbonServiceRole();
const integration = await getIntegration(serviceRole, "linear", companyId);
if (integration.error) {
- logger.error("Linear webhook: integration query failed", integration.error);
+ logger.error("Linear webhook: integration query failed", {
+ companyId,
+ error: integration.error
+ });
return data(
{ success: false, error: "Integration query failed" },
{ status: 400 }
@@ -50,11 +71,55 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const body = await request.json();
+ // Fail closed when the vault is unreadable: "no secret configured" cannot be
+ // told apart from "secret unavailable", and only the former may skip the
+ // signature check.
+ let signingSecret: string | null;
+ try {
+ signingSecret = await getWebhookSigningSecret(
+ serviceRole,
+ companyId,
+ "linear",
+ integration.data
+ );
+ } catch (error) {
+ logger.error("Linear webhook: failed to resolve signing secret", {
+ companyId,
+ error
+ });
+ return data({ success: false }, { status: 500 });
+ }
+
+ if (signingSecret) {
+ const verification = verifyLinearWebhook({
+ signature: request.headers.get("linear-signature"),
+ body,
+ secret: signingSecret
+ });
+ if (!verification.ok) {
+ logger.warning("Linear webhook rejected", {
+ companyId,
+ reason: verification.reason
+ });
+ return data({ success: false }, { status: 401 });
+ }
+ } else {
+ logger.warning(
+ "Linear webhook is unsigned: add the webhook's signing secret to the Linear integration settings to verify deliveries",
+ { companyId }
+ );
+ }
+
+ let event: unknown;
+ try {
+ event = JSON.parse(body);
+ } catch {
+ return data({ success: false, error: "Invalid JSON" }, { status: 400 });
+ }
const parsed = syncIssueFromLinearSchema.safeParse({
companyId,
- event: body
+ event
});
if (!parsed.success) {
@@ -68,7 +133,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trigger("sync-issue-from-linear", parsed.data);
return { success: true };
} catch (err) {
- logger.error("Linear webhook: failed to trigger task", { error: err });
+ logger.error("Linear webhook: failed to trigger task", {
+ companyId,
+ error: err
+ });
return data({ success: false }, { status: 500 });
}
}
diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts
index 8c99bc2e06..8cc53cd784 100644
--- a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts
+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts
@@ -96,11 +96,12 @@ describe("webhook.quickbooks payment accelerator", () => {
getProviderIntegration.mockReset();
getAccountingIntegration.mockResolvedValue({
+ companyId: "company-1",
active: true,
metadata: {
credentials: {
type: "oauth2",
- providerMetadata: { webhookVerifierToken: TOKEN }
+ providerMetadata: { webhookVerifierToken: TOKEN, realmId: "realm-1" }
}
}
});
@@ -161,6 +162,7 @@ describe("webhook.quickbooks payment accelerator", () => {
makeRequest({
eventNotifications: [
{
+ realmId: "realm-1",
dataChangeEvent: {
entities: [{ name: "Payment", id: "pay-1", operation: "Update" }]
}
@@ -182,6 +184,7 @@ describe("webhook.quickbooks payment accelerator", () => {
makeRequest({
eventNotifications: [
{
+ realmId: "realm-1",
dataChangeEvent: {
entities: [{ name: "Customer", id: "c-1", operation: "Update" }]
}
@@ -203,6 +206,7 @@ describe("webhook.quickbooks payment accelerator", () => {
it("returns 401 when no verifier token is configured", async () => {
getAccountingIntegration.mockResolvedValue({
+ companyId: "company-1",
active: true,
metadata: { credentials: { type: "oauth2", providerMetadata: {} } }
});
@@ -221,4 +225,45 @@ describe("webhook.quickbooks payment accelerator", () => {
process.env.QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN = original;
}
});
+
+ it("returns 404 when the resolved integration belongs to another company", async () => {
+ // getAccountingIntegration matches companyId OR a realm/tenant id, so a URL
+ // naming another company's realm must not resolve to that company.
+ getAccountingIntegration.mockResolvedValue({
+ companyId: "company-2",
+ active: true,
+ metadata: {
+ credentials: {
+ type: "oauth2",
+ providerMetadata: { webhookVerifierToken: TOKEN, realmId: "realm-1" }
+ }
+ }
+ });
+
+ const result = (await run(makeRequest(billPaymentEvent))) as {
+ init?: { status?: number };
+ };
+ expect(result.init?.status).toBe(404);
+ expect(getProviderIntegration).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("ignores notifications for a realm other than the company's own", async () => {
+ const result = (await run(
+ makeRequest({
+ eventNotifications: [
+ {
+ realmId: "realm-of-another-company",
+ dataChangeEvent: {
+ entities: [{ name: "Payment", id: "pay-1", operation: "Update" }]
+ }
+ }
+ ]
+ })
+ )) as { success: boolean; ignored?: boolean };
+
+ expect(result).toEqual({ success: true, ignored: true });
+ expect(getProviderIntegration).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts
index 16712f1453..dd39d4504a 100644
--- a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts
@@ -106,10 +106,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
serviceRole,
companyId,
ProviderID.QUICKBOOKS
- ).catch(() => null);
+ ).catch((error) => {
+ logger.warning("QuickBooks Online integration lookup failed", {
+ companyId,
+ error
+ });
+ return null;
+ });
+ // `getAccountingIntegration` also matches a realm/tenant id, so only trust a
+ // row that belongs to the company in the URL.
if (!integration || !integration.active) {
return data({ success: false }, { status: 404 });
}
+ if (integration.companyId !== companyId) {
+ logger.error("QuickBooks Online integration belongs to another company", {
+ companyId,
+ integrationCompanyId: integration.companyId
+ });
+ return data({ success: false }, { status: 404 });
+ }
// Intuit signs webhooks with the app's "verifier token" (base64
// HMAC-SHA256 of the raw body). VERIFY: it currently lives on the QBO
@@ -117,6 +132,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// env fallback for a single app-wide token — confirm where Carbon persists
// it during QBO setup and drop whichever branch is unused.
let verifierToken: string | null = null;
+ let realmId: string | null = null;
try {
const credentials = parseStoredCredentials(
integration.metadata.credentials
@@ -126,6 +142,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (typeof token === "string" && token.length > 0) {
verifierToken = token;
}
+ const storedRealmId = credentials.providerMetadata?.realmId;
+ if (typeof storedRealmId === "string" && storedRealmId.length > 0) {
+ realmId = storedRealmId;
+ }
}
} catch (error) {
logger.error("Failed to parse stored QuickBooks Online credentials", {
@@ -139,6 +159,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
if (!verifierToken) {
+ logger.error("QuickBooks Online webhook verifier token not configured", {
+ companyId
+ });
return data(
{ success: false, error: "Webhook verifier token not configured" },
{ status: 401 }
@@ -147,6 +170,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const signature = request.headers.get("intuit-signature");
if (!signature) {
+ logger.warning("QuickBooks Online webhook rejected", {
+ companyId,
+ reason: "missing_signature"
+ });
return data({ success: false }, { status: 401 });
}
@@ -154,6 +181,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
.update(body)
.digest("base64");
if (!signaturesMatch(signature, expected)) {
+ logger.warning("QuickBooks Online webhook rejected", {
+ companyId,
+ reason: "signature_mismatch"
+ });
return data({ success: false }, { status: 401 });
}
@@ -165,9 +196,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
return data({ success: false }, { status: 400 });
}
+ // The verifier token can be app-wide (the env fallback), so a validly signed
+ // delivery may carry other realms' notifications. Only act on this company's
+ // own realm — never on a realm the URL's company is not connected to.
+ const ownNotifications = parsed.eventNotifications.filter(
+ (notification) => realmId !== null && notification.realmId === realmId
+ );
+ if (ownNotifications.length < parsed.eventNotifications.length) {
+ logger.warning(
+ "Ignoring QuickBooks Online notifications for another realm",
+ {
+ companyId,
+ realmId,
+ ignored: parsed.eventNotifications.length - ownNotifications.length
+ }
+ );
+ }
+
// Forward-compatibility: unrecognized entity names are acknowledged and
// ignored, never rejected.
- const paymentNotifications = parsed.eventNotifications
+ const paymentNotifications = ownNotifications
.flatMap((notification) => notification.dataChangeEvent?.entities ?? [])
.filter((entity) => PAYMENT_ENTITY_NAMES.has(entity.name));
diff --git a/apps/erp/app/routes/api+/webhook.xero.test.ts b/apps/erp/app/routes/api+/webhook.xero.test.ts
index 62e3cf4032..bbd8ab72ca 100644
--- a/apps/erp/app/routes/api+/webhook.xero.test.ts
+++ b/apps/erp/app/routes/api+/webhook.xero.test.ts
@@ -1,7 +1,13 @@
+import { createHmac } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
-// Fail-open: no secret configured → signature verification is skipped.
-vi.mock("@carbon/auth", () => ({ XERO_WEBHOOK_SECRET: undefined }));
+const SECRET = "xero-webhook-key";
+const env = vi.hoisted(() => ({ secret: undefined as string | undefined }));
+vi.mock("@carbon/auth", () => ({
+ get XERO_WEBHOOK_SECRET() {
+ return env.secret;
+ }
+}));
vi.mock("@carbon/auth/client.server", () => ({
getCarbonServiceRole: () => ({})
}));
@@ -18,6 +24,7 @@ vi.mock("@carbon/ee/accounting", () => ({
getProviderIntegration: (...args: unknown[]) =>
getProviderIntegration(...args),
ProviderID: { XERO: "xero" },
+ parseStoredCredentials: (raw: unknown) => raw,
// Real composite-id shape (the syncer's contract): ACCREC prefix-less AR,
// ACCPAY `bill:`-prefixed AP.
getXeroPaymentSyncEntityId: (
@@ -49,10 +56,20 @@ function invoiceEvent() {
};
}
-function makeRequest(body: unknown) {
+function makeRequest(body: unknown, opts: { signature?: string | null } = {}) {
+ const text = JSON.stringify(body);
+ const headers = new Headers();
+ if (opts.signature !== null) {
+ headers.set(
+ "x-xero-signature",
+ opts.signature ??
+ createHmac("sha256", SECRET).update(text, "utf8").digest("base64")
+ );
+ }
return new Request("http://localhost/api/webhook/xero", {
method: "POST",
- body: JSON.stringify(body)
+ body: text,
+ headers
});
}
@@ -61,10 +78,16 @@ describe("webhook.xero Invoice-update payment accelerator", () => {
vi.mocked(trigger).mockReset();
getAccountingIntegration.mockReset();
getProviderIntegration.mockReset();
+ env.secret = SECRET;
getAccountingIntegration.mockResolvedValue({
companyId: "company-1",
- metadata: {}
+ metadata: {
+ credentials: {
+ type: "oauth2",
+ providerMetadata: { tenantId: "tenant-1" }
+ }
+ }
});
});
@@ -156,4 +179,48 @@ describe("webhook.xero Invoice-update payment accelerator", () => {
{ entityType: "bill", entityId: "inv-remote-1", operation: "update" }
]);
});
+
+ it("fails closed with 401 when XERO_WEBHOOK_SECRET is not configured", async () => {
+ env.secret = undefined;
+
+ const result = (await action({
+ request: makeRequest(invoiceEvent(), { signature: null })
+ } as never)) as { init?: { status?: number } };
+
+ expect(result.init?.status).toBe(401);
+ expect(getAccountingIntegration).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("rejects a missing or invalid signature with 401 before any lookup", async () => {
+ for (const signature of [null, "bad", "AAAA"]) {
+ const result = (await action({
+ request: makeRequest(invoiceEvent(), { signature })
+ } as never)) as { init?: { status?: number } };
+ expect(result.init?.status).toBe(401);
+ }
+ expect(getAccountingIntegration).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveBeenCalled();
+ });
+
+ it("refuses an integration row that matched on companyId rather than its own tenant", async () => {
+ getAccountingIntegration.mockResolvedValue({
+ companyId: "tenant-1",
+ metadata: {
+ credentials: {
+ type: "oauth2",
+ providerMetadata: { tenantId: "some-other-tenant" }
+ }
+ }
+ });
+
+ const result = (await action({
+ request: makeRequest(invoiceEvent())
+ } as never)) as { success: boolean; jobsTriggered: number };
+
+ expect(result.success).toBe(false);
+ expect(result.jobsTriggered).toBe(0);
+ expect(getProviderIntegration).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/erp/app/routes/api+/webhook.xero.ts b/apps/erp/app/routes/api+/webhook.xero.ts
index 7023a7c19b..f9606a9d56 100644
--- a/apps/erp/app/routes/api+/webhook.xero.ts
+++ b/apps/erp/app/routes/api+/webhook.xero.ts
@@ -31,7 +31,8 @@ import {
getProviderIntegration,
getXeroBillPaymentSyncEntityId,
getXeroPaymentSyncEntityId,
- ProviderID
+ ProviderID,
+ parseStoredCredentials
} from "@carbon/ee/accounting";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -61,51 +62,80 @@ const WebhookSchema = z.object({
lastEventSequence: z.number()
});
-function verifySignature(payload: string, header: string) {
- if (!XERO_WEBHOOK_SECRET) {
- logger.warning("XERO_WEBHOOK_SECRET is not configured");
- return payload;
- }
+function verifySignature(payload: string, header: string, secret: string) {
+ const expected = Buffer.from(
+ crypto.createHmac("sha256", secret).update(payload, "utf8").digest("base64")
+ );
+ const received = Buffer.from(header);
- const hmac = crypto
- .createHmac("sha256", XERO_WEBHOOK_SECRET)
- .update(payload, "utf8")
- .digest("base64");
+ // timingSafeEqual throws on unequal lengths; treat that as a mismatch.
+ return (
+ expected.length === received.length &&
+ crypto.timingSafeEqual(expected, received)
+ );
+}
- return crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(header));
+/**
+ * The Xero tenant the stored credentials belong to. `getAccountingIntegration`
+ * matches `companyId` OR the credential tenant id, so the resolved row is only
+ * trusted when its OWN tenant is the one the event names.
+ */
+function getStoredTenantId(credentials: unknown): string | null {
+ try {
+ const parsed = parseStoredCredentials(credentials);
+ if (
+ parsed.type === "oauth2" &&
+ typeof parsed.providerMetadata?.tenantId === "string"
+ ) {
+ return parsed.providerMetadata.tenantId;
+ }
+ } catch (error) {
+ logger.error("Failed to parse stored Xero credentials", { error });
+ }
+ return null;
}
export async function action({ request }: ActionFunctionArgs) {
// Get the raw payload for signature verification
const payloadText = await request.text();
+ // Fail closed: without the webhook key there is no way to tell Xero's
+ // deliveries from anyone else's, and every event triggers a sync job.
+ if (!XERO_WEBHOOK_SECRET) {
+ logger.error(
+ "Xero webhook rejected: XERO_WEBHOOK_SECRET is not configured"
+ );
+ return data(
+ { success: false, error: "Webhook secret not configured" },
+ { status: 401 }
+ );
+ }
+
// Verify webhook signature for security (Xero's intent-to-receive workflow)
- if (XERO_WEBHOOK_SECRET) {
- // If payload is empty or just contains intent-to-receive data, return 200
- if (!payloadText || payloadText.trim() === "" || payloadText === "{}") {
- return new Response("", { status: 200 });
- }
+ // If payload is empty or just contains intent-to-receive data, return 200
+ if (!payloadText || payloadText.trim() === "" || payloadText === "{}") {
+ return new Response("", { status: 200 });
+ }
- const signature = request.headers.get("x-xero-signature");
+ const signature = request.headers.get("x-xero-signature");
- if (!signature) {
- return data(
- { success: false, error: "Missing signature" },
- { status: 401 }
- );
- }
-
- const isValid = verifySignature(payloadText, signature);
+ if (!signature) {
+ logger.warning("Xero webhook rejected", { reason: "missing_signature" });
+ return data(
+ { success: false, error: "Missing signature" },
+ { status: 401 }
+ );
+ }
- if (!isValid) {
- return data(
- {
- success: false,
- error: "Invalid signature"
- },
- { status: 401 }
- );
- }
+ if (!verifySignature(payloadText, signature, XERO_WEBHOOK_SECRET)) {
+ logger.warning("Xero webhook rejected", { reason: "signature_mismatch" });
+ return data(
+ {
+ success: false,
+ error: "Invalid signature"
+ },
+ { status: 401 }
+ );
}
// Parse and validate the webhook payload for actual events
@@ -175,6 +205,18 @@ export async function action({ request }: ActionFunctionArgs) {
continue;
}
+ if (getStoredTenantId(integration.metadata.credentials) !== tenantId) {
+ logger.error("Xero webhook tenant does not match its integration", {
+ tenantId,
+ companyId: integration.companyId
+ });
+ errors.push({
+ tenantId,
+ error: "Tenant ID not found in integrations"
+ });
+ continue;
+ }
+
const companyId = integration.companyId;
const provider = getProviderIntegration(
diff --git a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
index 5ebeb686aa..1083286ff0 100644
--- a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
@@ -59,9 +59,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Failed to load job");
}
- // Verify job belongs to this company
+ // Verify job belongs to this company before anything else is read with the
+ // service role (every query below is keyed off this job).
if (job.data.companyId !== companyId) {
- throw new Error("Job does not belong to this company");
+ logger.error("Job does not belong to this company", { companyId, jobId });
+ throw new Response("Not found", { status: 404 });
}
// Get all make methods for this job
diff --git a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
index f4e5ae44d4..d040aa9321 100644
--- a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
+++ b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
@@ -6,7 +6,7 @@ import { getKanban } from "~/modules/inventory/inventory.service";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory"
});
@@ -17,7 +17,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Invalid kanban action");
}
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error) {
return data({ error: "Unauthorized" }, { status: 401 });
diff --git a/apps/erp/app/routes/file+/model+/$id.tsx b/apps/erp/app/routes/file+/model+/$id.tsx
index ef52f6ff76..a541d6fc2c 100644
--- a/apps/erp/app/routes/file+/model+/$id.tsx
+++ b/apps/erp/app/routes/file+/model+/$id.tsx
@@ -11,9 +11,12 @@ export async function loader({ params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw notFound("id not found");
+ // Unauthenticated (the headless thumbnail renderer loads it): the model id
+ // is the credential, so return only the GLB keys the viewer draws — not the
+ // rest of the row (companyId, raw source path, name, size…).
const model = await client
.from("modelUpload")
- .select("*")
+ .select("glbPath, optimizedModelPath")
.eq("id", id)
.single();
if (!model.data) throw notFound("model not found");
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index 92f2ef2090..6876f460ad 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -1,6 +1,11 @@
import { notFound } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { getContentType, MEDIA_CONTENT_TYPES, storage } from "@carbon/files";
+import {
+ getContentType,
+ isUnsafeStoragePath,
+ MEDIA_CONTENT_TYPES,
+ storage
+} from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
@@ -14,7 +19,11 @@ export async function loader({ params }: LoaderFunctionArgs) {
if (!path) throw new Error("Path not found");
- if (!path.includes("models")) {
+ // Unauthenticated: the unguessable model id in the key is the only
+ // credential, so serve model objects (`${companyId}/models/…`) and nothing
+ // else — never any object whose key merely contains "models".
+ if (path.split("/")[1] !== "models" || isUnsafeStoragePath(path)) {
+ logger.error("Refused a public model path", { path });
throw notFound("Invalid path");
}
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 1d1232e4e6..37ea5e4087 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -5,6 +5,7 @@ import {
effectiveExtension,
getCompanyPrivateBucket,
getContentType,
+ isUnsafeStoragePath,
LEGACY_PRIVATE_BUCKET,
storage,
TEMP_STAGING_BUCKET
@@ -25,6 +26,15 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
// Don't decode the path here - let Supabase handle the URL encoding
// path = decodeURIComponent(path);
+ if (isUnsafeStoragePath(path)) {
+ logger.error("Refused a storage path that escapes its prefix", {
+ companyId,
+ bucket,
+ path
+ });
+ return new Response(null, { status: 400 });
+ }
+
const fileType = path.split(".").pop()?.toLowerCase();
if (!fileType) {
diff --git a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
index f45591c570..200be86f37 100644
--- a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
@@ -62,6 +62,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
logger.error("Failed to load shipment", { error: shipment.error });
}
+ // RLS admits a shipment from any company the user belongs to, but the source
+ // document below is read with the service role — pin it to this company.
+ if (shipment.data && shipment.data.companyId !== companyId) {
+ logger.error("Shipment does not belong to this company", {
+ companyId,
+ shipmentId: id
+ });
+ throw new Response("Not found", { status: 404 });
+ }
+
if (shipmentLines.error) {
logger.error("Failed to load shipmentLines", {
error: shipmentLines.error
diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsx
index be2ad81a50..dd07b01c42 100644
--- a/apps/erp/app/routes/onboarding+/company.tsx
+++ b/apps/erp/app/routes/onboarding+/company.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, safeRedirect } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { ValidatedForm, validationError, validator } from "@carbon/form";
import {
@@ -36,6 +36,7 @@ import {
setOnboardingDraft
} from "~/services/onboarding-draft.server";
import { ONBOARDING_SHORTCUTS } from "~/shortcuts";
+import { path } from "~/utils/path";
export async function loader({ request }: ActionFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {});
@@ -73,7 +74,7 @@ export async function action({ request }: ActionFunctionArgs) {
company: companyData
});
- throw redirect(next, {
+ throw redirect(safeRedirect(next, path.to.onboarding.root), {
headers: [["Set-Cookie", draftCookie]]
});
}
diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsx
index 8e6ce4d397..754f7be418 100644
--- a/apps/erp/app/routes/onboarding+/industry.tsx
+++ b/apps/erp/app/routes/onboarding+/industry.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, safeRedirect } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { setCompanyId } from "@carbon/auth/company.server";
@@ -200,7 +200,7 @@ export async function action({ request }: ActionFunctionArgs) {
const companyIdCookie = setCompanyId(companyId);
const clearDraftCookie = await clearOnboardingDraft(request);
- throw redirect(next, {
+ throw redirect(safeRedirect(next, path.to.onboarding.root), {
headers: [
["Set-Cookie", sessionCookie],
["Set-Cookie", companyIdCookie],
diff --git a/apps/erp/app/routes/onboarding+/theme.tsx b/apps/erp/app/routes/onboarding+/theme.tsx
index 30e6c9d76a..c681897807 100644
--- a/apps/erp/app/routes/onboarding+/theme.tsx
+++ b/apps/erp/app/routes/onboarding+/theme.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, safeRedirect } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import {
Button,
@@ -65,7 +65,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { next, theme } = validation.data;
if (!next) throw new Error("Fatal: next is required");
- throw redirect(next, {
+ throw redirect(safeRedirect(next, path.to.onboarding.root), {
headers: { "Set-Cookie": setTheme(theme) }
});
}
diff --git a/apps/erp/app/routes/onboarding+/user.tsx b/apps/erp/app/routes/onboarding+/user.tsx
index 5e2535cdb0..6e6b87a3ae 100644
--- a/apps/erp/app/routes/onboarding+/user.tsx
+++ b/apps/erp/app/routes/onboarding+/user.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, safeRedirect } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { destroyAuthSession } from "@carbon/auth/session.server";
@@ -29,6 +29,7 @@ import {
} from "~/modules/account";
import { getUser } from "~/modules/users/users.server";
import { ONBOARDING_SHORTCUTS } from "~/shortcuts";
+import { path } from "~/utils/path";
const logger = getLogger("erp", "user");
@@ -69,7 +70,7 @@ export async function action({ request }: ActionFunctionArgs) {
throw new Error("Fatal: failed to update account");
}
- throw redirect(next);
+ throw redirect(safeRedirect(next, path.to.onboarding.root));
}
export default function OnboardingUser() {
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index d4a6f786b7..5f2bb23788 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -3,6 +3,7 @@ import { companyHasFeature } from "@carbon/ee/plan.server";
import {
getContentType,
hasCompanyPrivateObjectPathPrefix,
+ isUnsafeStoragePath,
MEDIA_CONTENT_TYPES,
storage
} from "@carbon/files";
@@ -63,6 +64,14 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {
path = decodeURIComponent(path);
+ if (isUnsafeStoragePath(path)) {
+ logger.error("Refused a storage path that escapes its prefix", {
+ companyId: shareCompanyId,
+ path
+ });
+ return new Response(null, { status: 404 });
+ }
+
// Private objects are keyed by companyId — a path outside the portal's
// company must not resolve to another tenant's bucket.
if (!hasCompanyPrivateObjectPathPrefix(customer.data.companyId, path)) {
diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsx
index cbb9de9de5..1e6d6f1017 100644
--- a/apps/erp/app/routes/share+/quote.$id.tsx
+++ b/apps/erp/app/routes/share+/quote.$id.tsx
@@ -64,11 +64,7 @@ import {
} from "~/hooks";
import { getCurrenciesList, getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
-import type {
- QuotationLine,
- QuotationPrice,
- SalesOrderLine
-} from "~/modules/sales";
+import type { SalesOrderLine } from "~/modules/sales";
import {
externalQuoteValidator,
getOpportunity,
@@ -205,19 +201,51 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
return acc;
}, {}) ?? {};
+ // Anyone holding the share link receives this payload, so it carries only
+ // what the page renders — never whole rows (unit cost, price trace, pricing
+ // rule, category markups, internal notes, notification groups…).
+ const { internalNotes: _internalNotes, ...publicQuote } = quote.data;
+
return {
state: QuoteState.Valid,
data: {
- quote: quote.data,
+ quote: publicQuote,
company: company.data,
- companySettings: companySettings.data,
+ companySettings: companySettings.data
+ ? {
+ digitalQuoteEnabled: companySettings.data.digitalQuoteEnabled,
+ digitalQuoteIncludesPurchaseOrders:
+ companySettings.data.digitalQuoteIncludesPurchaseOrders,
+ showCurrencyTrailingZeros:
+ companySettings.data.showCurrencyTrailingZeros
+ }
+ : null,
currencies: (await currenciesPromise)?.data ?? [],
quoteLines:
- quoteLines.data?.map(({ internalNotes, ...line }) => ({
- ...line
+ quoteLines.data?.map((line) => ({
+ id: line.id,
+ description: line.description,
+ itemReadableId: line.itemReadableId,
+ quantity: line.quantity,
+ additionalCharges: line.additionalCharges,
+ taxPercent: line.taxPercent,
+ unitPricePrecision: line.unitPricePrecision,
+ externalNotes: line.externalNotes
})) ?? [],
thumbnails: thumbnails,
- quoteLinePrices: quoteLinePrices.data,
+ quoteLinePrices:
+ quoteLinePrices.data?.map((price) => ({
+ quoteLineId: price.quoteLineId,
+ quantity: price.quantity,
+ unitPrice: price.unitPrice,
+ convertedUnitPrice: price.convertedUnitPrice,
+ netUnitPrice: price.netUnitPrice,
+ convertedNetUnitPrice: price.convertedNetUnitPrice,
+ discountPercent: price.discountPercent,
+ shippingCost: price.shippingCost,
+ convertedShippingCost: price.convertedShippingCost,
+ leadTime: price.leadTime
+ })) ?? null,
customerDetails: customerDetails.data,
quotePayment: quotePayment.data,
quoteShipment: quoteShipment.data,
@@ -228,7 +256,11 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
shippingMethod: shippingMethods.data?.find(
(method) => method.id === quoteShipment.data?.shippingMethodId
)?.name,
- salesOrderLines: salesOrderLines?.data ?? null
+ salesOrderLines:
+ salesOrderLines?.data?.map((line) => ({
+ id: line.id,
+ saleQuantity: line.saleQuantity
+ })) ?? null
}
};
}
@@ -358,24 +390,27 @@ const LineItems = ({
});
const pricingByLine = useMemo(
() =>
- quoteLines?.reduce<Record<string, QuotationPrice[]>>((acc, line) => {
- if (!line.id) {
+ quoteLines?.reduce<Record<string, QuoteLinePriceOption[]>>(
+ (acc, line) => {
+ if (!line.id) {
+ return acc;
+ }
+ // Scope to the breaks the line actually offers. A removed break can
+ // leave its price row behind, and an orphan here becomes a selectable
+ // option the customer was never meant to see.
+ acc[line.id!] =
+ quoteLinePrices
+ ?.filter(
+ (p) =>
+ p.quoteLineId === line.id &&
+ Array.isArray(line.quantity) &&
+ line.quantity.includes(p.quantity)
+ )
+ .sort((a, b) => a.quantity - b.quantity) ?? [];
return acc;
- }
- // Scope to the breaks the line actually offers. A removed break can
- // leave its price row behind, and an orphan here becomes a selectable
- // option the customer was never meant to see.
- acc[line.id!] =
- quoteLinePrices
- ?.filter(
- (p) =>
- p.quoteLineId === line.id &&
- Array.isArray(line.quantity) &&
- line.quantity.includes(p.quantity)
- )
- .sort((a, b) => a.quantity - b.quantity) ?? [];
- return acc;
- }, {}) ?? {},
+ },
+ {}
+ ) ?? {},
[quoteLines, quoteLinePrices]
);
@@ -508,8 +543,8 @@ const LineItems = ({
};
type LinePricingOptionsProps = {
- line: Omit<QuotationLine, "internalNotes">;
- options: QuotationPrice[];
+ line: QuoteData["quoteLines"][number];
+ options: QuoteLinePriceOption[];
quoteCurrency: string;
shouldConvertCurrency: boolean;
quoteExchangeRate: number;
@@ -1595,6 +1630,7 @@ export const ErrorMessage = ({
};
type QuoteData = NonNullable<Awaited<ReturnType<typeof loader>>["data"]>;
+type QuoteLinePriceOption = NonNullable<QuoteData["quoteLinePrices"]>[number];
export default function ExternalQuote() {
const { state, data } = useLoaderData<typeof loader>();
diff --git a/apps/erp/app/routes/share+/scar.$id.tsx b/apps/erp/app/routes/share+/scar.$id.tsx
index a226fda9b1..fd7cb8b06b 100644
--- a/apps/erp/app/routes/share+/scar.$id.tsx
+++ b/apps/erp/app/routes/share+/scar.$id.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import {
Button,
@@ -53,6 +54,13 @@ export const meta = () => {
return [{ title: "SCAR Report" }];
};
+const logger = getLogger("erp", "share", "scar");
+
+// The link is the only credential on this unauthenticated page: it must be a
+// SCAR link, and the issue it names must belong to the link's company.
+const isScarLink = (link: { documentType: string } | null) =>
+ link?.documentType === "Non-Conformance Supplier";
+
enum IssueState {
Valid,
NotFound
@@ -69,7 +77,11 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
const serviceRole = getCarbonServiceRole();
const externalLink = await getExternalLink(serviceRole, id);
- if (!externalLink.data || !externalLink.data?.documentId) {
+ if (
+ !externalLink.data ||
+ !externalLink.data?.documentId ||
+ !isScarLink(externalLink.data)
+ ) {
return {
state: IssueState.NotFound,
data: null
@@ -80,7 +92,13 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
serviceRole,
externalLink.data.documentId
);
- if (!issue.data) {
+ if (!issue.data || issue.data.companyId !== externalLink.data.companyId) {
+ if (issue.data) {
+ logger.error("SCAR link names an issue of another company", {
+ companyId: externalLink.data.companyId,
+ externalLinkId: id
+ });
+ }
return {
state: IssueState.NotFound,
data: null
@@ -139,7 +157,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!id) throw new Error("Could not find id");
const externalLink = await getExternalLink(serviceRole, id);
- if (!externalLink.data || !externalLink.data?.documentId) {
+ if (
+ !externalLink.data ||
+ !externalLink.data?.documentId ||
+ !isScarLink(externalLink.data)
+ ) {
+ logger.error("SCAR link not found", { externalLinkId: id });
throw new Error("Could not find id");
}
@@ -147,7 +170,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
serviceRole,
externalLink.data.documentId
);
- if (!issue.data) {
+ if (!issue.data || issue.data.companyId !== externalLink.data.companyId) {
+ logger.error("SCAR issue not found for link", {
+ companyId: externalLink.data.companyId,
+ externalLinkId: id,
+ error: issue.error
+ });
throw new Error("Could not find the issue");
}
diff --git a/apps/erp/app/routes/share+/supplier-quote.$id.tsx b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
index f4608ca5f6..0487c86232 100644
--- a/apps/erp/app/routes/share+/supplier-quote.$id.tsx
+++ b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
@@ -62,7 +62,7 @@ import type {
SupplierQuoteLinePrice
} from "~/modules/purchasing/types";
import type { Company } from "~/modules/settings";
-import { getCompany, getCompanySettings } from "~/modules/settings";
+import { getCompany } from "~/modules/settings";
import { getBase64ImageFromSupabase } from "~/modules/shared";
import type { action } from "~/routes/api+/purchasing.digital-quote.$id";
import { path } from "~/utils/path";
@@ -127,13 +127,14 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
};
}
- const [company, companySettings, quoteLines, quoteLinePrices] =
- await Promise.all([
- getCompany(serviceRole, quote.data.companyId),
- getCompanySettings(serviceRole, quote.data.companyId),
- getSupplierQuoteLines(serviceRole, quote.data.id),
- getSupplierQuoteLinePricesByQuoteId(serviceRole, quote.data.id)
- ]);
+ // No companySettings here: the page never reads it, and the row carries
+ // internal config (markups, notification groups, printing) that must not
+ // reach an unauthenticated supplier.
+ const [company, quoteLines, quoteLinePrices] = await Promise.all([
+ getCompany(serviceRole, quote.data.companyId),
+ getSupplierQuoteLines(serviceRole, quote.data.id),
+ getSupplierQuoteLinePricesByQuoteId(serviceRole, quote.data.id)
+ ]);
const thumbnailPaths = quoteLines.data?.reduce<Record<string, string | null>>(
(acc, line) => {
@@ -173,7 +174,6 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
data: {
quote: quote.data,
company: company.data,
- companySettings: companySettings.data,
quoteLines:
quoteLines.data?.map(({ internalNotes, ...line }) => ({
...line
diff --git a/apps/erp/app/routes/share+/training.$id.tsx b/apps/erp/app/routes/share+/training.$id.tsx
index 2e0b9913c8..1158830fa1 100644
--- a/apps/erp/app/routes/share+/training.$id.tsx
+++ b/apps/erp/app/routes/share+/training.$id.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import {
Alert,
@@ -55,6 +56,8 @@ import {
} from "~/modules/resources";
import type { TrainingQuestion } from "~/modules/resources/types";
+const logger = getLogger("erp", "share", "training");
+
const PASSING_THRESHOLD = 0.8;
interface ActionData {
@@ -164,14 +167,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const answersJson = formData.get("answers") as string;
- const questionsJson = formData.get("questions") as string;
- if (!answersJson || !questionsJson) {
+ if (!answersJson) {
return data({ error: "Missing answers or questions" }, { status: 400 });
}
const userAnswers = JSON.parse(answersJson) as Record<string, UserAnswer>;
- const questions = JSON.parse(questionsJson) as TrainingQuestion[];
+
+ // Grade against the training's stored questions, never the posted
+ // `questions` field — that carries its own answer key, so trusting it let
+ // anyone pass (and be granted the training's ability) with any answers.
+ const serviceRole = getCarbonServiceRole();
+ const assignment = await getAuthorizedAssignment(serviceRole, id, userId);
+
+ const training = assignment.training;
+ if (!training || Array.isArray(training)) {
+ logger.error("Training not found for assignment", {
+ companyId: assignment.companyId,
+ trainingAssignmentId: id
+ });
+ return data({ error: "Training not found" }, { status: 404 });
+ }
+
+ const questions = (training.trainingQuestion ?? []) as TrainingQuestion[];
let correctAnswers = 0;
const totalQuestions = questions.length;
@@ -247,14 +265,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
const passed = score >= PASSING_THRESHOLD;
if (passed) {
- const serviceRole = getCarbonServiceRole();
- const assignment = await getAuthorizedAssignment(serviceRole, id, userId);
-
- const training = assignment.training;
- if (!training || Array.isArray(training)) {
- return data({ error: "Training not found" }, { status: 404 });
- }
-
const { data: period } = await serviceRole.rpc(
"get_current_training_period",
{
diff --git a/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx
index 76232f6ec1..250870dc8c 100644
--- a/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx
+++ b/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx
@@ -1,6 +1,7 @@
import { error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import {
@@ -11,6 +12,8 @@ import {
import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "accounting-charts-ledger");
+
const LEDGER_PAGE_SIZE = 50;
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -31,8 +34,25 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const endDate = searchParams.get("endDate") || null;
const offset = Math.max(0, Number(searchParams.get("offset")) || 0);
- const [account, ledger, summary] = await Promise.all([
- getAccount(client, accountId),
+ // bypassRls makes `client` the service role and the ledger read below is
+ // unscoped by company, so the account must be proven to be this group's
+ // before any of its lines are read.
+ const account = await getAccount(client, accountId);
+ if (account.error || !account.data) {
+ throw redirect(
+ path.to.chartOfAccounts,
+ await flash(request, error(account.error, "Failed to load account"))
+ );
+ }
+ if (account.data.companyGroupId !== companyGroupId) {
+ logger.error("Account is not in the caller's company group", {
+ companyGroupId,
+ accountId
+ });
+ throw redirect(path.to.chartOfAccounts);
+ }
+
+ const [ledger, summary] = await Promise.all([
getAccountLedger(client, {
accountId,
companyId: null,
@@ -48,13 +68,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})
]);
- if (account.error || !account.data) {
- throw redirect(
- path.to.chartOfAccounts,
- await flash(request, error(account.error, "Failed to load account"))
- );
- }
-
return {
account: account.data,
lines: ledger.data ?? [],
diff --git a/apps/erp/app/routes/x+/acknowledge.tsx b/apps/erp/app/routes/x+/acknowledge.tsx
index caf9e3c997..a4d7c85a75 100644
--- a/apps/erp/app/routes/x+/acknowledge.tsx
+++ b/apps/erp/app/routes/x+/acknowledge.tsx
@@ -1,4 +1,8 @@
-import { ITAR_RIDER_SHA256, ITAR_RIDER_VERSION } from "@carbon/auth";
+import {
+ ITAR_RIDER_SHA256,
+ ITAR_RIDER_VERSION,
+ safeRedirect
+} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { insertAuditLogEntries } from "@carbon/ee/audit.server";
@@ -248,7 +252,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (redirectTo) {
- throw redirect(redirectTo);
+ throw redirect(safeRedirect(redirectTo));
}
return { success: true, message: "Flag updated" };
diff --git a/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx
index 89c8537038..5cce813c12 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx
@@ -4,35 +4,31 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateAssemblyInstructionStepMaterialOrder } from "~/modules/production";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "production"
});
if (!params.id) throw new Error("Could not find id");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
await updateAssemblyInstructionStepMaterialOrder(
getDatabaseClient(),
+ companyId,
+ userId,
+ params.id,
updates
);
} catch (err) {
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx
index 6e833642f8..e565862583 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateAssemblyInstructionStepOrder } from "~/modules/production";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "production"
});
if (!params.id) throw new Error("Could not find id");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateAssemblyInstructionStepOrder(getDatabaseClient(), updates);
+ await updateAssemblyInstructionStepOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.id,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx b/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx
index 135c8e1ab2..923546f6f4 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.sync-bop.tsx
@@ -36,6 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("jobOperation")
.select("id, job(status)")
.eq("id", operationId)
+ .eq("companyId", companyId)
.single();
if (operation.error) {
return data(
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
index 41da5f5c33..d42a189e34 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx
@@ -188,7 +188,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -220,6 +220,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
defaultStorageUnitId: pickMethodFields.defaultStorageUnitId,
sortMethod: pickMethodFields.sortMethod,
customFields: setCustomFields(formData),
+ companyId,
userId,
shelfLife: {
mode: shelfLifeMode,
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
index 07ab4d0011..e303c37e92 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
@@ -101,6 +101,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trx
.deleteFrom("supplierPartPrice")
.where("supplierPartId", "=", supplierPartId)
+ .where("companyId", "=", companyId)
.execute();
if (priceBreaks.length > 0) {
await trx
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx
index e81628369f..d08694827d 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx
@@ -13,6 +13,7 @@ import {
insertCustomerContact
} from "~/modules/sales";
import { CustomerContactForm } from "~/modules/sales/ui/Customer";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
import { customerContactsQuery } from "~/utils/react-query";
@@ -43,6 +44,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { id, contactId, customerLocationId, ...contact } = validation.data;
+ // The contact is written through the service role: the customer in the URL
+ // (and the location on the form) must belong to this company.
+ await Promise.all([
+ requireCompanyRecord(client, "customer", companyId, { id: customerId }),
+ customerLocationId
+ ? requireCompanyRecord(client, "customerLocation", companyId, {
+ id: customerLocationId,
+ customerId
+ })
+ : null
+ ]);
+
const createCustomerContact = await insertCustomerContact(client, {
customerId,
companyId,
diff --git a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx
index 9887682ada..a0ceac438c 100644
--- a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx
+++ b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx
@@ -77,6 +77,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("fixedAsset")
.select("*, fixedAssetClass:fixedAssetClassId(*)")
.eq("id", fixedAssetId)
+ .eq("companyId", companyId)
.single(),
client
.from("dimension")
diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
index 1c7423a48e..f32c38a710 100644
--- a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
+++ b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
@@ -13,7 +13,7 @@ import {
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory",
role: "employee"
});
@@ -21,7 +21,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw notFound("id not found");
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
return {
kanban: kanban?.data ?? null
diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx
index f524765915..cac1dd943e 100644
--- a/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/inventory+/kanbans.delete.$id.tsx
@@ -9,13 +9,13 @@ import { deleteKanban, getKanban } from "~/modules/inventory";
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory"
});
const { id } = params;
if (!id) throw notFound("id not found");
- const kanban = await getKanban(client, id);
+ const kanban = await getKanban(client, id, companyId);
if (kanban.error) {
throw redirect(
path.to.kanbans,
diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsx
index 6c6f9b0941..80a6166ec9 100644
--- a/apps/erp/app/routes/x+/issue+/$id.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.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 { getLogger } from "@carbon/logger";
import { VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
@@ -36,6 +37,8 @@ import { getTagsList } from "~/modules/shared";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "issue-detail");
+
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
{ breadcrumb: msg`Issues`, to: path.to.issues },
@@ -77,6 +80,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven to
+ // exist — not to be this company's.
+ if (nonConformance.data.companyId !== companyId) {
+ logger.error("Issue is not in the caller's company", {
+ companyId,
+ issueId: id
+ });
+ throw redirect(path.to.issues);
+ }
+
return {
associations: getIssueAssociations(client, id, companyId),
files: getItemFiles(client, id, companyId),
diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsx
index 758c31d745..add1dec73b 100644
--- a/apps/erp/app/routes/x+/issue+/new.tsx
+++ b/apps/erp/app/routes/x+/issue+/new.tsx
@@ -70,6 +70,49 @@ export async function action({ request }: ActionFunctionArgs) {
const d = validation.data;
+ // insertIssue writes through the service role, and every id below comes
+ // from the form or the query string — each lands in this company's issue as
+ // a reference whose single-column FK accepts another company's row. One
+ // scoped read per table; a miss refuses the whole create.
+ const url = new URL(request.url);
+ const trackedEntityIdsParam = url.searchParams.get("trackedEntityIds");
+ const trackedEntityIds = trackedEntityIdsParam
+ ? [...new Set(trackedEntityIdsParam.split(",").filter(Boolean))]
+ : [];
+ const refs: [string, string[]][] = [
+ ["location", [d.locationId]],
+ ["nonConformanceType", [d.nonConformanceTypeId]],
+ [
+ "nonConformanceWorkflow",
+ d.nonConformanceWorkflowId ? [d.nonConformanceWorkflowId] : []
+ ],
+ ["nonConformanceRequiredAction", [...new Set(d.requiredActionIds ?? [])]],
+ ["item", [...new Set(d.items ?? [])]],
+ ["customer", d.customerId ? [d.customerId] : []],
+ ["trackedEntity", trackedEntityIds]
+ ];
+ const owned = await Promise.all(
+ refs.map(async ([table, ids]) => {
+ if (ids.length === 0) return true;
+ const rows = await serviceRole
+ .from(table as "location")
+ .select("id")
+ .in("id", ids)
+ .eq("companyId", companyId);
+ return !rows.error && (rows.data ?? []).length === ids.length;
+ })
+ );
+ if (owned.some((ok) => !ok)) {
+ logger.error("Issue references records outside the company", {
+ companyId,
+ refs: refs.filter((_, index) => !owned[index])
+ });
+ throw redirect(
+ path.to.issues,
+ await flash(request, error(null, "Failed to insert issue"))
+ );
+ }
+
const createResult = await insertIssue(serviceRole, {
nonConformanceId: d.nonConformanceId || undefined,
name: d.name,
@@ -106,11 +149,6 @@ export async function action({ request }: ActionFunctionArgs) {
// Pre-associate tracked entities passed via query string (used by the
// "Create Issue from Inspection" button on inbound inspection lots).
- const url = new URL(request.url);
- const trackedEntityIdsParam = url.searchParams.get("trackedEntityIds");
- const trackedEntityIds = trackedEntityIdsParam
- ? trackedEntityIdsParam.split(",").filter(Boolean)
- : [];
if (trackedEntityIds.length > 0) {
await serviceRole.from("nonConformanceTrackedEntity").insert(
trackedEntityIds.map((trackedEntityId) => ({
@@ -269,10 +307,12 @@ async function autoLinkJobOperationDisposition(
) {
const { nonConformanceId, companyId, userId, jobOperationId } = args;
+ // Service role and a form id: scope both reads to the company.
const operation = await client
.from("jobOperation")
.select("jobMakeMethodId")
.eq("id", jobOperationId)
+ .eq("companyId", companyId)
.single();
const jobMakeMethodId = operation.data?.jobMakeMethodId ?? null;
if (!jobMakeMethodId) return;
@@ -281,6 +321,7 @@ async function autoLinkJobOperationDisposition(
.from("jobMakeMethod")
.select("itemId")
.eq("id", jobMakeMethodId)
+ .eq("companyId", companyId)
.single();
const itemId = makeMethod.data?.itemId ?? null;
if (!itemId) return;
diff --git a/apps/erp/app/routes/x+/issue+/update.tsx b/apps/erp/app/routes/x+/issue+/update.tsx
index 7a02e6fde2..ced49cb552 100644
--- a/apps/erp/app/routes/x+/issue+/update.tsx
+++ b/apps/erp/app/routes/x+/issue+/update.tsx
@@ -28,7 +28,8 @@ export async function action({ request }: ActionFunctionArgs) {
const issues = await client
.from("nonConformance")
.select("id, status")
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
const lockedError = requireUnlockedBulk({
statuses: (issues.data ?? []).map((i) => i.status),
@@ -48,7 +49,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
if (update.error) {
logger.error(update.error);
@@ -60,8 +62,9 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
// A silent reconcile failure leaves the column and the task list disagreeing.
+ // Only the issues the scoped read above found are this company's.
const reconciled = await Promise.all(
- ids.map((id) =>
+ (issues.data ?? []).map(({ id }) =>
serviceRole.functions.invoke("create", {
body: {
type: "nonConformanceTasks",
@@ -102,7 +105,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
default:
return {
error: { message: `Invalid field: ${field}` },
diff --git a/apps/erp/app/routes/x+/issue-workflow+/$id.tsx b/apps/erp/app/routes/x+/issue-workflow+/$id.tsx
index 1868eb2664..a1abbc3eee 100644
--- a/apps/erp/app/routes/x+/issue-workflow+/$id.tsx
+++ b/apps/erp/app/routes/x+/issue-workflow+/$id.tsx
@@ -58,6 +58,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven to
+ // exist — not to be this company's.
+ if (workflow.data.companyId !== companyId) {
+ logger.error("Issue workflow is not in the caller's company", {
+ companyId,
+ issueWorkflowId: id
+ });
+ throw redirect(path.to.issueWorkflows);
+ }
+
return {
workflow: workflow.data,
requiredActions: requiredActions.data ?? []
diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.action.order.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.action.order.tsx
index ca3c495887..7e98f8abd9 100644
--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.action.order.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.action.order.tsx
@@ -5,6 +5,7 @@ import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateChangeNoticeActionOrder } from "~/modules/items";
import { requireEditableChangeNoticeRoute } from "~/modules/items/items.server";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -24,28 +25,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (locked) return locked;
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(
- JSON.parse(updateMap) as Record<string, number>
- ).map(([id, sortOrder]) => ({
- id,
- sortOrder: Number(sortOrder),
- updatedBy: userId
- }));
-
try {
- await updateChangeNoticeActionOrder(getDatabaseClient(), {
- changeNoticeId,
+ await updateChangeNoticeActionOrder(
+ getDatabaseClient(),
companyId,
+ userId,
+ changeNoticeId,
updates
- });
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/items+/revisions.new.tsx b/apps/erp/app/routes/x+/items+/revisions.new.tsx
index 0531727e5b..ec072c3ea0 100644
--- a/apps/erp/app/routes/x+/items+/revisions.new.tsx
+++ b/apps/erp/app/routes/x+/items+/revisions.new.tsx
@@ -2,12 +2,15 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { revisionValidator } from "~/modules/items/items.models";
import { requireItemChangeNoticeUnlocked } from "~/modules/items/items.server";
import { createRevision, getItem } from "~/modules/items/items.service";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "items-revisions-new");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
@@ -43,6 +46,16 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: false, error: "Failed to get current item" };
}
+ // createRevision writes through the service role with the SOURCE item's
+ // companyId, and the RLS read above admits any company the user belongs to.
+ if (currentItem.data.companyId !== companyId) {
+ logger.error("Revision source item is not in the caller's company", {
+ companyId,
+ itemId: validation.data.copyFromId
+ });
+ return { success: false, error: "Failed to get current item" };
+ }
+
const result = await createRevision(getCarbonServiceRole(), {
item: currentItem.data,
revision: validation.data.revision,
diff --git a/apps/erp/app/routes/x+/job+/$jobId.batch.tsx b/apps/erp/app/routes/x+/job+/$jobId.batch.tsx
index 5a3cef4105..877b9fd9af 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.batch.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.batch.tsx
@@ -7,7 +7,7 @@ import { updateJobBatchNumber } from "~/modules/production/production.service";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "production",
bypassRls: true
});
@@ -19,8 +19,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const rawValue = formData.get("value");
const value = rawValue == null ? "" : String(rawValue).trim();
+ // `client` is the service role (bypassRls) and the tracked entity id comes
+ // from the form: scope the write to this company.
const update = await updateJobBatchNumber(
client,
+ companyId,
trackedEntityId,
value === "" ? null : value
);
diff --git a/apps/erp/app/routes/x+/job+/$jobId.details.tsx b/apps/erp/app/routes/x+/job+/$jobId.details.tsx
index 6904d1e26c..b558d41cf7 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.details.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.details.tsx
@@ -54,6 +54,7 @@ import {
import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
import PurchasingStatus from "~/modules/purchasing/ui/PurchaseOrder/PurchasingStatus";
import { getTagsList } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { useItems } from "~/stores";
import type { StorageItem } from "~/types";
import { setCustomFields } from "~/utils/form";
@@ -69,6 +70,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { jobId } = params;
if (!jobId) throw new Error("Could not find jobId");
+ // `client` is the service role (bypassRls) and every read keys on the URL id.
+ await requireCompanyRecord(client, "job", companyId, { id: jobId });
+
const job = await getJob(client, jobId);
if (job.error) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
index 0a1cf492e1..b62bc8fa05 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
@@ -26,6 +26,7 @@ import {
} from "~/modules/production/ui/Jobs";
import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
import { getModelByItemId, getTagsList } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -38,6 +39,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!jobId) throw new Error("Could not find jobId");
if (!methodId) throw new Error("Could not find methodId");
+ // `client` is the service role (bypassRls) and every read keys on the URL
+ // ids: the make method must belong to this job and company.
+ await requireCompanyRecord(client, "jobMakeMethod", companyId, {
+ id: methodId,
+ jobId
+ });
+
const [job, makeMethod, materials, operations, tags] = await Promise.all([
getJob(client, jobId),
getJobMakeMethodById(client, methodId, companyId),
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index 82c6aa8024..ffba3928f5 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -36,6 +36,9 @@ vi.mock("~/utils/path", () => ({
},
requestReferrer: () => null
}));
+vi.mock("~/modules/shared/shared.server", () => ({
+ requireCompanyRecord: vi.fn(async () => undefined)
+}));
vi.mock("~/modules/inventory", () => ({
cancelOpenPickingListsForJob: vi.fn()
}));
@@ -81,6 +84,7 @@ import {
returnPickedRemaindersForJob,
updateJobStatus
} from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { action } from "./$jobId.status";
type QueryResult = { data: unknown; error: unknown };
@@ -252,6 +256,30 @@ describe("Job release status action", () => {
});
});
+describe("Job status tenancy", () => {
+ it("refuses a job outside the caller's company before any side effect", async () => {
+ // The action runs MRP, scheduling and picking sweeps with the service role
+ // keyed on the URL id — a foreign job must stop at the ownership check.
+ vi.mocked(requireCompanyRecord).mockRejectedValueOnce(
+ new Response("Not found", { status: 404 })
+ );
+
+ const thrown = await runRelease().catch((e) => e);
+
+ expect(thrown).toBeInstanceOf(Response);
+ expect((thrown as Response).status).toBe(404);
+ expect(requireCompanyRecord).toHaveBeenCalledWith(
+ expect.anything(),
+ "job",
+ "company-1",
+ { id: "job-1" }
+ );
+ expect(updateJobStatus).not.toHaveBeenCalled();
+ expect(runLocationSchedule).not.toHaveBeenCalled();
+ expect(events).toEqual([]);
+ });
+});
+
describe("Job cancel status action", () => {
it("returns staged material, then cancels the job's open picking lists", async () => {
await expect(
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index 51375a6ce5..fe64014d00 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -16,6 +16,7 @@ import {
updateJobStatus
} from "~/modules/production";
import { releaseJobs } from "~/modules/production/production.server";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
@@ -30,6 +31,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { jobId: id } = params;
if (!id) throw new Error("Could not find id");
+ // Much of what follows (MRP, scheduling, picking sweeps, PO creation) runs
+ // with the service role or Kysely and keys on the URL job id.
+ await requireCompanyRecord(getCarbonServiceRole(), "job", companyId, { id });
+
const url = new URL(request.url);
const shouldSchedule = url.searchParams.get("schedule") === "1";
@@ -274,6 +279,7 @@ async function scheduleJobLocation({
.from("job")
.select("locationId")
.eq("id", id)
+ .eq("companyId", companyId)
.single();
if (!jobLocation?.locationId) {
throw new Error("Job has no location to schedule");
diff --git a/apps/erp/app/routes/x+/job+/bulk.new.tsx b/apps/erp/app/routes/x+/job+/bulk.new.tsx
index 4c29f53f37..67166fb718 100644
--- a/apps/erp/app/routes/x+/job+/bulk.new.tsx
+++ b/apps/erp/app/routes/x+/job+/bulk.new.tsx
@@ -9,6 +9,7 @@ import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { getDefaultStorageUnitForJob } from "~/modules/inventory";
import { bulkJobValidator, insertJob } from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -86,6 +87,27 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // insertJob runs with the service role, so every foreign-key id in the form
+ // is proven to belong to this company before any job is written.
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "item", companyId, {
+ id: jobData.itemId
+ }),
+ requireCompanyRecord(serviceRole, "location", companyId, {
+ id: jobData.locationId
+ }),
+ jobData.customerId
+ ? requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: jobData.customerId
+ })
+ : null,
+ jobData.modelUploadId
+ ? requireCompanyRecord(serviceRole, "modelUpload", companyId, {
+ id: jobData.modelUploadId
+ })
+ : null
+ ]);
+
const storageUnitId = await getDefaultStorageUnitForJob(
serviceRole,
jobData.itemId,
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 984d471060..a71f3b8b25 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -11,6 +11,7 @@ import {
recalculateJobOperationDependencies,
upsertJobMaterial
} from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
@@ -37,6 +38,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // `client` is the service role (bypassRls): the material must belong to this
+ // job and company, and so must the make method recalculated below and the
+ // operation it is assigned to.
+ await Promise.all([
+ requireCompanyRecord(client, "jobMaterial", companyId, {
+ id,
+ jobId,
+ jobMakeMethodId: validation.data.jobMakeMethodId
+ }),
+ validation.data.jobOperationId
+ ? requireCompanyRecord(client, "jobOperation", companyId, {
+ id: validation.data.jobOperationId,
+ jobId
+ })
+ : undefined
+ ]);
+
// Capture the previous methodType so we only pull the subassembly's method on
// the transition INTO "Make to Order" (not on every save of a material that is
// already Make to Order — that would re-pull and wipe existing edits).
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index ce7a9d5bac..db804c9efe 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -12,6 +12,7 @@ import {
recalculateJobOperationDependencies,
upsertJobMaterial
} from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
@@ -33,7 +34,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // The writes below use the service role, which bypasses RLS: the job and
+ // every parent id in the form must belong to this company.
const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "job", companyId, { id: jobId }),
+ requireCompanyRecord(serviceRole, "jobMakeMethod", companyId, {
+ id: validation.data.jobMakeMethodId,
+ jobId
+ }),
+ validation.data.jobOperationId
+ ? requireCompanyRecord(serviceRole, "jobOperation", companyId, {
+ id: validation.data.jobOperationId,
+ jobId
+ })
+ : undefined
+ ]);
+
const insertJobMaterial = await upsertJobMaterial(serviceRole, {
...validation.data,
jobId,
@@ -74,6 +91,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("job")
.select("status")
.eq("id", jobId)
+ .eq("companyId", companyId)
.single();
const isReleased = !["Draft", "Planned"].includes(job.data?.status ?? "");
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
index 37ebab6fb2..5dbc0e5bcf 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -11,6 +11,7 @@ import {
recalculateJobOperationDependencies,
upsertJobOperation
} from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
@@ -35,6 +36,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
const operationData = validation.data;
+ // The insert uses the service role, which bypasses RLS: the job and its make
+ // method must belong to this company.
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "job", companyId, { id: jobId }),
+ requireCompanyRecord(serviceRole, "jobMakeMethod", companyId, {
+ id: validation.data.jobMakeMethodId,
+ jobId
+ })
+ ]);
+
const insertJobOperation = await upsertJobOperation(serviceRole, {
...operationData,
jobId,
diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsx
index eb4d259307..b71f346721 100644
--- a/apps/erp/app/routes/x+/job+/new.tsx
+++ b/apps/erp/app/routes/x+/job+/new.tsx
@@ -11,6 +11,7 @@ import { getUnreleasedChangeOrderIssue } from "~/modules/items/items.server";
import { insertJob, jobValidator } from "~/modules/production";
import { JobForm } from "~/modules/production/ui/Jobs";
import type { MethodItemType } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -46,15 +47,35 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // insertJob runs with the service role, so every foreign-key id in the form
+ // is proven to belong to this company before it is written.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "item", companyId, { id: data.itemId }),
+ requireCompanyRecord(serviceRole, "location", companyId, {
+ id: data.locationId
+ }),
+ data.customerId
+ ? requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: data.customerId
+ })
+ : null,
+ data.modelUploadId
+ ? requireCompanyRecord(serviceRole, "modelUpload", companyId, {
+ id: data.modelUploadId
+ })
+ : null
+ ]);
+
// A job pulls the item's active make method, and for an item a change notice
// still holds that is the notice's un-approved draft BOM. Refuse the job until
// the notice releases. Checked here rather than only in the picker because this
// action is also reached by the API and the MCP tools.
if (data.itemId) {
- const unreleasedIssue = await getUnreleasedChangeOrderIssue(
- getCarbonServiceRole(),
- { itemId: data.itemId, companyId }
- );
+ const unreleasedIssue = await getUnreleasedChangeOrderIssue(serviceRole, {
+ itemId: data.itemId,
+ companyId
+ });
if (unreleasedIssue) {
return validationError({
fieldErrors: {
@@ -65,7 +86,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
const result = await insertJob(
- getCarbonServiceRole(),
+ serviceRole,
{
...data,
jobId: data.jobId || undefined,
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
index fc1c96fd35..fc2b9f0be5 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
@@ -32,7 +32,11 @@ const logger = getLogger("erp", "maintenance", "dispatch");
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId, companyId } = await requirePermissions(request, {});
+ // Issuing parts to a dispatch is an edit of the dispatch, like every other
+ // write under $dispatchId (the Add Part button is gated the same way).
+ const { userId, companyId } = await requirePermissions(request, {
+ update: "resources"
+ });
const { dispatchId } = params;
if (!dispatchId) {
@@ -46,6 +50,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
view: "resources"
});
const dispatch = await getMaintenanceDispatch(viewClient, dispatchId);
+ if (
+ dispatch.error ||
+ !dispatch.data ||
+ dispatch.data.companyId !== companyId
+ ) {
+ logger.error("Maintenance dispatch not found for add-and-issue", {
+ companyId,
+ dispatchId,
+ error: dispatch.error
+ });
+ return data(
+ { success: false, message: "Dispatch not found" },
+ { status: 404 }
+ );
+ }
await requireUnlocked({
request,
isLocked: isMaintenanceDispatchLocked(dispatch.data?.status),
diff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
index 275199bc6a..3faa0a63ca 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx
@@ -185,7 +185,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -217,6 +217,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
defaultStorageUnitId: pickMethodFields.defaultStorageUnitId,
sortMethod: pickMethodFields.sortMethod,
customFields: setCustomFields(formData),
+ companyId,
userId,
shelfLife: {
mode: shelfLifeMode,
diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
index fb41c96ece..16afa213d9 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
@@ -101,6 +101,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trx
.deleteFrom("supplierPartPrice")
.where("supplierPartId", "=", supplierPartId)
+ .where("companyId", "=", companyId)
.execute();
if (priceBreaks.length > 0) {
await trx
diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
index 1f4d4a4099..86fcab8bb7 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx
@@ -170,7 +170,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -202,6 +202,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
defaultStorageUnitId: pickMethodFields.defaultStorageUnitId,
sortMethod: pickMethodFields.sortMethod,
customFields: setCustomFields(formData),
+ companyId,
userId,
shelfLife: {
mode: shelfLifeMode,
diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
index b1e475da05..c6cb835a90 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
@@ -100,6 +100,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trx
.deleteFrom("supplierPartPrice")
.where("supplierPartId", "=", supplierPartId)
+ .where("companyId", "=", companyId)
.execute();
if (priceBreaks.length > 0) {
await trx
diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.line.quantity.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.line.quantity.tsx
index 244313d54f..b1702cc5c5 100644
--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.line.quantity.tsx
+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.line.quantity.tsx
@@ -3,12 +3,17 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { ActionFunctionArgs } from "react-router";
import { pickPickingListLine } from "~/modules/inventory";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
-export async function action({ request }: ActionFunctionArgs) {
+export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "inventory"
});
+ const { pickingListId } = params;
+ if (!pickingListId) {
+ return { success: false, message: "Missing pickingListId" };
+ }
const serviceRole = getCarbonServiceRole();
const formData = await request.formData();
@@ -20,11 +25,19 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: false, message: "Missing pickingListLineId" };
}
+ // The pick runs through the service role: the line must belong to this
+ // company and to the picking list in the URL.
+ await requireCompanyRecord(serviceRole, "pickingListLine", companyId, {
+ id: pickingListLineId,
+ pickingListId
+ });
+
const result = await pickPickingListLine(serviceRole, {
pickingListLineId,
quantity,
markShort,
- userId
+ userId,
+ companyId
});
if (result.error) {
diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tracked.$lineId.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tracked.$lineId.tsx
index 0728dfd32e..6dffb25fb2 100644
--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tracked.$lineId.tsx
+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tracked.$lineId.tsx
@@ -8,6 +8,7 @@ import {
setPickingListLineTrackedEntity
} from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
/**
* GET: available tracked lots for a picking line (non-lineside, deduped),
@@ -77,11 +78,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, { update: "inventory" });
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "inventory"
+ });
const serviceRole = getCarbonServiceRole();
- const { lineId } = params;
- if (!lineId) return { success: false, message: "Missing line" };
+ const { pickingListId, lineId } = params;
+ if (!pickingListId || !lineId) {
+ return { success: false, message: "Missing line" };
+ }
+
+ // The pick runs through the service role: the line must belong to this
+ // company and to the picking list in the URL.
+ await requireCompanyRecord(serviceRole, "pickingListLine", companyId, {
+ id: lineId,
+ pickingListId
+ });
const formData = await request.formData();
const trackedEntityId = formData.get("trackedEntityId") as string;
@@ -100,7 +112,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
fromStorageUnitId,
quantity,
unpick,
- userId
+ userId,
+ companyId
});
if (result.error) {
diff --git a/apps/erp/app/routes/x+/priority+/people.update.tsx b/apps/erp/app/routes/x+/priority+/people.update.tsx
index 750d2bd383..ab65c8f800 100644
--- a/apps/erp/app/routes/x+/priority+/people.update.tsx
+++ b/apps/erp/app/routes/x+/priority+/people.update.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
@@ -37,6 +38,66 @@ import {
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getDatabaseClient } from "~/services/database.server";
+const logger = getLogger("erp", "priority-people-update");
+
+type BoardReferenceTable =
+ | "department"
+ | "employee"
+ | "location"
+ | "shift"
+ | "workCenter";
+
+/**
+ * Every board mutation writes these ids into this company's rows through
+ * Kysely (no RLS), and their single-column FKs accept another company's row.
+ * One query per table; empty values are ignored so optional fields stay
+ * optional.
+ */
+async function referencesBelongToCompany(
+ companyId: string,
+ refs: Record<BoardReferenceTable, unknown[]>
+): Promise<boolean> {
+ const db = getDatabaseClient();
+ const results = await Promise.all(
+ (Object.entries(refs) as [BoardReferenceTable, unknown[]][]).map(
+ async ([table, values]) => {
+ const ids = [
+ ...new Set(
+ values.filter(
+ (value): value is string =>
+ typeof value === "string" && value.length > 0
+ )
+ )
+ ];
+ if (ids.length === 0) return true;
+ // Every table in the union has `id` + `companyId`; the cast only
+ // narrows the union so Kysely can type the builder.
+ const rows = await db
+ .selectFrom(table as "location")
+ .select("id")
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .execute();
+ return rows.length === ids.length;
+ }
+ )
+ );
+ return results.every(Boolean);
+}
+
+function dayRowWorkCenterIds(raw: FormDataEntryValue | null): unknown[] {
+ if (typeof raw !== "string" || !raw) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed)
+ ? parsed.map((row) => (row as { workCenterId?: unknown })?.workCenterId)
+ : [];
+ } catch {
+ // The intent's own validator reports the malformed field.
+ return [];
+ }
+}
+
/**
* Notify the replan pipeline once per station the person is assigned at on the
* date; when they're assigned nowhere, fall back to the unscoped people kind
@@ -81,6 +142,29 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const intent = formData.get("intent");
+ const refs = {
+ department: [formData.get("departmentId")],
+ employee: [formData.get("employeeId")],
+ location: [formData.get("locationId")],
+ shift: [formData.get("shiftId")],
+ workCenter: [
+ formData.get("workCenterId"),
+ formData.get("fromWorkCenterId"),
+ ...dayRowWorkCenterIds(formData.get("rows"))
+ ]
+ };
+ if (!(await referencesBelongToCompany(companyId, refs))) {
+ logger.error("People board reference is not in the caller's company", {
+ companyId,
+ intent,
+ refs
+ });
+ return data(
+ { success: false },
+ await flash(request, error(null, "Not found"))
+ );
+ }
+
if (intent === "assign") {
const validation = await validator(peopleAssignmentValidator).validate(
formData
@@ -251,7 +335,7 @@ export async function action({ request }: ActionFunctionArgs) {
validation.data;
try {
- await setPeopleDay(getDatabaseClient(), {
+ await setPeopleDay(getDatabaseClient(), userId, {
companyId,
locationId,
employeeId,
@@ -259,8 +343,7 @@ export async function action({ request }: ActionFunctionArgs) {
shiftId: shiftId || null,
note: note || null,
overtimeHours,
- rows,
- createdBy: userId
+ rows
});
await notifyForEmployeeDate(
client,
@@ -388,14 +471,13 @@ export async function action({ request }: ActionFunctionArgs) {
validation.data;
try {
- await assignPeopleWeek(getDatabaseClient(), {
+ await assignPeopleWeek(getDatabaseClient(), userId, {
companyId,
locationId,
employeeId,
workCenterId,
weekStart,
- shiftId: shiftId || null,
- createdBy: userId
+ shiftId: shiftId || null
});
await notifyScheduleInputsChanged(
companyId,
@@ -515,14 +597,13 @@ export async function action({ request }: ActionFunctionArgs) {
const { employeeId, fromDate, toDate, shiftId, note } = validation.data;
try {
- const result = await setPeopleAbsenceRange(getDatabaseClient(), {
+ const result = await setPeopleAbsenceRange(getDatabaseClient(), userId, {
companyId,
employeeId,
fromDate,
toDate,
shiftId: shiftId || null,
- note,
- createdBy: userId
+ note
});
await notifyScheduleInputsChanged(
companyId,
diff --git a/apps/erp/app/routes/x+/procedure+/$id.tsx b/apps/erp/app/routes/x+/procedure+/$id.tsx
index 05f1b1237d..9bd8089bef 100644
--- a/apps/erp/app/routes/x+/procedure+/$id.tsx
+++ b/apps/erp/app/routes/x+/procedure+/$id.tsx
@@ -1,6 +1,7 @@
import { error, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { generateHTML, useDebounce } from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
@@ -28,6 +29,8 @@ import { useDocumentStore } from "~/stores";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "procedure-detail");
+
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
{ breadcrumb: msg`Procedures`, to: path.to.procedures },
@@ -58,6 +61,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven to
+ // exist — not to be this company's.
+ if (procedure.data.companyId !== companyId) {
+ logger.error("Procedure is not in the caller's company", {
+ companyId,
+ procedureId: id
+ });
+ throw redirect(path.to.procedures);
+ }
+
return {
procedure: procedure.data,
tags: tags.data ?? [],
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index d3dd374cf2..b8dc77d396 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -101,6 +101,57 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // `client` is the service role (bypassRls) and every id below comes from
+ // the request body: prove the location, items and existing jobs are this
+ // company's before any job is created or rewritten. One query per type.
+ const itemIds = [...new Set(itemsToOrder.map((item) => item.id))];
+ const existingJobIds = [
+ ...new Set(
+ itemsToOrder.flatMap((item) =>
+ item.orders.flatMap((order) =>
+ order.existingId ? [order.existingId] : []
+ )
+ )
+ )
+ ];
+ const [ownedLocation, ownedItems, ownedJobs] = await Promise.all([
+ client
+ .from("location")
+ .select("id")
+ .eq("id", locationId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("item")
+ .select("id")
+ .in("id", itemIds)
+ .eq("companyId", companyId),
+ existingJobIds.length > 0
+ ? client
+ .from("job")
+ .select("id")
+ .in("id", existingJobIds)
+ .eq("companyId", companyId)
+ : Promise.resolve({ data: [] as { id: string }[], error: null })
+ ]);
+ if (
+ ownedLocation.error ||
+ !ownedLocation.data ||
+ ownedItems.error ||
+ (ownedItems.data ?? []).length !== itemIds.length ||
+ ownedJobs.error ||
+ (ownedJobs.data ?? []).length !== existingJobIds.length
+ ) {
+ logger.error("Planning order references records outside the company", {
+ companyId,
+ locationId,
+ itemIds,
+ existingJobIds,
+ error: ownedLocation.error ?? ownedItems.error ?? ownedJobs.error
+ });
+ return data({ success: false, message: "Not found" }, { status: 404 });
+ }
+
try {
const allJobIds: string[] = [];
const createdJobs: { id: string; readableId: string }[] = [];
@@ -139,6 +190,7 @@ export async function action({ request }: ActionFunctionArgs) {
"manufacturingBlocked, scrapPercentage, requiresConfiguration"
)
.eq("itemId", item.id)
+ .eq("companyId", companyId)
.single();
if (manufacturing.error) {
@@ -242,7 +294,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
updatedBy: userId
})
- .eq("id", order.existingId);
+ .eq("id", order.existingId)
+ .eq("companyId", companyId);
if (updateJob.error) {
const errorMsg = `Failed to update job ${order.existingId} for item ${item.id}: ${updateJob.error.message}`;
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx
index f29c3b35e4..11dd227ff6 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updatePurchaseInvoiceLineOrder } from "~/modules/invoicing";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "invoicing"
});
if (!params.invoiceId) throw new Error("Could not find invoiceId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updatePurchaseInvoiceLineOrder(getDatabaseClient(), updates);
+ await updatePurchaseInvoiceLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.invoiceId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
index a117ffa1e6..650d090579 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { Fragment } from "react/jsx-runtime";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -25,6 +26,8 @@ import { getCustomFields, setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "purchase-order-line-details");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "purchasing",
@@ -44,6 +47,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls hands back the service role and lineId comes from the URL: the
+ // line must belong to this company and to the order in the URL.
+ if (
+ line.data.companyId !== companyId ||
+ line.data.purchaseOrderId !== orderId
+ ) {
+ logger.error("Purchase order line not found for company", {
+ companyId,
+ orderId,
+ lineId
+ });
+ throw notFound("Purchase order line not found");
+ }
+
return {
line: line?.data ?? null,
files: getSupplierInteractionLineDocuments(client, companyId, lineId)
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 0be5d0751f..4ecb1d3d22 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
@@ -17,7 +17,7 @@ const logger = getLogger("erp", "orderid-delete");
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "purchasing"
});
@@ -28,6 +28,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Get PO status and check if it's in "Needs Approval"
const purchaseOrder = await getPurchaseOrder(serviceRole, orderId);
+ // The service role bypasses RLS and orderId comes from the URL.
+ if (purchaseOrder.data && purchaseOrder.data.companyId !== companyId) {
+ logger.error("Purchase order not found for company", {
+ companyId,
+ orderId
+ });
+ throw redirect(
+ path.to.purchaseOrders,
+ await flash(request, error(null, "Purchase order not found"))
+ );
+ }
+
if (purchaseOrder.error || !purchaseOrder.data) {
throw redirect(
path.to.purchaseOrders,
@@ -104,6 +116,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("documentType", "purchaseOrder")
.eq("documentId", orderId)
+ .eq("companyId", companyId)
.eq("status", "Pending");
}
}
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 cf26150d8a..1486f694f3 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -317,7 +317,7 @@ export async function action(args: ActionFunctionArgs) {
buyer
] = await Promise.all([
getCompany(serviceRole, companyId),
- getSupplierContact(serviceRole, supplierContact),
+ getSupplierContact(serviceRole, supplierContact, companyId),
getPurchaseOrder(serviceRole, orderId),
getPurchaseOrderLines(serviceRole, orderId),
getPurchaseOrderLocations(serviceRole, orderId),
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
index 7e5acbbe7b..c89dcf2258 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updatePurchaseOrderLineOrder } from "~/modules/purchasing";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "purchasing"
});
if (!params.orderId) throw new Error("Could not find orderId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updatePurchaseOrderLineOrder(getDatabaseClient(), updates);
+ await updatePurchaseOrderLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.orderId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
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 cc8771c052..a77916c93e 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
@@ -14,6 +14,7 @@ import {
reopenPurchaseOrderAsRevision,
updatePurchaseOrderStatus
} from "~/modules/purchasing";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
@@ -91,6 +92,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
+ // The approval writes below go through the service role, keyed on the URL's
+ // id: the purchase order must belong to this company first.
+ await requireCompanyRecord(serviceRole, "purchaseOrder", companyId, { id });
+
// Cancel pending approval requests when closing the PO
// Closed POs are terminal - no approvals should remain pending
// Note: Approved/Rejected requests are NOT cancelled - they serve as audit trail
@@ -106,6 +111,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("documentType", "purchaseOrder")
.eq("documentId", id)
+ .eq("companyId", companyId)
.eq("status", "Pending")
.select("id");
@@ -125,6 +131,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.select("*")
.eq("documentType", "purchaseOrder")
.eq("documentId", id)
+ .eq("companyId", companyId)
.eq("status", "Pending");
if (pendingApprovals.data && pendingApprovals.data.length > 0) {
@@ -139,6 +146,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("documentType", "purchaseOrder")
.eq("documentId", id)
+ .eq("companyId", companyId)
.eq("status", "Pending");
} else if (currentStatus === "Needs Approval") {
// Security check: Only allow reopening if user is the requester OR an approver
@@ -180,6 +188,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("documentType", "purchaseOrder")
.eq("documentId", id)
+ .eq("companyId", companyId)
.eq("status", "Pending");
}
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index dbbd582eb7..16fa23b71e 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -99,7 +99,13 @@ export async function action(args: ActionFunctionArgs) {
orderId
);
- if (!approvalRequest.data || approvalRequest.data.id !== approvalRequestId) {
+ // The service role bypasses RLS and orderId comes from the URL: the request
+ // must belong to this company, not just to a purchase order with this id.
+ if (
+ !approvalRequest.data ||
+ approvalRequest.data.id !== approvalRequestId ||
+ approvalRequest.data.companyId !== companyId
+ ) {
throw redirect(
path.to.purchaseOrder(orderId),
await flash(request, error(null, "Approval request not found"))
@@ -271,7 +277,7 @@ export async function action(args: ActionFunctionArgs) {
buyer
] = await Promise.all([
getCompany(serviceRole, companyId),
- getSupplierContact(serviceRole, supplierContact),
+ getSupplierContact(serviceRole, supplierContact, companyId),
getPurchaseOrderLines(serviceRole, orderId),
getPurchaseOrderLocations(serviceRole, orderId),
getPaymentTermsList(serviceRole, companyId),
diff --git a/apps/erp/app/routes/x+/purchase-order+/new.tsx b/apps/erp/app/routes/x+/purchase-order+/new.tsx
index accfa8389e..da1d2f6520 100644
--- a/apps/erp/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/new.tsx
@@ -13,6 +13,7 @@ import {
purchaseOrderValidator
} from "~/modules/purchasing";
import { PurchaseOrderForm } from "~/modules/purchasing/ui/PurchaseOrder";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -43,6 +44,27 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // bypassRls hands back the service role, and insertPurchaseOrder copies the
+ // supplier's payment and shipping defaults by these form ids.
+ const { supplierId, supplierLocationId, supplierContactId, locationId } =
+ validation.data;
+ await Promise.all([
+ requireCompanyRecord(client, "supplier", companyId, { id: supplierId }),
+ supplierLocationId
+ ? requireCompanyRecord(client, "supplierLocation", companyId, {
+ id: supplierLocationId
+ })
+ : null,
+ supplierContactId
+ ? requireCompanyRecord(client, "supplierContact", companyId, {
+ id: supplierContactId
+ })
+ : null,
+ locationId
+ ? requireCompanyRecord(client, "location", companyId, { id: locationId })
+ : null
+ ]);
+
const result = await insertPurchaseOrder(client, {
...validation.data,
purchaseOrderId: validation.data.purchaseOrderId || undefined,
diff --git a/apps/erp/app/routes/x+/purchase-return-order+/new.tsx b/apps/erp/app/routes/x+/purchase-return-order+/new.tsx
index 46bcda8b03..a918e9fc23 100644
--- a/apps/erp/app/routes/x+/purchase-return-order+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-return-order+/new.tsx
@@ -11,6 +11,7 @@ import {
purchaseReturnOrderValidator
} from "~/modules/purchasing";
import { PurchaseReturnOrderForm } from "~/modules/purchasing/ui/PurchaseReturnOrders";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -39,6 +40,34 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, status: _status, ...data } = validation.data;
+ // bypassRls hands back the service role, and insertPurchaseReturnOrder reads
+ // the supplier by this form id to copy its defaults.
+ await Promise.all([
+ requireCompanyRecord(client, "supplier", companyId, {
+ id: data.supplierId
+ }),
+ data.supplierLocationId
+ ? requireCompanyRecord(client, "supplierLocation", companyId, {
+ id: data.supplierLocationId
+ })
+ : null,
+ data.supplierContactId
+ ? requireCompanyRecord(client, "supplierContact", companyId, {
+ id: data.supplierContactId
+ })
+ : null,
+ data.locationId
+ ? requireCompanyRecord(client, "location", companyId, {
+ id: data.locationId
+ })
+ : null,
+ data.purchaseOrderId
+ ? requireCompanyRecord(client, "purchaseOrder", companyId, {
+ id: data.purchaseOrderId
+ })
+ : null
+ ]);
+
const result = await insertPurchaseReturnOrder(client, {
...data,
purchaseReturnOrderId: data.purchaseReturnOrderId || undefined,
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index 70726f3fdc..6fbe749e27 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -9,6 +9,7 @@ import {
plannedOrderValidator,
upsertPurchaseOrderLine
} from "~/modules/purchasing";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "purchasing", "planning");
@@ -181,16 +182,65 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // bypassRls hands back the service role, and every id below comes
+ // from the request body: the location, items and existing lines must
+ // belong to this company before anything is read or written by them
+ // (supplyForecast upserts on (itemId, locationId, periodId) alone).
+ const existingLineIds = existingLineUpdates.map(
+ ({ order }) => order.existingLineId!
+ );
+ await requireCompanyRecord(client, "location", companyId, {
+ id: locationId
+ });
+ const [ownedItems, ownedLines] = await Promise.all([
+ client
+ .from("item")
+ .select("id")
+ .in("id", Array.from(itemIds))
+ .eq("companyId", companyId),
+ existingLineIds.length > 0
+ ? client
+ .from("purchaseOrderLine")
+ .select("id")
+ .in("id", existingLineIds)
+ .eq("companyId", companyId)
+ : Promise.resolve({ data: [] as { id: string }[], error: null })
+ ]);
+ if (
+ ownedItems.error ||
+ ownedLines.error ||
+ (ownedItems.data?.length ?? 0) !== itemIds.size ||
+ (ownedLines.data?.length ?? 0) !== new Set(existingLineIds).size
+ ) {
+ logger.error("Planning order references records outside company", {
+ companyId,
+ userId,
+ locationId,
+ itemIds: Array.from(itemIds),
+ existingLineIds,
+ error: ownedItems.error ?? ownedLines.error
+ });
+ return data(
+ {
+ success: false,
+ message: "Item or purchase order line not found"
+ },
+ { status: 404 }
+ );
+ }
+
const [suppliers, supplierParts, periods, company, currencies] =
await Promise.all([
client
.from("supplier")
.select("id, name, taxPercent, currencyCode")
- .in("id", Array.from(supplierIds)),
+ .in("id", Array.from(supplierIds))
+ .eq("companyId", companyId),
client
.from("supplierPart")
.select("*")
- .in("itemId", Array.from(itemIds)),
+ .in("itemId", Array.from(itemIds))
+ .eq("companyId", companyId),
client.from("period").select("*").in("id", Array.from(periodIds)),
client
.from("company")
@@ -273,7 +323,8 @@ export async function action({ request }: ActionFunctionArgs) {
requiredDate: order.dueDate ?? null,
updatedBy: userId
})
- .eq("id", order.existingLineId!);
+ .eq("id", order.existingLineId!)
+ .eq("companyId", companyId);
if (updateLine.error) {
errors.push(
`Failed to update existing PO line ${order.existingLineId}: ${updateLine.error.message}`
@@ -312,6 +363,7 @@ export async function action({ request }: ActionFunctionArgs) {
)
.gte("requiredDate", period.startDate)
.lte("requiredDate", period.endDate)
+ .eq("companyId", companyId)
.eq("purchaseOrder.supplierId", supplierId)
.in("purchaseOrder.status", ["Draft", "Planned"])
.limit(1);
@@ -361,6 +413,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("itemReplenishment")
.select("purchasingBlocked")
.eq("itemId", itemId)
+ .eq("companyId", companyId)
.single();
if (purchasing.error) {
@@ -391,6 +444,7 @@ export async function action({ request }: ActionFunctionArgs) {
.select("id, purchaseQuantity")
.eq("purchaseOrderId", purchaseOrderId)
.eq("itemId", itemId)
+ .eq("companyId", companyId)
.limit(1);
if (existingLines?.[0]) {
@@ -402,7 +456,8 @@ export async function action({ request }: ActionFunctionArgs) {
(existing.purchaseQuantity ?? 0) + adjustedQuantity,
updatedBy: userId
})
- .eq("id", existing.id);
+ .eq("id", existing.id)
+ .eq("companyId", companyId);
if (updateLine.error) {
errors.push(
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx
index 99b4a7f573..a54803a39e 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updatePurchasingRFQLineOrder } from "~/modules/purchasing";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "purchasing"
});
if (!params.id) throw new Error("Could not find id");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updatePurchasingRFQLineOrder(getDatabaseClient(), updates);
+ await updatePurchasingRFQLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.id,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.$lineId.details.tsx
index d68cd81a76..c3b7534c6f 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.$lineId.details.tsx
@@ -1,8 +1,9 @@
-import { assertIsPost, error } from "@carbon/auth";
+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 { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { Fragment } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -28,6 +29,8 @@ import { setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "purchasing-rfq-line-details");
+
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { companyId } = await requirePermissions(request, {
view: "purchasing"
@@ -48,6 +51,20 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
);
}
+ // The service role bypasses RLS and lineId comes from the URL: the line must
+ // belong to this company and to the RFQ in the URL.
+ if (
+ line.data.companyId !== companyId ||
+ line.data.purchasingRfqId !== rfqId
+ ) {
+ logger.error("Purchasing RFQ line not found for company", {
+ companyId,
+ rfqId,
+ lineId
+ });
+ throw notFound("Purchasing RFQ line not found");
+ }
+
// purchasingRfqLines is the one line view that exposes modelPath without the
// model's id, so read the whole row off the item instead — only when the line
// says there is a model at all.
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.compare.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.compare.tsx
index daea6f2abe..b70870e863 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.compare.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.compare.tsx
@@ -2,14 +2,24 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { LoaderFunctionArgs } from "react-router";
import { getSupplierQuotesForComparison } from "~/modules/purchasing";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
export async function loader({ request, params }: LoaderFunctionArgs) {
- await requirePermissions(request, { view: "purchasing" });
+ const { companyId } = await requirePermissions(request, {
+ view: "purchasing"
+ });
const { rfqId } = params;
if (!rfqId) throw new Error("rfqId not found");
const serviceRole = getCarbonServiceRole();
+
+ // The comparison reads through the service role keyed on the URL's rfqId,
+ // so the RFQ must belong to this company first.
+ await requireCompanyRecord(serviceRole, "purchasingRfq", companyId, {
+ id: rfqId
+ });
+
const comparison = await getSupplierQuotesForComparison(serviceRole, rfqId);
return {
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
index 6ec015ecdb..5bf42ca4cc 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
@@ -24,6 +24,7 @@ import {
import { getCompany } from "~/modules/settings";
import type { ItemType } from "~/modules/shared";
import { itemType, upsertExternalLink } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getUser } from "~/modules/users/users.server";
import { path } from "~/utils/path";
@@ -41,6 +42,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { rfqId } = params;
if (!rfqId) throw new Error("Could not find rfqId");
+ // bypassRls hands back the service role and every read/write below is keyed
+ // on the URL's rfqId.
+ await requireCompanyRecord(client, "purchasingRfq", companyId, {
+ id: rfqId
+ });
+
// Validate form data
const validation = await validator(purchasingRfqFinalizeValidator).validate(
await request.formData()
@@ -205,7 +212,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (supplierContactData?.contactId && externalLinkResult.data) {
const supplierContact = await getSupplierContact(
client,
- supplierContactData.contactId
+ supplierContactData.contactId,
+ companyId
);
if (supplierContact?.data?.contact?.email) {
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx
index 4ce01f5551..e1ca72a805 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx
@@ -2,6 +2,7 @@ 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 { getLogger } from "@carbon/logger";
import { type JSONContent, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
@@ -23,6 +24,8 @@ import {
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "purchasing-rfq");
+
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
{ breadcrumb: msg`RFQs`, to: path.to.purchasingRfqs },
@@ -58,6 +61,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // The service role bypasses RLS and rfqId comes from the URL.
+ if (rfqSummary.data.companyId !== companyId) {
+ logger.error("Purchasing RFQ not found for company", { companyId, rfqId });
+ throw redirect(path.to.purchasingRfqs);
+ }
+
if (lines.error) {
throw redirect(
path.to.purchasingRfqs,
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx b/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx
index 39eebf8c7a..78e5d56f44 100644
--- a/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
@@ -17,6 +18,9 @@ import GaugeCalibrationRecordForm from "~/modules/quality/ui/Calibrations/GaugeC
import { getCustomFields, setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { getParams, path } from "~/utils/path";
+
+const logger = getLogger("erp", "calibration-detail");
+
export const handle: Handle = {
breadcrumb: msg`Gauges`,
to: path.to.gauges
@@ -46,6 +50,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven to
+ // exist — not to be this company's.
+ if (record.data.companyId !== companyId) {
+ logger.error("Gauge calibration record is not in the caller's company", {
+ companyId,
+ calibrationRecordId: id
+ });
+ throw redirect(path.to.gauges);
+ }
+
return {
record: record.data,
files: files ?? []
diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsx
index 54345634ee..fdcb8f845d 100644
--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx
@@ -109,9 +109,12 @@ export const handle: Handle = {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
- update: "quality"
- });
+ const { companyId: callerCompanyId, userId } = await requirePermissions(
+ request,
+ {
+ update: "quality"
+ }
+ );
const { id } = params;
if (!id) throw new Error("Could not find id");
@@ -135,7 +138,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
id
);
- if (!approvalRequest.data || approvalRequest.data.id !== approvalRequestId) {
+ // The request is read through the service role by a URL id, so it must be
+ // proven to be this company's before anything acts on it.
+ if (
+ !approvalRequest.data ||
+ approvalRequest.data.id !== approvalRequestId ||
+ approvalRequest.data.companyId !== callerCompanyId
+ ) {
+ logger.error("Quality document approval request not found", {
+ companyId: callerCompanyId,
+ documentId: id,
+ approvalRequestId
+ });
throw redirect(
path.to.qualityDocument(id),
await flash(request, error(null, "Approval request not found"))
@@ -247,6 +261,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven
+ // to exist — not to be this company's.
+ if (document.data.companyId !== companyId) {
+ logger.error("Quality document is not in the caller's company", {
+ companyId,
+ documentId: id
+ });
+ throw redirect(path.to.qualityDocuments);
+ }
+
return {
document: document.data,
versions: getQualityDocumentVersions(client, document.data, companyId),
diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsx
index 0a5d8955a3..c5a4dbec6f 100644
--- a/apps/erp/app/routes/x+/quality-document+/update.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx
@@ -105,7 +105,8 @@ async function processToActive(
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .eq("id", docId);
+ .eq("id", docId)
+ .eq("companyId", companyId);
}
const idsToUpdateToActive = ids.filter((id) => !idsToSkipActive.includes(id));
if (idsToUpdateToActive.length === 0) {
@@ -118,7 +119,8 @@ async function processToActive(
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", idsToUpdateToActive);
+ .in("id", idsToUpdateToActive)
+ .eq("companyId", companyId);
}
/**
@@ -199,7 +201,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
case "status": {
const statusValue = value as (typeof qualityDocumentStatus)[number];
if (!qualityDocumentStatus.includes(statusValue)) {
@@ -209,7 +212,10 @@ export async function action({ request }: ActionFunctionArgs) {
const currentDocs = await client
.from("qualityDocument")
.select("id, status")
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ // docList drives service-role approval writes below — this company's
+ // documents only.
+ .eq("companyId", companyId);
if (currentDocs.error) {
return { error: currentDocs.error, data: null };
@@ -247,7 +253,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", idList);
+ .in("id", idList)
+ .eq("companyId", companyId);
}
case "tags":
return await client
@@ -257,7 +264,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
default:
return { error: { message: "Invalid field" }, data: null };
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
index f0fc60570a..3eeabeb2d4 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
@@ -7,6 +7,7 @@ import { redirect } from "react-router";
import { getSupplierPriceBreaksForItems } from "~/modules/items";
import { upsertQuoteLineMethod } from "~/modules/sales/sales.service";
import { resolveBuyUnitCost } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -18,6 +19,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
+ // The method pull and price refresh below use the service role and key on
+ // the URL line id.
+ const serviceRole = getCarbonServiceRole();
+ await requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ });
+
const configuration = await request.json();
if (configuration) {
const [result, quoteLine] = await Promise.all([
@@ -47,7 +56,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const serviceRole = await getCarbonServiceRole();
const upsertMethod = await upsertQuoteLineMethod(serviceRole, {
quoteId,
quoteLineId: lineId,
@@ -70,6 +78,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("quoteMaterial")
.select("id, itemId, unitCost, unitCostSource")
.eq("quoteLineId", lineId)
+ .eq("companyId", companyId)
.eq("methodType", "Purchase to Order");
const buyItemIds = [
@@ -87,7 +96,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
await serviceRole
.from("quoteMaterial")
.update({ unitCost: price })
- .eq("id", mat.id);
+ .eq("id", mat.id)
+ .eq("companyId", companyId);
}
}
} else {
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 845950af45..2f67b9d8e4 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -70,6 +70,7 @@ import {
import QuoteLinePricingHistory from "~/modules/sales/ui/Quotes/QuoteLinePricingHistory";
import QuoteLineRiskRegister from "~/modules/sales/ui/Quotes/QuoteLineRiskRegister";
import { getTagsList, type SupplierPriceMap } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -85,6 +86,11 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
if (!lineId) throw new Error("Could not find lineId");
const serviceRole = await getCarbonServiceRole();
+ // Every read below uses the service role and keys on the URL line id.
+ await requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ });
const [line, operations, prices] = await Promise.all([
getQuoteLine(serviceRole, lineId),
@@ -180,6 +186,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
+ // The rule evaluation, evidence and price writes below use the service role
+ // (or Kysely) and key on the URL ids.
+ await requireCompanyRecord(getCarbonServiceRole(), "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ });
+
const { client: viewClient } = await requirePermissions(request, {
view: "sales"
});
@@ -247,7 +260,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const existingPrices = await serviceRole
.from("quoteLinePrice")
.select("quantity")
- .eq("quoteLineId", lineId);
+ .eq("quoteLineId", lineId)
+ .eq("companyId", companyId);
if (existingPrices.error) {
throw redirect(
@@ -328,6 +342,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
try {
await saveQuoteLineWithPrices({
+ companyId,
+ quoteId,
lineId,
line: {
...sanitize({ ...d, updatedBy: userId }),
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
index f2e319f634..012de53573 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -22,6 +22,7 @@ import {
import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";
import {
generateAndAttachSalesOrderPdf,
+ requireCompanyRecord,
sendSalesOrderEmail
} from "~/modules/shared/shared.server";
import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";
@@ -79,7 +80,9 @@ export async function action(args: ActionFunctionArgs) {
const customerContact = notificationValidation.data?.customerContact;
const cc = notificationValidation.data?.cc;
+ // Everything below runs with the service role and keys on the URL quote.
const serviceRole = getCarbonServiceRole();
+ await requireCompanyRecord(serviceRole, "quote", companyId, { id: quoteId });
// Terminal gate, in the route rather than inside the `convert` edge function:
// the edge function writes salesOrderLine rows directly and cannot run the
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
index 12e54b924b..9357631e6f 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
@@ -18,6 +18,7 @@ import {
upsertQuoteLine,
upsertQuoteLineMethod
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { path } from "~/utils/path";
const quoteDragValidator = z.object({
@@ -52,7 +53,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { name: fileName, path: documentPath, size, lineId } = validation.data;
+ // Lines and parts are created with the service role: the URL quote must
+ // belong to this company.
const serviceRole = getCarbonServiceRole();
+ await requireCompanyRecord(serviceRole, "quote", companyId, { id: quoteId });
const quote = await getQuote(serviceRole, quoteId);
if (quote.error || !quote.data) {
@@ -195,6 +199,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("quoteLine")
.select("itemId")
.eq("id", targetLineId)
+ .eq("quoteId", quoteId)
.eq("companyId", companyId)
.single();
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index ea076221c5..19730114cd 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -29,6 +29,7 @@ import {
import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";
import { getCompany, getCompanySettings } from "~/modules/settings";
import { upsertExternalLink } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
import { path } from "~/utils/path";
@@ -53,6 +54,10 @@ export async function action(args: ActionFunctionArgs) {
let fileName: string;
let documentFilePath: string;
+ // `client` is the service role (bypassRls): the URL quote must belong to
+ // this company before it is evaluated, linked, rendered or sent.
+ await requireCompanyRecord(client, "quote", companyId, { id: quoteId });
+
const quote = await getQuote(client, quoteId);
if (quote.error) {
throw redirect(
@@ -236,7 +241,7 @@ export async function action(args: ActionFunctionArgs) {
getCompany(client, companyId),
getCompanySettings(client, companyId),
getCustomer(client, quote.data.customerId!),
- getCustomerContact(client, customerContactId),
+ getCustomerContact(client, customerContactId, companyId),
getUser(client, userId)
]);
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx
index 325ba3c1d4..72d8dde699 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateQuoteLineOrder } from "~/modules/sales";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "sales"
});
if (!params.quoteId) throw new Error("Could not find quoteId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateQuoteLineOrder(getDatabaseClient(), updates);
+ await updateQuoteLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.quoteId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
index 58c7cc07f5..ca08e3d6ef 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
@@ -23,6 +23,7 @@ import {
upsertQuoteLineMethod
} from "~/modules/sales";
import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -38,6 +39,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { quoteId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
+ // The line is inserted with the service role, which bypasses RLS: the quote
+ // must belong to this company.
+ const serviceRole = getCarbonServiceRole();
+ await requireCompanyRecord(serviceRole, "quote", companyId, {
+ id: quoteId
+ });
+
const { client: viewClient } = await requirePermissions(request, {
view: "sales"
});
@@ -67,8 +75,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- const serviceRole = getCarbonServiceRole();
-
// Sales-rule enforcement: evaluate before the line is written. Blocked
// submissions return violations for the form's violation modal;
// acknowledged warns pass through on re-submit.
@@ -110,6 +116,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const createQuotationLine = await upsertQuoteLine(serviceRole, {
...d,
+ // The URL quote was verified above; the form's copy was not.
+ quoteId,
companyId,
configuration,
createdBy: userId,
@@ -214,6 +222,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const recalcResult = await recalculateQuoteLinePrices(
serviceRole,
+ companyId,
quoteId,
quoteLineId,
userId
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
index 1d23db43a3..3a2f56d48e 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
@@ -10,6 +10,7 @@ import {
recalculateQuoteLinePrices,
upsertQuoteMaterial
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -36,7 +37,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // The update below uses the service role, which bypasses RLS: the material,
+ // its line and every parent id in the form must belong to this company.
const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ }),
+ requireCompanyRecord(serviceRole, "quoteMaterial", companyId, {
+ id,
+ quoteLineId: lineId
+ }),
+ validation.data.quoteOperationId
+ ? requireCompanyRecord(serviceRole, "quoteOperation", companyId, {
+ id: validation.data.quoteOperationId,
+ quoteLineId: lineId
+ })
+ : undefined
+ ]);
+
const updateQuoteMaterial = await upsertQuoteMaterial(serviceRole, {
quoteId,
quoteLineId: lineId,
@@ -71,7 +91,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);
+ await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ userId
+ );
return {
id: quoteMaterialId,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
index b49eca88f7..60965c2e2a 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
@@ -8,10 +8,11 @@ import {
deleteQuoteMaterial,
recalculateQuoteLinePrices
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "sales"
});
@@ -26,6 +27,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
throw new Error("id not found");
}
+ // The price recalculation below uses the service role: the material and its
+ // line must belong to this company before anything is touched.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ }),
+ requireCompanyRecord(serviceRole, "quoteMaterial", companyId, {
+ id,
+ quoteLineId: lineId
+ })
+ ]);
+
const deleteMaterial = await deleteQuoteMaterial(client, id);
if (deleteMaterial.error) {
return data(
@@ -39,8 +54,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const serviceRole = getCarbonServiceRole();
- await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);
+ await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ userId
+ );
return {};
}
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
index 387bf05aa8..0e829fa64b 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
@@ -11,6 +11,7 @@ import {
upsertQuoteMaterial,
upsertQuoteMaterialMakeMethod
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -34,7 +35,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // The writes below use the service role, which bypasses RLS: every id from
+ // the URL and the form must belong to this company and this quote line.
const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ }),
+ requireCompanyRecord(serviceRole, "quoteMakeMethod", companyId, {
+ id: validation.data.quoteMakeMethodId,
+ quoteLineId: lineId
+ }),
+ validation.data.quoteOperationId
+ ? requireCompanyRecord(serviceRole, "quoteOperation", companyId, {
+ id: validation.data.quoteOperationId,
+ quoteLineId: lineId
+ })
+ : undefined
+ ]);
+
const insertQuoteMaterial = await upsertQuoteMaterial(serviceRole, {
...validation.data,
quoteId,
@@ -73,6 +93,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("quoteMaterialWithMakeMethodId")
.select("*")
.eq("id", quoteMaterialId)
+ .eq("companyId", companyId)
.single();
if (materialMakeMethod.error) {
return data(
@@ -105,7 +126,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);
+ await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ userId
+ );
return {
id: quoteMaterialId,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
index bb2c5d8ce9..752398a66b 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
@@ -10,6 +10,7 @@ import {
recalculateQuoteLinePrices,
upsertQuoteOperation
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -38,6 +39,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // The recalculation below uses the service role: the operation and its line
+ // must belong to this company.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ }),
+ requireCompanyRecord(serviceRole, "quoteOperation", companyId, {
+ id,
+ quoteLineId: lineId
+ })
+ ]);
+
const updateQuoteOperation = await upsertQuoteOperation(client, {
quoteId,
quoteLineId: lineId,
@@ -72,8 +87,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const serviceRole = getCarbonServiceRole();
- await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);
+ await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ userId
+ );
return {
id: quoteOperationId,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
index cd105071fb..c9afe0d507 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
@@ -10,6 +10,7 @@ import {
recalculateQuoteLinePrices,
upsertQuoteOperation
} from "~/modules/sales";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -35,6 +36,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // RLS only checks the new row's companyId, and the recalculation below uses
+ // the service role: the line and make method must belong to this company.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: lineId,
+ quoteId
+ }),
+ requireCompanyRecord(serviceRole, "quoteMakeMethod", companyId, {
+ id: validation.data.quoteMakeMethodId,
+ quoteLineId: lineId
+ })
+ ]);
+
const insertQuoteOperation = await upsertQuoteOperation(client, {
...validation.data,
quoteId,
@@ -68,8 +83,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const serviceRole = getCarbonServiceRole();
- await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);
+ await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ userId
+ );
return {
id: quoteOperationId,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx
index d70bc7760d..0821cfc1bb 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx
@@ -5,7 +5,7 @@ import { data } from "react-router";
import { recalculateQuoteLinePrices } from "~/modules/sales";
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "sales"
});
@@ -26,9 +26,14 @@ export async function action({ request }: ActionFunctionArgs) {
.from("quoteOperation")
.select("quoteId, quoteLineId")
.eq("id", id)
+ .eq("companyId", companyId)
.single();
- const { error } = await client.from("quoteOperation").delete().eq("id", id);
+ const { error } = await client
+ .from("quoteOperation")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
if (error) {
return data(
@@ -43,6 +48,7 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
await recalculateQuoteLinePrices(
serviceRole,
+ companyId,
op.data.quoteId,
op.data.quoteLineId,
userId
diff --git a/apps/erp/app/routes/x+/quote+/new.tsx b/apps/erp/app/routes/x+/quote+/new.tsx
index 3331bac206..938f4074fa 100644
--- a/apps/erp/app/routes/x+/quote+/new.tsx
+++ b/apps/erp/app/routes/x+/quote+/new.tsx
@@ -10,6 +10,7 @@ import { useUrlParams, useUser } from "~/hooks";
import type { QuotationStatusType } from "~/modules/sales";
import { insertQuote, quoteValidator } from "~/modules/sales";
import { QuoteForm } from "~/modules/sales/ui/Quotes";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -37,6 +38,45 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, ...data } = validation.data;
+ // `client` is the service role (bypassRls): insertQuote copies the customer's
+ // payment and shipping terms, so the customer must belong to this company —
+ // and every contact/location id must hang off that customer, in this company.
+ const customerId = data.customerId;
+ await Promise.all([
+ requireCompanyRecord(client, "customer", companyId, { id: customerId }),
+ requireCompanyRecord(client, "location", companyId, {
+ id: data.locationId
+ }),
+ data.customerContactId
+ ? requireCompanyRecord(client, "customerContact", companyId, {
+ id: data.customerContactId,
+ customerId
+ })
+ : null,
+ data.customerEngineeringContactId
+ ? requireCompanyRecord(client, "customerContact", companyId, {
+ id: data.customerEngineeringContactId,
+ customerId
+ })
+ : null,
+ data.customerLocationId
+ ? requireCompanyRecord(client, "customerLocation", companyId, {
+ id: data.customerLocationId,
+ customerId
+ })
+ : null,
+ data.salesPersonId
+ ? requireCompanyRecord(client, "employee", companyId, {
+ id: data.salesPersonId
+ })
+ : null,
+ data.estimatorId
+ ? requireCompanyRecord(client, "employee", companyId, {
+ id: data.estimatorId
+ })
+ : null
+ ]);
+
const result = await insertQuote(client, {
...data,
quoteId: data.quoteId || undefined,
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index 02d2e53cb4..8e94d40588 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -92,7 +92,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.select(
"id, purchaseOrderLineId, received, serialNumber, purchaseOrderLine:purchaseOrderLineId(assetId, description, fixedAsset:assetId(name, fixedAssetId, serialNumber))"
)
- .eq("receiptId", receiptId);
+ .eq("receiptId", receiptId)
+ .eq("companyId", companyId);
fixedAssetLines = (faLineRecords.data ?? [])
.filter((row) => {
diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
index e5c67bfb12..75a096abb3 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
@@ -5,6 +5,7 @@ import { getLogger } from "@carbon/logger";
import type { TrackedEntityAttributes } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "receipt", "tracking");
@@ -22,6 +23,21 @@ export async function action({ request, context }: ActionFunctionArgs) {
| "serial"
| "returnEntity";
+ // The batch and serial paths write through service-role RPCs that key on
+ // these form ids alone (and upsert the tracked entity by id), so the receipt
+ // line must belong to this receipt and company before either runs.
+ if (trackingType === "batch" || trackingType === "serial") {
+ await requireCompanyRecord(
+ getCarbonServiceRole(),
+ "receiptLine",
+ companyId,
+ {
+ id: receiptLineId,
+ receiptId
+ }
+ );
+ }
+
if (trackingType === "batch") {
const batchNumber = formData.get("batchNumber") as string;
const quantity = Number(formData.get("quantity"));
@@ -35,7 +51,16 @@ export async function action({ request, context }: ActionFunctionArgs) {
// Line so a stale batch-number rename never orphans the prior entity.
let trackedEntityId: string | undefined =
passedTrackedEntityId ?? undefined;
- if (!trackedEntityId) {
+ if (trackedEntityId) {
+ // The RPC upserts by this id, so an id from another company would
+ // overwrite that company's lot.
+ await requireCompanyRecord(
+ getCarbonServiceRole(),
+ "trackedEntity",
+ companyId,
+ { id: trackedEntityId }
+ );
+ } else {
const { data: existing, error: batchQueryError } = await client
.from("trackedEntity")
.select("id")
diff --git a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
index 93748b666a..bf6ef397bf 100644
--- a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { isUnsafeStoragePath } from "@carbon/files";
import { validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { postSuggestionToCarbonSlack } from "@carbon/lib/slack.server";
@@ -36,7 +37,9 @@ export async function action({ request }: ActionFunctionArgs) {
// formUserId is only an anonymous on/off signal — attribute the session user or nobody
const suggestionUserId = formUserId ? userId : null;
const suggestionAttachmentPath =
- attachmentPath && attachmentPath.startsWith(`${companyId}/suggestions/`)
+ attachmentPath &&
+ attachmentPath.startsWith(`${companyId}/suggestions/`) &&
+ !isUnsafeStoragePath(attachmentPath)
? attachmentPath
: null;
diff --git a/apps/erp/app/routes/x+/sales+/price-list.$overrideId.tsx b/apps/erp/app/routes/x+/sales+/price-list.$overrideId.tsx
index 1999ed6db4..3c855598fd 100644
--- a/apps/erp/app/routes/x+/sales+/price-list.$overrideId.tsx
+++ b/apps/erp/app/routes/x+/sales+/price-list.$overrideId.tsx
@@ -1,5 +1,6 @@
import { assertIsPost, error, notFound, 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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -11,6 +12,7 @@ import {
upsertCustomerItemPriceOverride
} from "~/modules/sales";
import PriceOverrideForm from "~/modules/sales/ui/Pricing/PriceOverrideForm";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { getParams, path } from "~/utils/path";
@@ -79,6 +81,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
validTo
} = validation.data;
+ // The override is written through Kysely (RLS bypassed) and references the
+ // item, customer and customer type by the form's ids.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "item", companyId, { id: itemId }),
+ customerId
+ ? requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: customerId
+ })
+ : null,
+ customerTypeId
+ ? requireCompanyRecord(serviceRole, "customerType", companyId, {
+ id: customerTypeId
+ })
+ : null
+ ]);
+
const result = await upsertCustomerItemPriceOverride(
getDatabaseClient(),
companyId,
diff --git a/apps/erp/app/routes/x+/sales+/price-list.new.tsx b/apps/erp/app/routes/x+/sales+/price-list.new.tsx
index 998af59f73..8c954f8091 100644
--- a/apps/erp/app/routes/x+/sales+/price-list.new.tsx
+++ b/apps/erp/app/routes/x+/sales+/price-list.new.tsx
@@ -1,5 +1,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 { datetime } from "@carbon/utils";
@@ -11,6 +12,7 @@ import {
upsertCustomerItemPriceOverride
} from "~/modules/sales";
import PriceOverrideForm from "~/modules/sales/ui/Pricing/PriceOverrideForm";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getDatabaseClient } from "~/services/database.server";
import { getParams, path } from "~/utils/path";
@@ -84,6 +86,23 @@ export async function action({ request }: ActionFunctionArgs) {
validTo
} = validation.data;
+ // The override is written through Kysely (RLS bypassed) and references the
+ // item, customer and customer type by the form's ids.
+ const serviceRole = getCarbonServiceRole();
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "item", companyId, { id: itemId }),
+ customerId
+ ? requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: customerId
+ })
+ : null,
+ customerTypeId
+ ? requireCompanyRecord(serviceRole, "customerType", companyId, {
+ id: customerTypeId
+ })
+ : null
+ ]);
+
const result = await upsertCustomerItemPriceOverride(
getDatabaseClient(),
companyId,
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx
index fba5c58168..2a86ae814a 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateSalesInvoiceLineOrder } from "~/modules/invoicing";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "invoicing"
});
if (!params.invoiceId) throw new Error("Could not find invoiceId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateSalesInvoiceLineOrder(getDatabaseClient(), updates);
+ await updateSalesInvoiceLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.invoiceId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index 935189d2e3..a83ea89955 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -44,6 +44,7 @@ import {
import { getCustomerContact, updateCustomerContact } from "~/modules/sales";
import { recordSalesRuleOutcome } from "~/modules/sales/sales.server";
import { getCompany } from "~/modules/settings";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/sales-invoice+/$id[.]pdf";
@@ -317,7 +318,13 @@ async function preflightStripeSend({
}
if (stripeContactEmail) {
- const contact = await getCustomerContact(serviceRole, customerContact);
+ // customerContact comes from the form and the service role bypasses RLS:
+ // scope it so another company's contact is never read or rewritten.
+ const contact = await getCustomerContact(
+ serviceRole,
+ customerContact,
+ companyId
+ );
if (contact.data && !contact.data.contact?.email) {
const update = await updateCustomerContact(serviceRole, {
contactId: contact.data.contactId,
@@ -510,6 +517,13 @@ export async function action(args: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
+ // Everything below reads and writes through the service role (and the
+ // Stripe preflight runs before the edge function re-checks the invoice), so
+ // the URL's invoiceId must belong to this company before anything happens.
+ await requireCompanyRecord(serviceRole, "salesInvoice", companyId, {
+ id: invoiceId
+ });
+
const formData = await request.formData();
const validation = await validator(salesInvoicePostValidator).validate(
formData
@@ -812,7 +826,7 @@ export async function action(args: ActionFunctionArgs) {
paymentTerms
] = await Promise.all([
getCompany(serviceRole, companyId),
- getCustomerContact(serviceRole, customerContact),
+ getCustomerContact(serviceRole, customerContact, companyId),
getSalesInvoice(serviceRole, invoiceId),
getSalesInvoiceLines(serviceRole, invoiceId),
getSalesInvoiceCustomerDetails(serviceRole, invoiceId),
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
index a07165784a..af8d00fc56 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
@@ -9,6 +9,7 @@ import {
resolveSalesOrderShipTo
} from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { Card, CardHeader, CardTitle } from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -53,6 +54,8 @@ import { getCustomFields, setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "sales-order-line-details");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { companyId } = await requirePermissions(request, {
view: "sales",
@@ -78,6 +81,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // The service role bypasses RLS and lineId comes from the URL: the line must
+ // belong to this company and to the order in the URL.
+ if (line.data.companyId !== companyId || line.data.salesOrderId !== orderId) {
+ logger.error("Sales order line not found for company", {
+ companyId,
+ orderId,
+ lineId
+ });
+ throw notFound("Sales order line not found");
+ }
+
const itemId = line.data.itemId;
return {
@@ -87,8 +101,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
? getItemReplenishment(serviceRole, itemId, companyId)
: Promise.resolve({ data: null }),
files: getOpportunityLineDocuments(serviceRole, companyId, lineId, itemId),
- jobs: jobs?.data ?? [],
- shipments: shipments?.data ?? []
+ jobs: (jobs?.data ?? []).filter((job) => job.companyId === companyId),
+ shipments: (shipments?.data ?? []).filter(
+ (shipment) => shipment.companyId === companyId
+ )
};
}
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
index abfc9d24f3..6a6c32781c 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
@@ -7,6 +7,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { insertJob, salesOrderToJobValidator } from "~/modules/production";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -36,12 +37,47 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id: _id, ...d } = validation.data;
+ // The service role bypasses RLS and every id below comes from the request:
+ // each must belong to this company (and the line to the order in the URL)
+ // before a job is written that references them. The job is attached to the
+ // verified order and line, never the form's copies.
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "salesOrderLine", companyId, {
+ id: lineId,
+ salesOrderId: orderId
+ }),
+ requireCompanyRecord(serviceRole, "item", companyId, { id: d.itemId }),
+ requireCompanyRecord(serviceRole, "location", companyId, {
+ id: d.locationId
+ }),
+ d.customerId
+ ? requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: d.customerId
+ })
+ : null,
+ d.quoteId
+ ? requireCompanyRecord(serviceRole, "quote", companyId, { id: d.quoteId })
+ : null,
+ d.quoteLineId
+ ? requireCompanyRecord(serviceRole, "quoteLine", companyId, {
+ id: d.quoteLineId
+ })
+ : null,
+ d.modelUploadId
+ ? requireCompanyRecord(serviceRole, "modelUpload", companyId, {
+ id: d.modelUploadId
+ })
+ : null
+ ]);
+
const methodSource = d.quoteId && d.quoteLineId ? "quoteLine" : "item";
const createJob = await insertJob(
serviceRole,
{
...d,
+ salesOrderId: orderId,
+ salesOrderLineId: lineId,
jobId: d.jobId || undefined,
companyId,
createdBy: userId,
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx
index 8d300f198b..d31ff1b01b 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateSalesOrderLineOrder } from "~/modules/sales";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "sales"
});
if (!params.orderId) throw new Error("Could not find orderId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateSalesOrderLineOrder(getDatabaseClient(), updates);
+ await updateSalesOrderLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.orderId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/sales-order+/new.tsx b/apps/erp/app/routes/x+/sales-order+/new.tsx
index e51b474e03..0c1d7498da 100644
--- a/apps/erp/app/routes/x+/sales-order+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/new.tsx
@@ -8,6 +8,7 @@ import { redirect } from "react-router";
import { useUrlParams, useUser } from "~/hooks";
import { insertSalesOrder, salesOrderValidator } from "~/modules/sales";
import { SalesOrderForm } from "~/modules/sales/ui/SalesOrder";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -34,6 +35,35 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, ...data } = validation.data;
+ // bypassRls hands back the service role, and insertSalesOrder copies the
+ // customer's payment and shipping defaults by these form ids.
+ await Promise.all([
+ requireCompanyRecord(client, "customer", companyId, {
+ id: data.customerId
+ }),
+ requireCompanyRecord(client, "location", companyId, {
+ id: data.locationId
+ }),
+ data.customerLocationId
+ ? requireCompanyRecord(client, "customerLocation", companyId, {
+ id: data.customerLocationId
+ })
+ : null,
+ data.customerContactId
+ ? requireCompanyRecord(client, "customerContact", companyId, {
+ id: data.customerContactId
+ })
+ : null,
+ data.customerEngineeringContactId
+ ? requireCompanyRecord(client, "customerContact", companyId, {
+ id: data.customerEngineeringContactId
+ })
+ : null,
+ data.quoteId
+ ? requireCompanyRecord(client, "quote", companyId, { id: data.quoteId })
+ : null
+ ]);
+
const result = await insertSalesOrder(client, {
...data,
salesOrderId: data.salesOrderId || undefined,
diff --git a/apps/erp/app/routes/x+/sales-return-order+/new.tsx b/apps/erp/app/routes/x+/sales-return-order+/new.tsx
index 44d8aeff9c..f703e0b587 100644
--- a/apps/erp/app/routes/x+/sales-return-order+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-return-order+/new.tsx
@@ -11,6 +11,7 @@ import {
salesReturnOrderValidator
} from "~/modules/sales";
import { SalesReturnOrderForm } from "~/modules/sales/ui/SalesReturnOrders";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -39,6 +40,34 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, status: _status, ...data } = validation.data;
+ // bypassRls hands back the service role, and insertSalesReturnOrder reads
+ // the customer by this form id to copy its defaults.
+ await Promise.all([
+ requireCompanyRecord(client, "customer", companyId, {
+ id: data.customerId
+ }),
+ data.customerLocationId
+ ? requireCompanyRecord(client, "customerLocation", companyId, {
+ id: data.customerLocationId
+ })
+ : null,
+ data.customerContactId
+ ? requireCompanyRecord(client, "customerContact", companyId, {
+ id: data.customerContactId
+ })
+ : null,
+ data.locationId
+ ? requireCompanyRecord(client, "location", companyId, {
+ id: data.locationId
+ })
+ : null,
+ data.salesOrderId
+ ? requireCompanyRecord(client, "salesOrder", companyId, {
+ id: data.salesOrderId
+ })
+ : null
+ ]);
+
const result = await insertSalesReturnOrder(client, {
...data,
salesReturnOrderId: data.salesReturnOrderId || undefined,
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
index 34099e780c..67da65edad 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
@@ -1,8 +1,9 @@
-import { assertIsPost, error } from "@carbon/auth";
+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 { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { Fragment } from "react";
@@ -28,6 +29,8 @@ import { setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "sales-rfq-line-details");
+
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { companyId } = await requirePermissions(request, {
view: "sales"
@@ -48,6 +51,17 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
);
}
+ // The service role bypasses RLS and lineId comes from the URL: the line must
+ // belong to this company and to the RFQ in the URL.
+ if (line.data.companyId !== companyId || line.data.salesRfqId !== rfqId) {
+ logger.error("Sales RFQ line not found for company", {
+ companyId,
+ rfqId,
+ lineId
+ });
+ throw notFound("Sales RFQ line not found");
+ }
+
const itemId = line.data.itemId;
return {
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx
index 9a175ea88c..a2d1c042a2 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateSalesRFQLineOrder } from "~/modules/sales";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "sales"
});
if (!params.rfqId) throw new Error("Could not find rfqId");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateSalesRFQLineOrder(getDatabaseClient(), updates);
+ await updateSalesRFQLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.rfqId,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
index d8f8fb3844..6a0da3797c 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { supportedModelTypes } from "@carbon/files/cad";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import type { DragEndEvent } from "@dnd-kit/core";
@@ -28,6 +29,8 @@ import { useOptimisticDocumentDrag } from "~/modules/sales/ui/SalesRFQ/useOptimi
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "sales-rfq");
+
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
{ breadcrumb: msg`RFQs`, to: path.to.salesRfqs },
@@ -51,6 +54,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getSalesRFQLines(serviceRole, rfqId)
]);
+ // The service role bypasses RLS and rfqId comes from the URL.
+ if (rfqSummary.data && rfqSummary.data.companyId !== companyId) {
+ logger.error("Sales RFQ not found for company", { companyId, rfqId });
+ throw redirect(path.to.salesRfqs);
+ }
+
const opportunity = await getOpportunity(
serviceRole,
rfqSummary.data?.opportunityId ?? null
diff --git a/apps/erp/app/routes/x+/sales-rfq+/new.tsx b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
index a92a776508..b6d058e3d0 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
@@ -1,5 +1,6 @@
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 { storage } from "@carbon/files";
import { validationError, validator } from "@carbon/form";
@@ -17,6 +18,7 @@ import {
upsertSalesRFQLine
} from "~/modules/sales";
import { SalesRFQForm } from "~/modules/sales/ui/SalesRFQ";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
@@ -41,6 +43,42 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ // insertSalesRFQ writes through Kysely, which bypasses RLS: every id the
+ // form references must belong to this company.
+ const serviceRole = getCarbonServiceRole();
+ const {
+ customerId,
+ customerContactId,
+ customerEngineeringContactId,
+ customerLocationId,
+ locationId
+ } = validation.data;
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "customer", companyId, {
+ id: customerId
+ }),
+ customerContactId
+ ? requireCompanyRecord(serviceRole, "customerContact", companyId, {
+ id: customerContactId
+ })
+ : null,
+ customerEngineeringContactId
+ ? requireCompanyRecord(serviceRole, "customerContact", companyId, {
+ id: customerEngineeringContactId
+ })
+ : null,
+ customerLocationId
+ ? requireCompanyRecord(serviceRole, "customerLocation", companyId, {
+ id: customerLocationId
+ })
+ : null,
+ locationId
+ ? requireCompanyRecord(serviceRole, "location", companyId, {
+ id: locationId
+ })
+ : null
+ ]);
+
const result = await insertSalesRFQ(client, getDatabaseClient(), {
...validation.data,
rfqId: validation.data.rfqId || undefined,
diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx
index 3c45911554..65756ad5cd 100644
--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx
@@ -101,6 +101,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trx
.deleteFrom("supplierPartPrice")
.where("supplierPartId", "=", supplierPartId)
+ .where("companyId", "=", companyId)
.execute();
if (priceBreaks.length > 0) {
await trx
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
index faef89f88a..cc4669f61b 100644
--- a/apps/erp/app/routes/x+/settings+/audit-logs.tsx
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
@@ -11,6 +11,7 @@ import {
syncAuditSubscriptions
} from "@carbon/ee/audit.server";
import { requireFeature } from "@carbon/ee/plan.server";
+import { getLogger } from "@carbon/logger";
import { Button, Heading, ScrollArea, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
@@ -22,6 +23,8 @@ import { AuditLogSettings, AuditLogUpgradeOverlay } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "settings-audit-logs");
+
export const handle: Handle = {
breadcrumb: msg`Audit Log`,
to: path.to.auditLog
@@ -156,10 +159,19 @@ export async function action({ request }: ActionFunctionArgs) {
try {
const serviceRole = getCarbonServiceRole();
- const downloadUrl = await getArchiveDownloadUrl(serviceRole, archiveId);
+ const downloadUrl = await getArchiveDownloadUrl(
+ serviceRole,
+ archiveId,
+ companyId
+ );
// Redirect to the signed URL for download
return redirect(downloadUrl);
} catch (err) {
+ logger.error("Failed to generate audit archive download URL", {
+ companyId,
+ archiveId,
+ error: err
+ });
throw redirect(
path.to.auditLog,
await flash(request, error(err, "Failed to generate download URL"))
diff --git a/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx
index 31e1f74c16..d5ccd8ffad 100644
--- a/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx
@@ -2,6 +2,7 @@ import { error, notFound, 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 { getLogger } from "@carbon/logger";
import { isInternalEmail } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
@@ -9,6 +10,8 @@ import { ConfirmDelete } from "~/components/Modals";
import { deleteSubsidiary, getSubsidiary } from "~/modules/settings";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "settings-companies-delete");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, email } = await requirePermissions(request, {
view: "settings"
@@ -34,7 +37,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export async function action({ request, params }: ActionFunctionArgs) {
- const { email } = await requirePermissions(request, {
+ const { companyGroupId, email } = await requirePermissions(request, {
delete: "settings"
});
@@ -51,10 +54,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const { error: deleteError } = await deleteSubsidiary(
- getCarbonServiceRole(),
- id
- );
+ const serviceRole = getCarbonServiceRole();
+
+ // The delete runs as the service role on a URL id: prove the company is in
+ // the caller's own group first, or any company id could be deleted.
+ const subsidiary = await serviceRole
+ .from("company")
+ .select("id")
+ .eq("id", id)
+ .eq("companyGroupId", companyGroupId)
+ .maybeSingle();
+ if (subsidiary.error || !subsidiary.data) {
+ logger.error("Subsidiary not found in the caller's company group", {
+ companyGroupId,
+ subsidiaryId: id,
+ error: subsidiary.error
+ });
+ throw redirect(
+ path.to.companies,
+ await flash(request, error(subsidiary.error, "Subsidiary not found"))
+ );
+ }
+
+ const { error: deleteError } = await deleteSubsidiary(serviceRole, id);
if (deleteError) {
throw redirect(
path.to.companies,
diff --git a/apps/erp/app/routes/x+/settings+/companies.new.tsx b/apps/erp/app/routes/x+/settings+/companies.new.tsx
index 7d2908bc97..ad16a6b9bc 100644
--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx
@@ -9,6 +9,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { enableAuditLog } from "@carbon/ee/audit.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import {
Modal,
ModalBody,
@@ -31,9 +32,11 @@ import {
} from "~/modules/settings";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "settings-companies-new");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId, email } = await requirePermissions(request, {
+ const { companyGroupId, userId, email } = await requirePermissions(request, {
create: "settings"
});
@@ -58,6 +61,28 @@ export async function action({ request }: ActionFunctionArgs) {
const client = getCarbonServiceRole();
+ // seed-company joins the new company to its parent's group, so a parent id
+ // from another group would place it inside another tenant's group.
+ if (parentCompanyId) {
+ const parent = await client
+ .from("company")
+ .select("id")
+ .eq("id", parentCompanyId)
+ .eq("companyGroupId", companyGroupId)
+ .maybeSingle();
+ if (parent.error || !parent.data) {
+ logger.error("Parent company not found in the caller's company group", {
+ companyGroupId,
+ parentCompanyId,
+ error: parent.error
+ });
+ throw redirect(
+ path.to.companies,
+ await flash(request, error(parent.error, "Parent company not found"))
+ );
+ }
+ }
+
const companyInsert = await insertCompany(client, {
...locationData,
baseCurrencyCode
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index f28399f14d..5940663497 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -46,7 +46,11 @@ import {
getIntegrationServerHooks,
onshapeConnectionHasWriteScope
} from "@carbon/ee/hooks.server";
-import { getPath, SECRET_KEYS } from "@carbon/ee/integrations/secrets";
+import {
+ getPath,
+ SECRET_KEYS,
+ WEBHOOK_SIGNING_SECRET_KEY
+} from "@carbon/ee/integrations/secrets";
import { isIntegrationWhitelisted } from "@carbon/ee/plan";
import { requireFeature } from "@carbon/ee/plan.server";
import { STRIPE_SECRET_KEY } from "@carbon/env";
@@ -1648,10 +1652,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
]);
if (FORM_SECRET_INTEGRATIONS.has(integrationId)) {
const alreadyVaulted = existing.data?.secretRef != null;
- const providedSecret = (SECRET_KEYS[integrationId] ?? []).some((p) => {
- const v = getPath(metadata, p);
- return typeof v === "string" && v.trim().length > 0;
- });
+ // The optional webhook signing secret is not a credential: it must not
+ // satisfy the "a credential is required" check on its own.
+ const providedSecret = (SECRET_KEYS[integrationId] ?? [])
+ .filter((p) => p !== WEBHOOK_SIGNING_SECRET_KEY)
+ .some((p) => {
+ const v = getPath(metadata, p);
+ return typeof v === "string" && v.trim().length > 0;
+ });
if (!alreadyVaulted && !providedSecret) {
return data(
{},
diff --git a/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts b/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts
index d5a1a9c15a..6fb453dd9f 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts
+++ b/apps/erp/app/routes/x+/settings+/integrations.oauth-state.test.ts
@@ -7,7 +7,12 @@ vi.mock("@carbon/auth", () => ({ error: vi.fn() }));
vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions }));
vi.mock("@carbon/auth/session.server", () => ({ flash: vi.fn() }));
vi.mock("@carbon/ee", () => ({
- integrations: [],
+ integrations: [
+ { id: "ramp", oauth: { clientId: "ramp-client" } },
+ { id: "xero", oauth: { clientId: "xero-client" } },
+ // Slack and Onshape start their flows elsewhere (no `oauth` config).
+ { id: "slack" }
+ ],
quickInstallConnectors: []
}));
vi.mock("@carbon/react", () => ({ toast: { error: vi.fn() } }));
@@ -28,7 +33,7 @@ vi.mock("~/utils/path", () => ({
import { loader } from "./integrations";
describe("integrations OAuth state loader", () => {
- it("issues a server-bound Ramp state and sends its signed cookie", async () => {
+ it("issues a server-bound state per OAuth integration in one signed cookie", async () => {
requirePermissions.mockResolvedValue({
client: {},
userId: "user-1",
@@ -44,9 +49,17 @@ describe("integrations OAuth state loader", () => {
init?: { headers?: HeadersInit };
};
- expect(result.data?.oauthStates?.ramp).toMatch(
- /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+ const uuid =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+ expect(result.data?.oauthStates?.ramp).toMatch(uuid);
+ expect(result.data?.oauthStates?.xero).toMatch(uuid);
+ expect(result.data?.oauthStates?.ramp).not.toBe(
+ result.data?.oauthStates?.xero
);
+ expect(Object.keys(result.data?.oauthStates ?? {})).toEqual([
+ "ramp",
+ "xero"
+ ]);
expect(new Headers(result.init?.headers).get("Set-Cookie")).toContain(
"carbon-oauth-state="
);
diff --git a/apps/erp/app/routes/x+/settings+/integrations.tsx b/apps/erp/app/routes/x+/settings+/integrations.tsx
index e2d7d04e59..5d142bdab7 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.tsx
@@ -1,6 +1,6 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { issueOAuthState } from "@carbon/auth/oauth-state.server";
+import { issueOAuthStates } from "@carbon/auth/oauth-state.server";
import { flash } from "@carbon/auth/session.server";
import {
integrations as availableIntegrations,
@@ -48,21 +48,26 @@ export async function loader({ request }: LoaderFunctionArgs) {
health: i.health
}));
- const rampOAuthState = await issueOAuthState({
- integrationId: "ramp",
- userId,
- companyId
- });
+ // Every integration whose Connect button builds an authorize URL
+ // (IntegrationCard) gets a single-use state bound to this browser, user and
+ // company; its OAuth callback consumes it with `consumeOAuthState`.
+ const oauthStates = await issueOAuthStates(
+ request,
+ availableIntegrations
+ .filter((integration) => "oauth" in integration && !!integration.oauth)
+ .map((integration) => ({
+ integrationId: integration.id,
+ userId,
+ companyId
+ }))
+ );
return data(
{
integrations: items,
- // Existing OAuth callbacks still receive a server-generated correlation
- // value. Ramp uses the browser-bound, single-use value below.
- state: crypto.randomUUID(),
- oauthStates: { ramp: rampOAuthState.state }
+ oauthStates: oauthStates.states
},
- { headers: { "Set-Cookie": rampOAuthState.cookie } }
+ { headers: { "Set-Cookie": oauthStates.cookie } }
);
}
diff --git a/apps/erp/app/routes/x+/settings+/people.tsx b/apps/erp/app/routes/x+/settings+/people.tsx
index e55637bb5c..d93dc9f0ad 100644
--- a/apps/erp/app/routes/x+/settings+/people.tsx
+++ b/apps/erp/app/routes/x+/settings+/people.tsx
@@ -34,6 +34,7 @@ import { redirect, useFetcher, useLoaderData } from "react-router";
import { UpgradeOverlayUpgradeButton } from "~/components/UpgradeOverlay";
import { usePlanGate } from "~/hooks/usePlanGate";
import { getCompanySettings, updateTimeCardSetting } from "~/modules/settings";
+import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -90,6 +91,7 @@ export async function action({ request }: ActionFunctionArgs) {
const update = await updateConsoleSetting(
client,
+ getDatabaseClient(),
companyId,
enabled,
userId
@@ -97,23 +99,22 @@ export async function action({ request }: ActionFunctionArgs) {
if (update.error) return { success: false, message: update.error.message };
- // Check if a PIN was auto-generated for the user
- if (enabled) {
- const userPin = await client
- .from("employee")
- .select("pin" as any)
- .eq("id", userId)
- .eq("companyId", companyId)
- .maybeSingle();
+ // A PIN generated for the enabling user is returned ONCE here — it is
+ // stored hashed and can never be read back.
+ if (update.pin) {
+ return {
+ success: true,
+ message: "Console mode enabled",
+ pin: update.pin
+ };
+ }
- const pin = (userPin.data as any)?.pin;
- if (pin) {
- return {
- success: true,
- message: "Console mode enabled",
- pin
- };
- }
+ // Console mode is on; only the enabling user's PIN is missing.
+ if (update.pinError) {
+ return {
+ success: false,
+ message: `Console mode enabled, but ${update.pinError.toLowerCase()}. Set one from Users → Employees → Set Console PIN.`
+ };
}
return { success: true, message: "Console mode settings updated" };
@@ -299,8 +300,8 @@ export default function PeopleSettingsRoute() {
</div>
<p className="text-xs text-muted-foreground text-center">
<Trans>
- Remember this PIN. You will need it to exit console mode on
- MES terminals.
+ This PIN will not be shown again. You will need it to exit
+ console mode on MES terminals.
</Trans>
</p>
</VStack>
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index 44f45a20db..73d8d06c52 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -64,7 +64,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
.eq("id", shipmentId)
// Service-role read: companyId scope is not backstopped by RLS here.
.eq("companyId", companyId)
- .single();
+ .maybeSingle();
+
+ // Everything below reads through the service role by shipmentId (the
+ // packing slip included), so a shipment outside this company stops here.
+ if (!shipmentForSurface) {
+ logger.error("Shipment not found for company", { companyId, shipmentId });
+ throw redirect(
+ path.to.shipments,
+ await flash(request, error(null, "Shipment not found"))
+ );
+ }
+
const surfaces: ("shipment" | "warehouseTransfer")[] = ["shipment"];
if (shipmentForSurface?.sourceDocument === "Outbound Transfer") {
surfaces.push("warehouseTransfer");
@@ -271,6 +282,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("shipment")
.select("sourceDocument, sourceDocumentId, shipmentId")
.eq("id", shipmentId)
+ .eq("companyId", companyId)
.single();
// If the shipment is related to a sales order, save the packing slip PDF
@@ -284,6 +296,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("salesOrder")
.select("opportunityId")
.eq("id", shipment.sourceDocumentId)
+ .eq("companyId", companyId)
.single();
if (salesOrder?.opportunityId) {
@@ -370,6 +383,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.from("shipment")
.select("locationId")
.eq("id", shipmentId)
+ .eq("companyId", companyId)
.single();
const locationId = shipmentForPrint?.locationId as string | undefined;
if (locationId) {
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
index 346b065295..f14f243dae 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
@@ -65,7 +65,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.select(
"id, salesOrderLineId, shipped, serialNumber, salesOrderLine:salesOrderLineId(assetId, description, fixedAsset:assetId(name, fixedAssetId, serialNumber))"
)
- .eq("shipmentId", shipmentId);
+ .eq("shipmentId", shipmentId)
+ .eq("companyId", companyId);
fixedAssetLines = (faLineRecords.data ?? [])
.filter((row) => {
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
index 2983720b51..d0663693ec 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
@@ -20,6 +20,7 @@ import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { supplierApprovalDecisionValidator } from "~/modules/purchasing";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
@@ -34,6 +35,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { supplierId } = params;
if (!supplierId) throw new Error("Could not find supplierId");
+ // Approval requests, their lookups and the approve/reject status writes all
+ // go through the service role (or Kysely) keyed on the URL's supplierId.
+ await requireCompanyRecord(getCarbonServiceRole(), "supplier", companyId, {
+ id: supplierId
+ });
+
const formData = await request.formData();
const intent = formData.get("intent");
@@ -163,7 +170,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
supplierId
);
- if (!approvalRequest.data || approvalRequest.data.id !== approvalRequestId) {
+ if (
+ !approvalRequest.data ||
+ approvalRequest.data.id !== approvalRequestId ||
+ approvalRequest.data.companyId !== companyId
+ ) {
throw redirect(
path.to.supplier(supplierId),
await flash(request, error(null, "Approval request not found"))
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
index 68a928fb72..3e769f35b0 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
@@ -13,6 +13,7 @@ import {
supplierContactValidator
} from "~/modules/purchasing";
import SupplierContactForm from "~/modules/purchasing/ui/Supplier/SupplierContactForm";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
import { supplierContactsQuery } from "~/utils/react-query";
@@ -43,6 +44,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { id, contactId, supplierLocationId, ...contact } = validation.data;
+ // The contact is written through the service role: the supplier in the URL
+ // (and the location on the form) must belong to this company.
+ await Promise.all([
+ requireCompanyRecord(client, "supplier", companyId, { id: supplierId }),
+ supplierLocationId
+ ? requireCompanyRecord(client, "supplierLocation", companyId, {
+ id: supplierLocationId,
+ supplierId
+ })
+ : null
+ ]);
+
const createSupplierContact = await insertSupplierContact(client, {
supplierId,
companyId,
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.$lineId.details.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.$lineId.details.tsx
index 27dbcde50b..c273cc08f0 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.$lineId.details.tsx
@@ -1,8 +1,9 @@
-import { assertIsPost, error } from "@carbon/auth";
+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 { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { useRouteData } from "@carbon/react";
import { Fragment } from "react";
@@ -35,6 +36,8 @@ import { setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "supplier-quote-line-details");
+
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { companyId } = await requirePermissions(request, {
view: "purchasing"
@@ -58,6 +61,17 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
);
}
+ // The service role bypasses RLS and lineId comes from the URL: the line must
+ // belong to this company and to the quote in the URL.
+ if (line.data.companyId !== companyId || line.data.supplierQuoteId !== id) {
+ logger.error("Supplier quote line not found for company", {
+ companyId,
+ supplierQuoteId: id,
+ lineId
+ });
+ throw notFound("Supplier quote line not found");
+ }
+
return {
line: line.data,
files: getSupplierInteractionLineDocuments(serviceRole, companyId, lineId),
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 db9bb13a38..65df5cc6f3 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
@@ -60,6 +60,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
isApprovalRequired(serviceRole, "supplier", companyId)
]);
+ // The service role bypasses RLS and id comes from the URL.
+ if (!quote.data || quote.data.companyId !== companyId) {
+ logger.error("Supplier quote not found for company", {
+ companyId,
+ supplierQuoteId: id,
+ error: quote.error
+ });
+ throw redirect(
+ path.to.supplierQuotes,
+ await flash(request, error(null, "Supplier quote not found"))
+ );
+ }
+
if (supplierApprovalRequired && quote.data?.supplierId) {
const supplier = await getSupplier(serviceRole, quote.data.supplierId);
if (supplier.data?.status !== "Active") {
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
index 42730b8134..dd9fa81002 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
@@ -11,6 +11,7 @@ import {
getSupplierQuoteLines
} from "~/modules/purchasing";
import { upsertExternalLink } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { path } from "~/utils/path";
const logger = getLogger("erp", "id-finalize");
@@ -28,6 +29,10 @@ export async function action(args: ActionFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find supplier quote id");
+ // bypassRls hands back the service role and every read/write below is keyed
+ // on the URL's id.
+ await requireCompanyRecord(client, "supplierQuote", companyId, { id });
+
const quote = await getSupplierQuote(client, id);
if (quote.error) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx
index 1d1eb59af0..9db1e759e2 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx
@@ -4,34 +4,33 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { updateSupplierQuoteLineOrder } from "~/modules/purchasing";
+import { parseSortOrderUpdates } from "~/modules/shared/sort-order";
import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "purchasing"
});
if (!params.id) throw new Error("Could not find id");
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
+ const updates = parseSortOrderUpdates(await request.formData());
+ if (!updates) {
return data(
{ success: false },
await flash(request, error(null, "Failed to receive a new sort order"))
);
}
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, sortOrderString]) => ({
- id,
- sortOrder: Number(sortOrderString),
- updatedBy: userId
- })
- );
-
try {
- await updateSupplierQuoteLineOrder(getDatabaseClient(), updates);
+ await updateSupplierQuoteLineOrder(
+ getDatabaseClient(),
+ companyId,
+ userId,
+ params.id,
+ updates
+ );
} catch (err) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.new.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.new.tsx
index a910ff5c7b..b8d0344b2b 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.new.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.new.tsx
@@ -11,6 +11,7 @@ import {
supplierQuoteLineValidator,
upsertSupplierQuoteLine
} from "~/modules/purchasing";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -48,8 +49,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...d } = validation.data;
const serviceRole = getCarbonServiceRole();
+
+ // The line is written through the service role: the quote in the URL and
+ // the item on the form must belong to this company, and the line is always
+ // attached to the URL's quote rather than the form's copy.
+ await Promise.all([
+ requireCompanyRecord(serviceRole, "supplierQuote", companyId, {
+ id: supplierQuoteId
+ }),
+ d.itemId
+ ? requireCompanyRecord(serviceRole, "item", companyId, { id: d.itemId })
+ : null
+ ]);
+
const createQuotationLine = await upsertSupplierQuoteLine(serviceRole, {
...d,
+ supplierQuoteId,
companyId,
createdBy: userId,
customFields: setCustomFields(formData)
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
index e38e163d77..69c5169a3f 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
@@ -18,6 +18,7 @@ import {
} from "~/modules/purchasing";
import { getCompany } from "~/modules/settings";
import { upsertExternalLink } from "~/modules/shared";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { getUser } from "~/modules/users/users.server";
import { path } from "~/utils/path";
@@ -36,6 +37,10 @@ export async function action(args: ActionFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find supplier quote id");
+ // bypassRls hands back the service role and every read/write below is keyed
+ // on the URL's id.
+ await requireCompanyRecord(client, "supplierQuote", companyId, { id });
+
const quote = await getSupplierQuote(client, id);
if (quote.error) {
throw redirect(
@@ -101,7 +106,7 @@ export async function action(args: ActionFunctionArgs) {
const [company, supplierContact, supplierQuote, user] =
await Promise.all([
getCompany(client, companyId),
- getSupplierContact(client, supplierContactId),
+ getSupplierContact(client, supplierContactId, companyId),
getSupplierQuote(client, id),
getUser(client, userId)
]);
diff --git a/apps/erp/app/routes/x+/supplier-quote+/new.tsx b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
index f0eda89121..4dfb98c34f 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/new.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
@@ -11,6 +11,7 @@ import {
supplierQuoteValidator
} from "~/modules/purchasing";
import { SupplierQuoteForm } from "~/modules/purchasing/ui/SupplierQuote";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -38,6 +39,24 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, ...data } = validation.data;
+ // bypassRls hands back the service role: the supplier (and its contact and
+ // location) on the form must belong to this company.
+ await Promise.all([
+ requireCompanyRecord(client, "supplier", companyId, {
+ id: data.supplierId
+ }),
+ data.supplierContactId
+ ? requireCompanyRecord(client, "supplierContact", companyId, {
+ id: data.supplierContactId
+ })
+ : null,
+ data.supplierLocationId
+ ? requireCompanyRecord(client, "supplierLocation", companyId, {
+ id: data.supplierLocationId
+ })
+ : null
+ ]);
+
const result = await insertSupplierQuote(client, {
...data,
supplierQuoteId: data.supplierQuoteId || undefined,
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
index e40b274739..670ccf27b7 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx
@@ -177,7 +177,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -209,6 +209,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
defaultStorageUnitId: pickMethodFields.defaultStorageUnitId,
sortMethod: pickMethodFields.sortMethod,
customFields: setCustomFields(formData),
+ companyId,
userId,
shelfLife: {
mode: shelfLifeMode,
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
index 30d14f4365..7a92975a58 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
@@ -101,6 +101,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
await trx
.deleteFrom("supplierPartPrice")
.where("supplierPartId", "=", supplierPartId)
+ .where("companyId", "=", companyId)
.execute();
if (priceBreaks.length > 0) {
await trx
diff --git a/apps/erp/app/routes/x+/traceability+/graph.tsx b/apps/erp/app/routes/x+/traceability+/graph.tsx
index 099b9005ba..b5131b61cf 100644
--- a/apps/erp/app/routes/x+/traceability+/graph.tsx
+++ b/apps/erp/app/routes/x+/traceability+/graph.tsx
@@ -29,6 +29,7 @@ import { useTraceabilityStore } from "~/modules/inventory/ui/Traceability/store"
import { TraceabilityGraph } from "~/modules/inventory/ui/Traceability/TraceabilityGraph";
import { TraceabilitySidebar } from "~/modules/inventory/ui/Traceability/TraceabilitySidebar";
import { stateEntityId } from "~/modules/inventory/ui/Traceability/utils";
+import { requireCompanyRecord } from "~/modules/shared/shared.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -43,7 +44,7 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory",
bypassRls: true
});
@@ -59,6 +60,25 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw redirect(path.to.traceability);
}
+ // bypassRls makes `client` the service role and the lineage reads below are
+ // not company-scoped, so every root id from the query string must be proven
+ // to be this company's first.
+ await Promise.all([
+ trackedEntityId
+ ? requireCompanyRecord(client, "trackedEntity", companyId, {
+ id: trackedEntityId
+ })
+ : null,
+ jobId
+ ? requireCompanyRecord(client, "job", companyId, { id: jobId })
+ : null,
+ trackedActivityId
+ ? requireCompanyRecord(client, "trackedActivity", companyId, {
+ id: trackedActivityId
+ })
+ : null
+ ]);
+
if (trackedEntityId) {
let payload = await fetchLineageSubgraph(
client,
diff --git a/apps/erp/app/routes/x+/training+/$id.tsx b/apps/erp/app/routes/x+/training+/$id.tsx
index 25ff793534..066bd1cfb6 100644
--- a/apps/erp/app/routes/x+/training+/$id.tsx
+++ b/apps/erp/app/routes/x+/training+/$id.tsx
@@ -1,6 +1,7 @@
import { error, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { generateHTML, Input, useDebounce } from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
@@ -28,6 +29,8 @@ import type { action } from "~/routes/x+/training+/update";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "training-detail");
+
export const handle: Handle = {
breadcrumb: detailBreadcrumb(
{ breadcrumb: msg`Training`, to: path.to.trainings },
@@ -57,6 +60,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // bypassRls makes `client` the service role, so the URL id is only proven to
+ // exist — not to be this company's.
+ if (training.data.companyId !== companyId) {
+ logger.error("Training is not in the caller's company", {
+ companyId,
+ trainingId: id
+ });
+ throw redirect(path.to.trainings);
+ }
+
return {
training: training.data,
tags: tags.data ?? []
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 ffd0c1d120..f2ea26604b 100644
--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
@@ -1,9 +1,11 @@
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 { requireFeature } from "@carbon/ee/plan.server";
import { validationError, validator } from "@carbon/form";
import { batchTrigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -12,6 +14,8 @@ import {
} from "~/modules/users";
import { getParams, path } from "~/utils/path";
+const logger = getLogger("erp", "users-bulk-edit-permissions");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
@@ -57,6 +61,26 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // The job writes these users' grants as the service role: every id must be
+ // an employee of this company. One batched read.
+ const uniqueUserIds = [...new Set(userIds)];
+ const members = await getCarbonServiceRole()
+ .from("employee")
+ .select("id")
+ .in("id", uniqueUserIds)
+ .eq("companyId", companyId);
+ if (members.error || (members.data ?? []).length !== uniqueUserIds.length) {
+ logger.error("Bulk permission edit names users outside the company", {
+ companyId,
+ userIds: uniqueUserIds,
+ error: members.error
+ });
+ throw redirect(
+ path.to.employeeAccounts,
+ await flash(request, error(members.error, "Employee not found"))
+ );
+ }
+
const ip = request.headers.get("x-forwarded-for") ?? undefined;
const batchPayload = userIds.map((id) => ({
diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsx
index 647053e612..5eb53881a9 100644
--- a/apps/erp/app/routes/x+/users+/customers.new.tsx
+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx
@@ -32,7 +32,7 @@ const logger = getLogger("erp", "customers-new");
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- view: "users"
+ create: "users"
});
const validation = await validator(createCustomerAccountValidator).validate(
diff --git a/apps/erp/app/routes/x+/users+/operators.new.tsx b/apps/erp/app/routes/x+/users+/operators.new.tsx
index d1c23a617f..c688eb4d44 100644
--- a/apps/erp/app/routes/x+/users+/operators.new.tsx
+++ b/apps/erp/app/routes/x+/users+/operators.new.tsx
@@ -1,13 +1,14 @@
-import { assertIsPost, error, success } from "@carbon/auth";
+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 { generateConsolePin, setEmployeePin } from "@carbon/ee/console.server";
import { ValidatedForm, validationError, validator } from "@carbon/form";
import { getLogger } from "@carbon/logger";
import {
+ Button,
+ Copy,
HStack,
- IconButton,
- Label,
Modal,
ModalBody,
ModalContent,
@@ -18,25 +19,18 @@ import {
VStack
} from "@carbon/react";
import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
-import { useLingui } from "@lingui/react/macro";
-import { useState } from "react";
-import { LuCheck, LuCopy, LuRefreshCw } from "react-icons/lu";
+import { Trans, useLingui } from "@lingui/react/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useNavigate } from "react-router";
import { Input, Location, Submit } from "~/components/Form";
import { useUser } from "~/hooks";
import { createOperatorValidator } from "~/modules/users/users.models";
import { createConsoleOperator } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
+import { path } from "~/utils/path";
const logger = getLogger("erp", "operators-new");
-function generatePin(): string {
- return Math.floor(1000 + Math.random() * 9000).toString();
-}
-
-import type { Result } from "~/types";
-import { path } from "~/utils/path";
-
export async function loader({ request }: LoaderFunctionArgs) {
await requirePermissions(request, { create: "users" });
return null;
@@ -56,7 +50,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { firstName, lastName, locationId, pin } = validation.data;
+ const { firstName, lastName, locationId } = validation.data;
// Auto-assign Console Operator employee type
const serviceRole = getCarbonServiceRole();
@@ -99,127 +93,152 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- // Set PIN if provided (employee record is already created by createConsoleOperator)
- if (pin) {
- const pinUpdate = await serviceRole
- .from("employee")
- .update({ pin } as any)
- .eq("id", result.userId)
- .eq("companyId", companyId);
-
- if (pinUpdate.error) {
- logger.error("Failed to set PIN for operator:", pinUpdate.error);
- }
+ // The PIN is generated HERE, on the server, and stored only as a hash — the
+ // action returns it so the modal can show it to the admin exactly once.
+ const pin = generateConsolePin();
+ try {
+ await setEmployeePin(getDatabaseClient(), {
+ employeeId: result.userId,
+ companyId,
+ pin,
+ updatedBy: userId
+ });
+ } catch (err) {
+ logger.error("Failed to set PIN for operator", {
+ companyId,
+ operatorId: result.userId,
+ error: err
+ });
+ await updateSubscriptionQuantityForCompany(companyId);
+ throw redirect(
+ path.to.operators,
+ await flash(
+ request,
+ error(
+ err,
+ "Operator created, but the PIN could not be set. Use Reset PIN."
+ )
+ )
+ );
}
await updateSubscriptionQuantityForCompany(companyId);
- throw redirect(
- path.to.operators,
- await flash(request, success("Console operator created successfully"))
- );
+ return { success: true as const, pin, name: result.name };
}
export default function NewOperatorRoute() {
const { t } = useLingui();
const { defaults } = useUser();
const navigate = useNavigate();
- const formFetcher = useFetcher<Result>();
- const [pinValue, setPinValue] = useState(generatePin);
- const [copied, setCopied] = useState(false);
+ const formFetcher = useFetcher<typeof action>();
+ const created =
+ formFetcher.data && "pin" in formFetcher.data ? formFetcher.data : null;
return (
<Modal
open
onOpenChange={(open) => {
- if (!open) navigate(-1);
+ if (open) return;
+ if (created) navigate(path.to.operators);
+ else navigate(-1);
}}
>
<ModalOverlay />
<ModalContent>
- <ValidatedForm
- method="post"
- action={path.to.newOperator}
- validator={createOperatorValidator}
- defaultValues={{
- locationId: defaults?.locationId ?? undefined,
- pin: pinValue
- }}
- fetcher={formFetcher}
- className="flex flex-col h-full"
- >
- <ModalHeader>
- <ModalTitle>Add Console Operator</ModalTitle>
- </ModalHeader>
-
- <ModalBody>
- <VStack spacing={4}>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
- <Input name="firstName" label={t`First Name`} />
- <Input name="lastName" label={t`Last Name`} />
- </div>
- <Location name="locationId" label={t`Location`} />
- <div className="space-y-2 w-full">
- <Label htmlFor="pin">PIN</Label>
- <HStack>
- <Input
- name="pin"
- value={pinValue}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
- const val = e.target.value.replace(/\D/g, "").slice(0, 4);
- setPinValue(val);
- }}
- maxLength={4}
- inputMode="numeric"
- className="font-mono text-lg tracking-[0.3em] text-center"
- />
- <IconButton
- type="button"
- variant="outline"
- size="sm"
- aria-label={t`Copy PIN`}
- icon={
- copied ? (
- <LuCheck className="text-emerald-500" />
- ) : (
- <LuCopy />
- )
- }
- onClick={() => {
- navigator.clipboard.writeText(pinValue);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }}
- />
- <IconButton
- type="button"
- variant="outline"
- size="sm"
- aria-label={t`Generate new PIN`}
- icon={<LuRefreshCw />}
- onClick={() => {
- const newPin = generatePin();
- setPinValue(newPin);
- setCopied(false);
- }}
- />
- </HStack>
+ {created ? (
+ <CreatedOperatorPin
+ name={created.name}
+ pin={created.pin}
+ onDone={() => navigate(path.to.operators)}
+ />
+ ) : (
+ <ValidatedForm
+ method="post"
+ action={path.to.newOperator}
+ validator={createOperatorValidator}
+ defaultValues={{
+ locationId: defaults?.locationId ?? undefined
+ }}
+ fetcher={formFetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Add Console Operator</Trans>
+ </ModalTitle>
+ </ModalHeader>
+
+ <ModalBody>
+ <VStack spacing={4}>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <Input name="firstName" label={t`First Name`} />
+ <Input name="lastName" label={t`Last Name`} />
+ </div>
+ <Location name="locationId" label={t`Location`} />
<p className="text-xs text-muted-foreground">
- Share this PIN with the operator so they can pin in at MES
- terminals.
+ <Trans>
+ A 4-digit PIN is generated when the operator is created.
+ </Trans>
</p>
- </div>
- </VStack>
- </ModalBody>
- <ModalFooter>
- <HStack>
- <Submit isLoading={formFetcher.state !== "idle"}>
- Create Operator
- </Submit>
- </HStack>
- </ModalFooter>
- </ValidatedForm>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Submit isLoading={formFetcher.state !== "idle"}>
+ <Trans>Create Operator</Trans>
+ </Submit>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ )}
</ModalContent>
</Modal>
);
}
+
+function CreatedOperatorPin({
+ name,
+ pin,
+ onDone
+}: {
+ name: string;
+ pin: string;
+ onDone: () => void;
+}) {
+ return (
+ <>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Console Operator Created</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Share this PIN with {name} so they can pin in at MES terminals.
+ </Trans>
+ </p>
+ <div className="flex items-center justify-center gap-3 w-full">
+ <span className="font-mono text-3xl tracking-[0.4em]">{pin}</span>
+ <Copy text={pin} />
+ </div>
+ <p className="text-xs text-muted-foreground text-center w-full">
+ <Trans>
+ This PIN will not be shown again. If it is lost, reset it from the
+ operators list.
+ </Trans>
+ </p>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button onClick={onDone}>
+ <Trans>Done</Trans>
+ </Button>
+ </HStack>
+ </ModalFooter>
+ </>
+ );
+}
diff --git a/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx b/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx
index 90cb22ddf4..e921c5d5e7 100644
--- a/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx
+++ b/apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx
@@ -1,16 +1,12 @@
-import { assertIsPost, error, success } from "@carbon/auth";
+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 { generateConsolePin, setEmployeePin } from "@carbon/ee/console.server";
+import { getLogger } from "@carbon/logger";
import {
Button,
Copy,
HStack,
- IconButton,
- InputOTP,
- InputOTPGroup,
- InputOTPSlot,
- Label,
Modal,
ModalBody,
ModalContent,
@@ -20,27 +16,28 @@ import {
ModalTitle,
VStack
} from "@carbon/react";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { useState } from "react";
-import { LuRefreshCw } from "react-icons/lu";
+import { Trans } from "@lingui/react/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useFetcher, useLoaderData, useNavigate } from "react-router";
-import type { Result } from "~/types";
+import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
-function generatePin(): string {
- return Math.floor(1000 + Math.random() * 9000).toString();
-}
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, { update: "users" });
+const logger = getLogger("erp", "operators-reset-pin");
- const { operatorId } = params;
- if (!operatorId) throw new Error("Operator ID is required");
+/**
+ * A PIN pins in as that person at any MES console, so resetting one hands over
+ * their shop-floor identity. `users_update` covers console operators (PIN-only
+ * accounts made for exactly this); anyone else — an admin included — also
+ * needs `settings_update`, the permission that turns console mode on.
+ */
+async function requireResetPinPermission(request: Request, operatorId: string) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "users"
+ });
const user = await client
.from("user")
- .select("id, firstName, lastName")
+ .select("id, firstName, lastName, isConsoleOperator")
.eq("id", operatorId)
.single();
@@ -51,54 +48,76 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- return { operator: user.data };
-}
+ if (!user.data.isConsoleOperator) {
+ await requirePermissions(request, { update: "settings" });
+ }
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { companyId } = await requirePermissions(request, {
- update: "users"
- });
+ return { companyId, userId, operator: user.data };
+}
+export async function loader({ request, params }: LoaderFunctionArgs) {
const { operatorId } = params;
if (!operatorId) throw new Error("Operator ID is required");
- const formData = await request.formData();
- const newPin = formData.get("pin") as string;
+ const { operator } = await requireResetPinPermission(request, operatorId);
+ return {
+ operator: {
+ id: operator.id,
+ firstName: operator.firstName,
+ lastName: operator.lastName
+ }
+ };
+}
- if (!newPin || !/^\d{4}$/.test(newPin)) {
- return { success: false, message: "PIN must be 4 digits" };
- }
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { operatorId } = params;
+ if (!operatorId) throw new Error("Operator ID is required");
- const serviceRole = getCarbonServiceRole();
- const update = await serviceRole
- .from("employee")
- .update({ pin: newPin } as any)
- .eq("id", operatorId)
- .eq("companyId", companyId);
+ const { companyId, userId } = await requireResetPinPermission(
+ request,
+ operatorId
+ );
- if (update.error) {
- return { success: false, message: update.error.message };
+ // Generated on the server and stored only as a hash (the (employee, company)
+ // FK refuses an operator outside this company). Returned so the modal can
+ // show it once — it cannot be read back later.
+ const pin = generateConsolePin();
+ try {
+ await setEmployeePin(getDatabaseClient(), {
+ employeeId: operatorId,
+ companyId,
+ pin,
+ updatedBy: userId
+ });
+ } catch (err) {
+ logger.error("Failed to reset operator PIN", {
+ companyId,
+ operatorId,
+ error: err
+ });
+ return { success: false as const, message: "Failed to reset PIN" };
}
- throw redirect(
- path.to.operators,
- await flash(request, success("PIN reset successfully"))
- );
+ return { success: true as const, pin };
}
export default function ResetPinRoute() {
const { operator } = useLoaderData<typeof loader>();
const navigate = useNavigate();
- const formFetcher = useFetcher<Result>();
- const [pinValue, setPinValue] = useState(generatePin);
- const { t } = useLingui();
+ const formFetcher = useFetcher<typeof action>();
+ const newPin =
+ formFetcher.data?.success === true ? formFetcher.data.pin : null;
+ const failure =
+ formFetcher.data?.success === false ? formFetcher.data.message : null;
return (
<Modal
open
onOpenChange={(open) => {
- if (!open) navigate(-1);
+ if (open) return;
+ if (newPin) navigate(path.to.operators);
+ else navigate(-1);
}}
>
<ModalOverlay />
@@ -113,57 +132,56 @@ export default function ResetPinRoute() {
</ModalHeader>
<ModalBody>
- <VStack spacing={4}>
- <p className="text-sm text-muted-foreground">
- <Trans>
- Generate a new 4-digit PIN. Share it with the operator so they
- can pin in at MES terminals.
- </Trans>
- </p>
- <div className="space-y-2 w-full">
- <Label>
- <Trans>New PIN</Trans>
- </Label>
- <div className="flex items-center justify-center gap-3">
- <input type="hidden" name="pin" value={pinValue} />
- <InputOTP
- maxLength={4}
- value={pinValue}
- onChange={(value) => setPinValue(value)}
- autoFocus={false}
- >
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- </InputOTPGroup>
- </InputOTP>
- <Copy text={pinValue} size="sm" />
- <IconButton
- type="button"
- variant="outline"
- size="sm"
- aria-label={t`Generate new PIN`}
- icon={<LuRefreshCw />}
- onClick={() => {
- const newPin = generatePin();
- setPinValue(newPin);
- }}
- />
+ {newPin ? (
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Share this PIN with the operator so they can pin in at MES
+ terminals.
+ </Trans>
+ </p>
+ <div className="flex items-center justify-center gap-3 w-full">
+ <span className="font-mono text-3xl tracking-[0.4em]">
+ {newPin}
+ </span>
+ <Copy text={newPin} />
</div>
- </div>
- </VStack>
+ <p className="text-xs text-muted-foreground text-center w-full">
+ <Trans>This PIN will not be shown again.</Trans>
+ </p>
+ </VStack>
+ ) : (
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Generate a new 4-digit PIN. The operator's current PIN stops
+ working immediately.
+ </Trans>
+ </p>
+ {failure && (
+ <p className="text-sm text-destructive">{failure}</p>
+ )}
+ </VStack>
+ )}
</ModalBody>
<ModalFooter>
<HStack>
- <Button
- type="submit"
- isLoading={formFetcher.state !== "idle"}
- isDisabled={formFetcher.state !== "idle" || pinValue.length < 4}
- >
- <Trans>Reset PIN</Trans>
- </Button>
+ {newPin ? (
+ <Button
+ type="button"
+ onClick={() => navigate(path.to.operators)}
+ >
+ <Trans>Done</Trans>
+ </Button>
+ ) : (
+ <Button
+ type="submit"
+ isLoading={formFetcher.state !== "idle"}
+ isDisabled={formFetcher.state !== "idle"}
+ >
+ <Trans>Reset PIN</Trans>
+ </Button>
+ )}
</HStack>
</ModalFooter>
</formFetcher.Form>
diff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsx
index a6ddc10992..9d7e082ea3 100644
--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx
+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx
@@ -32,7 +32,7 @@ const logger = getLogger("erp", "suppliers-new");
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- view: "users"
+ create: "users"
});
const validation = await validator(createSupplierAccountValidator).validate(
diff --git a/apps/erp/app/services/onboarding.server.ts b/apps/erp/app/services/onboarding.server.ts
index 7304becd31..679acc83ee 100644
--- a/apps/erp/app/services/onboarding.server.ts
+++ b/apps/erp/app/services/onboarding.server.ts
@@ -1,7 +1,11 @@
import { Readable } from "node:stream";
-import { CarbonEdition } from "@carbon/auth";
+import {
+ CarbonEdition,
+ getClaims,
+ makePermissionsFromClaims
+} from "@carbon/auth";
import type { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { Database } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { Edition } from "@carbon/utils";
@@ -121,6 +125,38 @@ async function startCompanyTemplate(
}
}
+/**
+ * Refuse unless `userId` is an employee of `companyId` holding settings_update
+ * there. Reads claims fresh from the database (not the Redis cache) so a
+ * company the caller created moments ago in a failed first attempt counts.
+ */
+async function assertCanUpdateCompany(
+ serviceRole: ServiceRole,
+ userId: string,
+ companyId: string
+): Promise<void> {
+ const rawClaims = await getClaims(serviceRole, userId, companyId);
+ const claims = rawClaims.error
+ ? null
+ : makePermissionsFromClaims(rawClaims.data as Json[]);
+
+ const allowed =
+ claims?.role === "employee" &&
+ (claims.permissions.settings?.update ?? []).includes(companyId);
+
+ if (!allowed) {
+ logger.error("Onboarding re-entry refused: caller cannot update company", {
+ userId,
+ companyId,
+ role: claims?.role ?? null,
+ error: rawClaims.error
+ });
+ throw new Response("You do not have permission to update this company", {
+ status: 403
+ });
+ }
+}
+
/**
* Insert-or-update the onboarding company, provision its data, and create the
* headquarters location plus the owner's employee job. Returns the companyId.
@@ -163,6 +199,14 @@ export async function provisionOnboardingCompany(
// Re-entry: a company + location already exist — just update them. No reseed.
if (company && location) {
+ // The re-entry target is simply the caller's first membership, and the
+ // writes below run with the service role: they overwrite the company
+ // profile and, for a template, wipe its business data. So the caller must
+ // hold the authority that editing company settings needs — an employee
+ // with settings_update — or any portal user / regular employee could
+ // rewrite the company by POSTing this step.
+ await assertCanUpdateCompany(serviceRole, userId, company.id!);
+
const [companyUpdate, locationUpdate] = await Promise.all([
updateCompany(serviceRole, company.id!, {
...companyData,
@@ -185,7 +229,9 @@ export async function provisionOnboardingCompany(
});
throw new Error("Fatal: failed to update location");
}
- // Re-entry still honours the template — the job refuses if items already exist.
+ // Re-entry still honours the template. The job snapshots the company and
+ // then WIPES its business data before seeding (revertible from the
+ // snapshot) — it no longer refuses a company that already has items.
await startCompanyTemplate(company.id!, userId, template);
return company.id!;
}
diff --git a/apps/erp/app/utils/supabase.test.ts b/apps/erp/app/utils/supabase.test.ts
index 5d8dc74259..405b8f36f1 100644
--- a/apps/erp/app/utils/supabase.test.ts
+++ b/apps/erp/app/utils/supabase.test.ts
@@ -42,6 +42,9 @@ describe("parseJobFilePath", () => {
it("rejects dot segments", () => {
expect(parseJobFilePath("co123/job/op456/../op789/file.png")).toBeNull();
expect(parseJobFilePath("co123/job/op456/./x/file.png")).toBeNull();
+ expect(parseJobFilePath("co123/job/../file.png")).toBeNull();
+ expect(parseJobFilePath("co123/job/op456/%2e%2e/file.png")).toBeNull();
+ expect(parseJobFilePath("co123/job/op456/..\\..\\x.png")).toBeNull();
});
it("rejects empty and undefined input", () => {
diff --git a/apps/erp/test/method-row-reparenting.test.ts b/apps/erp/test/method-row-reparenting.test.ts
new file mode 100644
index 0000000000..74cd48e518
--- /dev/null
+++ b/apps/erp/test/method-row-reparenting.test.ts
@@ -0,0 +1,201 @@
+import { createClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+
+// The method-row update helpers are called with a service-role client and a
+// form payload. The payload carries the row's parent ids (quote, line, job,
+// make method) and the tenant id; if those reach the UPDATE, a row can be
+// re-parented into another company's quote or job. Pin that they never do.
+
+// Same module-graph stubs as production.service.test.ts: glossary and the
+// onboarding content build Lingui `msg` descriptors at module load.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>
+ Array.isArray(strings)
+ ? strings.reduce(
+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),
+ ""
+ )
+ : String(strings)
+}));
+
+const { upsertJobMaterial, upsertJobOperation } = await import(
+ "~/modules/production/production.service"
+);
+const { upsertQuoteMaterial, upsertQuoteOperation } = await import(
+ "~/modules/sales/sales.service"
+);
+
+// The boundary is PostgREST's HTTP API: a REAL supabase-js client whose fetch
+// records the request it would have sent. The service code and supabase-js's
+// query building run for real; only the network is stubbed.
+type SentRequest = { method: string; url: URL; body: Record<string, unknown> };
+
+function recordingClient() {
+ const calls: {
+ table: string;
+ update: Record<string, unknown>;
+ filters: [string, unknown][];
+ }[] = [];
+ const fetchStub = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const sent: SentRequest = {
+ method: init?.method ?? "GET",
+ url: new URL(String(input)),
+ body: init?.body ? JSON.parse(String(init.body)) : {}
+ };
+ if (sent.method === "PATCH") {
+ calls.push({
+ table: sent.url.pathname.split("/").pop() ?? "",
+ update: sent.body,
+ // PostgREST filters: `?id=eq.qm1&companyId=eq.c1` (select is not one).
+ filters: [...sent.url.searchParams.entries()]
+ .filter(([key]) => key !== "select")
+ .map(([key, value]) => [key, value.replace(/^eq\./, "")])
+ });
+ }
+ return new Response(JSON.stringify({ id: "row" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" }
+ });
+ };
+ const client = createClient("http://localhost:54321", "anon-key", {
+ auth: { persistSession: false, autoRefreshToken: false },
+ global: { fetch: fetchStub as typeof fetch }
+ });
+ return { client: client as never, calls };
+}
+
+describe("method row updates cannot re-parent a row", () => {
+ it("upsertQuoteMaterial strips parent ids and scopes to the company", async () => {
+ const { client, calls } = recordingClient();
+ await upsertQuoteMaterial(client, {
+ id: "qm1",
+ quoteId: "victim-quote",
+ quoteLineId: "victim-line",
+ quoteMakeMethodId: "victim-method",
+ companyId: "c1",
+ updatedBy: "u1",
+ order: 1,
+ itemType: "Part",
+ methodType: "Pull from Inventory",
+ itemId: "item1",
+ kit: false,
+ description: "Bracket",
+ quantity: 1,
+ unitCost: 0,
+ unitCostSource: "system",
+ unitOfMeasureCode: "EA"
+ });
+
+ expect(calls).toHaveLength(1);
+ const [call] = calls;
+ for (const column of [
+ "id",
+ "quoteId",
+ "quoteLineId",
+ "quoteMakeMethodId",
+ "companyId"
+ ]) {
+ expect(call.update).not.toHaveProperty(column);
+ }
+ expect(call.filters).toEqual([
+ ["id", "qm1"],
+ ["companyId", "c1"]
+ ]);
+ });
+
+ it("upsertQuoteOperation strips parent ids and scopes to the company", async () => {
+ const { client, calls } = recordingClient();
+ await upsertQuoteOperation(client, {
+ id: "qo1",
+ quoteId: "victim-quote",
+ quoteLineId: "victim-line",
+ quoteMakeMethodId: "victim-method",
+ companyId: "c1",
+ updatedBy: "u1",
+ order: 1,
+ operationOrder: "After Previous",
+ operationType: "Process",
+ processId: "p1",
+ description: "Cut"
+ });
+
+ const [call] = calls;
+ for (const column of [
+ "id",
+ "quoteId",
+ "quoteLineId",
+ "quoteMakeMethodId",
+ "companyId"
+ ]) {
+ expect(call.update).not.toHaveProperty(column);
+ }
+ expect(call.filters).toEqual([
+ ["id", "qo1"],
+ ["companyId", "c1"]
+ ]);
+ });
+
+ it("upsertJobMaterial strips parent ids and scopes to the company", async () => {
+ const { client, calls } = recordingClient();
+ await upsertJobMaterial(client, {
+ id: "jm1",
+ jobId: "victim-job",
+ jobMakeMethodId: "victim-method",
+ companyId: "c1",
+ updatedBy: "u1",
+ description: "Bracket",
+ itemType: "Part",
+ methodType: "Pull from Inventory",
+ itemId: "item1",
+ kit: false,
+ order: 1,
+ quantity: 1,
+ requiresBatchTracking: false,
+ requiresSerialTracking: false,
+ unitCost: 0,
+ unitOfMeasureCode: "EA"
+ });
+
+ const [call] = calls;
+ for (const column of ["id", "jobId", "jobMakeMethodId", "companyId"]) {
+ expect(call.update).not.toHaveProperty(column);
+ }
+ expect(call.filters).toEqual([
+ ["id", "jm1"],
+ ["companyId", "c1"]
+ ]);
+ });
+
+ it("upsertJobOperation strips parent ids and scopes to the company", async () => {
+ const { client, calls } = recordingClient();
+ await upsertJobOperation(client, {
+ id: "jo1",
+ jobId: "victim-job",
+ jobMakeMethodId: "victim-method",
+ companyId: "c1",
+ updatedBy: "u1",
+ order: 1,
+ operationOrder: "After Previous",
+ operationType: "Process",
+ processId: "p1",
+ description: "Cut"
+ } as never);
+
+ const [call] = calls;
+ for (const column of ["id", "jobId", "jobMakeMethodId", "companyId"]) {
+ expect(call.update).not.toHaveProperty(column);
+ }
+ expect(call.filters).toEqual([
+ ["id", "jo1"],
+ ["companyId", "c1"]
+ ]);
+ });
+});
diff --git a/apps/mes/app/components/PinInOverlay.tsx b/apps/mes/app/components/PinInOverlay.tsx
index d8c5463ce3..0f08201702 100644
--- a/apps/mes/app/components/PinInOverlay.tsx
+++ b/apps/mes/app/components/PinInOverlay.tsx
@@ -83,9 +83,8 @@ export function PinInOverlay({
(person: Person, pinValue: string) => {
addRecentOperator(companyId, person.id);
const formData = new FormData();
+ // The server looks up name and avatar itself; only the id is trusted.
formData.append("userId", person.id);
- formData.append("name", person.name);
- formData.append("avatarUrl", person.avatarUrl ?? "");
if (pinValue) formData.append("pin", pinValue);
pinInFetcher.submit(formData, {
method: "POST",
diff --git a/apps/mes/app/middleware/user.ts b/apps/mes/app/middleware/user.ts
index e221ee1741..f05bcd179d 100644
--- a/apps/mes/app/middleware/user.ts
+++ b/apps/mes/app/middleware/user.ts
@@ -1,37 +1,99 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ clearConsolePinIn,
+ resolveConsolePinIn
+} from "@carbon/auth/console-pin.server";
+import { updateSessionConsole } from "@carbon/auth/session.server";
+import { isConsoleModeEnabledForCompany } from "@carbon/ee/console.server";
+import { getLogger } from "@carbon/logger";
import type { MiddlewareFunction } from "react-router";
import { redirect } from "react-router";
import { userContext } from "~/context";
-import { getConsolePinIn } from "~/services/console.server";
import { getLocation, setLocation } from "~/services/location.server";
+import { path } from "~/utils/path";
+
+const log = getLogger("mes", "user-middleware");
+
+// Only a GET/HEAD can be redirected back to its own URL: a POST's URL is
+// usually an action-only resource route, and the browser would follow the
+// redirect with a GET that has no loader to answer it.
+const isRead = (request: Request) =>
+ request.method === "GET" || request.method === "HEAD";
+
+export const userMiddleware: MiddlewareFunction = async (
+ { context, request },
+ next
+) => {
+ const { client, companyId, userId, sessionUserId, consoleMode } =
+ await requirePermissions(request, {});
+
+ // The session flag alone is not trusted: console mode is a commercial
+ // feature, and the company flag outlives a lapsed entitlement. When the
+ // company has DEFINITELY switched console mode off or is not entitled to it,
+ // take the terminal out of console mode (and drop any pin-in) before any
+ // loader or action runs as a pinned operator. A settings read error (`null`)
+ // is not that answer — tearing the session down on a blip would strand the
+ // kiosk out of console mode for good — so it keeps the session and logs.
+ const consoleEnabled = consoleMode
+ ? await isConsoleModeEnabledForCompany(client, companyId)
+ : false;
+
+ if (consoleMode && consoleEnabled === null) {
+ log.warn("Console mode state unknown; keeping the console session", {
+ companyId
+ });
+ }
+
+ if (consoleMode && consoleEnabled === false) {
+ const headers = new Headers();
+ headers.append(
+ "Set-Cookie",
+ await updateSessionConsole(request, undefined)
+ );
+ headers.append("Set-Cookie", await clearConsolePinIn(companyId));
+ // A write never runs: it was authenticated as the pinned operator. Reads
+ // retry their own URL; writes land on the shell, which has a loader.
+ const { pathname, search } = new URL(request.url);
+ return redirect(
+ isRead(request) ? `${pathname}${search}` : path.to.authenticatedRoot,
+ { headers }
+ );
+ }
-export const userMiddleware: MiddlewareFunction = async ({
- context,
- request
-}) => {
- const { client, companyId, userId, consoleMode } = await requirePermissions(
- request,
- {}
- );
const { location, updated } = await getLocation(request, client, {
companyId,
userId
});
- // Read pin-in state from cookies (console mode comes from auth session)
- const pinIn = consoleMode ? getConsolePinIn(request, companyId) : null;
+ // Pin-in state from the signed cookie, re-validated against the database
+ // (console mode comes from the auth session). `requirePermissions` resolved
+ // the same value into `userId`, memoized for this request.
+ const pinIn = consoleMode
+ ? await resolveConsolePinIn(request, companyId, sessionUserId)
+ : null;
context.set(userContext, {
locationId: location,
companyId,
consoleMode,
- effectiveUserId: pinIn?.userId ?? userId,
+ consoleEnabled: consoleMode ? consoleEnabled : null,
+ effectiveUserId: pinIn?.userId ?? sessionUserId,
pinnedInUser: pinIn
? { userId: pinIn.userId, name: pinIn.name, avatarUrl: pinIn.avatarUrl }
: null
});
if (updated) {
+ const locationCookie = setLocation(companyId, location);
+
+ // A write keeps going with the new cookie on its response — the request
+ // already has `location` in context. Redirecting it would drop the write.
+ if (!isRead(request)) {
+ const response = (await next()) as Response;
+ response.headers.append("Set-Cookie", locationCookie);
+ return response;
+ }
+
// Redirect back to the originally-requested URL (not the root) so deep
// links survive the one-time location-cookie bootstrap. The re-run finds
// the cookie set, so `updated` is false the second time through.
@@ -45,7 +107,7 @@ export const userMiddleware: MiddlewareFunction = async ({
const { pathname, search } = new URL(request.url);
return redirect(`${pathname}${search}`, {
headers: {
- "Set-Cookie": setLocation(companyId, location)
+ "Set-Cookie": locationCookie
}
});
}
diff --git a/apps/mes/app/routes/_public+/callback.tsx b/apps/mes/app/routes/_public+/callback.tsx
index 820399c853..4fc71118e4 100644
--- a/apps/mes/app/routes/_public+/callback.tsx
+++ b/apps/mes/app/routes/_public+/callback.tsx
@@ -28,6 +28,7 @@ import {
} from "@carbon/ee/sso.server";
import { validator } from "@carbon/form";
import { AccountLockout, redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
import {
Alert,
AlertDescription,
@@ -43,6 +44,8 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, Link, redirect, useFetcher, useLocation } from "react-router";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "callback");
+
export async function loader({ request }: LoaderFunctionArgs) {
const authSession = await getAuthSession(request);
@@ -90,6 +93,21 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // The form's `userId` is caller-supplied: the membership read above, the SSO
+ // lookup and the self-signup gate below all key on it. Only the refresh
+ // token proves identity, so a `userId` that is not the token's owner would
+ // stamp another user's company onto this session — refuse it.
+ if (authSession.userId !== userId) {
+ logger.warn("Callback userId does not match the refresh token's user", {
+ userId,
+ sessionUserId: authSession.userId
+ });
+ return redirect(
+ path.to.root,
+ await flash(request, error(null, "Invalid refresh token"))
+ );
+ }
+
// ── SSO branch ─────────────────────────────────────────────────────────
// Mirrors the ERP callback's enforcement (provider → company binding +
// registered email domain), but MES runs no invite migration: a first SSO
diff --git a/apps/mes/app/routes/_public+/unlock.tsx b/apps/mes/app/routes/_public+/unlock.tsx
index 768cd29bb2..0c93c40af3 100644
--- a/apps/mes/app/routes/_public+/unlock.tsx
+++ b/apps/mes/app/routes/_public+/unlock.tsx
@@ -284,6 +284,15 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // Absolute cap already passed → termination wins over lock, as in the loader
+ // and requireAuthSession. Both unlock paths below re-stamp createdAt (the
+ // passkey path directly, TOTP via makeAuthSession), so a POST here would
+ // otherwise revive a session past its absolute cap.
+ const lockedSession = await getAuthSession(request);
+ if (lockedSession && isSessionExpiredAbsolute(lockedSession)) {
+ throw await destroyAuthSession(request);
+ }
+
// Passkey unlock arrives as JSON (the credential assertion); TOTP unlock is a
// form POST. Branch on content type — the TOTP path below is unchanged.
const contentType = request.headers.get("content-type") ?? "";
diff --git a/apps/mes/app/routes/api+/session.heartbeat.ts b/apps/mes/app/routes/api+/session.heartbeat.ts
index 5033f8a6a7..b7c108eb67 100644
--- a/apps/mes/app/routes/api+/session.heartbeat.ts
+++ b/apps/mes/app/routes/api+/session.heartbeat.ts
@@ -9,7 +9,7 @@ import { data } from "react-router";
// cookie with lastActiveAt = now. requirePermissions runs requireAuthSession, so once the
// session is already idle-locked this redirects to /unlock instead of resuming it — only a
// real re-auth clears the lock. Console DEVICE sessions are exempt from the lock and never
-// redirect here (see console.server / requireAuthSession).
+// redirect here (see @carbon/auth console-pin.server / requireAuthSession).
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
await requirePermissions(request, {});
diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
index c3fc23defa..83c431638f 100644
--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
@@ -5,6 +5,7 @@ import {
effectiveExtension,
getCompanyPrivateBucket,
getContentType,
+ isUnsafeStoragePath,
LEGACY_PRIVATE_BUCKET,
storage,
TEMP_STAGING_BUCKET
@@ -45,11 +46,24 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
// Authorize against the companyId as a full path segment (prefix or
// slash-bounded), not a loose substring — `.includes(companyId)` lets
// `<otherCo>/.../<yourCompanyId>.pdf` serve another company's private file.
+ if (isUnsafeStoragePath(path)) {
+ log.warn("Refused a storage path that escapes its prefix", {
+ companyId,
+ bucket,
+ path
+ });
+ return new Response(null, { status: 400 });
+ }
const decodedPath = decodeURIComponent(path);
const ownsPath =
decodedPath.startsWith(`${companyId}/`) ||
decodedPath.includes(`/${companyId}/`);
if (!ownsPath) {
+ log.warn("Refused file preview outside the caller's company", {
+ companyId,
+ bucket,
+ path
+ });
return new Response(null, { status: 403 });
}
@@ -66,6 +80,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
bucket !== "public" &&
bucket !== TEMP_STAGING_BUCKET
) {
+ log.warn("Refused file preview from another bucket", {
+ companyId,
+ bucket
+ });
return new Response(null, { status: 403 });
}
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index ec66772ef8..4035c11067 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -6,17 +6,21 @@ import {
getCarbon,
getCompanies,
getUser,
+ hasPermission,
ITAR_RIDER_PDF_PATH,
isAuthProviderEnabled,
SESSION_HEARTBEAT_MS,
SESSION_IDLE_LOCK_MS
} from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { setConsolePinIn } from "@carbon/auth/console-pin.server";
import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
import {
destroyAuthSession,
requireAuthSession
} from "@carbon/auth/session.server";
+import { getUserClaims } from "@carbon/auth/users.server";
+import { isConsoleModeEnabledForCompany } from "@carbon/ee/console.server";
import type { PrintingSettings } from "@carbon/printing";
import { getPrinterRoutes } from "@carbon/printing";
import { PrintingProvider } from "@carbon/printing/ui";
@@ -65,7 +69,6 @@ import { TimeCardWarning } from "~/components/TimeCardWarning";
import { userContext } from "~/context";
import { useIdle } from "~/hooks";
import { userMiddleware } from "~/middleware/user";
-import { refreshConsolePinIn } from "~/services/console.server";
import { getItarCertificationStatus } from "~/services/itar.service";
import { getActiveMaintenanceEventsCount } from "~/services/maintenance.service";
import {
@@ -191,7 +194,26 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
const locationEmployeeIds =
locationEmployees.data?.map((e: { id: string }) => e.id) ?? [];
const timeCardEnabled = companySettings.data?.timeCardEnabled ?? false;
- const consoleEnabled = companySettings.data?.consoleEnabled ?? false;
+ // Console mode as the gate sees it (flag AND entitlement), never the raw
+ // flag. A console session was already checked by `userMiddleware`, which
+ // kept it through a settings read error (`null`); otherwise the flag this
+ // loader read is passed in, so the entitlement check adds no second read.
+ const consoleEnabled = consoleMode
+ ? ctx?.consoleEnabled !== false
+ : (await isConsoleModeEnabledForCompany(client, companyId, {
+ consoleEnabled: companySettings.data?.consoleEnabled ?? false
+ })) === true;
+ // Entering console mode needs `settings_update` on the SESSION user (the
+ // console.toggle action enforces it); the sidebar only offers the switch to
+ // them, or to a terminal already in console mode so it can always leave.
+ const canEnterConsoleMode =
+ consoleEnabled &&
+ hasPermission(
+ (await getUserClaims(userId, companyId)).permissions,
+ "settings",
+ "update",
+ companyId
+ );
// Org-enforced MFA, mirroring the ERP shell. Enrollment itself lives only in
// the ERP (MES has no account settings), so the gate here points there.
@@ -239,7 +261,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
if (pinnedInUser && ctx) {
headers.append(
"Set-Cookie",
- refreshConsolePinIn(companyId, {
+ await setConsolePinIn(companyId, userId, {
userId: pinnedInUser.userId,
name: pinnedInUser.name,
avatarUrl: pinnedInUser.avatarUrl,
@@ -260,6 +282,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
company,
companies: companies.data ?? [],
consoleEnabled,
+ canEnterConsoleMode,
consoleMode: consoleEnabled && consoleMode,
location: locationId,
locationEmployeeIds,
@@ -304,6 +327,7 @@ export default function AuthenticatedRoute() {
company,
companies,
consoleEnabled,
+ canEnterConsoleMode,
consoleMode,
location,
locationEmployeeIds,
@@ -334,7 +358,7 @@ export default function AuthenticatedRoute() {
// Console (shared-kiosk) idle lock (NIST 3.1.10). A controlled-environment
// console session is exempt from the session-wide lock above (sessionTimeout.
// enabled is false for it) — its lock is the operator pin-in. On idle, reload:
- // the server-tightened pin-in (console.server) has by then expired, so the
+ // the server-tightened pin-in (console-pin.server) has by then expired, so the
// reload surfaces the PinInOverlay and the operator must re-PIN.
const { isIdle: consoleIsIdle } = useIdle({
enabled: CONTROLLED_ENVIRONMENT && consoleMode,
@@ -483,7 +507,9 @@ export default function AuthenticatedRoute() {
activeMaintenanceCount={activeMaintenanceCount}
company={company}
companies={companies}
- consoleEnabled={consoleEnabled}
+ consoleEnabled={
+ consoleEnabled && (consoleMode || canEnterConsoleMode)
+ }
consoleMode={consoleMode}
location={location}
locations={locations}
diff --git a/apps/mes/app/routes/x+/acknowledge.tsx b/apps/mes/app/routes/x+/acknowledge.tsx
index 7ffcc33e85..f9a7acb92b 100644
--- a/apps/mes/app/routes/x+/acknowledge.tsx
+++ b/apps/mes/app/routes/x+/acknowledge.tsx
@@ -1,3 +1,4 @@
+import { safeRedirect } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getLogger } from "@carbon/logger";
import { requiresItarEntityCertification } from "@carbon/utils";
@@ -9,6 +10,7 @@ import {
itarUserCertificationValidator,
recordItarCertification
} from "~/services/itar.service";
+import { path } from "~/utils/path";
const logger = getLogger("mes", "acknowledge");
@@ -39,7 +41,8 @@ export async function action({ request }: ActionFunctionArgs) {
await client.from("user").update({ flags: updatedFlags }).eq("id", userId);
if (redirectTo) {
- throw redirect(redirectTo);
+ // Form-supplied, so only same-origin paths are honoured.
+ throw redirect(safeRedirect(redirectTo, path.to.authenticatedRoot));
}
return { success: true, message: "University acknowledged" };
diff --git a/apps/mes/app/routes/x+/assembly.$operationId.tsx b/apps/mes/app/routes/x+/assembly.$operationId.tsx
index 4cfd83d0a9..1e3e65de3a 100644
--- a/apps/mes/app/routes/x+/assembly.$operationId.tsx
+++ b/apps/mes/app/routes/x+/assembly.$operationId.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { getUserClaims } from "@carbon/auth/users.server";
+import { getLogger } from "@carbon/logger";
import type { ComponentProps } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useParams } from "react-router";
@@ -14,6 +15,7 @@ import {
getJobMakeMethod,
getJobMaterialsByOperationId,
getJobOperationById,
+ getJobOperationForCompany,
getJobOperationProcedure,
getKanbanByJobId,
getModelUploadsByIds,
@@ -33,6 +35,8 @@ import { path } from "~/utils/path";
type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
+const logger = getLogger("mes", "assembly");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
@@ -53,6 +57,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
+ // Every read below is service-role: verify the operation is this company's.
+ const ownedOperation = await getJobOperationForCompany(
+ serviceRole,
+ operationId,
+ companyId
+ );
+ if (!ownedOperation.data) {
+ logger.warn("Operation not found in company", {
+ companyId,
+ operationId,
+ error: ownedOperation.error
+ });
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(null, "Operation not found"))
+ );
+ }
+
const [job, operation] = await Promise.all([
getJobByOperationId(serviceRole, operationId),
getJobOperationById(serviceRole, operationId)
diff --git a/apps/mes/app/routes/x+/batch.$batchId.complete.tsx b/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
index 0b695b3b6b..35f20aa7e3 100644
--- a/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
+++ b/apps/mes/app/routes/x+/batch.$batchId.complete.tsx
@@ -3,6 +3,7 @@ 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 { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { completeJobOperationBatchValidator } from "~/services/models";
@@ -11,6 +12,8 @@ import {
type JobOperationBatch
} from "~/services/operations.service";
+const logger = getLogger("mes", "batch-complete");
+
// A batch planned with a combined output merges every member's produced lot
// into the planned lot number once completion lands. Parent ids are derived
// SERVER-SIDE from membership: this route invokes `issue` with the SERVICE
@@ -69,6 +72,47 @@ export async function action({ request, params }: ActionFunctionArgs) {
// number on every member's output; otherwise each member keeps its own
// planned number (null leaves the entity's readableId untouched, and the
// edge fn refuses an output with no number at all).
+ // The edge function is invoked with the service role, so the submitted
+ // member ids must be this batch's members, and any tracked entity this
+ // company's — one scoped query for the entity list.
+ const memberIds = new Set(
+ (planned.data.operations ?? []).map((operation) => operation.id)
+ );
+ const foreignMember = validation.data.members.find(
+ (m) => !memberIds.has(m.jobOperationId)
+ );
+ const submittedEntityIds = [
+ ...new Set(
+ validation.data.members
+ .map((m) => m.trackedEntityId)
+ .filter((id): id is string => Boolean(id))
+ )
+ ];
+ const ownedEntities = submittedEntityIds.length
+ ? await serviceRole
+ .from("trackedEntity")
+ .select("id")
+ .in("id", submittedEntityIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (
+ foreignMember ||
+ ownedEntities.error ||
+ (ownedEntities.data ?? []).length !== submittedEntityIds.length
+ ) {
+ logger.warn("Batch completion references records outside the batch", {
+ companyId,
+ batchId,
+ jobOperationId: foreignMember?.jobOperationId,
+ trackedEntityIds: submittedEntityIds,
+ error: ownedEntities.error
+ });
+ return data(
+ {},
+ await flash(request, error(null, "Batch member not found"))
+ );
+ }
+
const plannedLotNumber = planned.data.mergeOutput
? planned.data.outputLotNumber
: null;
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 096794ee97..2a89a5bd9d 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -40,7 +40,10 @@ async function autoPrintFirstOperationLabel({
.from("trackedEntity")
.select("attributes")
.eq("id", trackedEntityId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
+ // Service-role read: an entity outside the caller's company prints nothing.
+ if (!entity) return;
const attributes = (entity?.attributes ?? {}) as Record<string, unknown>;
const operationCount = Object.keys(attributes).filter((k) =>
@@ -53,7 +56,8 @@ async function autoPrintFirstOperationLabel({
.from("workCenter")
.select("locationId")
.eq("id", workCenterId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
const locationId = workCenter?.locationId ?? undefined;
if (!locationId) return;
@@ -99,9 +103,15 @@ export async function action({ request }: ActionFunctionArgs) {
.from("jobOperation")
.select("*")
.eq("id", validation.data.jobOperationId)
+ .eq("companyId", companyId)
.maybeSingle();
if (jobOperation.error || !jobOperation.data) {
+ log.error("Job operation not found in company", {
+ companyId,
+ jobOperationId: validation.data.jobOperationId,
+ error: jobOperation.error
+ });
return data(
{},
await flash(request, {
@@ -111,6 +121,39 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // The production event ids ride along into the productionQuantity row and
+ // the issue call; RLS does not check a foreign key's tenant, so verify them.
+ const productionEventIds = [
+ validation.data.setupProductionEventId,
+ validation.data.laborProductionEventId,
+ validation.data.machineProductionEventId
+ ].filter((id): id is string => Boolean(id));
+ if (productionEventIds.length > 0) {
+ const uniqueEventIds = [...new Set(productionEventIds)];
+ const ownedEvents = await serviceRole
+ .from("productionEvent")
+ .select("id")
+ .in("id", uniqueEventIds)
+ .eq("companyId", companyId);
+ if (
+ ownedEvents.error ||
+ (ownedEvents.data ?? []).length !== uniqueEventIds.length
+ ) {
+ log.error("Production event not found in company", {
+ companyId,
+ productionEventIds: uniqueEventIds,
+ error: ownedEvents.error
+ });
+ return data(
+ {},
+ await flash(request, {
+ ...error(ownedEvents.error, "Production event not found"),
+ flash: "error"
+ })
+ );
+ }
+ }
+
// Mirror the DB auto-Done predicate (sync_update_job_operation_quantities,
// 20260807090629): scrap does NOT count toward targetQuantity — the op is
// finished only once GOOD (+ reworked) quantity reaches the target.
diff --git a/apps/mes/app/routes/x+/console.pin-in.tsx b/apps/mes/app/routes/x+/console.pin-in.tsx
index 457e95e601..a8fc8278eb 100644
--- a/apps/mes/app/routes/x+/console.pin-in.tsx
+++ b/apps/mes/app/routes/x+/console.pin-in.tsx
@@ -1,66 +1,168 @@
import { assertIsPost } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
+import { logAuthEvent, requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { setConsolePinIn } from "@carbon/auth/console-pin.server";
+import { verifyEmployeePin } from "@carbon/ee/console.server";
+import { AccountLockout, Ratelimit, redis } from "@carbon/kv";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { setConsolePinIn } from "~/services/console.server";
+import { userContext } from "~/context";
+import { getDatabaseClient } from "~/services/database.server";
-export async function action({ request }: ActionFunctionArgs) {
+// A PIN is four digits — 10,000 values — so the verifier, not the PIN, is what
+// stops a guess-every-code attack. Two layers, both in Redis (fail-open, like
+// login):
+// - per OPERATOR (`AccountLockout`): 5 wrong PINs in 15 min lock that operator's
+// pin-in with exponential backoff, however many terminals the guesses come from;
+// - per TERMINAL (`Ratelimit`): caps how many WRONG PINs one console session can
+// submit across all operators, so spreading guesses across people does not
+// reset the budget. Only failures count — a busy shift change must not lock
+// the kiosk.
+// Both are CONSUMED before the PIN is checked and given back when the request
+// turns out not to be a wrong guess. Checking first and recording only on
+// failure let a parallel burst all pass the check before any failure landed,
+// so the limit capped nothing.
+const pinLockout = new AccountLockout({
+ redis,
+ prefix: "@carbon/console-pin",
+ maxAttempts: 5,
+ window: "15 m"
+});
+
+const terminalRatelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(30, "15 m"),
+ prefix: "@carbon/console-pin:terminal"
+});
+
+const GENERIC_PIN_ERROR = "Incorrect PIN";
+const LOCKED_PIN_ERROR =
+ "Too many incorrect PINs. Please wait a few minutes and try again.";
+
+export async function action({ request, context }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId } = await requirePermissions(request, {});
+ const { companyId, sessionUserId, consoleMode } = await requirePermissions(
+ request,
+ {}
+ );
+
+ // `userMiddleware` already asked the console gate (flag AND entitlement) for
+ // this console session; `null` there means it could not tell, and pinning in
+ // on an unknown answer is refused.
+ if (!consoleMode || context.get(userContext)?.consoleEnabled !== true) {
+ return data({ error: "Console mode is not enabled" }, { status: 403 });
+ }
const formData = await request.formData();
- const userId = formData.get("userId") as string;
- const name = formData.get("name") as string;
- const avatarUrl = (formData.get("avatarUrl") as string) || null;
- const pin = (formData.get("pin") as string) || null;
+ const userId = formData.get("userId");
+ const pin = formData.get("pin");
- if (!userId || !name) {
- return data({ error: "userId and name are required" }, { status: 400 });
+ if (typeof userId !== "string" || !userId) {
+ return data({ error: "userId is required" }, { status: 400 });
}
- const serviceRole = await getCarbonServiceRole();
+ const ip = request.headers.get("x-forwarded-for") ?? undefined;
+ const lockoutKey = `${companyId}:${userId}`;
+ const terminalKey = `${companyId}:${sessionUserId}`;
- // Validate user exists and is active
- const userCheck = await serviceRole
- .from("user")
- .select("id, active")
- .eq("id", userId)
- .single();
-
- if (userCheck.error || !userCheck.data?.active) {
- return data({ error: "User not found or inactive" }, { status: 400 });
+ // The Lua script counts and refuses in one step, so of N concurrent requests
+ // at most the remaining budget get past here. Redis down → fails open, like
+ // login.
+ const terminal = await terminalRatelimit.limit(terminalKey);
+ if (!terminal.success) {
+ logAuthEvent("login_rate_limited", {
+ userId: sessionUserId,
+ companyId,
+ ip,
+ reason: "console pin-in terminal rate limit"
+ });
+ return data({ error: LOCKED_PIN_ERROR }, { status: 429 });
}
- const employeeCheck = await serviceRole
- .from("employee")
- .select("*")
+ const serviceRole = getCarbonServiceRole();
+
+ // `employees` only lists users whose `user.active` is true; `employee.active`
+ // is false once the person is deactivated in this company.
+ const employee = await serviceRole
+ .from("employees")
+ .select("id, name, avatarUrl")
.eq("id", userId)
.eq("companyId", companyId)
- .single();
+ .eq("active", true)
+ .maybeSingle();
- if (employeeCheck.error || !employeeCheck.data) {
+ if (employee.error || !employee.data) {
+ // Not a PIN guess: give the terminal's attempt back.
+ await terminalRatelimit.refund(terminalKey);
return data(
{ error: "Employee not found in this company" },
{ status: 400 }
);
}
- const storedPin: string | null = (employeeCheck.data as any)?.pin ?? null;
+ // Counts this attempt against the operator. Same atomic window, so a burst
+ // gets at most `maxAttempts` PIN checks; the one after engages the lock.
+ const attempt = await pinLockout.recordFailure(lockoutKey);
+ if (attempt.locked) {
+ await terminalRatelimit.refund(terminalKey);
+ logAuthEvent("login_locked", {
+ userId,
+ companyId,
+ ip,
+ reason: "console pin-in locked",
+ retryAfterSeconds: attempt.retryAfterSeconds,
+ terminalUserId: sessionUserId
+ });
+ return data({ error: LOCKED_PIN_ERROR }, { status: 429 });
+ }
+
+ // PINs are bcrypt hashes in `employeePin`, which no API role can read — the
+ // check runs in the database over the server's direct connection.
+ const pinCheck = await verifyEmployeePin(getDatabaseClient(), {
+ employeeId: userId,
+ companyId,
+ pin: typeof pin === "string" ? pin : ""
+ });
- if (!storedPin) {
+ if (!pinCheck.hasPin) {
+ // Nothing to guess: give both attempts back.
+ await Promise.all([
+ pinLockout.reset(lockoutKey),
+ terminalRatelimit.refund(terminalKey)
+ ]);
return data(
{
- error: "No PIN set. Please set a PIN in your account settings."
+ error: "No PIN set. Ask an admin to set a console PIN for you."
},
{ status: 400 }
);
}
- if (!pin || pin !== storedPin) {
- return data({ error: "Incorrect PIN" }, { status: 400 });
+ if (!pinCheck.valid) {
+ // Both attempts were already counted above; a wrong PIN keeps them.
+ logAuthEvent("login_failed", {
+ userId,
+ companyId,
+ ip,
+ reason: "console pin-in: incorrect PIN",
+ terminalUserId: sessionUserId
+ });
+ return data({ error: GENERIC_PIN_ERROR }, { status: 400 });
}
+ // A correct PIN counts against neither budget.
+ await Promise.all([
+ pinLockout.reset(lockoutKey),
+ terminalRatelimit.refund(terminalKey)
+ ]);
+ logAuthEvent("login_success", {
+ userId,
+ companyId,
+ ip,
+ method: "console-pin",
+ terminalUserId: sessionUserId
+ });
+
// 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.
@@ -68,10 +170,12 @@ export async function action({ request }: ActionFunctionArgs) {
{ success: true },
{
headers: {
- "Set-Cookie": setConsolePinIn(companyId, {
+ "Set-Cookie": await setConsolePinIn(companyId, sessionUserId, {
userId,
- name,
- avatarUrl,
+ // From the database, never the form: the cookie is signed, so what it
+ // says about the operator must be what we looked up.
+ name: employee.data.name ?? "",
+ avatarUrl: employee.data.avatarUrl ?? null,
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 bd170f14b3..b7b4b1bc09 100644
--- a/apps/mes/app/routes/x+/console.pin-out.tsx
+++ b/apps/mes/app/routes/x+/console.pin-out.tsx
@@ -1,8 +1,8 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { clearConsolePinIn } from "@carbon/auth/console-pin.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { clearConsolePinIn } from "~/services/console.server";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -15,7 +15,7 @@ export async function action({ request }: ActionFunctionArgs) {
{ success: true },
{
headers: {
- "Set-Cookie": clearConsolePinIn(companyId)
+ "Set-Cookie": await clearConsolePinIn(companyId)
}
}
);
diff --git a/apps/mes/app/routes/x+/console.toggle.tsx b/apps/mes/app/routes/x+/console.toggle.tsx
index dd83527cd4..8eac4dbf54 100644
--- a/apps/mes/app/routes/x+/console.toggle.tsx
+++ b/apps/mes/app/routes/x+/console.toggle.tsx
@@ -1,28 +1,31 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { clearConsolePinIn } from "@carbon/auth/console-pin.server";
import { updateSessionConsole } from "@carbon/auth/session.server";
+import { isConsoleModeEnabledForCompany } from "@carbon/ee/console.server";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { clearConsolePinIn } from "~/services/console.server";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId } = await requirePermissions(request, {});
-
const formData = await request.formData();
const enabled = formData.get("consoleMode") === "true";
- // Only allow enabling if company has console mode turned on
- if (enabled) {
- const settings = await client
- .from("companySettings")
- .select("consoleEnabled")
- .eq("id", companyId)
- .single();
+ // Entering console mode turns this terminal into one every pinned operator
+ // acts through, so it takes `settings_update` (checked against the SESSION
+ // user, never a pinned operator). Leaving it only drops back to the session
+ // user's own identity and stays open to anyone, so a terminal is never stuck
+ // in console mode.
+ const { client, companyId } = await requirePermissions(
+ request,
+ enabled ? { update: "settings" } : {}
+ );
- if (!settings.data?.consoleEnabled) {
- throw new Response("Console mode is not enabled", { status: 403 });
- }
+ // Only allow enabling if the company has console mode turned on AND is
+ // entitled to it — the flag outlives a lapsed entitlement. An unreadable
+ // setting (`null`) refuses too.
+ if (enabled && !(await isConsoleModeEnabledForCompany(client, companyId))) {
+ throw new Response("Console mode is not enabled", { status: 403 });
}
const headers = new Headers();
@@ -33,7 +36,7 @@ export async function action({ request }: ActionFunctionArgs) {
// When disabling console mode, also clear any active pin-in
if (!enabled) {
- headers.append("Set-Cookie", clearConsolePinIn(companyId));
+ headers.append("Set-Cookie", await clearConsolePinIn(companyId));
}
// Return data (not a redirect) so the caller's fetcher auto-revalidates the
diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
index 9993e00ba8..c13a1b74cb 100644
--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
@@ -2,10 +2,13 @@ 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 { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { addMaintenanceDispatchItem } from "~/services/maintenance.service";
+const logger = getLogger("mes", "dispatch-item");
+
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {});
@@ -36,6 +39,35 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The insert runs as the service role: the dispatch and the item must both
+ // belong to this company.
+ const [dispatch, item] = await Promise.all([
+ serviceRole
+ .from("maintenanceDispatch")
+ .select("id")
+ .eq("id", dispatchId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ serviceRole
+ .from("item")
+ .select("id")
+ .eq("id", itemId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+ if (!dispatch.data || !item.data) {
+ logger.warn("Dispatch or item not found for company", {
+ companyId,
+ dispatchId,
+ itemId,
+ error: dispatch.error ?? item.error
+ });
+ return data(
+ {},
+ await flash(request, error(null, "Failed to add spare part"))
+ );
+ }
+
const result = await addMaintenanceDispatchItem(serviceRole, {
maintenanceDispatchId: dispatchId,
itemId,
diff --git a/apps/mes/app/routes/x+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsx
index f57595a49b..09703fa64e 100644
--- a/apps/mes/app/routes/x+/dispatch.new.tsx
+++ b/apps/mes/app/routes/x+/dispatch.new.tsx
@@ -30,6 +30,50 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
+ // The insert below is service-role, so every referenced id from the form
+ // must belong to this company: one scoped query per id type. The work
+ // center's location is read here too (it is stamped on the dispatch).
+ const failureModeIds = [
+ ...new Set(
+ [
+ validation.data.suspectedFailureModeId,
+ validation.data.actualFailureModeId
+ ].filter((id): id is string => Boolean(id))
+ )
+ ];
+ const [workCenter, failureModes] = await Promise.all([
+ serviceRole
+ .from("workCenter")
+ .select("locationId")
+ .eq("id", validation.data.workCenterId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ failureModeIds.length
+ ? serviceRole
+ .from("maintenanceFailureMode")
+ .select("id")
+ .in("id", failureModeIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null }
+ ]);
+ if (
+ !workCenter.data ||
+ failureModes.error ||
+ (failureModes.data ?? []).length !== failureModeIds.length
+ ) {
+ log.warn("Dispatch references records outside the company", {
+ companyId,
+ workCenterId: validation.data.workCenterId,
+ failureModeIds,
+ error: workCenter.error ?? failureModes.error
+ });
+ return data(
+ {},
+ await flash(request, error(null, "Work center or failure mode not found"))
+ );
+ }
+ const locationId = workCenter.data.locationId ?? undefined;
+
// Get the next sequence for maintenance dispatch
const nextSequence = await serviceRole.rpc("get_next_sequence", {
sequence_name: "maintenanceDispatch",
@@ -60,19 +104,6 @@ export async function action({ request }: ActionFunctionArgs) {
const currentTime = datetime.timestamp();
- // Get locationId from work center
- let locationId: string | undefined;
- if (validation.data.workCenterId) {
- const workCenter = await serviceRole
- .from("workCenter")
- .select("locationId")
- .eq("id", validation.data.workCenterId)
- .single();
- if (!workCenter.error && workCenter.data?.locationId) {
- locationId = workCenter.data.locationId;
- }
- }
-
const insertDispatch = await serviceRole
.from("maintenanceDispatch")
.insert([
@@ -140,6 +171,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("maintenanceFailureMode")
.select("type")
.eq("id", validation.data.suspectedFailureModeId)
+ .eq("companyId", companyId)
.single();
if (!failureMode.error && failureMode.data?.type) {
diff --git a/apps/mes/app/routes/x+/end-shift.tsx b/apps/mes/app/routes/x+/end-shift.tsx
index 0ec8b2e5ec..36f0de985e 100644
--- a/apps/mes/app/routes/x+/end-shift.tsx
+++ b/apps/mes/app/routes/x+/end-shift.tsx
@@ -1,10 +1,10 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { clearConsolePinIn } from "@carbon/auth/console-pin.server";
import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import { clearConsolePinIn } from "~/services/console.server";
import { endProductionEvents } from "~/services/operations.service";
const log = getLogger("mes");
@@ -58,7 +58,7 @@ export async function action({ request }: ActionFunctionArgs) {
// In console mode, pin out the operator after ending their shift
const headers = new Headers();
if (consoleMode) {
- headers.append("Set-Cookie", clearConsolePinIn(companyId));
+ headers.append("Set-Cookie", await clearConsolePinIn(companyId));
}
return data(
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index 422b0bad8f..7649617951 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
+import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -14,6 +15,8 @@ import {
} from "~/services/operations.service";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "end-operation");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
@@ -52,6 +55,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
if (jobOperation.data?.companyId !== companyId) {
+ logger.warn("Job operation does not belong to company", {
+ companyId,
+ operationId
+ });
return redirect(
path.to.operations,
await flash(request, {
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx
index e679a72562..53a80b2e9b 100644
--- a/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.sample.tsx
@@ -3,11 +3,14 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { upsertInspectionSample } from "@carbon/database/quality";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { getDatabaseClient } from "~/services/database.server";
import { inspectionSampleValidator } from "~/services/models";
+const logger = getLogger("mes", "inspection-lot-sample");
+
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {
@@ -33,7 +36,32 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const result = await upsertInspectionSample(getDatabaseClient(), {
+ const db = getDatabaseClient();
+
+ // The sample write runs as the superuser and links the tracked entity, so
+ // the entity must belong to this company.
+ const { trackedEntityId } = validation.data;
+ if (trackedEntityId) {
+ const entity = await db
+ .selectFrom("trackedEntity")
+ .select("id")
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!entity) {
+ logger.warn("Tracked entity not found for company", {
+ companyId,
+ inspectionId: id,
+ trackedEntityId
+ });
+ return data(
+ { error: { message: "Tracked entity not found" } },
+ await flash(request, error(null, "Tracked entity not found"))
+ );
+ }
+ }
+
+ const result = await upsertInspectionSample(db, {
...validation.data,
companyId,
inspectedBy: userId
diff --git a/apps/mes/app/routes/x+/inspection.$operationId.tsx b/apps/mes/app/routes/x+/inspection.$operationId.tsx
index 04a089aec5..d6ea4d4ac4 100644
--- a/apps/mes/app/routes/x+/inspection.$operationId.tsx
+++ b/apps/mes/app/routes/x+/inspection.$operationId.tsx
@@ -6,6 +6,7 @@ import {
getOrCreateJobOperationInspection,
reconcileInspectionSamplingPlans
} from "@carbon/database/quality";
+import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useParams } from "react-router";
import { InspectionView } from "~/components/Inspection/InspectionView";
@@ -30,6 +31,8 @@ import { makeDurations } from "~/utils/durations";
import { resolveOperationView } from "~/utils/operationView";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "inspection");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
@@ -39,6 +42,29 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const url = new URL(request.url);
const serviceRole = await getCarbonServiceRole();
+ // Every read below uses the service role, so prove the operation belongs to
+ // this company before any of them runs.
+ const scopedOperation = await serviceRole
+ .from("jobOperation")
+ .select("id")
+ .eq("id", operationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (scopedOperation.error || !scopedOperation.data) {
+ logger.warn("Job operation not found for company", {
+ companyId,
+ operationId,
+ error: scopedOperation.error
+ });
+ throw redirect(
+ path.to.operations,
+ await flash(
+ request,
+ error(scopedOperation.error, "Failed to fetch operation")
+ )
+ );
+ }
+
const [job, operation] = await Promise.all([
getJobByOperationId(serviceRole, operationId),
getJobOperationById(serviceRole, operationId)
diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsx
index c977b7e643..eb83bf3742 100644
--- a/apps/mes/app/routes/x+/issue.tsx
+++ b/apps/mes/app/routes/x+/issue.tsx
@@ -4,11 +4,14 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { issueValidator } from "~/services/models";
import { path, requestReferrer } from "~/utils/path";
+const logger = getLogger("mes", "issue");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { userId, companyId } = await requirePermissions(request, {});
@@ -41,9 +44,21 @@ export async function action({ request }: ActionFunctionArgs) {
.from("jobOperation")
.select("workCenterId")
.eq("id", jobOperationId)
+ .eq("companyId", companyId)
.maybeSingle();
- if (jobOpRow?.workCenterId) {
+ if (!jobOpRow) {
+ logger.warn("Job operation not found for company", {
+ companyId,
+ jobOperationId
+ });
+ throw redirect(
+ requestReferrer(request) ?? path.to.operations,
+ await flash(request, error(null, "Job operation not found"))
+ );
+ }
+
+ if (jobOpRow.workCenterId) {
const ruleEval = await evaluateLinesForSurface({
client: serviceRole,
companyId,
diff --git a/apps/mes/app/routes/x+/job.$jobId.tsx b/apps/mes/app/routes/x+/job.$jobId.tsx
index 060bdbcae0..b7ac32ff7b 100644
--- a/apps/mes/app/routes/x+/job.$jobId.tsx
+++ b/apps/mes/app/routes/x+/job.$jobId.tsx
@@ -1,9 +1,10 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import { Heading, SidebarTrigger } from "@carbon/react";
import { LuArrowLeft } from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
-import { Link, useLoaderData } from "react-router";
+import { Link, redirect, useLoaderData } from "react-router";
import { JobDag } from "~/components/JobDag";
import {
getJobOperationDependencies,
@@ -11,21 +12,39 @@ import {
} from "~/services/operations.service";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "job-dag");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
- await requirePermissions(request, {});
+ const { companyId } = await requirePermissions(request, {});
const serviceRole = getCarbonServiceRole();
const { jobId } = params;
if (!jobId) throw new Error("Could not find jobId");
- const [job, operations, dependencies] = await Promise.all([
- serviceRole.from("jobs").select("jobId").eq("id", jobId).single(),
+ // Service-role reads below are keyed on jobId alone, so the job must be
+ // verified as this company's before any of them run.
+ const job = await serviceRole
+ .from("job")
+ .select("jobId")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (!job.data) {
+ logger.warn("Job not found in company", {
+ companyId,
+ jobId,
+ error: job.error
+ });
+ throw redirect(path.to.jobs);
+ }
+
+ const [operations, dependencies] = await Promise.all([
getJobOperations(serviceRole, jobId),
getJobOperationDependencies(serviceRole, jobId)
]);
return {
- readableId: job.data?.jobId ?? jobId,
+ readableId: job.data.jobId ?? jobId,
operations: operations.data ?? [],
dependencies: dependencies.data ?? []
};
diff --git a/apps/mes/app/routes/x+/maintenance-event.tsx b/apps/mes/app/routes/x+/maintenance-event.tsx
index 3985391d3b..5c180385a1 100644
--- a/apps/mes/app/routes/x+/maintenance-event.tsx
+++ b/apps/mes/app/routes/x+/maintenance-event.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 { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
@@ -13,6 +14,8 @@ import {
import { notifyScheduleInputsChanged } from "~/services/operations.service";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "maintenance-event");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {});
@@ -30,6 +33,37 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
const currentTime = datetime.timestamp();
+ // Every write below is service-role and the ids come from the form, so the
+ // dispatch (and, on Start, the work center) must be this company's.
+ const [ownedDispatch, ownedWorkCenter] = await Promise.all([
+ serviceRole
+ .from("maintenanceDispatch")
+ .select("id")
+ .eq("id", dispatchId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ action === "Start" && workCenterId
+ ? serviceRole
+ .from("workCenter")
+ .select("id")
+ .eq("id", workCenterId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null
+ ]);
+ if (!ownedDispatch.data || (ownedWorkCenter && !ownedWorkCenter.data)) {
+ logger.warn("Dispatch or work center not found in company", {
+ companyId,
+ dispatchId,
+ workCenterId,
+ error: ownedDispatch.error ?? ownedWorkCenter?.error
+ });
+ return data(
+ {},
+ await flash(request, error(null, "Maintenance dispatch not found"))
+ );
+ }
+
// A dispatch that takes its work center offline moves the schedule's downtime
// window when it starts (down begins) or completes (down ends) — stamp the
// work center so the wave regenerates its location.
@@ -38,6 +72,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("maintenanceDispatch")
.select("takesWorkCenterOffline, workCenterId")
.eq("id", dispatchId)
+ .eq("companyId", companyId)
.single();
if (dispatch?.takesWorkCenterOffline && dispatch.workCenterId) {
await notifyScheduleInputsChanged(
@@ -75,7 +110,8 @@ export async function action({ request }: ActionFunctionArgs) {
dispatchId,
status: "In Progress",
actualStartTime: currentTime,
- updatedBy: userId
+ updatedBy: userId,
+ companyId
});
await stampScheduleIfOffline();
@@ -97,7 +133,8 @@ export async function action({ request }: ActionFunctionArgs) {
const endEvent = await endMaintenanceEvent(serviceRole, {
eventId,
endTime: currentTime,
- updatedBy: userId
+ updatedBy: userId,
+ companyId
});
if (endEvent.error) {
@@ -119,7 +156,8 @@ export async function action({ request }: ActionFunctionArgs) {
await endMaintenanceEvent(serviceRole, {
eventId,
endTime: currentTime,
- updatedBy: userId
+ updatedBy: userId,
+ companyId
});
}
@@ -129,7 +167,8 @@ export async function action({ request }: ActionFunctionArgs) {
status: "Completed",
actualEndTime: currentTime,
completedAt: currentTime,
- updatedBy: userId
+ updatedBy: userId,
+ companyId
});
if (updateStatus.error) {
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index 163c5f5248..f719e9576a 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { activeJobStatuses } from "@carbon/database";
+import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useParams } from "react-router";
import { JobOperation } from "~/components/JobOperation";
@@ -17,6 +18,7 @@ import {
getJobMethodBomIdMap,
getJobOperationBatch,
getJobOperationById,
+ getJobOperationForCompany,
getJobOperationProcedure,
getKanbanByJobId,
getNextIncompleteSerialEntity,
@@ -37,6 +39,8 @@ import { makeDurations } from "~/utils/durations";
import { resolveOperationView } from "~/utils/operationView";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "operation");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
@@ -48,6 +52,32 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
+ // Every read below is service-role, so verify the caller-supplied ids belong
+ // to this company first (the tracked entity feeds the genealogy lookup).
+ const [ownedOperation, ownedEntity] = await Promise.all([
+ getJobOperationForCompany(serviceRole, operationId, companyId),
+ trackedEntityId
+ ? serviceRole
+ .from("trackedEntity")
+ .select("id")
+ .eq("id", trackedEntityId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null
+ ]);
+ if (!ownedOperation.data || (ownedEntity && !ownedEntity.data)) {
+ logger.warn("Operation or tracked entity not found in company", {
+ companyId,
+ operationId,
+ trackedEntityId,
+ error: ownedOperation.error ?? ownedEntity?.error
+ });
+ throw redirect(
+ path.to.operations,
+ await flash(request, error(null, "Operation not found"))
+ );
+ }
+
let [events, quantities, job, operation] = await Promise.all([
getProductionEventsForJobOperation(serviceRole, {
operationId,
diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx
index 97cd2707ec..7ac68d5181 100644
--- a/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx
+++ b/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx
@@ -2,6 +2,7 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { trackWorkEvent } from "@carbon/lib/telemetry";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { userContext } from "~/context";
import { getCompanySettings } from "~/services/inventory.service";
@@ -13,6 +14,8 @@ import {
type PickingListStatus = (typeof pickingListStatus)[number];
+const logger = getLogger("mes", "picking-status");
+
export async function action({ context, request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { userId, companyId } = await requirePermissions(request, {});
@@ -36,7 +39,15 @@ export async function action({ context, request, params }: ActionFunctionArgs) {
.select("status")
.eq("id", pickingListId)
.eq("companyId", companyId)
- .single();
+ .maybeSingle();
+ if (current.error || !current.data) {
+ logger.warn("Picking list not found for company", {
+ companyId,
+ pickingListId,
+ error: current.error
+ });
+ return { success: false, message: "Picking list not found" };
+ }
if (
isPickingListLocked(current.data?.status) &&
!isPickingListLocked(status)
diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.tracked.$lineId.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.tracked.$lineId.tsx
index 6d9f57552e..f2c29717d3 100644
--- a/apps/mes/app/routes/x+/picking.$pickingListId.tracked.$lineId.tsx
+++ b/apps/mes/app/routes/x+/picking.$pickingListId.tracked.$lineId.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { userContext } from "~/context";
import {
@@ -10,6 +11,8 @@ import {
} from "~/services/inventory.service";
import { setPickingListLineTrackedEntity } from "~/services/picking.service";
+const logger = getLogger("mes", "picking-tracked-line");
+
/**
* GET: available tracked lots for a picking line (non-lineside, deduped),
* smart-ordered for the TrackedEntityPicker. POST: pick/unpick a chosen lot.
@@ -25,9 +28,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
"id, itemId, quantityToPick, quantityPicked, pickingList(locationId), item(itemTrackingType)"
)
.eq("id", lineId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
if (lineResult.error || !lineResult.data) {
+ logger.warn("Picking line not found for company", {
+ companyId,
+ lineId,
+ error: lineResult.error
+ });
throw new Response("Line not found", { status: 404 });
}
@@ -76,7 +85,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ context, request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { userId } = await requirePermissions(request, {});
+ const { userId, companyId } = await requirePermissions(request, {});
const effectiveUserId = context.get(userContext)?.effectiveUserId ?? userId;
const serviceRole = getCarbonServiceRole();
@@ -100,10 +109,17 @@ export async function action({ context, request, params }: ActionFunctionArgs) {
fromStorageUnitId,
quantity,
unpick,
- userId: effectiveUserId
+ userId: effectiveUserId,
+ companyId
});
if (result.error) {
+ logger.error("Failed to pick tracked entity", {
+ companyId,
+ lineId,
+ trackedEntityId,
+ error: result.error
+ });
return {
success: false,
message:
diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsx
index 3a5d435a31..2e7302ffdd 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -4,6 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { activeJobStatuses } from "@carbon/database";
import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
+import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -16,6 +17,8 @@ import {
} from "~/services/operations.service";
import { path } from "~/utils/path";
+const logger = getLogger("mes", "start-operation");
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
const { operationId } = params;
@@ -50,6 +53,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
if (jobOperation.data?.companyId !== companyId) {
+ logger.warn("Job operation does not belong to company", {
+ companyId,
+ operationId
+ });
throw redirect(
path.to.operations,
await flash(
diff --git a/apps/mes/app/routes/x+/steps.inspection.tsx b/apps/mes/app/routes/x+/steps.inspection.tsx
index a2d02f3575..8c3bd9401a 100644
--- a/apps/mes/app/routes/x+/steps.inspection.tsx
+++ b/apps/mes/app/routes/x+/steps.inspection.tsx
@@ -2,20 +2,84 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
+const logger = getLogger("mes", "steps-inspection");
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId } = await requirePermissions(request, {});
+ const { companyId, userId } = await requirePermissions(request, {});
const payload = await request.json();
let insertedSteps: Database["public"]["Tables"]["jobOperationStep"]["Insert"][] =
[];
if (Array.isArray(payload)) {
- insertedSteps = payload.filter((step) => step.companyId === companyId);
+ // Rows are rebuilt from the fields the client is allowed to set (tenant and
+ // audit columns come from the session), since the insert is service-role.
+ insertedSteps = payload
+ .filter((step) => step?.companyId === companyId)
+ .map((step) => ({
+ companyId,
+ createdBy: userId,
+ operationId: String(step.operationId ?? ""),
+ name: String(step.name ?? ""),
+ type: "Inspection" as const,
+ ...(typeof step.sortOrder === "number"
+ ? { sortOrder: step.sortOrder }
+ : {}),
+ nonConformanceActionId: step.nonConformanceActionId
+ ? String(step.nonConformanceActionId)
+ : null
+ }));
if (insertedSteps.length > 0) {
const serviceRole = await getCarbonServiceRole();
+
+ // The operation and action ids come from the request body: verify each
+ // belongs to this company, one scoped query per id type.
+ const operationIds = [
+ ...new Set(insertedSteps.map((step) => step.operationId))
+ ];
+ const actionIds = [
+ ...new Set(
+ insertedSteps
+ .map((step) => step.nonConformanceActionId)
+ .filter((id): id is string => Boolean(id))
+ )
+ ];
+ const [operations, actions] = await Promise.all([
+ serviceRole
+ .from("jobOperation")
+ .select("id")
+ .in("id", operationIds)
+ .eq("companyId", companyId),
+ actionIds.length
+ ? serviceRole
+ .from("nonConformanceActionTask")
+ .select("id")
+ .in("id", actionIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null }
+ ]);
+ if (
+ operations.error ||
+ actions.error ||
+ (operations.data ?? []).length !== operationIds.length ||
+ (actions.data ?? []).length !== actionIds.length
+ ) {
+ logger.warn("Inspection steps reference records outside the company", {
+ companyId,
+ operationIds,
+ actionIds,
+ error: operations.error ?? actions.error
+ });
+ return data(
+ { success: false, message: "Operation not found" },
+ { status: 404 }
+ );
+ }
+
const result = await serviceRole
.from("jobOperationStep")
.insert(insertedSteps);
diff --git a/apps/mes/app/routes/x+/suggestion.tsx b/apps/mes/app/routes/x+/suggestion.tsx
index 4297cea760..d9c03cdb62 100644
--- a/apps/mes/app/routes/x+/suggestion.tsx
+++ b/apps/mes/app/routes/x+/suggestion.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { isUnsafeStoragePath } from "@carbon/files";
import { validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { postSuggestionToCarbonSlack } from "@carbon/lib/slack.server";
@@ -35,7 +36,9 @@ export async function action({ request }: ActionFunctionArgs) {
// formUserId is only an anonymous on/off signal — attribute the session user or nobody
const suggestionUserId = formUserId ? userId : null;
const suggestionAttachmentPath =
- attachmentPath && attachmentPath.startsWith(`${companyId}/suggestions/`)
+ attachmentPath &&
+ attachmentPath.startsWith(`${companyId}/suggestions/`) &&
+ !isUnsafeStoragePath(attachmentPath)
? attachmentPath
: null;
diff --git a/apps/mes/app/routes/x+/unconsume.tsx b/apps/mes/app/routes/x+/unconsume.tsx
index 118f9e6d18..3e5318d2d2 100644
--- a/apps/mes/app/routes/x+/unconsume.tsx
+++ b/apps/mes/app/routes/x+/unconsume.tsx
@@ -7,7 +7,7 @@ import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { issueTrackedEntityValidator } from "~/services/models";
-const log = getLogger("mes");
+const log = getLogger("mes", "unconsume");
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -43,9 +43,18 @@ export async function action({ request }: ActionFunctionArgs) {
.from("jobMaterial")
.select("jobOperationId, itemId, quantity")
.eq("id", materialId)
+ .eq("companyId", companyId)
.maybeSingle();
- if (matRow?.jobOperationId) {
+ if (!matRow) {
+ log.warn("Job material not found for company", { companyId, materialId });
+ return data(
+ { success: false, message: "Material not found" },
+ { status: 404 }
+ );
+ }
+
+ if (matRow.jobOperationId) {
// `workInstructionId` is in the runtime row but absent from the generated
// DB types (stale until next regen). Select only the typed column;
// pick up `workInstructionId` via cast below.
@@ -53,6 +62,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("jobOperation")
.select("workCenterId")
.eq("id", matRow.jobOperationId)
+ .eq("companyId", companyId)
.maybeSingle();
if (jobOpRow?.workCenterId) {
diff --git a/apps/mes/app/services/console.server.ts b/apps/mes/app/services/console.server.ts
deleted file mode 100644
index 8ab9685407..0000000000
--- a/apps/mes/app/services/console.server.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { CONTROLLED_ENVIRONMENT, SESSION_IDLE_LOCK_MS } from "@carbon/auth";
-import * as cookie from "cookie";
-
-const CONSOLE_PIN_PREFIX = "console-pin-";
-const CONSOLE_PIN_MAX_AGE = 60 * 60; // 1 hour in seconds
-const CONSOLE_PIN_MAX_AGE_MS = CONSOLE_PIN_MAX_AGE * 1000;
-
-// A controlled environment (ITAR/CUI, NIST 3.1.10) drops a shared-console operator
-// to re-PIN after the standard idle-lock window instead of 1h. pinnedAt is refreshed
-// on every shell navigation (see x+/_layout loader), so this is an inactivity window.
-const consolePinMaxAgeMs = () =>
- CONTROLLED_ENVIRONMENT ? SESSION_IDLE_LOCK_MS : CONSOLE_PIN_MAX_AGE_MS;
-
-// --- Console Pin-In State ---
-
-export interface ConsolePinIn {
- userId: string;
- name: string;
- avatarUrl: string | null;
- pinnedAt: number; // unix timestamp ms
-}
-
-export function getConsolePinIn(
- request: Request,
- companyId: string
-): ConsolePinIn | null {
- const cookieHeader = request.headers.get("cookie");
- if (!cookieHeader) return null;
-
- const raw = cookie.parse(cookieHeader)[`${CONSOLE_PIN_PREFIX}${companyId}`];
- if (!raw) return null;
-
- try {
- const parsed: ConsolePinIn = JSON.parse(raw);
- // Check manual expiry (defense-in-depth alongside cookie maxAge)
- const elapsed = Date.now() - parsed.pinnedAt;
- if (elapsed > consolePinMaxAgeMs()) return null;
- return parsed;
- } catch {
- return null;
- }
-}
-
-export function setConsolePinIn(companyId: string, data: ConsolePinIn): string {
- return cookie.serialize(
- `${CONSOLE_PIN_PREFIX}${companyId}`,
- JSON.stringify(data),
- {
- path: "/",
- maxAge: CONSOLE_PIN_MAX_AGE
- }
- );
-}
-
-export function clearConsolePinIn(companyId: string): string {
- return cookie.serialize(`${CONSOLE_PIN_PREFIX}${companyId}`, "", {
- path: "/",
- maxAge: 0
- });
-}
-
-export function refreshConsolePinIn(
- companyId: string,
- existing: ConsolePinIn
-): string {
- return setConsolePinIn(companyId, {
- ...existing,
- pinnedAt: Date.now()
- });
-}
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index 191bba0d62..37a6f8659c 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -56,6 +56,7 @@ export async function getBatchNumbersForItem(
.from("item")
.select("*")
.eq("id", args.itemId)
+ .eq("companyId", args.companyId)
.single();
if (item.data?.type === "Material") {
const items = await client
@@ -132,6 +133,7 @@ export async function getSerialNumbersForItem(
.from("item")
.select("*")
.eq("id", args.itemId)
+ .eq("companyId", args.companyId)
.single();
if (item.data?.type === "Material") {
const items = await client
diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.ts
index 8a4cf16562..e0fbe181ad 100644
--- a/apps/mes/app/services/location.server.ts
+++ b/apps/mes/app/services/location.server.ts
@@ -1,8 +1,11 @@
import { notFound } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import * as cookie from "cookie";
+const logger = getLogger("mes", "location");
+
export function getCompanySettings(request: Request, companyId: string) {
const cookieHeader = request.headers.get("cookie");
const parsed = cookieHeader ? cookie.parse(cookieHeader)[companyId] : null;
@@ -35,6 +38,25 @@ export async function getLocation(
let updated = false;
+ // The cookie is client-controlled: only honor it when it names a location
+ // of this company, otherwise fall through to the defaults below.
+ if (location) {
+ const owned = await client
+ .from("location")
+ .select("id")
+ .eq("id", location)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (owned.error) {
+ logger.error("Failed to verify the location cookie", {
+ companyId,
+ locationId: location,
+ error: owned.error
+ });
+ }
+ if (!owned.data) location = undefined;
+ }
+
if (!location) {
const employeeJob = await client
.from("employeeJob")
diff --git a/apps/mes/app/services/maintenance.service.ts b/apps/mes/app/services/maintenance.service.ts
index 206e1329ce..b98fbbb06a 100644
--- a/apps/mes/app/services/maintenance.service.ts
+++ b/apps/mes/app/services/maintenance.service.ts
@@ -138,6 +138,7 @@ export async function endMaintenanceEvent(
eventId: string;
endTime: string;
updatedBy: string;
+ companyId: string;
}
) {
return client
@@ -147,6 +148,7 @@ export async function endMaintenanceEvent(
updatedBy: args.updatedBy
})
.eq("id", args.eventId)
+ .eq("companyId", args.companyId)
.select("id")
.single();
}
@@ -160,6 +162,7 @@ export async function updateMaintenanceDispatchStatus(
actualStartTime?: string;
actualEndTime?: string;
completedAt?: string;
+ companyId: string;
}
) {
return client
@@ -172,6 +175,7 @@ export async function updateMaintenanceDispatchStatus(
updatedBy: args.updatedBy
})
.eq("id", args.dispatchId)
+ .eq("companyId", args.companyId)
.select("id")
.single();
}
@@ -182,6 +186,7 @@ export async function assignMaintenanceDispatch(
dispatchId: string;
assignee: string;
updatedBy: string;
+ companyId: string;
}
) {
return client
@@ -192,6 +197,7 @@ export async function assignMaintenanceDispatch(
updatedBy: args.updatedBy
})
.eq("id", args.dispatchId)
+ .eq("companyId", args.companyId)
.select("id")
.single();
}
@@ -266,9 +272,14 @@ export async function addMaintenanceDispatchItem(
export async function deleteMaintenanceDispatchItem(
client: SupabaseClient<Database>,
- itemId: string
+ itemId: string,
+ companyId: string
) {
- return client.from("maintenanceDispatchItem").delete().eq("id", itemId);
+ return client
+ .from("maintenanceDispatchItem")
+ .delete()
+ .eq("id", itemId)
+ .eq("companyId", companyId);
}
export async function getMaintenanceDispatchItemTrackedEntities(
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 34da66e241..86fc118462 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -42,6 +42,28 @@ function isMissingQuantityColumn(
return error?.code === "42703" || error?.code === "PGRST204";
}
+/**
+ * A `{ data, error }` failure shaped like a PostgREST response, for when a
+ * caller-supplied record id does not belong to the caller's company. Callers
+ * of these services pass service-role clients, so the companyId check is the
+ * only tenant boundary — a miss must stop the write, not no-op past it.
+ */
+function notFoundResponse(message: string) {
+ return {
+ data: null,
+ error: {
+ name: "PostgrestError",
+ message,
+ details: "",
+ hint: "",
+ code: "PGRST116"
+ } as PostgrestError,
+ count: null,
+ status: 404,
+ statusText: "Not Found"
+ };
+}
+
export async function getOpenJobs(
client: SupabaseClient<Database>,
args: { companyId: string; locationId: string }
@@ -288,13 +310,26 @@ export async function finishJobOperation(
companyId: string;
}
) {
+ // Callers pass a service-role client, so the companyId filter is the tenant
+ // check: an operation id from another company updates nothing, and nothing
+ // downstream (GL posting, picked-material returns, moments) may run for it.
const result = await client
.from("jobOperation")
.update({
status: "Done",
updatedBy: args.userId
})
- .eq("id", args.jobOperationId);
+ .eq("id", args.jobOperationId)
+ .eq("companyId", args.companyId)
+ .select("id");
+
+ if (!result.error && result.data.length === 0) {
+ log.warn("finishJobOperation: job operation not found in company", {
+ companyId: args.companyId,
+ jobOperationId: args.jobOperationId
+ });
+ return notFoundResponse("Job operation not found");
+ }
if (!result.error) {
client
@@ -660,6 +695,24 @@ export async function getJobAttributesByOperationId(
.eq("operationId", operationId);
}
+/**
+ * Tenant check for a caller-supplied job operation id. Routes read operations
+ * with a service-role client (operators often lack RLS rights), so this scoped
+ * lookup is the boundary: null data means the id is not in the company.
+ */
+export async function getJobOperationForCompany(
+ client: SupabaseClient<Database>,
+ operationId: string,
+ companyId: string
+) {
+ return client
+ .from("jobOperation")
+ .select("id, jobId")
+ .eq("id", operationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+}
+
export async function getJobByOperationId(
client: SupabaseClient<Database>,
operationId: string
@@ -1362,6 +1415,7 @@ export async function backflushUntrackedMaterialsOnStepRecord(
.from("jobOperationStep")
.select("id, operationId")
.eq("id", args.jobOperationStepId)
+ .eq("companyId", args.companyId)
.single();
if (step.error || !step.data.operationId) return { error: step.error };
const operationId = step.data.operationId;
@@ -1614,6 +1668,7 @@ export async function getOperationEligibility(
.from("jobOperation")
.select("processId")
.eq("id", operationId)
+ .eq("companyId", companyId)
.maybeSingle();
if (operation.error) {
@@ -2157,6 +2212,24 @@ export async function insertAttributeRecord(
createdBy: string;
}
) {
+ // Callers pass a service-role client and the step id comes from the form.
+ // The upsert's conflict target is (jobOperationStepId, index), so a foreign
+ // step id would overwrite — and re-tenant — another company's record.
+ const step = await client
+ .from("jobOperationStep")
+ .select("id")
+ .eq("id", data.jobOperationStepId)
+ .eq("companyId", data.companyId)
+ .maybeSingle();
+ if (step.error) return step;
+ if (!step.data) {
+ log.warn("insertAttributeRecord: step not found in company", {
+ companyId: data.companyId,
+ jobOperationStepId: data.jobOperationStepId
+ });
+ return notFoundResponse("Job operation step not found");
+ }
+
return client.from("jobOperationStepRecord").upsert(data, {
onConflict: "jobOperationStepId, index",
ignoreDuplicates: false
@@ -2422,12 +2495,13 @@ export async function endProductionEventsByWorkCenter(
// block the production event that already succeeded.
async function autoStartJobAndOperation(
client: SupabaseClient<Database>,
- args: { jobOperationId: string; userId: string }
+ args: { jobOperationId: string; userId: string; companyId: string }
) {
const op = await client
.from("jobOperation")
.select("jobId, status")
.eq("id", args.jobOperationId)
+ .eq("companyId", args.companyId)
.maybeSingle();
if (op.error || !op.data) return;
@@ -2438,6 +2512,7 @@ async function autoStartJobAndOperation(
.from("jobOperation")
.update({ status: "In Progress", updatedBy: args.userId })
.eq("id", args.jobOperationId)
+ .eq("companyId", args.companyId)
.in("status", ["Todo", "Ready", "Waiting"])
);
}
@@ -2447,12 +2522,88 @@ async function autoStartJobAndOperation(
.from("job")
.update({ status: "In Progress", updatedBy: args.userId })
.eq("id", op.data.jobId)
+ .eq("companyId", args.companyId)
.in("status", ["Draft", "Planned", "Ready"])
);
}
await Promise.all(updates);
}
+/**
+ * Every record id a production event references must belong to the event's
+ * company. `startProductionEvent` is called with a service-role client (the
+ * QR start route) as well as the user client, and a foreign id here would
+ * attach another tenant's operation, work center, batch or serial to this
+ * company's timer and genealogy. One scoped query per id type.
+ */
+async function verifyProductionEventRefs(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ jobOperationId: string;
+ workCenterId?: string;
+ jobOperationBatchId?: string;
+ trackedEntityId?: string;
+ }
+): Promise<{ ok: true } | { ok: false; message: string }> {
+ const { companyId } = args;
+ const [operation, workCenter, batch, entity] = await Promise.all([
+ client
+ .from("jobOperation")
+ .select("id")
+ .eq("id", args.jobOperationId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ args.workCenterId
+ ? client
+ .from("workCenter")
+ .select("id")
+ .eq("id", args.workCenterId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null,
+ args.jobOperationBatchId
+ ? client
+ .from("jobOperationBatch")
+ .select("id")
+ .eq("id", args.jobOperationBatchId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null,
+ args.trackedEntityId
+ ? client
+ .from("trackedEntity")
+ .select("id")
+ .eq("id", args.trackedEntityId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null
+ ]);
+
+ const missing = [
+ !operation.data && "Job operation",
+ workCenter && !workCenter.data && "Work center",
+ batch && !batch.data && "Operation batch",
+ entity && !entity.data && "Tracked entity"
+ ].filter(Boolean) as string[];
+
+ if (missing.length > 0) {
+ log.warn("startProductionEvent: referenced record not found in company", {
+ companyId,
+ missing,
+ jobOperationId: args.jobOperationId,
+ workCenterId: args.workCenterId,
+ jobOperationBatchId: args.jobOperationBatchId,
+ trackedEntityId: args.trackedEntityId,
+ error:
+ operation.error ?? workCenter?.error ?? batch?.error ?? entity?.error
+ });
+ return { ok: false, message: `${missing[0]} not found` };
+ }
+
+ return { ok: true };
+}
+
export async function startProductionEvent(
client: SupabaseClient<Database>,
data: Omit<
@@ -2471,6 +2622,15 @@ export async function startProductionEvent(
/** `mes_qr` when the operator scanned a traveller rather than tapping a station. */
source: WorkSource = "mes"
) {
+ const refs = await verifyProductionEventRefs(client, {
+ companyId: data.companyId,
+ jobOperationId: data.jobOperationId,
+ workCenterId: data.workCenterId,
+ jobOperationBatchId: data.jobOperationBatchId,
+ trackedEntityId
+ });
+ if (!refs.ok) return notFoundResponse(refs.message);
+
if (trackedEntityId) {
const activityId = nanoid();
@@ -2480,6 +2640,7 @@ export async function startProductionEvent(
.from("jobOperation")
.select("*")
.eq("id", data.jobOperationId)
+ .eq("companyId", data.companyId)
.single()
]);
@@ -2535,7 +2696,8 @@ export async function startProductionEvent(
await autoStartJobAndOperation(client, {
jobOperationId: data.jobOperationId,
- userId: data.createdBy
+ userId: data.createdBy,
+ companyId: data.companyId
});
trackWorkEvent("job_operation_started", {
@@ -2558,7 +2720,8 @@ export async function startProductionEvent(
if (!eventInsert.error) {
await autoStartJobAndOperation(client, {
jobOperationId: data.jobOperationId,
- userId: data.createdBy
+ userId: data.createdBy,
+ companyId: data.companyId
});
const inserted = eventInsert.data?.[0];
diff --git a/apps/mes/app/services/picking.service.ts b/apps/mes/app/services/picking.service.ts
index b115ab9e74..432e389ed1 100644
--- a/apps/mes/app/services/picking.service.ts
+++ b/apps/mes/app/services/picking.service.ts
@@ -322,6 +322,7 @@ export async function setPickingListLineTrackedEntity(
quantity?: number;
unpick?: boolean;
userId: string;
+ companyId: string;
}
) {
const lineResult = await client
@@ -330,7 +331,8 @@ export async function setPickingListLineTrackedEntity(
"*, pickingList(locationId, companyId, status), item(itemTrackingType)"
)
.eq("id", args.pickingListLineId)
- .single();
+ .eq("companyId", args.companyId)
+ .maybeSingle();
if (lineResult.error || !lineResult.data) {
return { data: null, error: lineResult.error ?? "Line not found" };
@@ -381,7 +383,7 @@ export async function setPickingListLineTrackedEntity(
trackedEntityId: args.trackedEntityId,
locationId: pickingList.locationId,
userId: args.userId,
- companyId: pickingList.companyId
+ companyId: args.companyId
};
if (!args.unpick) {
body.fromStorageUnitId = args.fromStorageUnitId ?? null;
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
index e7c38f4fce..18f6e76b69 100644
--- a/apps/mes/app/services/quality.server.ts
+++ b/apps/mes/app/services/quality.server.ts
@@ -2,6 +2,7 @@ import type { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import { getLocationTimeZone } from "@carbon/database";
import { lockIssueDispositions } from "@carbon/database/quality";
+import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getDatabaseClient } from "~/services/database.server";
@@ -18,6 +19,8 @@ import {
type ServiceRole = Awaited<ReturnType<typeof getCarbonServiceRole>>;
+const logger = getLogger("mes", "quality");
+
export type ProductionEventIds = {
setupProductionEventId?: string;
laborProductionEventId?: string;
@@ -89,6 +92,51 @@ export async function createQualityIssue(
return { data: null, error: context.error, message: context.message };
}
+ // Caller-supplied references written with the service role: each must
+ // belong to this company, or the issue would link another tenant's rows.
+ const [issueType, inspection] = await Promise.all([
+ args.nonConformanceTypeId
+ ? serviceRole
+ .from("nonConformanceType")
+ .select("id")
+ .eq("id", args.nonConformanceTypeId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null,
+ args.inspectionId
+ ? serviceRole
+ .from("inspection")
+ .select("id")
+ .eq("id", args.inspectionId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : null
+ ]);
+ if (issueType && (issueType.error || !issueType.data)) {
+ logger.warn("Quality issue type not found for company", {
+ companyId,
+ nonConformanceTypeId: args.nonConformanceTypeId,
+ error: issueType.error
+ });
+ return {
+ data: null,
+ error: issueType.error,
+ message: "Quality issue type not found"
+ };
+ }
+ if (inspection && (inspection.error || !inspection.data)) {
+ logger.warn("Inspection not found for company", {
+ companyId,
+ inspectionId: args.inspectionId,
+ error: inspection.error
+ });
+ return {
+ data: null,
+ error: inspection.error,
+ message: "Inspection not found"
+ };
+ }
+
const nextSequence = await serviceRole.rpc("get_next_sequence", {
sequence_name: "nonConformance",
company_id: companyId
@@ -255,6 +303,18 @@ export async function getInspectionOutcomeState(
};
}
const inspection = inspectionResult.data as any;
+ // getInspection reads with the service role by id alone.
+ if (inspection.companyId !== args.companyId) {
+ logger.warn("Inspection not found for company", {
+ companyId: args.companyId,
+ inspectionId: args.inspectionId
+ });
+ return {
+ data: null,
+ error: null,
+ message: "Failed to load inspection"
+ };
+ }
const jobOperationId = inspection.sourceDocumentLineId as string | null;
if (inspection.sourceDocument !== "Job Operation" || !jobOperationId) {
return {
diff --git a/apps/mes/app/types/index.ts b/apps/mes/app/types/index.ts
index 8438462ee2..f48cba8163 100644
--- a/apps/mes/app/types/index.ts
+++ b/apps/mes/app/types/index.ts
@@ -13,6 +13,12 @@ export type UserContext = {
locationId: string;
companyId: string;
consoleMode: boolean;
+ /**
+ * Console mode as `userMiddleware` found it for a console session: `true`,
+ * or `null` when the settings could not be read (the session is kept). Not
+ * checked — `null` — outside console mode.
+ */
+ consoleEnabled: boolean | null;
effectiveUserId: string;
pinnedInUser: PinnedInUser | null;
};
diff --git a/docs/content/docs/building/architecture.mdx b/docs/content/docs/building/architecture.mdx
index 9ffa09284f..77dd13d6f2 100644
--- a/docs/content/docs/building/architecture.mdx
+++ b/docs/content/docs/building/architecture.mdx
@@ -414,19 +414,29 @@ so it can open a real transaction. This is the answer to the "three inserts aren
atomic" problem from [Part 2](#part-2-follow-one-click-all-the-way-down):
```ts
-return db.transaction().execute(async (trx) => {
- for (const { id, sortOrder, updatedBy } of updates) {
- await trx
- .updateTable("quoteLine")
- .set({ sortOrder, updatedBy })
- .where("id", "=", id)
- .execute();
- }
+// updateSortOrder (apps/erp/app/modules/shared/sort-order.ts), which every
+// drag-to-reorder route uses: one UPDATE for all the rows, inside a transaction.
+await db.transaction().execute(async (trx) => {
+ const { rows } = await sql<{ id: string }>`
+ UPDATE "quoteLine" AS t SET "sortOrder" = v."sortOrder", …
+ FROM (VALUES ${values}) AS v("id", "sortOrder")
+ WHERE t."id" = v."id"
+ AND t."companyId" = ${companyId}
+ AND t."quoteId" = ${quoteId}
+ RETURNING t."id"`.execute(trx);
+ // A row from another company or another quote matched nothing. Throwing
+ // here rolls back the rows that did match: all or nothing.
+ if (rows.length !== updates.length) throw new Error("…");
});
```
-Three warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it
-in `try/catch`. It applies **no** RLS, so authorize before you call it. And the pool it
+Four warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it
+in `try/catch`. It applies **no** RLS, so authorize before you call it, and then scope
+**every** statement yourself: `companyId` always, plus the parent document's id whenever
+the row ids come from the request. Without the parent filter, a request sent through one
+quote's URL could reorder the lines of any other quote in the company, including one
+that is already closed. Write one statement for the whole set rather than a query per row
+inside a loop. And the pool it
draws from is small (edge functions ask for exactly one connection,
`getConnectionPool(1)`): if code inside a transaction reaches for a second connection from
the same pool, that second request queues behind a transaction that cannot finish until it
diff --git a/docs/content/docs/integrations/project-management.mdx b/docs/content/docs/integrations/project-management.mdx
index d4afd26c7a..624e4e1f29 100644
--- a/docs/content/docs/integrations/project-management.mdx
+++ b/docs/content/docs/integrations/project-management.mdx
@@ -13,6 +13,19 @@ to an external issue and keep the two in step, status, assignee, and notes sync
Authenticate with a **Linear API key** (it begins with `lin_api`).
<Steps>
+ <Step>
+ ### Create the webhook in Linear
+
+ In Linear's API settings, create a new webhook and paste the URL shown in Carbon's setup instructions
+ (`/api/webhook/linear/<your company id>`). This is how changes made in Linear reach Carbon.
+ </Step>
+ <Step>
+ ### Copy the signing secret
+
+ Linear shows a **signing secret** on the webhook's detail page. Paste it into **Webhook Signing Secret**.
+ With it saved, Carbon only accepts webhook requests Linear has signed, and rejects any that are more
+ than a minute old.
+ </Step>
<Step>
### Paste your Linear API key
@@ -28,16 +41,31 @@ Authenticate with a **Linear API key** (it begins with `lin_api`).
| Setting | What it controls |
| --- | --- |
| API key | Your Linear API key — Carbon checks the `lin_api` prefix. |
+| Webhook signing secret | Optional. When set, webhook requests without a valid Linear signature are rejected. |
+
+<Callout type="warn">
+A Linear or Jira webhook with no secret saved in Carbon still works, so older setups keep syncing, but
+Carbon cannot tell its requests from forged ones. Add the secret to every webhook you create.
+</Callout>
## Jira
-Connect over **OAuth**. There are no fields to fill in beyond authorizing Carbon.
+Connect over **OAuth**. The only setting is an optional webhook secret.
<Steps>
<Step>
### Authorize over OAuth
- Authorize Carbon in Jira. There are no fields to fill in.
+ Authorize Carbon in Jira.
+ </Step>
+ <Step>
+ ### Create the webhook in Jira (optional)
+
+ For changes made in Jira to reach Carbon straight away, go to **System → WebHooks** in Jira and create a
+ webhook with the URL shown in Carbon's setup instructions (`/api/webhook/jira/<your company id>`),
+ subscribed to **Issue updated** and **Issue deleted**. Fill in the webhook's **Secret** field, and paste
+ the same value into **Webhook Secret** in Carbon. With it saved, Carbon only accepts webhook requests
+ Jira has signed.
</Step>
<Step>
### Link an action task
@@ -46,6 +74,10 @@ Connect over **OAuth**. There are no fields to fill in beyond authorizing Carbon
</Step>
</Steps>
+| Setting | What it controls |
+| --- | --- |
+| Webhook secret | Optional. When set, webhook requests without a valid Jira signature are rejected. |
+
<Callout type="warn">
Jira only appears when its OAuth client is configured server-side (`JIRA_CLIENT_ID`) — see
[Environment variables](/docs/platform/self-hosting/environment-variables).
diff --git a/docs/content/docs/reference/company-settings.mdx b/docs/content/docs/reference/company-settings.mdx
index 5a6a576d89..7b90bbd996 100644
--- a/docs/content/docs/reference/company-settings.mdx
+++ b/docs/content/docs/reference/company-settings.mdx
@@ -35,7 +35,7 @@ Company membership is per-user: one login can hold several companies and switch
<FieldTable>
<Field name="accountingEnabled" type="boolean">Master switch for the ledger. When off, operations complete without posting journal entries.</Field>
<Field name="timeCardEnabled" type="boolean">Turns on shop-floor time cards.</Field>
- <Field name="consoleEnabled" type="boolean">Enables the support/impersonation console.</Field>
+ <Field name="consoleEnabled" type="boolean">Enables MES console (shared-station) mode, where operators pin in with a 4-digit PIN. Business plan; toggled from **Settings → People** by someone with `settings_update`, and only through that screen — the API refuses a direct write to this column. See [console mode](/docs/reference/mes#console-shared-station-mode).</Field>
<Field name="requireMfa" type="boolean">Everyone needs an authenticator app to open this company. Edited from **Settings → System → Security**; locked on in controlled (ITAR) deployments. See [two-factor authentication](/docs/reference/two-factor).</Field>
<Field name="useMetric" type="boolean">Whether material units default to metric.</Field>
<Field name="materialGeneratedIds" type="boolean">Whether new materials get an auto-generated readable id.</Field>
diff --git a/docs/content/docs/reference/mes.mdx b/docs/content/docs/reference/mes.mdx
index ab4e9d9eb4..0639e7db0f 100644
--- a/docs/content/docs/reference/mes.mdx
+++ b/docs/content/docs/reference/mes.mdx
@@ -15,9 +15,9 @@ Once in, the operator sets their context. If the company has more than one locat
### Console (shared-station) mode
-A single tablet bolted to a work center can't ask every operator to log in and out all shift. **Console mode** turns that station into a shared kiosk. It's gated by the `consoleEnabled` company setting, and when on, the sidebar exposes a **"Console Mode"** toggle.
+A single tablet bolted to a work center can't ask every operator to log in and out all shift. **Console mode** turns that station into a shared kiosk. It's gated by the `consoleEnabled` company setting (Business plan), and when on, the sidebar exposes a **"Console Mode"** toggle. Switching a station INTO console mode takes `settings_update` on the account the station is signed in with; switching it back out is open to anyone, so a station is never stuck.
-In console mode an operator identifies themselves with a **4-digit PIN**, not a full login. The station prompts to enter a PIN for the named operator, checks it, and attributes the work to that person. Two things stop cold when the PIN is wrong or missing: the station shows **"Incorrect PIN"**, or **"No PIN set. Please set a PIN in your account settings."** if the person never configured one.
+In console mode an operator identifies themselves with a **4-digit PIN**, not a full login. PINs are generated by Carbon and handed out by an admin — shown once when an operator is created or a PIN is reset, and stored only as a hash (see [shop-floor PIN accounts](/docs/reference/permissions#shop-floor-pin-accounts)). The station prompts to enter a PIN for the named operator, checks it, and attributes the work to that person. Three things stop it: **"Incorrect PIN"**, **"Too many incorrect PINs. Please wait a few minutes and try again."** after repeated wrong guesses, or **"No PIN set. Ask an admin to set a console PIN for you."** if the person has none yet.
<Callout type="note" title="One station, many operators">
A shared station is meant to hand off. **"Switch Operator"** re-prompts for a PIN so the next person takes over, and **"Pin Out"** clears the current operator. Ending the shift also pins out automatically. The PIN identifies *who did the work*; it is not a substitute for the person's real account.
@@ -150,8 +150,11 @@ The exact blocks operators hit on the floor, and what unblocks each.
### "Incorrect PIN"
In console mode the 4-digit PIN entered for the named operator didn't match. Re-enter it, or use **"Switch Operator"** to pick the right person. The PIN identifies who did the work; it is not the person's login password.
-### "No PIN set. Please set a PIN in your account settings."
-The named operator has never configured a console PIN, so console mode can't attribute work to them. They set one in their account settings (in the ERP), then the station can pin them in.
+### "Too many incorrect PINs. Please wait a few minutes and try again."
+Five wrong PINs for one person within 15 minutes lock that person's pin-in, from every station, for a minute at first (doubling on repeat offenses, up to an hour). A station is also capped at 30 wrong PINs in 15 minutes across all operators — and stations signed in with the same account share that cap. Wait, then enter the right PIN.
+
+### "No PIN set. Ask an admin to set a console PIN for you."
+The named person has no console PIN, so console mode can't attribute work to them. PINs aren't chosen on the floor: an admin generates one in the ERP — **Reset PIN** under **Settings → Users → Operators** for an operator, or **Set Console PIN** on the **Accounts** list for anyone else (that one also needs `settings_update`). Then the station can pin them in.
### "This picking list is closed. Reopen it from the ERP to continue."
The picking list is already `Completed` or `Cancelled`, which locks it — the floor can't pick, unpick, short, or scan against a closed list. Reopening it requires an inventory permission the MES doesn't hold; a user reopens it from the ERP.
@@ -163,7 +166,7 @@ The picking list is already `Completed` or `Cancelled`, which locks it — the f
A time card was left open for twelve hours or more. Choose **"I'm Still Working"** to keep the shift open, or **"Set Clock Out"** to close it. Time cards are labor/presence time for payroll — separate from the per-operation production events that drive job costing.
### The Console Mode toggle or the time card isn't there
-Both are company-setting gated. **"Console Mode"** only appears when `consoleEnabled` is on; the **"Clock In"/"Clock Out"** time card (and the 12-hour prompt) only appear when `timeCardEnabled` is on. If a floor needs either, an admin enables it in company settings.
+Both are company-setting gated. **"Console Mode"** only appears when `consoleEnabled` is on and the plan includes it, and then only to an account with `settings_update` (or on a station already in console mode, so it can leave); the **"Clock In"/"Clock Out"** time card (and the 12-hour prompt) only appear when `timeCardEnabled` is on. If a floor needs either, an admin enables it in company settings.
### I can't drag a card to reschedule on the floor
The MES **"Schedule"** board is display and filter only — it never reschedules. Rebalancing the plan (moving an operation to another work center, or shifting a job's dates) happens on the [ERP scheduling boards](/docs/reference/scheduling), where a planner owns the sequence.
diff --git a/docs/content/docs/reference/permissions.mdx b/docs/content/docs/reference/permissions.mdx
index dd36917341..cc828e49ce 100644
--- a/docs/content/docs/reference/permissions.mdx
+++ b/docs/content/docs/reference/permissions.mdx
@@ -82,7 +82,7 @@ An invite is a company-scoped record keyed by email, and it carries the permissi
Not everyone who needs to touch Carbon has an email inbox. A machinist on the floor signs in to the [MES](/docs/reference/mes) with a **4-digit PIN** on a shared station tablet, not a magic link. These are **console operators**, and they're a distinct kind of account.
-Add one under **Settings → Users → Operators** (visible only when console mode is enabled for the company) with a name, a location, and a 4-digit PIN (`apps/erp/app/modules/users/users.models.ts:31`). Carbon creates a lightweight account with no email login and assigns it the **Console Operator** employee type automatically. On the shop floor the operator taps their name and enters the PIN, which Carbon checks against the account before starting their session (`apps/mes/app/routes/x+/console.pin-in.tsx:61`). You can reset an operator's PIN at any time from the same screen.
+Add one under **Settings → Users → Operators** (visible only when console mode is enabled for the company) with a name and a location. Carbon creates a lightweight account with no email login, assigns it the **Console Operator** employee type automatically, and generates a 4-digit PIN that is shown once, when the operator is created — Carbon stores only a hash of it, so copy it then. On the shop floor the operator taps their name and enters the PIN, which Carbon checks before starting their session. If a PIN is lost, reset it from the same screen to generate a new one; the old PIN stops working immediately. Resetting an operator's PIN takes `users_update`; setting a console PIN for any other employee (from the **Accounts** list) also takes `settings_update`.
<Callout type="note" title="An operator can graduate to a full user">
When a PIN account needs real ERP access, convert it: give it an email and a full employee type, and Carbon promotes the same person to a normal invited user without losing their history (`apps/erp/app/modules/users/users.server.ts:905`). Their old floor activity stays attached to the one identity.
@@ -112,11 +112,11 @@ Access gates, PIN accounts, and why a permission change didn't take.
### "Incorrect PIN"
The 4-digit PIN entered on the shop-floor station doesn't match the operator's account. Re-enter it, or reset the operator's PIN from **Settings → Users → Operators**.
-### "No PIN set. Please set a PIN in your account settings."
-The operator account being signed into has no PIN on record. Set one for that operator from the Operators screen before they can sign in on the floor.
+### "Too many incorrect PINs. Please wait a few minutes and try again."
+Five wrong PINs for one person within 15 minutes lock that person's pin-in for a while, from every station; the lock lasts a minute at first and doubles on repeat offenses. A single station is also capped at 30 wrong PINs in 15 minutes across everyone, and stations signed in with the same login share that cap. Wait it out — a correct PIN afterwards clears the person's count.
-### "PIN must be 4 digits"
-Creating or resetting an operator rejects anything that isn't exactly four digits. Enter a 4-digit numeric PIN.
+### "No PIN set. Ask an admin to set a console PIN for you."
+The person has no PIN on record, and PINs are never chosen on the floor: an admin generates one. For an operator, use **Reset PIN** on **Settings → Users → Operators** (needs `users_update`). For any other employee, use **Set Console PIN** on the **Accounts** list, which also needs `settings_update`, because a PIN lets whoever holds it act as that person on the floor.
### "Group members are required"
A bulk action — bulk permission edit, group edit, deactivate, resend/revoke invite — was submitted with no users selected. Select at least one user first.
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index ddc07a5247..17a724f946 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -41,6 +41,7 @@ pnpm --filter @carbon/auth test
| `./company.server` | Company switching, `updateCompanySession` |
| `./users.server` | `getUserClaims`, deactivation flows, cache invalidation |
| `./passkey.server` | WebAuthn/passkey registration and authentication |
+| `./console-pin.server` | MES console pin-in cookie (signed, bound to company + terminal session user): `setConsolePinIn`, `clearConsolePinIn`, `resolveConsolePinIn` (re-validated against the DB, memoized per read), `ConsolePinIn`; `requirePermissions` uses it to derive `userId` in console mode |
| `./self-signup.server` | Cloud self-signup blocklist: `isSelfSignupBlockedForEmail`, `SELF_SIGNUP_BLOCKED_MESSAGE` (free/disposable email domains; used by ERP login/verify/callback + MES callback) |
| `./middleware/flash.server` | Flash message middleware |
diff --git a/packages/auth/package.json b/packages/auth/package.json
index f8683a1b5e..0ca74a00cf 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -18,6 +18,7 @@
"./download-token.server": "./src/lib/download-token.server.ts",
"./oauth-state.server": "./src/lib/oauth-state.server.ts",
"./company.server": "./src/services/company.server.ts",
+ "./console-pin.server": "./src/services/console-pin.server.ts",
"./mfa.server": "./src/services/mfa.server.ts",
"./session.server": "./src/services/session.server.ts",
"./self-signup.server": "./src/services/self-signup.server.ts",
diff --git a/packages/auth/src/lib/oauth-state.server.test.ts b/packages/auth/src/lib/oauth-state.server.test.ts
index 3d6b3c48c0..f928d7a74d 100644
--- a/packages/auth/src/lib/oauth-state.server.test.ts
+++ b/packages/auth/src/lib/oauth-state.server.test.ts
@@ -6,7 +6,16 @@ vi.mock("../config/env", () => ({
SESSION_SECRET: "test-session-secret"
}));
-import { consumeOAuthState, issueOAuthState } from "./oauth-state.server";
+import {
+ consumeOAuthState,
+ issueOAuthState,
+ issueOAuthStates
+} from "./oauth-state.server";
+
+/** The cookie value (name=value) from a Set-Cookie header, as a browser sends it. */
+function cookieHeader(setCookie: string) {
+ return setCookie.split(";")[0]!;
+}
function requestWithCookie(cookie: string) {
return new Request("http://localhost/api/integrations/ramp/oauth", {
@@ -82,7 +91,7 @@ describe("OAuth state session", () => {
it("rejects an expired state", async () => {
const issued = await issueOAuthState(expected);
- vi.advanceTimersByTime(10 * 60 * 1000 + 1);
+ vi.advanceTimersByTime(60 * 60 * 1000 + 1);
const consumed = await consumeOAuthState(
requestWithCookie(issued.cookie),
@@ -92,4 +101,91 @@ describe("OAuth state session", () => {
expect(consumed.valid).toBe(false);
});
+
+ it("keeps one pending state per integration", async () => {
+ const onshape = { ...expected, integrationId: "onshape" };
+ const ramp = await issueOAuthState(expected);
+ const both = await issueOAuthState(
+ onshape,
+ requestWithCookie(cookieHeader(ramp.cookie))
+ );
+
+ const onshapeConsumed = await consumeOAuthState(
+ requestWithCookie(cookieHeader(both.cookie)),
+ both.state,
+ onshape
+ );
+ const rampConsumed = await consumeOAuthState(
+ requestWithCookie(cookieHeader(onshapeConsumed.cookie)),
+ ramp.state,
+ expected
+ );
+
+ expect(onshapeConsumed.valid).toBe(true);
+ expect(rampConsumed.valid).toBe(true);
+ });
+
+ it("issues several states in one cookie", async () => {
+ const payloads = ["ramp", "xero", "jira"].map((integrationId) => ({
+ ...expected,
+ integrationId
+ }));
+ const issued = await issueOAuthStates(null, payloads);
+
+ for (const payload of payloads) {
+ const consumed = await consumeOAuthState(
+ requestWithCookie(cookieHeader(issued.cookie)),
+ issued.states[payload.integrationId]!,
+ payload
+ );
+ expect(consumed.valid).toBe(true);
+ }
+ });
+
+ it("does not accept one integration's state for another", async () => {
+ const issued = await issueOAuthStates(null, [
+ expected,
+ { ...expected, integrationId: "xero" }
+ ]);
+
+ const consumed = await consumeOAuthState(
+ requestWithCookie(cookieHeader(issued.cookie)),
+ issued.states.ramp!,
+ { ...expected, integrationId: "xero" }
+ );
+
+ expect(consumed.valid).toBe(false);
+ });
+
+ it("reuses a still-fresh state so a second page load does not invalidate the first", async () => {
+ const first = await issueOAuthState(expected);
+ vi.advanceTimersByTime(60 * 1000);
+ const second = await issueOAuthState(
+ expected,
+ requestWithCookie(cookieHeader(first.cookie))
+ );
+
+ expect(second.state).toBe(first.state);
+ });
+
+ it("replaces a state bound to a different user instead of reusing it", async () => {
+ const first = await issueOAuthState(expected);
+ const second = await issueOAuthState(
+ { ...expected, userId: "user-2" },
+ requestWithCookie(cookieHeader(first.cookie))
+ );
+
+ expect(second.state).not.toBe(first.state);
+ });
+
+ it("rejects an empty state even when one is stored", async () => {
+ const issued = await issueOAuthState(expected);
+ const consumed = await consumeOAuthState(
+ requestWithCookie(cookieHeader(issued.cookie)),
+ "",
+ expected
+ );
+
+ expect(consumed.valid).toBe(false);
+ });
});
diff --git a/packages/auth/src/lib/oauth-state.server.ts b/packages/auth/src/lib/oauth-state.server.ts
index 760f19c143..9d0d2358f4 100644
--- a/packages/auth/src/lib/oauth-state.server.ts
+++ b/packages/auth/src/lib/oauth-state.server.ts
@@ -3,8 +3,21 @@ import { createCookieSessionStorage } from "react-router";
import { CarbonEdition, DOMAIN, SESSION_SECRET } from "../config/env";
import { getCookieDomain } from "../utils/cookie";
-const OAUTH_STATE_MAX_AGE_SECONDS = 10 * 60;
-const OAUTH_STATE_KEY = "oauth-state";
+// Long enough to outlive an integrations page left open for a while: the state
+// is issued when the page loads, not when Connect is clicked. It is single-use
+// and bound to integration + user + company, so the lifetime is not what
+// protects it.
+const OAUTH_STATE_MAX_AGE_SECONDS = 60 * 60;
+// A still-valid state with at least this much life left is handed out again
+// instead of being replaced, so two tabs of the integrations page (or a page
+// revalidation) do not invalidate each other's Connect links.
+const OAUTH_STATE_REUSE_MIN_REMAINING_MS =
+ (OAUTH_STATE_MAX_AGE_SECONDS * 1000) / 2;
+// One entry per integration, so several connect flows can be in flight at once.
+const OAUTH_STATES_KEY = "oauth-states";
+// The pre-keyed shape held a single state; read it so a flow started before
+// the upgrade still completes.
+const LEGACY_OAUTH_STATE_KEY = "oauth-state";
export type OAuthStatePayload = {
integrationId: string;
@@ -17,6 +30,8 @@ type StoredOAuthState = OAuthStatePayload & {
expiresAt: number;
};
+type StoredOAuthStates = Record<string, StoredOAuthState>;
+
const isTestEdition = CarbonEdition === Edition.Test;
const cookieDomain = isTestEdition ? undefined : getCookieDomain(DOMAIN);
@@ -33,23 +48,123 @@ const oauthStateStorage = createCookieSessionStorage({
}
});
-export async function issueOAuthState(payload: OAuthStatePayload) {
- const session = await oauthStateStorage.getSession();
- const state = crypto.randomUUID();
- session.set(OAUTH_STATE_KEY, {
- ...payload,
- state,
- expiresAt: Date.now() + OAUTH_STATE_MAX_AGE_SECONDS * 1000
- } satisfies StoredOAuthState);
+type OAuthStateSession = Awaited<
+ ReturnType<typeof oauthStateStorage.getSession>
+>;
+
+function isStoredOAuthState(value: unknown): value is StoredOAuthState {
+ if (!value || typeof value !== "object") return false;
+ const v = value as Record<string, unknown>;
+ return (
+ typeof v.state === "string" &&
+ typeof v.integrationId === "string" &&
+ typeof v.userId === "string" &&
+ typeof v.companyId === "string" &&
+ typeof v.expiresAt === "number"
+ );
+}
+
+/** The live (unexpired) states in the session, keyed by integration. */
+function readStates(session: OAuthStateSession): StoredOAuthStates {
+ const states: StoredOAuthStates = {};
+ const now = Date.now();
+
+ const legacy = session.get(LEGACY_OAUTH_STATE_KEY);
+ if (isStoredOAuthState(legacy) && legacy.expiresAt > now) {
+ states[legacy.integrationId] = legacy;
+ }
+
+ const stored = session.get(OAUTH_STATES_KEY);
+ if (stored && typeof stored === "object") {
+ for (const [integrationId, value] of Object.entries(stored)) {
+ if (
+ isStoredOAuthState(value) &&
+ value.integrationId === integrationId &&
+ value.expiresAt > now
+ ) {
+ states[integrationId] = value;
+ }
+ }
+ }
+
+ return states;
+}
+
+async function commitStates(
+ session: OAuthStateSession,
+ states: StoredOAuthStates
+) {
+ session.unset(LEGACY_OAUTH_STATE_KEY);
+ if (Object.keys(states).length === 0) {
+ return oauthStateStorage.destroySession(session);
+ }
+ session.set(OAUTH_STATES_KEY, states);
+ return oauthStateStorage.commitSession(session, {
+ maxAge: OAUTH_STATE_MAX_AGE_SECONDS
+ });
+}
+
+/**
+ * Issue a state per payload, keeping every other integration's pending state
+ * already in the request's cookie. Returns the states keyed by integration id
+ * and ONE Set-Cookie value that carries all of them.
+ */
+export async function issueOAuthStates(
+ request: Request | null,
+ payloads: OAuthStatePayload[]
+) {
+ const session = await oauthStateStorage.getSession(
+ request?.headers.get("Cookie")
+ );
+ const states = readStates(session);
+ const now = Date.now();
+ const issued: Record<string, string> = {};
+
+ for (const payload of payloads) {
+ const existing = states[payload.integrationId];
+ const reusable =
+ !!existing &&
+ existing.userId === payload.userId &&
+ existing.companyId === payload.companyId &&
+ existing.expiresAt - now >= OAUTH_STATE_REUSE_MIN_REMAINING_MS;
+
+ if (reusable) {
+ issued[payload.integrationId] = existing.state;
+ continue;
+ }
+
+ const state = crypto.randomUUID();
+ states[payload.integrationId] = {
+ ...payload,
+ state,
+ expiresAt: now + OAUTH_STATE_MAX_AGE_SECONDS * 1000
+ };
+ issued[payload.integrationId] = state;
+ }
return {
- state,
- cookie: await oauthStateStorage.commitSession(session, {
- maxAge: OAUTH_STATE_MAX_AGE_SECONDS
- })
+ states: issued,
+ cookie: await commitStates(session, states)
};
}
+/**
+ * Issue one integration's state. Pass the request so other integrations'
+ * pending states in its cookie survive the new Set-Cookie.
+ */
+export async function issueOAuthState(
+ payload: OAuthStatePayload,
+ request: Request | null = null
+) {
+ const { states, cookie } = await issueOAuthStates(request, [payload]);
+ return { state: states[payload.integrationId]!, cookie };
+}
+
+/**
+ * Check a callback's `state` against the one stored for `expected.integrationId`
+ * and remove it — single-use whether or not it matched. Other integrations'
+ * pending states are left in place.
+ */
export async function consumeOAuthState(
request: Request,
state: string,
@@ -58,19 +173,22 @@ export async function consumeOAuthState(
const session = await oauthStateStorage.getSession(
request.headers.get("Cookie")
);
- const stored = session.get(OAUTH_STATE_KEY) as StoredOAuthState | undefined;
+ const states = readStates(session);
+ const stored = states[expected.integrationId];
const valid =
!!stored &&
+ !!state &&
stored.expiresAt > Date.now() &&
stored.state === state &&
stored.integrationId === expected.integrationId &&
stored.userId === expected.userId &&
stored.companyId === expected.companyId;
+ delete states[expected.integrationId];
+
return {
valid,
- // State is single-use regardless of whether the supplied value matched.
- cookie: await oauthStateStorage.destroySession(session)
+ cookie: await commitStates(session, states)
};
}
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index afc78e9c4f..42af007ece 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -15,10 +15,8 @@ import { createHash } from "crypto";
import { redirect } from "react-router";
import {
CarbonEdition,
- CONTROLLED_ENVIRONMENT,
IS_LOCAL_DEV,
REFRESH_ACCESS_TOKEN_THRESHOLD,
- SESSION_IDLE_LOCK_MS,
STRIPE_BYPASS_COMPANY_IDS,
VERCEL_URL
} from "../config/env";
@@ -31,6 +29,7 @@ import { error } from "../utils/result";
import { type ApiKeyRecord, getApiKeyRecord } from "./api-key.server";
import { logAuthEvent } from "./auth-events.server";
import { isCarbonOwnedCompany } from "./company.server";
+import { resolveConsolePinIn } from "./console-pin.server";
import {
destroyAuthSession,
flash,
@@ -166,44 +165,21 @@ export function makeAuthSession(
* If console mode is on and an operator is pinned in, returns
* the operator's ID. Otherwise returns the session user's ID.
*
- * Console mode is read from the auth session; pin-in state is
- * still read from the `console-pin-{companyId}` cookie.
+ * Console mode is read from the auth session; the pin-in from the SIGNED
+ * `console-pin-{companyId}` cookie, re-validated against the database on every
+ * request (`resolveConsolePinIn`): a forged, legacy, stale or foreign cookie,
+ * a pinned user who is not an active employee of this company, or console mode
+ * switched off for the company all fall back to the session user.
*/
-function getEffectiveUser(
+async function getEffectiveUser(
request: Request,
companyId: string,
sessionUserId: string,
consoleMode: boolean
-): string {
+): Promise<string> {
if (!consoleMode) return sessionUserId;
-
- const cookieHeader = request.headers.get("cookie");
- if (!cookieHeader) return sessionUserId;
-
- // Parse only the pin-in cookie we need
- const cookies = Object.fromEntries(
- cookieHeader.split(";").map((c) => {
- const [key, ...rest] = c.trim().split("=");
- return [key, decodeURIComponent(rest.join("="))];
- })
- );
-
- const pinRaw = cookies[`console-pin-${companyId}`];
- if (!pinRaw) return sessionUserId;
-
- try {
- const pinIn = JSON.parse(pinRaw);
- const elapsed = Date.now() - pinIn.pinnedAt;
- // Console operator idle window. A controlled environment (ITAR/CUI, NIST
- // 3.1.10) drops the operator to re-PIN after the standard idle-lock window
- // instead of the default 1h — pinnedAt is refreshed on every shell
- // navigation, so this is effectively an inactivity timeout.
- const maxAge = CONTROLLED_ENVIRONMENT ? SESSION_IDLE_LOCK_MS : 3600000;
- if (elapsed > maxAge) return sessionUserId;
- return pinIn.userId ?? sessionUserId;
- } catch {
- return sessionUserId;
- }
+ const pinIn = await resolveConsolePinIn(request, companyId, sessionUserId);
+ return pinIn?.userId ?? sessionUserId;
}
export async function requirePermissions(
@@ -369,7 +345,7 @@ export async function requirePermissions(
companyId,
companyGroupId,
email,
- userId: getEffectiveUser(request, companyId, userId, consoleMode),
+ userId: await getEffectiveUser(request, companyId, userId, consoleMode),
sessionUserId: userId,
consoleMode
};
@@ -430,7 +406,7 @@ export async function requirePermissions(
companyId,
companyGroupId,
email,
- userId: getEffectiveUser(request, companyId, userId, consoleMode),
+ userId: await getEffectiveUser(request, companyId, userId, consoleMode),
sessionUserId: userId,
consoleMode
};
diff --git a/packages/auth/src/services/console-pin.server.test.ts b/packages/auth/src/services/console-pin.server.test.ts
new file mode 100644
index 0000000000..3ad16036dc
--- /dev/null
+++ b/packages/auth/src/services/console-pin.server.test.ts
@@ -0,0 +1,160 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../config/env", () => ({
+ CarbonEdition: "Community",
+ CONTROLLED_ENVIRONMENT: false,
+ DOMAIN: "localhost",
+ SESSION_IDLE_LOCK_MS: 15 * 60 * 1000,
+ SESSION_SECRET: "test-session-secret"
+}));
+
+// Import-safety only: these tests exercise the cookie (real react-router
+// signing); the database re-validation in `resolveConsolePinIn` is not faked.
+vi.mock("../lib/supabase/client.server", () => ({
+ getCarbonServiceRole: vi.fn()
+}));
+
+import {
+ readConsolePinInCookieUnverified,
+ setConsolePinIn
+} from "./console-pin.server";
+
+const companyId = "company-1";
+const terminal = "terminal-user";
+const operator = {
+ userId: "operator-1",
+ name: "Op One",
+ avatarUrl: null,
+ pinnedAt: 0
+};
+
+function cookieValue(setCookie: string) {
+ return setCookie.split(";")[0]!;
+}
+
+function requestWithCookie(cookie: string) {
+ return new Request("http://localhost/x/operations", {
+ headers: { Cookie: cookie }
+ });
+}
+
+describe("console pin-in cookie", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-09-26T12:00:00Z"));
+ operator.pinnedAt = Date.now();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("round-trips a signed pin-in", async () => {
+ const cookie = await setConsolePinIn(companyId, terminal, operator);
+ expect(cookie).toMatch(/HttpOnly/i);
+ const read = await readConsolePinInCookieUnverified(
+ requestWithCookie(cookieValue(cookie)),
+ companyId,
+ terminal
+ );
+ expect(read).toEqual(operator);
+ });
+
+ it("rejects a hand-crafted unsigned (legacy) cookie", async () => {
+ const forged = encodeURIComponent(
+ JSON.stringify({ ...operator, userId: "someone-else" })
+ );
+ const read = await readConsolePinInCookieUnverified(
+ requestWithCookie(`console-pin-${companyId}=${forged}`),
+ companyId,
+ terminal
+ );
+ expect(read).toBeNull();
+ });
+
+ // The two tests around this one send values react-router cannot decode, so
+ // they read as null with or without a signature. This one is exactly what an
+ // UNSIGNED cookie would serialize to — correct shape, company, terminal and
+ // a fresh pinnedAt — so only the missing signature can reject it.
+ it("rejects a well-formed unsigned cookie naming another operator", async () => {
+ const forged = encodeURIComponent(
+ btoa(
+ JSON.stringify({
+ ...operator,
+ userId: "someone-else",
+ companyId,
+ sessionUserId: terminal,
+ pinnedAt: Date.now()
+ })
+ )
+ );
+ const read = await readConsolePinInCookieUnverified(
+ requestWithCookie(`console-pin-${companyId}=${forged}`),
+ companyId,
+ terminal
+ );
+ expect(read).toBeNull();
+ });
+
+ it("rejects a signed cookie whose payload was edited", async () => {
+ const cookie = cookieValue(
+ await setConsolePinIn(companyId, terminal, operator)
+ );
+ const [name, value] = cookie.split("=");
+ const [payload, signature] = decodeURIComponent(value!).split(".");
+ const edited = btoa(
+ JSON.stringify({
+ ...JSON.parse(atob(payload!)),
+ userId: "someone-else"
+ })
+ );
+ const read = await readConsolePinInCookieUnverified(
+ requestWithCookie(
+ `${name}=${encodeURIComponent(`${edited}.${signature}`)}`
+ ),
+ companyId,
+ terminal
+ );
+ expect(read).toBeNull();
+ });
+
+ it("is bound to the company and the terminal session user", async () => {
+ const cookie = cookieValue(
+ await setConsolePinIn(companyId, terminal, operator)
+ );
+ // Renamed to another company's cookie name: the signature still verifies
+ // (it covers the value only), the embedded companyId does not.
+ const renamed = cookie.replace(
+ `console-pin-${companyId}`,
+ "console-pin-company-2"
+ );
+ expect(
+ await readConsolePinInCookieUnverified(
+ requestWithCookie(renamed),
+ "company-2",
+ terminal
+ )
+ ).toBeNull();
+ expect(
+ await readConsolePinInCookieUnverified(
+ requestWithCookie(cookie),
+ companyId,
+ "another-terminal"
+ )
+ ).toBeNull();
+ });
+
+ it("expires after the idle window", async () => {
+ const cookie = cookieValue(
+ await setConsolePinIn(companyId, terminal, operator)
+ );
+ vi.setSystemTime(Date.now() + 61 * 60 * 1000);
+ expect(
+ await readConsolePinInCookieUnverified(
+ requestWithCookie(cookie),
+ companyId,
+ terminal
+ )
+ ).toBeNull();
+ });
+});
diff --git a/packages/auth/src/services/console-pin.server.ts b/packages/auth/src/services/console-pin.server.ts
new file mode 100644
index 0000000000..a0d8494a1f
--- /dev/null
+++ b/packages/auth/src/services/console-pin.server.ts
@@ -0,0 +1,194 @@
+import { oncePerRead } from "@carbon/logger/middleware.server";
+import { Edition } from "@carbon/utils";
+import { type Cookie, createCookie } from "react-router";
+import {
+ CarbonEdition,
+ CONTROLLED_ENVIRONMENT,
+ DOMAIN,
+ SESSION_IDLE_LOCK_MS,
+ SESSION_SECRET
+} from "../config/env";
+import { getCarbonServiceRole } from "../lib/supabase/client.server";
+import { getCookieDomain } from "../utils/cookie";
+
+/**
+ * Console (shared MES kiosk) pin-in state.
+ *
+ * A console terminal is logged in as ONE session user; an operator "pins in"
+ * with their PIN and every action is then attributed to them (`requirePermissions`
+ * returns their id as `userId`). The pin-in lives in the `console-pin-<companyId>`
+ * cookie, which is therefore an identity claim and must be:
+ *
+ * - SIGNED (`SESSION_SECRET`, like the `carbon` session cookie) so a hand-crafted
+ * value is rejected. A legacy unsigned value fails `unsign` and reads as
+ * "not pinned" — the operator simply pins in again.
+ * - BOUND to the company and the terminal's session user, so a cookie copied to
+ * another company name or another terminal is ignored.
+ * - RE-VALIDATED against the database on every request (`resolveConsolePinIn`):
+ * the pinned user must still be an ACTIVE employee of THIS company and console
+ * mode must still be switched on. A signature only proves we issued the cookie,
+ * not that the operator is still allowed to act.
+ */
+
+const CONSOLE_PIN_PREFIX = "console-pin-";
+const CONSOLE_PIN_MAX_AGE = 60 * 60; // 1 hour in seconds
+const CONSOLE_PIN_MAX_AGE_MS = CONSOLE_PIN_MAX_AGE * 1000;
+
+// A controlled environment (ITAR/CUI, NIST 3.1.10) drops a shared-console operator
+// to re-PIN after the standard idle-lock window instead of 1h. pinnedAt is refreshed
+// on every shell navigation (see MES x+/_layout loader), so this is an inactivity
+// window.
+const consolePinMaxAgeMs = () =>
+ CONTROLLED_ENVIRONMENT ? SESSION_IDLE_LOCK_MS : CONSOLE_PIN_MAX_AGE_MS;
+
+export interface ConsolePinIn {
+ userId: string;
+ name: string;
+ avatarUrl: string | null;
+ pinnedAt: number; // unix timestamp ms
+}
+
+interface StoredConsolePinIn extends ConsolePinIn {
+ companyId: string;
+ sessionUserId: string;
+}
+
+const isTestEdition = CarbonEdition === Edition.Test;
+const secure = !!getCookieDomain(DOMAIN);
+
+const cookies = new Map<string, Cookie>();
+
+function getConsolePinCookie(companyId: string): Cookie {
+ let cookie = cookies.get(companyId);
+ if (!cookie) {
+ cookie = createCookie(`${CONSOLE_PIN_PREFIX}${companyId}`, {
+ httpOnly: true,
+ path: "/",
+ sameSite: isTestEdition ? "none" : "lax",
+ secrets: [SESSION_SECRET!],
+ secure,
+ maxAge: CONSOLE_PIN_MAX_AGE
+ });
+ cookies.set(companyId, cookie);
+ }
+ return cookie;
+}
+
+function isStoredConsolePinIn(value: unknown): value is StoredConsolePinIn {
+ if (!value || typeof value !== "object") return false;
+ const v = value as Record<string, unknown>;
+ return (
+ typeof v.userId === "string" &&
+ v.userId.length > 0 &&
+ typeof v.companyId === "string" &&
+ typeof v.sessionUserId === "string" &&
+ typeof v.name === "string" &&
+ (v.avatarUrl === null || typeof v.avatarUrl === "string") &&
+ typeof v.pinnedAt === "number" &&
+ Number.isFinite(v.pinnedAt)
+ );
+}
+
+/**
+ * Read the pin-in cookie WITHOUT touching the database: signature, shape,
+ * company/terminal binding and idle window. Exported for its tests only — use
+ * `resolveConsolePinIn` for any identity decision.
+ */
+export async function readConsolePinInCookieUnverified(
+ request: Request,
+ companyId: string,
+ sessionUserId: string
+): Promise<ConsolePinIn | null> {
+ const cookieHeader = request.headers.get("cookie");
+ if (!cookieHeader) return null;
+
+ let parsed: unknown;
+ try {
+ parsed = await getConsolePinCookie(companyId).parse(cookieHeader);
+ } catch {
+ return null;
+ }
+
+ if (!isStoredConsolePinIn(parsed)) return null;
+ if (parsed.companyId !== companyId) return null;
+ if (parsed.sessionUserId !== sessionUserId) return null;
+ if (Date.now() - parsed.pinnedAt > consolePinMaxAgeMs()) return null;
+
+ return {
+ userId: parsed.userId,
+ name: parsed.name,
+ avatarUrl: parsed.avatarUrl,
+ pinnedAt: parsed.pinnedAt
+ };
+}
+
+async function loadConsolePinIn(
+ request: Request,
+ companyId: string,
+ sessionUserId: string
+): Promise<ConsolePinIn | null> {
+ const pinIn = await readConsolePinInCookieUnverified(
+ request,
+ companyId,
+ sessionUserId
+ );
+ if (!pinIn) return null;
+
+ const serviceRole = getCarbonServiceRole();
+ // `employees` only lists users whose `user.active` is true; `employee.active`
+ // is false once the person is deactivated in this company.
+ const [employee, settings] = await Promise.all([
+ serviceRole
+ .from("employees")
+ .select("id")
+ .eq("id", pinIn.userId)
+ .eq("companyId", companyId)
+ .eq("active", true)
+ .maybeSingle(),
+ serviceRole
+ .from("companySettings")
+ .select("consoleEnabled")
+ .eq("id", companyId)
+ .maybeSingle()
+ ]);
+
+ if (employee.error || settings.error) return null;
+ if (!employee.data || !settings.data?.consoleEnabled) return null;
+
+ return pinIn;
+}
+
+/**
+ * The operator pinned in at this console terminal, or null. Null whenever the
+ * cookie is missing, forged, legacy (unsigned), bound to another company or
+ * terminal, idle past its window, names someone who is not an active employee
+ * of `companyId`, or console mode has been switched off for the company.
+ *
+ * Memoized per read request — `requirePermissions` and the MES shell middleware
+ * both resolve it.
+ */
+export function resolveConsolePinIn(
+ request: Request,
+ companyId: string,
+ sessionUserId: string
+): Promise<ConsolePinIn | null> {
+ return oncePerRead(`console-pin:${companyId}:${sessionUserId}`, () =>
+ loadConsolePinIn(request, companyId, sessionUserId)
+ );
+}
+
+export function setConsolePinIn(
+ companyId: string,
+ sessionUserId: string,
+ data: ConsolePinIn
+): Promise<string> {
+ return getConsolePinCookie(companyId).serialize({
+ ...data,
+ companyId,
+ sessionUserId
+ } satisfies StoredConsolePinIn);
+}
+
+export function clearConsolePinIn(companyId: string): Promise<string> {
+ return getConsolePinCookie(companyId).serialize("", { maxAge: 0 });
+}
diff --git a/packages/auth/src/utils/http.test.ts b/packages/auth/src/utils/http.test.ts
new file mode 100644
index 0000000000..2060a7df4e
--- /dev/null
+++ b/packages/auth/src/utils/http.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { safeRedirect } from "./http";
+
+describe("safeRedirect", () => {
+ it("keeps a same-origin path", () => {
+ expect(safeRedirect("/x/sales/orders?tab=open", "/x")).toBe(
+ "/x/sales/orders?tab=open"
+ );
+ });
+
+ it.each([
+ ["an absolute URL", "https://evil.com"],
+ ["a protocol-relative URL", "//evil.com"],
+ ["a backslash host", "/\\evil.com"],
+ ["a relative path", "x/sales"],
+ ["an empty value", ""],
+ ["no value", null]
+ ])("falls back for %s", (_label, to) => {
+ expect(safeRedirect(to, "/x")).toBe("/x");
+ });
+});
diff --git a/packages/auth/src/utils/http.ts b/packages/auth/src/utils/http.ts
index 3fc0e82e3e..6fb60218a8 100644
--- a/packages/auth/src/utils/http.ts
+++ b/packages/auth/src/utils/http.ts
@@ -87,11 +87,15 @@ export function safeRedirect(
to: FormDataEntryValue | string | null | undefined,
defaultRedirect = path.to.authenticatedRoot
) {
+ // Only a same-origin path. Browsers read `/\host` like `//host` (a
+ // protocol-relative URL to another origin), so a backslash in second place is
+ // refused along with `//`.
if (
!to ||
typeof to !== "string" ||
!to.startsWith("/") ||
- to.startsWith("//")
+ to.startsWith("//") ||
+ to.startsWith("/\\")
) {
return defaultRedirect;
}
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 2981f0ef1e..1b96e65bd0 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -31,13 +31,15 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
## Key Patterns
-- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
+- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn`, `noRequiredColumnWithoutDefault`, `noViewWithoutInvoker` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount; `noViewWithoutInvoker` fails a `CREATE [OR REPLACE] VIEW` that does not state `security_invoker` — `CREATE OR REPLACE` replaces a view's options, so omitting the clause turns it into an owner-rights view that bypasses RLS for every PostgREST caller, and `openJobMaterialLines` leaked every company's rows that way. `security_invoker = false` passes, so an owner-rights view is a visible decision; materialized views are not matched. It reads one file's text, so an `EXECUTE format(...)` view or a later `ALTER VIEW … RESET` escapes it — the invariant below is the backstop); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
+- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app` or `packages/jobs/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. Edge functions and `packages/ee` are out of scope (see the file header). No baseline entries — every hit was fixed when it was added
- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential first
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
-- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
+- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + snippet` (no line number, so edits above a baselined hit don't un-baseline it)
- **Invariants**: SQL queries loaded from directory, injected `Query` for testability
+- **`view-without-security-invoker.sql`**: every `public` view runs as its caller (`security_invoker` true in `pg_class.reloptions`), whatever put it there — the live-catalog backstop for `noViewWithoutInvoker`. `modules` and `eventSystemTrigger` are excluded by name (no tenant data). Like every invariant it needs a live connection and does not run in CI
- **`tracked-entity-zero-available.sql`**: a lot whose quantity is gone must be `Consumed`, never a live status. `Scrapped`/`Rejected` are excluded — both are quality markers kept as historical record and already excluded from on-hand. Enforcement of the drain rule is per-writer, so this is the net that catches husks from ANY source: rows predating the rule, and any writer that revives a drained lot (unconsume, shipment void, disposition Use As Is / Rework). Run it before deciding whether to promote the rule to a DB CHECK
- **Workflows**: two DB-backed drift checks, answering different questions.
`src/invariants/workflow-trigger-event-drift.sql` (via `pnpm --filter @carbon/checks invariants`)
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index 8a9ebed2f7..da4b857090 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -568,5 +568,53 @@
"no-required-column-without-default::20240915192542_job-methods.sql::ADD COLUMN \"jobMakeMethodId\" TEXT NOT NULL",
"no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN \"supplierInteractionId\" TEXT NOT NULL",
"no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN IF NOT EXISTS \"supplierInteractionId\" TEXT NOT NULL",
- "no-required-column-without-default::20260402000000_journal-entries.sql::ADD COLUMN \"journalEntryId\" TEXT NOT NULL"
+ "no-required-column-without-default::20260402000000_journal-entries.sql::ADD COLUMN \"journalEntryId\" TEXT NOT NULL",
+ "no-view-without-invoker::20230123004409_permissions.sql::CREATE VIEW \"modules\" AS",
+ "no-view-without-invoker::20230123004436_employee.sql::CREATE OR REPLACE VIEW \"companies\" AS",
+ "no-view-without-invoker::20230123004632_groups.sql::CREATE OR REPLACE VIEW \"groupMembers\" AS",
+ "no-view-without-invoker::20230123004632_groups.sql::CREATE OR REPLACE VIEW \"groups\" AS",
+ "no-view-without-invoker::20230123004632_groups.sql::CREATE RECURSIVE VIEW groups_recursive ( \"groupId\", \"name\", \"companyId\", \"parentId\", \"isIdentityGroup\", \"isEmployeeTypeGroup\", \"isCustomerOrgGroup\", \"isCustomerTypeGroup\", \"isSupplierOrgGroup\", \"isSupplierTypeGroup\", \"user\" ) AS",
+ "no-view-without-invoker::20230315222231_holidays.sql::CREATE OR REPLACE VIEW \"holidayYears\" AS",
+ "no-view-without-invoker::20230319224154_partners.sql::CREATE OR REPLACE VIEW \"partners\" AS",
+ "no-view-without-invoker::20230329021751_contractors.sql::CREATE OR REPLACE VIEW \"contractors\" AS",
+ "no-view-without-invoker::20230330024715_accounts.sql::CREATE OR REPLACE VIEW \"accountCategories\" AS",
+ "no-view-without-invoker::20230330024715_accounts.sql::CREATE OR REPLACE VIEW \"accounts\" AS",
+ "no-view-without-invoker::20230423023136_documents.sql::CREATE OR REPLACE VIEW \"documentLabels\" AS",
+ "no-view-without-invoker::20230423023136_documents.sql::CREATE OR REPLACE VIEW \"documents\" AS",
+ "no-view-without-invoker::20230510035345_purchasing.sql::CREATE OR REPLACE VIEW \"purchaseOrderSuppliers\" AS",
+ "no-view-without-invoker::20230510035345_purchasing.sql::CREATE OR REPLACE VIEW \"purchaseOrders\" AS",
+ "no-view-without-invoker::20230704160029_supplier-view.sql::CREATE OR REPLACE VIEW \"customers\" AS",
+ "no-view-without-invoker::20230704160029_supplier-view.sql::CREATE OR REPLACE VIEW \"suppliers\" AS",
+ "no-view-without-invoker::20230704161623_parts-view.sql::CREATE OR REPLACE VIEW \"parts\" AS",
+ "no-view-without-invoker::20230810035313_defaults.sql::CREATE OR REPLACE VIEW \"userDefaults\" AS",
+ "no-view-without-invoker::20230915193213_quantity-on-hand.sql::CREATE OR REPLACE VIEW \"itemQuantities\" AS",
+ "no-view-without-invoker::20230924004608_accounts-payable.sql::CREATE OR REPLACE VIEW \"purchaseInvoices\" AS",
+ "no-view-without-invoker::20240412224648_sales-orders.sql::CREATE OR REPLACE VIEW \"salesOrderCustomers\" AS",
+ "no-view-without-invoker::20240412224648_sales-orders.sql::CREATE OR REPLACE VIEW \"salesOrders\" AS",
+ "no-view-without-invoker::20240905235530_update-itemQuantities-view.sql::CREATE OR REPLACE VIEW \"itemQuantities\" AS",
+ "no-view-without-invoker::20240909194622_jobs.sql::CREATE VIEW \"modules\" AS",
+ "no-view-without-invoker::20250325103806_quality-module.sql::CREATE VIEW \"modules\" AS",
+ "no-view-without-invoker::20250429130223_operation-dependencies.sql::CREATE VIEW \"jobOperationsWithDependencies\" AS",
+ "no-view-without-invoker::20250603011801_make-method-version.sql::CREATE OR REPLACE VIEW \"activeMakeMethods\" AS",
+ "no-view-without-invoker::20250610000433_demand-planning.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS",
+ "no-view-without-invoker::20250610000433_demand-planning.sql::CREATE OR REPLACE VIEW \"openProductionOrders\" AS",
+ "no-view-without-invoker::20250610000433_demand-planning.sql::CREATE OR REPLACE VIEW \"openPurchaseOrderLines\" AS",
+ "no-view-without-invoker::20250610000433_demand-planning.sql::CREATE OR REPLACE VIEW \"openSalesOrderLines\" AS",
+ "no-view-without-invoker::20250616131548_production-planning.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS",
+ "no-view-without-invoker::20250616131548_production-planning.sql::CREATE OR REPLACE VIEW \"openProductionOrders\" AS",
+ "no-view-without-invoker::20251007014240_stock-transfers.sql::CREATE VIEW \"stockTransferLines\" AS",
+ "no-view-without-invoker::20251213153733_suggestions.sql::CREATE OR REPLACE VIEW \"suggestions\" AS",
+ "no-view-without-invoker::20251226000001_maintenance_schedule_days.sql::CREATE OR REPLACE VIEW \"maintenanceSchedules\" AS",
+ "no-view-without-invoker::20260116215036_event_system_impl.sql::CREATE VIEW \"eventSystemTrigger\" AS",
+ "no-view-without-invoker::20260229000003_chart-of-accounts-tree.sql::CREATE OR REPLACE VIEW \"accounts\" AS",
+ "no-view-without-invoker::20260321143847_method-type-migration.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS",
+ "no-view-without-invoker::20260321143847_method-type-migration.sql::CREATE OR REPLACE VIEW \"openSalesOrderLines\" AS",
+ "no-view-without-invoker::20260326000000_print-manager.sql::CREATE VIEW \"modules\" AS",
+ "no-view-without-invoker::20260410030406_event-system-after-interceptors.sql::CREATE VIEW \"eventSystemTrigger\" AS",
+ "no-view-without-invoker::20260417000300_storage-unit-recreate-dependents.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS",
+ "no-view-without-invoker::20260417000300_storage-unit-recreate-dependents.sql::CREATE OR REPLACE VIEW \"openSalesOrderLines\" AS",
+ "no-view-without-invoker::20260810100100_workflows-foundation.sql::CREATE VIEW \"modules\" AS",
+ "no-view-without-invoker::20260811123619_widen-sales-production-scale.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS",
+ "no-view-without-invoker::20260812002453_event-system-statement-handlers.sql::CREATE VIEW \"eventSystemTrigger\" AS",
+ "no-view-without-invoker::20260908211552_picking-supersession-consume-first.sql::CREATE OR REPLACE VIEW \"openJobMaterialLines\" AS"
]
diff --git a/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts b/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts
new file mode 100644
index 0000000000..1f7be7947c
--- /dev/null
+++ b/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from "vitest";
+import { noUnscopedKyselyWrite } from "./no-unscoped-kysely-write";
+
+const SERVICE = "apps/erp/app/modules/sales/sales.service.ts";
+const scan = (ts: string, file = SERVICE) =>
+ noUnscopedKyselyWrite.scan(file, ts);
+
+describe("noUnscopedKyselyWrite", () => {
+ it("flags the reported shape: an update keyed by id alone", () => {
+ const ts = [
+ "for (const { id, sortOrder, updatedBy } of updates) {",
+ " await trx",
+ ' .updateTable("quoteLine")',
+ " .set({ sortOrder, updatedBy })",
+ ' .where("id", "=", id)',
+ " .execute();",
+ "}"
+ ].join("\n");
+ const v = scan(ts);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.line).toBe(3);
+ expect(v[0]?.snippet).toBe('.updateTable("quoteLine")');
+ });
+
+ it("flags a delete keyed by a parent id alone", () => {
+ const ts =
+ 'await trx.deleteFrom("jobMaterialStep").where("jobOperationStepId", "in", ids).execute();';
+ expect(scan(ts)).toHaveLength(1);
+ });
+
+ it("allows a write scoped by companyId", () => {
+ const ts = [
+ "await trx",
+ ' .updateTable("quoteLine")',
+ " .set({ sortOrder })",
+ ' .where("id", "=", id)',
+ ' .where("companyId", "=", companyId)',
+ " .execute();"
+ ].join("\n");
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("accepts an aliased table's qualified companyId", () => {
+ const ts =
+ 'await trx.updateTable("job as j").set({ status }).where("j.id", "=", id).where("j.companyId", "=", companyId).executeTakeFirst();';
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("requires the predicate on a table named by a variable too", () => {
+ const ts = [
+ 'const slideTable = "jobOperationStepSlide" as const;',
+ 'await trx.deleteFrom(slideTable).where("stepId", "in", ids).execute();'
+ ].join("\n");
+ expect(scan(ts)).toHaveLength(1);
+ });
+
+ it("does not count companyId in the SET as scoping", () => {
+ const ts =
+ 'await trx.updateTable("item").set({ companyId, name }).where("id", "=", id).execute();';
+ expect(scan(ts)).toHaveLength(1);
+ });
+
+ it("does not let a NEIGHBOURING statement's companyId scope this one", () => {
+ const ts = [
+ 'await trx.updateTable("quoteLine").set({ sortOrder }).where("id", "=", id).execute();',
+ 'await trx.updateTable("quote").set({ status }).where("id", "=", quoteId).where("companyId", "=", companyId).execute();'
+ ].join("\n");
+ const v = scan(ts);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.line).toBe(1);
+ });
+
+ it("does not let a sibling array element's companyId scope this one", () => {
+ const ts = [
+ "await Promise.all([",
+ ' trx.deleteFrom("a").where("id", "=", id),',
+ ' trx.deleteFrom("b").where("id", "=", id).where("companyId", "=", companyId)',
+ "]);"
+ ].join("\n");
+ const v = scan(ts);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.line).toBe(2);
+ });
+
+ it("ignores a companyId predicate that is only in a comment", () => {
+ const ts = [
+ "await trx",
+ ' .updateTable("quoteLine")',
+ ' // .where("companyId", "=", companyId)',
+ ' .where("id", "=", id)',
+ " .execute();"
+ ].join("\n");
+ expect(scan(ts)).toHaveLength(1);
+ });
+
+ it("ignores a write that is only in a comment", () => {
+ const ts = '// trx.updateTable("quoteLine").where("id", "=", id)';
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("stops at a semicolon inside a SET callback only at depth 0", () => {
+ const ts = [
+ "await trx",
+ ' .updateTable("methodMaterial")',
+ " .set((eb) => { const x = 1; return { x }; })",
+ ' .where("companyId", "=", companyId)',
+ " .execute();"
+ ].join("\n");
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("accepts a link table scoped through its parent in a subquery", () => {
+ const ts = [
+ "await trx",
+ ' .deleteFrom("jobMaterialStep")',
+ ' .where("jobOperationStepId", "in", (eb) =>',
+ " eb",
+ ' .selectFrom("jobOperationStep")',
+ ' .select("id")',
+ ' .where("id", "in", ids)',
+ ' .where("companyId", "=", companyId)',
+ " )",
+ " .execute();"
+ ].join("\n");
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("exempts the company table, whose id is the tenant", () => {
+ const ts =
+ 'await trx.updateTable("company").set(fields).where("id", "=", companyId).execute();';
+ expect(scan(ts)).toHaveLength(0);
+ });
+
+ it("covers routes, MES and jobs", () => {
+ const ts = 'await db.deleteFrom("kanban").where("id", "=", id).execute();';
+ for (const file of [
+ "apps/erp/app/routes/x+/kanban+/delete.$id.tsx",
+ "apps/mes/app/services/operations.service.ts",
+ "packages/jobs/src/inngest/functions/tasks/foo.ts"
+ ]) {
+ expect(scan(ts, file)).toHaveLength(1);
+ }
+ });
+
+ it("ignores edge functions and packages/ee", () => {
+ const ts = 'await db.deleteFrom("user").where("id", "=", id).execute();';
+ for (const file of [
+ "packages/database/supabase/functions/post-receipt/index.ts",
+ "packages/ee/src/sso/provisioning.server.ts"
+ ]) {
+ expect(scan(ts, file)).toHaveLength(0);
+ }
+ });
+});
diff --git a/packages/checks/src/conformance/no-unscoped-kysely-write.ts b/packages/checks/src/conformance/no-unscoped-kysely-write.ts
new file mode 100644
index 0000000000..10327093d3
--- /dev/null
+++ b/packages/checks/src/conformance/no-unscoped-kysely-write.ts
@@ -0,0 +1,166 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+/**
+ * Every Kysely `updateTable` / `deleteFrom` must carry a `companyId` predicate.
+ *
+ * Kysely runs on the Postgres superuser connection (`getDatabaseClient()`), so
+ * RLS never applies to it — the `.where("companyId", …)` in the statement is
+ * the ONLY thing between a caller and another tenant's rows. The ids these
+ * statements key on usually come from the request body or the URL, and
+ * `requirePermissions` proves the caller may act in THEIR company, nothing
+ * about the ids. The public API makes that worse: it auto-publishes every
+ * `*.service.ts` export and hands a `db` parameter that same superuser client,
+ * so a service that updates by `id` alone is a cross-tenant write reachable
+ * with an ordinary API key. Ten drag-sort functions (`updateQuoteLineOrder`
+ * and friends) shipped exactly that way and were reported as a security
+ * disclosure; they now go through `updateSortOrder`
+ * (`apps/erp/app/modules/shared/sort-order.ts`).
+ *
+ * The rule is deliberately blunt: scope the WRITE itself, even when the ids
+ * were read under `companyId` a few lines up. A scoped read proves nothing
+ * once the code is refactored so the ids come from somewhere else, and the
+ * extra predicate costs nothing. The only exemption is `company`, whose `id`
+ * IS the tenant.
+ *
+ * Scope: Node code that holds the superuser `db` — the ERP's modules and
+ * routes, the MES app, and `packages/jobs`. Edge functions are out of scope
+ * (their document-level reads are scoped per
+ * `.claude/rules/workflow-edge-function.md`, and their follow-on writes key on
+ * ids from those reads), as is `packages/ee`, whose sync providers write
+ * global tables (`user`, `invite`) that have no `companyId`.
+ *
+ * A statement is the text from `.updateTable(`/`.deleteFrom(` to the first
+ * `.execute…(` / `.compile(` / `;` / `,` at the same bracket depth (or the
+ * bracket that closes around it), comments blanked.
+ * A statement built across several variables (`let q = …; q = q.where(…)`)
+ * ends at the first `;` and is flagged — inline it or baseline it.
+ */
+
+const MESSAGE =
+ 'Kysely bypasses RLS: this updateTable/deleteFrom has no companyId predicate, so ids from the request can reach another tenant\'s rows. Add .where("companyId", "=", companyId) to the statement.';
+
+const SCOPED_PREFIXES = [
+ "apps/erp/app/modules/",
+ "apps/erp/app/routes/",
+ "apps/mes/app/",
+ "packages/jobs/src/"
+];
+
+/** Tables whose own `id` is the tenant key. */
+const EXEMPT_TABLES = new Set(["company"]);
+
+const WRITE = /\.(updateTable|deleteFrom)\s*\(/g;
+const COMPANY_PREDICATE =
+ /\.where(?:Ref)?\s*\(\s*["'`](?:\w+\.)?companyId["'`]/;
+const STATEMENT_END = /^\.(?:execute\w*|compile)\s*\(/;
+
+/**
+ * Replace comment text with spaces (newlines kept, so offsets and line numbers
+ * survive). String contents are left alone — the predicate is a string.
+ */
+export function blankComments(src: string): string {
+ const out = src.split("");
+ let i = 0;
+ let quote: string | null = null;
+ while (i < src.length) {
+ const ch = src[i];
+ if (quote) {
+ if (ch === "\\") {
+ i += 2;
+ continue;
+ }
+ if (ch === quote) quote = null;
+ i++;
+ continue;
+ }
+ if (ch === '"' || ch === "'" || ch === "`") {
+ quote = ch;
+ i++;
+ continue;
+ }
+ if (ch === "/" && src[i + 1] === "/") {
+ while (i < src.length && src[i] !== "\n") out[i++] = " ";
+ continue;
+ }
+ if (ch === "/" && src[i + 1] === "*") {
+ while (i < src.length && !(src[i] === "*" && src[i + 1] === "/")) {
+ if (src[i] !== "\n") out[i] = " ";
+ i++;
+ }
+ if (i < src.length) out[i] = out[i + 1] = " ";
+ i += 2;
+ continue;
+ }
+ i++;
+ }
+ return out.join("");
+}
+
+/** The statement's text from `from` to its end at depth 0 (see header). */
+function statementFrom(text: string, from: number): string {
+ let depth = 0;
+ for (let i = from; i < text.length; i++) {
+ const ch = text[i];
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
+ else if (ch === ")" || ch === "]" || ch === "}") {
+ if (depth === 0) return text.slice(from, i);
+ depth--;
+ } else if (depth === 0) {
+ if (ch === ";" || ch === ",") return text.slice(from, i);
+ if (ch === "." && STATEMENT_END.test(text.slice(i, i + 40))) {
+ return text.slice(from, i);
+ }
+ }
+ }
+ return text.slice(from);
+}
+
+/** The table named by the call's first argument, when it is a literal. */
+function literalTable(text: string, openParen: number): string | null {
+ const m = text
+ .slice(openParen + 1, openParen + 200)
+ .match(/^\s*["'`]([\w$]+)(?:\s+as\s+\w+)?["'`]/);
+ return m?.[1] ?? null;
+}
+
+export const noUnscopedKyselyWrite: ConformanceCheck = {
+ id: "no-unscoped-kysely-write",
+ description:
+ "Every Kysely updateTable/deleteFrom in app/jobs code carries a companyId predicate — Kysely bypasses RLS, so the statement's own WHERE is the only tenant boundary.",
+ provenance: {
+ deprecates:
+ 'a Kysely write keyed by id alone (e.g. updateQuoteLineOrder\'s `.where("id", "=", id)`), reachable cross-tenant through the public API\'s superuser `db`',
+ replacedBy:
+ '.where("companyId", "=", companyId) on every updateTable/deleteFrom; drag-sorts go through updateSortOrder in modules/shared/sort-order.ts'
+ },
+ scan(file, contents) {
+ if (!SCOPED_PREFIXES.some((prefix) => file.startsWith(prefix))) return [];
+ if (
+ !contents.includes(".updateTable") &&
+ !contents.includes(".deleteFrom")
+ ) {
+ return [];
+ }
+
+ const text = blankComments(contents);
+ const violations: Violation[] = [];
+ for (const m of text.matchAll(WRITE)) {
+ const start = m.index ?? 0;
+ const openParen = start + m[0].length - 1;
+ const table = literalTable(text, openParen);
+ if (table && EXEMPT_TABLES.has(table)) continue;
+
+ const statement = statementFrom(text, start + 1);
+ if (COMPANY_PREDICATE.test(statement)) continue;
+
+ const call = text.slice(start, text.indexOf(")", openParen) + 1);
+ violations.push({
+ file,
+ line: text.slice(0, start).split("\n").length,
+ snippet: call.length <= 80 ? call : m[0],
+ message: MESSAGE
+ });
+ }
+ return violations;
+ }
+};
diff --git a/packages/checks/src/conformance/no-view-without-invoker.test.ts b/packages/checks/src/conformance/no-view-without-invoker.test.ts
new file mode 100644
index 0000000000..b535f6ce6d
--- /dev/null
+++ b/packages/checks/src/conformance/no-view-without-invoker.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { noViewWithoutInvoker } from "./no-view-without-invoker";
+
+describe("noViewWithoutInvoker", () => {
+ it("flags a CREATE OR REPLACE VIEW with no option list", () => {
+ const sql =
+ 'SELECT 1;\nCREATE OR REPLACE VIEW "openJobMaterialLines" AS (\n SELECT 1\n);';
+ const v = noViewWithoutInvoker.scan("p.sql", sql);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.line).toBe(2);
+ expect(v[0]?.message).toContain('"openJobMaterialLines"');
+ });
+
+ it("flags a view whose option list omits security_invoker", () => {
+ const sql = 'CREATE VIEW "x" WITH (check_option = local) AS SELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(1);
+ });
+
+ it("allows security_invoker in any casing and spacing", () => {
+ const sql = [
+ 'CREATE OR REPLACE VIEW "a" WITH (security_invoker = true) AS SELECT 1;',
+ 'CREATE OR REPLACE VIEW "b" WITH(SECURITY_INVOKER=true) AS SELECT 1;',
+ 'CREATE VIEW public."c"\nWITH (security_invoker=true)\nAS\nSELECT 1;'
+ ].join("\n");
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+
+ it("allows an explicit owner-rights view", () => {
+ const sql =
+ 'CREATE VIEW "modules" WITH (security_invoker = false) AS SELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+
+ it("ignores materialized views", () => {
+ const sql = 'CREATE MATERIALIZED VIEW "itemLedgerSnapshot" AS SELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+
+ it("ignores a view in a comment", () => {
+ const sql = '-- CREATE OR REPLACE VIEW "x" AS\nSELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+
+ it("handles a column list before the option list", () => {
+ const sql = 'CREATE VIEW "x" ("a", "b") AS SELECT 1, 2;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(1);
+ });
+
+ it("ignores a view in a block comment", () => {
+ const sql = '/*\nCREATE OR REPLACE VIEW "x" AS\n*/\nSELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+
+ it("keeps line numbers after a block comment", () => {
+ const sql = '/* one\ntwo */\nCREATE VIEW "x" AS SELECT 1;';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)[0]?.line).toBe(3);
+ });
+
+ it("flags ALTER VIEW … RESET (security_invoker)", () => {
+ const sql = 'ALTER VIEW "openJobMaterialLines" RESET (security_invoker);';
+ const v = noViewWithoutInvoker.scan("p.sql", sql);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.message).toContain("RESET");
+ });
+
+ it("allows ALTER VIEW … SET (security_invoker = true)", () => {
+ const sql = 'ALTER VIEW "x" SET (security_invoker = true);';
+ expect(noViewWithoutInvoker.scan("p.sql", sql)).toHaveLength(0);
+ });
+});
diff --git a/packages/checks/src/conformance/no-view-without-invoker.ts b/packages/checks/src/conformance/no-view-without-invoker.ts
new file mode 100644
index 0000000000..52b5ce79d9
--- /dev/null
+++ b/packages/checks/src/conformance/no-view-without-invoker.ts
@@ -0,0 +1,77 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+/**
+ * Matches a `CREATE [OR REPLACE] VIEW` header up to `AS`, capturing an optional
+ * `WITH (...)` option list. `CREATE MATERIALIZED VIEW` never matches, because
+ * `MATERIALIZED` is not among the tokens allowed between `CREATE` and `VIEW`:
+ * a materialized view cannot run as its caller at all, so the clause does not
+ * apply to it (it must have SELECT revoked from anon and authenticated
+ * instead).
+ *
+ * Every view in "public" is a PostgREST endpoint reachable with the anon key the
+ * apps publish. Without `security_invoker` a view runs as its owner and the RLS
+ * on the tables underneath never sees the caller — `openJobMaterialLines`
+ * served every company's rows to anyone for months, after four migrations
+ * recreated it from a copy that lacked the clause.
+ *
+ * Any mention of `security_invoker` in the option list passes, including
+ * `security_invoker = false`: the rule is that a view states how it runs, so an
+ * owner-rights view is a visible decision rather than an omission.
+ */
+const CREATE_VIEW =
+ /CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:RECURSIVE\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?((?:"[^"]+"|\w+)(?:\s*\.\s*(?:"[^"]+"|\w+))?)\s*(?:\(\s*[^)]*\))?\s*(WITH\s*\([^)]*\))?\s*AS\b/gi;
+
+/**
+ * `ALTER VIEW … RESET (security_invoker)` puts a view back on the owner-rights
+ * default just as silently as a recreation without the clause does.
+ */
+const RESET_INVOKER =
+ /ALTER\s+VIEW\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|\w+)(?:\s*\.\s*(?:"[^"]+"|\w+))?)\s+RESET\s*\([^)]*security_invoker[^)]*\)/gi;
+
+/**
+ * Blank out `--` and `/* … *\/` comments, keeping every newline so line numbers
+ * stay right.
+ */
+function stripComments(sql: string): string {
+ return sql
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
+ .replace(/--[^\n]*/g, (m) => " ".repeat(m.length));
+}
+
+function lineOf(sql: string, index: number | undefined): number {
+ return sql.slice(0, index).split("\n").length;
+}
+
+export const noViewWithoutInvoker: ConformanceCheck = {
+ id: "no-view-without-invoker",
+ description:
+ "A view must state security_invoker, or it runs as its owner and bypasses RLS.",
+ provenance: {
+ deprecates: 'CREATE OR REPLACE VIEW "x" AS',
+ replacedBy: 'CREATE OR REPLACE VIEW "x" WITH (security_invoker = true) AS',
+ since: "20260926093417_open-job-material-lines-invoker.sql"
+ },
+ scan(file, contents) {
+ const violations: Violation[] = [];
+ const sql = stripComments(contents);
+ for (const m of sql.matchAll(CREATE_VIEW)) {
+ const options = m[2] ?? "";
+ if (/security_invoker/i.test(options)) continue;
+ violations.push({
+ file,
+ line: lineOf(sql, m.index),
+ snippet: m[0].replace(/\s+/g, " "),
+ message: `View ${m[1]} has no security_invoker, so it runs as its owner: the RLS on the tables underneath never applies, and PostgREST serves every company's rows to anyone holding the anon key. Add WITH (security_invoker = true).`
+ });
+ }
+ for (const m of sql.matchAll(RESET_INVOKER)) {
+ violations.push({
+ file,
+ line: lineOf(sql, m.index),
+ snippet: m[0].replace(/\s+/g, " "),
+ message: `RESET (security_invoker) puts view ${m[1]} back on owner rights, bypassing RLS for every PostgREST caller. Use SET (security_invoker = true), or state security_invoker = false if owner rights are intended.`
+ });
+ }
+ return violations;
+ }
+};
diff --git a/packages/checks/src/invariants/view-without-security-invoker.sql b/packages/checks/src/invariants/view-without-security-invoker.sql
new file mode 100644
index 0000000000..88bef8f5ce
--- /dev/null
+++ b/packages/checks/src/invariants/view-without-security-invoker.sql
@@ -0,0 +1,30 @@
+-- invariant: every view in "public" runs as its caller
+-- returns rows that VIOLATE the rule (none = healthy)
+--
+-- Every view in "public" is a PostgREST endpoint, reachable with the anon key
+-- the apps publish. A view without security_invoker runs as its owner, so the
+-- RLS on the tables underneath never sees the querying role and the view serves
+-- every company's rows to anyone (openJobMaterialLines,
+-- 20260926093417_open-job-material-lines-invoker).
+--
+-- The no-view-without-invoker conformance check catches this in a migration's
+-- text; this catches it in the live catalog, whatever put it there.
+--
+-- Excluded by name, each holding no tenant data:
+-- modules — unnest(enum_range(NULL::module))
+-- eventSystemTrigger — trigger metadata from pg_trigger
+-- Materialized views are not listed: they cannot run as the caller at all, and
+-- must instead have SELECT revoked from anon and authenticated.
+SELECT c.relname AS view
+FROM pg_class c
+WHERE c.relnamespace = 'public'::regnamespace
+ AND c.relkind = 'v'
+ AND c.relname NOT IN ('modules', 'eventSystemTrigger')
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype = 'e')
+ AND NOT COALESCE(
+ (SELECT option_value::boolean
+ FROM pg_options_to_table(c.reloptions)
+ WHERE option_name = 'security_invoker'),
+ false
+ )
+ORDER BY 1;
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index 37f8011643..c7d84c5b58 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -18,6 +18,8 @@ import { noNumericPrecision } from "./conformance/no-numeric-precision";
import { noRawRounding } from "./conformance/no-raw-rounding";
import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";
import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-quantity";
+import { noUnscopedKyselyWrite } from "./conformance/no-unscoped-kysely-write";
+import { noViewWithoutInvoker } from "./conformance/no-view-without-invoker";
import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
import { loadEdgeFunctions } from "./sources/edge-functions";
import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";
@@ -29,7 +31,8 @@ export const CONFORMANCE_CHECKS: ConformanceCheck[] = [
noNumericPrecision,
noLegacyRls,
noDerivedPercentColumn,
- noRequiredColumnWithoutDefault
+ noRequiredColumnWithoutDefault,
+ noViewWithoutInvoker
];
/** Checks that run over server-side TS, not SQL migrations. */
@@ -44,7 +47,8 @@ export const TS_CHECKS: ConformanceCheck[] = [
noInlineFractionDigits,
noDbClientInService,
noDefaultOnEffects,
- noUnroundedTrackedQuantity
+ noUnroundedTrackedQuantity,
+ noUnscopedKyselyWrite
];
/** Checks that run once per edge function, over all of its .ts files. */
diff --git a/packages/database/src/datasets/wipe.ts b/packages/database/src/datasets/wipe.ts
index 35400ea515..27c5059373 100644
--- a/packages/database/src/datasets/wipe.ts
+++ b/packages/database/src/datasets/wipe.ts
@@ -19,6 +19,8 @@ const PRESERVED_TABLES = new Set([
"customerStatus",
"employee",
"employeeJob",
+ // Console PIN hashes belong to the employees above, not to the story
+ "employeePin",
"employeeType",
"fiscalYearSettings",
"fixedAssetClass",
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b3b9408f2b..f7c5044953 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -56724,9 +56724,6 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active"
},
- {
- $ref: "#/parameters/rowFilter.employee.pin"
- },
{
$ref: "#/parameters/select"
},
@@ -56798,9 +56795,6 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active"
},
- {
- $ref: "#/parameters/rowFilter.employee.pin"
- },
{
$ref: "#/parameters/preferReturn"
}
@@ -56826,9 +56820,6 @@ export default {
{
$ref: "#/parameters/rowFilter.employee.active"
},
- {
- $ref: "#/parameters/rowFilter.employee.pin"
- },
{
$ref: "#/parameters/body.employee"
},
@@ -91731,6 +91722,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -91740,9 +91734,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -91940,6 +91931,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -91949,9 +91943,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -92103,6 +92094,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -92112,9 +92106,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -96845,6 +96836,58 @@ export default {
tags: ["(rpc) get_production_projections"]
}
},
+ "/rpc/set_employee_pin": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_employee_id: {
+ format: "text",
+ type: "string"
+ },
+ p_pin: {
+ format: "text",
+ type: "string"
+ },
+ p_updated_by: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: [
+ "p_employee_id",
+ "p_company_id",
+ "p_pin",
+ "p_updated_by"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) set_employee_pin"]
+ }
+ },
"/rpc/get_or_create_work_center_lineside": {
post: {
parameters: [
@@ -103602,6 +103645,85 @@ export default {
tags: ["(rpc) get_ar_open_by_customer"]
}
},
+ "/rpc/verify_employee_pin": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_employee_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_company_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_pin",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) verify_employee_pin"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_employee_id: {
+ format: "text",
+ type: "string"
+ },
+ p_pin: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_employee_id", "p_company_id", "p_pin"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) verify_employee_pin"]
+ }
+ },
"/rpc/sync_create_supplier_type_group": {
post: {
parameters: [
@@ -132616,10 +132738,6 @@ export default {
default: false,
format: "boolean",
type: "boolean"
- },
- pin: {
- format: "text",
- type: "string"
}
},
type: "object"
@@ -149556,10 +149674,10 @@ export default {
"incompletePickingListPolicy",
"includeMaterialsOnTraveler",
"returnPickedMaterialTiming",
+ "salesRuleNotificationGroup",
"showCurrencyTrailingZeros",
"requireMfa",
"allowLowercaseItemIds",
- "salesRuleNotificationGroup",
"includeOperationsOnTraveler"
],
properties: {
@@ -149807,6 +149925,13 @@ export default {
format: "text",
type: "string"
},
+ salesRuleNotificationGroup: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
showCurrencyTrailingZeros: {
default: true,
format: "boolean",
@@ -149822,13 +149947,6 @@ export default {
format: "boolean",
type: "boolean"
},
- salesRuleNotificationGroup: {
- format: "text[]",
- items: {
- type: "string"
- },
- type: "array"
- },
includeOperationsOnTraveler: {
default: true,
format: "boolean",
@@ -180170,12 +180288,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.employee.pin": {
- name: "pin",
- required: false,
- in: "query",
- type: "string"
- },
"body.activeMaintenanceDispatchesByLocation": {
name: "activeMaintenanceDispatchesByLocation",
description: "activeMaintenanceDispatchesByLocation",
@@ -199267,6 +199379,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.salesRuleNotificationGroup": {
+ name: "salesRuleNotificationGroup",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.showCurrencyTrailingZeros": {
name: "showCurrencyTrailingZeros",
required: false,
@@ -199285,12 +199403,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.companySettings.salesRuleNotificationGroup": {
- name: "salesRuleNotificationGroup",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.companySettings.includeOperationsOnTraveler": {
name: "includeOperationsOnTraveler",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 56a0f29b7f..65c0f4f7ed 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -14010,21 +14010,18 @@ export type Database = {
companyId: string
employeeTypeId: string
id: string
- pin: string | null
}
Insert: {
active?: boolean
companyId: string
employeeTypeId: string
id?: string
- pin?: string | null
}
Update: {
active?: boolean
companyId?: string
employeeTypeId?: string
id?: string
- pin?: string | null
}
Relationships: [
{
@@ -14376,6 +14373,101 @@ export type Database = {
}
]
}
+ employeePin: {
+ Row: {
+ companyId: string
+ employeeId: string
+ pinHash: string
+ updatedAt: string
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ employeeId: string
+ pinHash: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ employeeId?: string
+ pinHash?: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_employee_fkey"
+ columns: ["employeeId", "companyId"]
+ isOneToOne: true
+ referencedRelation: "employee"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ }
+ ]
+ }
employeeShift: {
Row: {
companyId: string
@@ -84398,6 +84490,15 @@ export type Database = {
Args: { p_company_id: string }
Returns: undefined
}
+ set_employee_pin: {
+ Args: {
+ p_company_id: string
+ p_employee_id: string
+ p_pin: string
+ p_updated_by: string
+ }
+ Returns: undefined
+ }
set_shelf_life_for_operation: {
Args: {
p_event: Database["public"]["Enums"]["shelfLifeTriggerTiming"]
@@ -84790,6 +84891,10 @@ export type Database = {
}
uuid_generate_v4: { Args: never; Returns: string }
uuid_to_base58: { Args: { _uuid: string }; Returns: string }
+ verify_employee_pin: {
+ Args: { p_company_id: string; p_employee_id: string; p_pin: string }
+ Returns: boolean
+ }
workflow_merge_custom_fields: {
Args: {
p_company_id: string
diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.ts
index 4691b32f46..952385024a 100644
--- a/packages/database/supabase/functions/close-job/index.ts
+++ b/packages/database/supabase/functions/close-job/index.ts
@@ -79,6 +79,7 @@ serve(async (req: Request) => {
const job = await trx
.selectFrom("job")
.where("id", "=", jobId)
+ .where("companyId", "=", companyId)
.select(["jobId", "itemId", "locationId"])
.executeTakeFirstOrThrow();
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 41dd2675a6..3553a8d9cc 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -7,6 +7,7 @@ import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { format } from "https://deno.land/[email protected]/datetime/format.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { toJson } from "../lib/json.ts";
+import { RecordNotFoundError } from "../lib/company-records.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -192,8 +193,10 @@ serve(async (req: Request) => {
.from("makeMethod")
.select("*")
.eq("id", makeMethodId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
if (makeMethod.error) throw new Error(makeMethod.error.message);
+ if (!makeMethod.data) throw new RecordNotFoundError("Make method not found");
const [relatedMakeMethods, draftQuotes, draftJobs] = await Promise.all([
client
@@ -287,24 +290,28 @@ serve(async (req: Request) => {
.from("purchaseOrder")
.select("*")
.eq("id", purchaseOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("purchaseOrderLine")
.select("*")
- .eq("purchaseOrderId", purchaseOrderId),
+ .eq("purchaseOrderId", purchaseOrderId)
+ .eq("companyId", companyId),
client
.from("purchaseOrderPayment")
.select("*")
.eq("id", purchaseOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("purchaseOrderDelivery")
.select("*")
.eq("id", purchaseOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
]);
- if (!purchaseOrder.data) throw new Error("Purchase order not found");
+ if (!purchaseOrder.data) throw new RecordNotFoundError("Purchase order not found");
if (purchaseOrderLines.error)
throw new Error(purchaseOrderLines.error.message);
if (!purchaseOrderPayment.data)
@@ -484,23 +491,44 @@ serve(async (req: Request) => {
quoteShipping,
company,
] = await Promise.all([
- client.from("quote").select("*").eq("id", id).single(),
+ client
+ .from("quote")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
fetchAllRows((from, to) =>
- client.from("quoteLine").select("*").eq("quoteId", id).range(from, to)
+ client
+ .from("quoteLine")
+ .select("*")
+ .eq("quoteId", id)
+ .eq("companyId", companyId)
+ .range(from, to)
),
fetchAllRows((from, to) =>
client
.from("quoteLinePrice")
.select("*")
.eq("quoteId", id)
+ .eq("companyId", companyId)
.range(from, to)
),
- client.from("quotePayment").select("*").eq("id", id).single(),
- client.from("quoteShipment").select("*").eq("id", id).single(),
+ client
+ .from("quotePayment")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("quoteShipment")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
client.from("company").select("*").eq("id", companyId).single(),
]);
- if (quote.error) throw new Error(`Quote with id ${id} not found`);
+ if (quote.error) throw new RecordNotFoundError(`Quote with id ${id} not found`);
if (quoteLines.error)
throw new Error(`Quote Lines with id ${id} not found`);
if (quoteLinePrices.error)
@@ -812,25 +840,33 @@ serve(async (req: Request) => {
salesOrderPayment,
salesOrderShipment,
] = await Promise.all([
- client.from("salesOrder").select("*").eq("id", salesOrderId).single(),
+ client
+ .from("salesOrder")
+ .select("*")
+ .eq("id", salesOrderId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("salesOrderLine")
.select("*")
- .eq("salesOrderId", salesOrderId),
+ .eq("salesOrderId", salesOrderId)
+ .eq("companyId", companyId),
client
.from("salesOrderPayment")
.select("*")
.eq("id", salesOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("salesOrderShipment")
.select("*")
.eq("id", salesOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
]);
if (salesOrder.error) throw new Error(salesOrder.error.message);
- if (!salesOrder.data) throw new Error("Sales order not found");
+ if (!salesOrder.data) throw new RecordNotFoundError("Sales order not found");
if (salesOrderLines.error)
throw new Error(salesOrderLines.error.message);
if (salesOrderPayment.error) throw new Error(salesOrderPayment.error.message);
@@ -970,12 +1006,21 @@ serve(async (req: Request) => {
}
case "salesRfqToQuote": {
const [salesRfq, salesRfqLines] = await Promise.all([
- client.from("salesRfq").select("*").eq("id", id).single(),
- client.from("salesRfqLines").select("*").eq("salesRfqId", id),
+ client
+ .from("salesRfq")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("salesRfqLines")
+ .select("*")
+ .eq("salesRfqId", id)
+ .eq("companyId", companyId),
]);
if (salesRfq.error)
- throw new Error(`Sales RFQ with id ${id} not found`);
+ throw new RecordNotFoundError(`Sales RFQ with id ${id} not found`);
if (salesRfq.data?.status !== "Ready for Quote")
throw new Error(
`Sales RFQ with id ${id} is not in Ready for Quote status`
@@ -1054,16 +1099,19 @@ serve(async (req: Request) => {
.from("customerPayment")
.select("*")
.eq("customerId", salesRfq.data.customerId)
+ .eq("companyId", companyId)
.single(),
client
.from("customerShipping")
.select("*")
.eq("customerId", salesRfq.data.customerId)
+ .eq("companyId", companyId)
.single(),
client
.from("customer")
.select("*")
.eq("id", salesRfq.data.customerId)
+ .eq("companyId", companyId)
.single(),
client.from("company").select("*").eq("id", companyId).single(),
]);
@@ -1347,16 +1395,27 @@ serve(async (req: Request) => {
const shipmentId = id;
const [shipment, shipmentLines, shipmentFixedAssetLines] =
await Promise.all([
- client.from("shipment").select("*").eq("id", shipmentId).single(),
- client.from("shipmentLine").select("*").eq("shipmentId", shipmentId),
+ client
+ .from("shipment")
+ .select("*")
+ .eq("id", shipmentId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("shipmentLine")
+ .select("*")
+ .eq("shipmentId", shipmentId)
+ .eq("companyId", companyId),
client
.from("shipmentFixedAssetLine")
.select("*")
.eq("shipmentId", shipmentId)
+ .eq("companyId", companyId)
.eq("shipped", true),
]);
if (shipment.error) throw shipment.error;
+ if (!shipment.data) throw new RecordNotFoundError("Shipment not found");
if (shipmentLines.error) throw shipmentLines.error;
if (shipmentFixedAssetLines.error) throw shipmentFixedAssetLines.error;
@@ -1396,22 +1455,29 @@ serve(async (req: Request) => {
.from("salesOrder")
.select("*")
.eq("id", shipment.data?.sourceDocumentId)
- .single(),
- client.from("salesOrderLine").select("*").in("id", salesOrderLineIds),
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("salesOrderLine")
+ .select("*")
+ .in("id", salesOrderLineIds)
+ .eq("companyId", companyId),
client
.from("salesOrderPayment")
.select("*")
.eq("id", shipment.data?.sourceDocumentId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("salesOrderShipment")
.select("*")
.eq("id", shipment.data?.sourceDocumentId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
]);
if (salesOrder.error) throw new Error(salesOrder.error.message);
- if (!salesOrder.data) throw new Error("Sales order not found");
+ if (!salesOrder.data) throw new RecordNotFoundError("Sales order not found");
if (salesOrderLines.error)
throw new Error(salesOrderLines.error.message);
if (salesOrderPayment.error) throw new Error(salesOrderPayment.error.message);
@@ -1566,11 +1632,17 @@ serve(async (req: Request) => {
const { selectedLines } = payload;
const [quote, quoteLines, company, employeeJob] = await Promise.all([
- client.from("supplierQuote").select("*").eq("id", id).single(),
+ client
+ .from("supplierQuote")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
client
.from("supplierQuoteLine")
.select("*, item(type)")
- .eq("supplierQuoteId", id),
+ .eq("supplierQuoteId", id)
+ .eq("companyId", companyId),
client.from("company").select("*").eq("id", companyId).single(),
client
.from("employeeJob")
@@ -1580,7 +1652,7 @@ serve(async (req: Request) => {
.single(),
]);
- if (quote.error) throw new Error(`Quote with id ${id} not found`);
+ if (quote.error) throw new RecordNotFoundError(`Quote with id ${id} not found`);
if (quoteLines.error)
throw new Error(`Quote Lines with id ${id} not found`);
@@ -1590,16 +1662,19 @@ serve(async (req: Request) => {
.from("supplierPayment")
.select("*")
.eq("supplierId", quote.data.supplierId)
+ .eq("companyId", companyId)
.single(),
client
.from("supplierShipping")
.select("*")
.eq("supplierId", quote.data.supplierId)
+ .eq("companyId", companyId)
.single(),
client
.from("supplier")
.select("*")
.eq("id", quote.data.supplierId)
+ .eq("companyId", companyId)
.single(),
client
@@ -1609,7 +1684,8 @@ serve(async (req: Request) => {
"itemId",
quoteLines.data.map((line) => line.itemId)
)
- .eq("locationId", employeeJob.data?.locationId ?? ""),
+ .eq("locationId", employeeJob.data?.locationId ?? "")
+ .eq("companyId", companyId),
]);
if (supplierPayment.error) throw supplierPayment.error;
@@ -1886,7 +1962,8 @@ serve(async (req: Request) => {
const { data: linkedRfqs } = await client
.from("purchasingRfqToSupplierQuote")
.select("purchasingRfqId")
- .eq("supplierQuoteId", id);
+ .eq("supplierQuoteId", id)
+ .eq("companyId", companyId);
if (linkedRfqs && linkedRfqs.length > 0) {
await client.from("purchasingRfqToPurchaseOrder").insert(
@@ -1910,15 +1987,19 @@ serve(async (req: Request) => {
.from("warehouseTransfer")
.select("*")
.eq("id", warehouseTransferId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("warehouseTransferLine")
.select("*")
- .eq("transferId", warehouseTransferId),
+ .eq("transferId", warehouseTransferId)
+ .eq("companyId", companyId),
]);
if (warehouseTransfer.error)
throw new Error(warehouseTransfer.error.message);
+ if (!warehouseTransfer.data)
+ throw new RecordNotFoundError("Warehouse transfer not found");
if (warehouseTransferLines.error)
throw new Error(warehouseTransferLines.error.message);
@@ -1982,15 +2063,19 @@ serve(async (req: Request) => {
.from("warehouseTransfer")
.select("*")
.eq("id", warehouseTransferId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("warehouseTransferLine")
.select("*")
- .eq("transferId", warehouseTransferId),
+ .eq("transferId", warehouseTransferId)
+ .eq("companyId", companyId),
]);
if (warehouseTransfer.error)
throw new Error(warehouseTransfer.error.message);
+ if (!warehouseTransfer.data)
+ throw new RecordNotFoundError("Warehouse transfer not found");
if (warehouseTransferLines.error)
throw new Error(warehouseTransferLines.error.message);
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 5317d87251..9166f77d6d 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -5,6 +5,10 @@ import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import z from "npm:zod@^4.5.4";
import { getFunctionLogger } from "../lib/logging.ts";
+import {
+ assertCompanyRecords,
+ RecordNotFoundError,
+} from "../lib/company-records.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database, Json } from "../lib/types.ts";
@@ -205,6 +209,16 @@ serve(async (req: Request) => {
permissionsByType[type] ?? { update: "settings" }
);
+ // Every receipt/shipment type writes the body's locationId onto the new
+ // document (and its lines); the FK alone accepts another company's location.
+ await assertCompanyRecords(
+ db,
+ "location",
+ [payload.locationId],
+ companyId,
+ "Location"
+ );
+
switch (type) {
case "nonConformanceTasks": {
const { id } = payload;
@@ -219,28 +233,38 @@ serve(async (req: Request) => {
approvalTasks,
existingReviewers,
] = await Promise.all([
- client.from("nonConformance").select("*").eq("id", id).single(),
+ client
+ .from("nonConformance")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("nonConformanceActionTask")
.select("*")
- .eq("nonConformanceId", id),
+ .eq("nonConformanceId", id)
+ .eq("companyId", companyId),
client
.from("nonConformanceApprovalTask")
.select("*")
- .eq("nonConformanceId", id),
+ .eq("nonConformanceId", id)
+ .eq("companyId", companyId),
client
.from("nonConformanceReviewer")
.select("*")
- .eq("nonConformanceId", id),
+ .eq("nonConformanceId", id)
+ .eq("companyId", companyId),
]);
if (nonConformance.error) throw new Error(nonConformance.error.message);
+ if (!nonConformance.data) throw new RecordNotFoundError("Non-conformance not found");
const workflow = nonConformance.data?.nonConformanceWorkflowId
? await client
.from("nonConformanceWorkflow")
.select("*")
.eq("id", nonConformance.data?.nonConformanceWorkflowId)
+ .eq("companyId", companyId)
.maybeSingle()
: null;
@@ -450,15 +474,35 @@ serve(async (req: Request) => {
try {
const [job, jobOperations] = await Promise.all([
- client.from("job").select("*").eq("id", jobId).single(),
+ client
+ .from("job")
+ .select("*")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("jobOperation")
.select("*, jobMakeMethod(itemId)")
- .eq("jobId", jobId),
+ .eq("jobId", jobId)
+ .eq("companyId", companyId),
]);
+ if (job.error) throw new Error(job.error.message);
+ if (!job.data) throw new RecordNotFoundError("Job not found");
if (jobOperations.error) throw new Error(jobOperations.error.message);
+ // Caller-chosen existing POs must belong to this company — lines are
+ // appended to them by id below.
+ await assertCompanyRecords(
+ db,
+ "purchaseOrder",
+ Object.values(purchaseOrdersBySupplierId as Record<string, string>).filter(
+ (poId) => poId && poId !== "new"
+ ),
+ companyId,
+ "Purchase order"
+ );
+
const outsideOperations = jobOperations.data?.filter(
(d) => d.operationType === "Outside Processing"
);
@@ -482,17 +526,20 @@ serve(async (req: Request) => {
.from("supplierProcess")
.select("*")
.in("id", Array.from(supplierProcessIds))
+ .eq("companyId", companyId)
: Promise.resolve({ data: [], error: null }),
outsideProcessIds.size > 0
? client
.from("supplierProcess")
.select("*")
.in("processId", Array.from(outsideProcessIds))
+ .eq("companyId", companyId)
: Promise.resolve({ data: [], error: null }),
client
.from("purchaseOrderLine")
.select("*")
.eq("jobId", jobId)
+ .eq("companyId", companyId)
.in(
"jobOperationId",
outsideOperations.map((d) => d.id)
@@ -575,16 +622,23 @@ serve(async (req: Request) => {
client
.from("supplier")
.select("*")
- .in("id", Array.from(supplierIds)),
+ .in("id", Array.from(supplierIds))
+ .eq("companyId", companyId),
client
.from("supplierPayment")
.select("*")
- .in("supplierId", Array.from(supplierIds)),
+ .in("supplierId", Array.from(supplierIds))
+ .eq("companyId", companyId),
client
.from("supplierShipping")
.select("*")
- .in("supplierId", Array.from(supplierIds)),
- client.from("item").select("*").in("id", Array.from(itemIds)),
+ .in("supplierId", Array.from(supplierIds))
+ .eq("companyId", companyId),
+ client
+ .from("item")
+ .select("*")
+ .in("id", Array.from(itemIds))
+ .eq("companyId", companyId),
]);
if (suppliers.error) throw new Error(suppliers.error.message);
@@ -854,11 +908,13 @@ serve(async (req: Request) => {
client
.from("purchaseOrders")
.select("*")
+ .eq("companyId", companyId)
.eq("id", purchaseOrderId)
.single(),
client
.from("purchaseOrderLine")
.select("*")
+ .eq("companyId", companyId)
.eq("purchaseOrderId", purchaseOrderId)
.in("purchaseOrderLineType", [
"Part",
@@ -870,16 +926,18 @@ serve(async (req: Request) => {
client
.from("purchaseOrderLine")
.select("id, purchaseOrderLineType, assetId, purchaseQuantity, quantityReceived, receivedComplete")
+ .eq("companyId", companyId)
.eq("purchaseOrderId", purchaseOrderId)
.eq("purchaseOrderLineType", "Fixed Asset"),
client
.from("receipt")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingReceiptId)
.maybeSingle(),
]);
- if (!purchaseOrder.data) throw new Error("Purchase order not found");
+ if (!purchaseOrder.data) throw new RecordNotFoundError("Purchase order not found");
if (purchaseOrderLines.error)
throw new Error(purchaseOrderLines.error.message);
@@ -896,6 +954,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
purchaseOrderLines.data
@@ -925,6 +984,7 @@ serve(async (req: Request) => {
const pickMethods = await client
.from("pickMethod")
.select("itemId, locationId, defaultStorageUnitId")
+ .eq("companyId", companyId)
.in("itemId", receiptItemIds);
const pickMethodKey = (itemId: string, loc: string | null) =>
`${itemId}::${loc ?? ""}`;
@@ -938,6 +998,10 @@ serve(async (req: Request) => {
}
}
+ // A supplied id that is not this company's receipt is a 404, not a
+ // silent create-new.
+ if (existingReceiptId && !receipt.data)
+ throw new RecordNotFoundError("Receipt not found");
const hasReceipt = !!receipt.data?.id;
const isOutsideOperation =
purchaseOrder.data.purchaseOrderType === "Outside Processing";
@@ -1109,21 +1173,24 @@ serve(async (req: Request) => {
client
.from("warehouseTransfer")
.select("*")
+ .eq("companyId", companyId)
.eq("id", warehouseTransferId)
.single(),
client
.from("warehouseTransferLine")
.select("*")
+ .eq("companyId", companyId)
.eq("transferId", warehouseTransferId),
client
.from("receipt")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingReceiptId)
.maybeSingle(),
]);
if (!warehouseTransfer.data)
- throw new Error("Warehouse transfer not found");
+ throw new RecordNotFoundError("Warehouse transfer not found");
if (warehouseTransferLines.error)
throw new Error(warehouseTransferLines.error.message);
@@ -1132,6 +1199,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
warehouseTransferLines.data
@@ -1149,6 +1217,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's receipt is a 404, not a
+ // silent create-new.
+ if (existingReceiptId && !receipt.data)
+ throw new RecordNotFoundError("Receipt not found");
const hasReceipt = !!receipt.data?.id;
const previouslyReceivedQuantitiesByLine = (
@@ -1290,12 +1362,13 @@ serve(async (req: Request) => {
client
.from("receipt")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingReceiptId)
.maybeSingle(),
]);
if (!salesReturnOrder.data)
- throw new Error("Sales return order not found");
+ throw new RecordNotFoundError("Sales return order not found");
if (salesReturnOrder.data.status !== "To Receive")
throw new Error(
`Cannot receive against a return order in ${salesReturnOrder.data.status} status`
@@ -1316,6 +1389,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in("id", returnItemIds);
const serializedItems = new Set(
items.data
@@ -1331,6 +1405,7 @@ serve(async (req: Request) => {
const pickMethods = await client
.from("pickMethod")
.select("itemId, locationId, defaultStorageUnitId")
+ .eq("companyId", companyId)
.in("itemId", returnItemIds);
const defaultStorageUnitByItem = new Map<string, string>();
for (const row of pickMethods.data ?? []) {
@@ -1339,6 +1414,10 @@ serve(async (req: Request) => {
}
}
+ // A supplied id that is not this company's receipt is a 404, not a
+ // silent create-new.
+ if (existingReceiptId && !receipt.data)
+ throw new RecordNotFoundError("Receipt not found");
const hasReceipt = !!receipt.data?.id;
// Re-targeting deletes and rebuilds the lines — only a Draft may be
// rebuilt; a Posted document's lines are referenced by ledger rows.
@@ -1457,21 +1536,24 @@ serve(async (req: Request) => {
client
.from("warehouseTransfer")
.select("*")
+ .eq("companyId", companyId)
.eq("id", warehouseTransferId)
.single(),
client
.from("warehouseTransferLine")
.select("*")
+ .eq("companyId", companyId)
.eq("transferId", warehouseTransferId),
client
.from("receipt")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingReceiptId)
.maybeSingle(),
]);
if (!warehouseTransfer.data)
- throw new Error("Warehouse transfer not found");
+ throw new RecordNotFoundError("Warehouse transfer not found");
if (warehouseTransferLines.error)
throw new Error(warehouseTransferLines.error.message);
@@ -1480,6 +1562,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
warehouseTransferLines.data
@@ -1497,6 +1580,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's receipt is a 404, not a
+ // silent create-new.
+ if (existingReceiptId && !receipt.data)
+ throw new RecordNotFoundError("Receipt not found");
const hasReceipt = !!receipt.data?.id;
const previouslyReceivedQuantitiesByLine = (
@@ -1623,17 +1710,19 @@ serve(async (req: Request) => {
client
.from("receiptLine")
.select("*")
+ .eq("companyId", companyId)
.eq("id", receiptLineId)
.single(),
client
.from("trackedEntity")
.select("*")
+ .eq("companyId", companyId)
.eq("attributes->> Receipt Line", receiptLineId),
]);
logger.debug({ trackedEntities });
- if (!receiptLine.data) throw new Error("Receipt line not found");
+ if (!receiptLine.data) throw new RecordNotFoundError("Receipt line not found");
await db.transaction().execute(async (trx) => {
const { id, ...data } = receiptLine.data;
@@ -1782,21 +1871,24 @@ serve(async (req: Request) => {
client
.from("warehouseTransfer")
.select("*")
+ .eq("companyId", companyId)
.eq("id", warehouseTransferId)
.single(),
client
.from("warehouseTransferLine")
.select("*")
+ .eq("companyId", companyId)
.eq("transferId", warehouseTransferId),
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
]);
if (!warehouseTransfer.data)
- throw new Error("Warehouse transfer not found");
+ throw new RecordNotFoundError("Warehouse transfer not found");
if (warehouseTransferLines.error)
throw new Error(warehouseTransferLines.error.message);
@@ -1805,6 +1897,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
warehouseTransferLines.data
@@ -1822,6 +1915,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
const previouslyShippedQuantitiesByLine = (
@@ -1964,12 +2061,13 @@ serve(async (req: Request) => {
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
]);
if (!salesReturnOrder.data)
- throw new Error("Sales return order not found");
+ throw new RecordNotFoundError("Sales return order not found");
if (salesReturnOrderLines.error)
throw new Error(salesReturnOrderLines.error.message);
// Goods can only go back out once they came in: the return must be
@@ -2008,6 +2106,7 @@ serve(async (req: Request) => {
const priorLines = await client
.from("shipmentLine")
.select("lineId, shippedQuantity")
+ .eq("companyId", companyId)
.in("shipmentId", priorShipmentIds);
for (const line of priorLines.data ?? []) {
if (!line.lineId) continue;
@@ -2025,6 +2124,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in("id", returnItemIds);
const serializedItems = new Set(
items.data
@@ -2037,6 +2137,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
if (hasShipment && shipment.data!.status !== "Draft")
throw new Error(
@@ -2174,12 +2278,13 @@ serve(async (req: Request) => {
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
]);
if (!purchaseReturnOrder.data)
- throw new Error("Purchase return order not found");
+ throw new RecordNotFoundError("Purchase return order not found");
if (purchaseReturnOrder.data.status !== "To Ship")
throw new Error(
`Cannot ship against a return order in ${purchaseReturnOrder.data.status} status`
@@ -2198,6 +2303,7 @@ serve(async (req: Request) => {
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in("id", returnItemIds);
const serializedItems = new Set(
items.data
@@ -2210,6 +2316,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
if (hasShipment && shipment.data!.status !== "Draft")
throw new Error(
@@ -2415,11 +2525,13 @@ serve(async (req: Request) => {
client
.from("purchaseOrder")
.select("*")
+ .eq("companyId", companyId)
.eq("id", purchaseOrderId)
.single(),
client
.from("purchaseOrderLine")
.select("*")
+ .eq("companyId", companyId)
.eq("purchaseOrderId", purchaseOrderId)
.in("purchaseOrderLineType", [
"Part",
@@ -2432,22 +2544,25 @@ serve(async (req: Request) => {
client
.from("purchaseOrderDelivery")
.select("*")
+ .eq("companyId", companyId)
.eq("id", purchaseOrderId)
.maybeSingle(),
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
]);
- if (!purchaseOrder.data) throw new Error("Purchase order not found");
+ if (!purchaseOrder.data) throw new RecordNotFoundError("Purchase order not found");
if (purchaseOrderLines.error)
throw new Error(purchaseOrderLines.error.message);
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
purchaseOrderLines.data.map((d) => d.itemId)
@@ -2463,6 +2578,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
const isOutsideOperation =
purchaseOrder.data.purchaseOrderType === "Outside Processing";
@@ -2607,10 +2726,16 @@ serve(async (req: Request) => {
shipment,
jobs,
] = await Promise.all([
- client.from("salesOrder").select("*").eq("id", salesOrderId).single(),
+ client
+ .from("salesOrder")
+ .select("*")
+ .eq("id", salesOrderId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("salesOrderLine")
.select("*")
+ .eq("companyId", companyId)
.eq("salesOrderId", salesOrderId)
.in("salesOrderLineType", [
"Part",
@@ -2623,32 +2748,37 @@ serve(async (req: Request) => {
client
.from("salesOrderLine")
.select("id, salesOrderLineType, assetId, saleQuantity, quantitySent, sentComplete")
+ .eq("companyId", companyId)
.eq("salesOrderId", salesOrderId)
.eq("salesOrderLineType", "Fixed Asset"),
client
.from("salesOrderShipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", salesOrderId)
.maybeSingle(),
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
client
.from("job")
.select("*")
+ .eq("companyId", companyId)
.eq("salesOrderId", salesOrderId)
.neq("status", "Cancelled"),
]);
- if (!salesOrder.data) throw new Error("Sales order not found");
+ if (!salesOrder.data) throw new RecordNotFoundError("Sales order not found");
if (salesOrderLines.error)
throw new Error(salesOrderLines.error.message);
const items = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.in(
"id",
salesOrderLines.data.map((d) => d.itemId)
@@ -2664,6 +2794,10 @@ serve(async (req: Request) => {
.map((d) => d.id)
);
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
// Group jobs by sales order line ID
@@ -2826,6 +2960,7 @@ serve(async (req: Request) => {
const trackedEntities = await client
.from("trackedEntity")
.select("*")
+ .eq("companyId", companyId)
.eq("attributes->>Job Make Method", jobMakeMethod.id)
.order("createdAt", { ascending: true });
@@ -2949,12 +3084,13 @@ serve(async (req: Request) => {
const salesOrderLine = await client
.from("salesOrderLine")
.select("*")
+ .eq("companyId", companyId)
.eq("id", salesOrderLineId)
.eq("locationId", locationId)
.single();
if (!salesOrderLine.data || !salesOrderLine.data.itemId)
- throw new Error("Sales order line not found");
+ throw new RecordNotFoundError("Sales order line not found");
// Services are never shipped
if (salesOrderLine.data.salesOrderLineType === "Service")
throw new Error("Service lines cannot be shipped");
@@ -2965,38 +3101,47 @@ serve(async (req: Request) => {
client
.from("salesOrder")
.select("*")
+ .eq("companyId", companyId)
.eq("id", salesOrderId)
.single(),
client
.from("salesOrderShipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", salesOrderId)
.maybeSingle(),
client
.from("shipment")
.select("*")
+ .eq("companyId", companyId)
.eq("id", existingShipmentId)
.maybeSingle(),
client
.from("job")
.select("*")
+ .eq("companyId", companyId)
.eq("salesOrderLineId", salesOrderLineId)
.neq("status", "Cancelled"),
]);
- if (!salesOrder.data) throw new Error("Sales order not found");
+ if (!salesOrder.data) throw new RecordNotFoundError("Sales order not found");
const item = await client
.from("item")
.select("id, itemTrackingType")
+ .eq("companyId", companyId)
.eq("id", salesOrderLine.data.itemId)
.single();
- if (!item.data) throw new Error("Item not found");
+ if (!item.data) throw new RecordNotFoundError("Item not found");
const isSerial = item.data.itemTrackingType === "Serial";
const isBatch = item.data.itemTrackingType === "Batch";
+ // A supplied id that is not this company's shipment is a 404, not a
+ // silent create-new.
+ if (existingShipmentId && !shipment.data)
+ throw new RecordNotFoundError("Shipment not found");
const hasShipment = !!shipment.data?.id;
const previouslyShippedQuantity = salesOrderLine.data.quantitySent ?? 0;
@@ -3121,6 +3266,7 @@ serve(async (req: Request) => {
const trackedEntities = await client
.from("trackedEntity")
.select("*")
+ .eq("companyId", companyId)
.eq("attributes->>Job Make Method", jobMakeMethod.id)
.order("createdAt", { ascending: true });
@@ -3199,11 +3345,12 @@ serve(async (req: Request) => {
client
.from("shipmentLine")
.select("*")
+ .eq("companyId", companyId)
.eq("id", shipmentLineId)
.single(),
]);
- if (!shipmentLine.data) throw new Error("Shipment line not found");
+ if (!shipmentLine.data) throw new RecordNotFoundError("Shipment line not found");
await db.transaction().execute(async (trx) => {
const { id, ...data } = shipmentLine.data;
diff --git a/packages/database/supabase/functions/download/index.ts b/packages/database/supabase/functions/download/index.ts
index 0f834b5e62..872a47066c 100644
--- a/packages/database/supabase/functions/download/index.ts
+++ b/packages/database/supabase/functions/download/index.ts
@@ -14,6 +14,30 @@ const downloadValidator = z.object({
userId: z.string(),
});
+// The storage API receives the path as a raw URL path: its parser ends the
+// path at a raw `?`/`#`, drops tabs/newlines, reads `\` as `/` and resolves
+// `.`/`..` segments even when percent-encoded (`%2e%2e`). So the segment and
+// prefix checks run on the DECODED form — checking the raw string lets
+// `<companyId>/%2e%2e/<otherCompanyId>/…` through.
+function isCompanyStoragePath(path: string, companyId: string): boolean {
+ if (/[?#]/.test(path)) return false;
+ let decoded: string;
+ try {
+ decoded = decodeURIComponent(path);
+ } catch {
+ return false;
+ }
+ for (const char of decoded) {
+ const code = char.charCodeAt(0);
+ if (code < 0x20 || code === 0x7f) return false;
+ }
+ const segments = decoded.split(/[/\\]/);
+ if (segments.some((segment) => segment === "." || segment === "..")) {
+ return false;
+ }
+ return segments[0] === companyId;
+}
+
serve(async (req: Request) => {
const preflight = corsPreflight(req);
if (preflight) return preflight;
@@ -28,6 +52,20 @@ serve(async (req: Request) => {
// verify that the request is authorized by an API key or service role
const serviceRole = await requirePermissions(req, companyId, userId, { view: "documents" });
+ // The client is service-role, so storage RLS is bypassed: requirePermissions
+ // proved the caller may act in companyId, not that bucket/path are its own.
+ // Allow the company's own bucket (or the legacy shared `private` bucket, or
+ // the shared `public` / `temp-staging` buckets), and only a path under the
+ // companyId segment.
+ const allowedBucket =
+ bucket === companyId ||
+ bucket === "private" ||
+ bucket === "public" ||
+ bucket === "temp-staging";
+ if (!allowedBucket || !isCompanyStoragePath(path, companyId)) {
+ return errorResponse("File not found", 404);
+ }
+
const signedUrl = await serviceRole.storage
.from(bucket)
.createSignedUrl(path, 60);
diff --git a/packages/database/supabase/functions/embed/index.ts b/packages/database/supabase/functions/embed/index.ts
index 8657a6d3e2..fd9420b909 100644
--- a/packages/database/supabase/functions/embed/index.ts
+++ b/packages/database/supabase/functions/embed/index.ts
@@ -5,6 +5,7 @@ import z from "npm:zod@^4.5.4";
import { generateEmbedding } from "../lib/ai/embedding.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { getFunctionLogger } from "../lib/logging.ts";
+import { isServiceRoleRequest } from "../lib/supabase.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -71,14 +72,41 @@ serve(async (req: Request) => {
});
}
- const pendingJobs = parseResult.data;
-
// Track jobs that completed successfully
const completedJobs: Job[] = [];
// Track jobs that failed due to an error
const failedJobs: FailedJob[] = [];
+ // Postgres (pg_net) calls this function with the anon key, so anyone can
+ // send it a body. From such a caller, act only on jobs still queued for
+ // exactly that row: that stops a caller deleting other queue messages or
+ // buying embeddings for rows nothing asked to embed. The service role (the
+ // Inngest embedding handler) is trusted and sends synthetic negative jobIds
+ // that were never queued, so it skips the check.
+ let pendingJobs = parseResult.data;
+ if (!isServiceRoleRequest(req)) {
+ let queued: Awaited<ReturnType<typeof getQueuedJobs>>;
+ try {
+ queued = await getQueuedJobs(db, pendingJobs);
+ } catch (error) {
+ const described = describeError(error);
+ logger.error("queue lookup failed", { error: described.detail });
+ queued = new Map();
+ }
+ pendingJobs = pendingJobs.filter((job) => {
+ const message = queued.get(job.jobId);
+ if (message && message.id === job.id && message.table === job.table) {
+ return true;
+ }
+ failedJobs.push({
+ ...job,
+ error: `Job ${job.jobId} is not a queued embedding of ${job.table} ${job.id}`,
+ });
+ return false;
+ });
+ }
+
async function processJobs() {
let currentJob: Job | undefined;
@@ -134,6 +162,30 @@ serve(async (req: Request) => {
});
});
+/** The queued message for each of the jobs' ids, in one query. */
+async function getQueuedJobs(
+ db: Kysely<DB>,
+ jobs: Job[]
+): Promise<Map<number, { id: string | null; table: string | null }>> {
+ const jobIds = [...new Set(jobs.map((job) => job.jobId))];
+ const queued = new Map<number, { id: string | null; table: string | null }>();
+ if (jobIds.length === 0) return queued;
+
+ const result = await sql<{
+ msgId: string;
+ id: string | null;
+ table: string | null;
+ }>`
+ select msg_id::text as "msgId", message->>'id' as id, message->>'table' as "table"
+ from ${sql.table(`pgmq.q_${QUEUE_NAME}`)}
+ where msg_id = any(${jobIds}::bigint[])
+ `.execute(db);
+ for (const row of result.rows) {
+ queued.set(Number(row.msgId), { id: row.id, table: row.table });
+ }
+ return queued;
+}
+
/**
* Processes an embedding job.
*/
@@ -264,10 +316,15 @@ async function processJob(db: Kysely<DB>, job: Job) {
logger.debug("Customer update result", { result });
}
- logger.debug(`Deleting job ${jobId} from queue...`);
- const deleteResult =
- await sql`select pgmq.delete(${QUEUE_NAME}, ${jobId}::bigint)`.execute(db);
- logger.debug("Queue delete result", { deleteResult });
+ // Synthetic (non-positive) jobIds from the Inngest handler were never queued.
+ if (jobId > 0) {
+ logger.debug(`Deleting job ${jobId} from queue...`);
+ const deleteResult =
+ await sql`select pgmq.delete(${QUEUE_NAME}, ${jobId}::bigint)`.execute(
+ db
+ );
+ logger.debug("Queue delete result", { deleteResult });
+ }
logger.debug(`Job ${jobId} processing completed successfully`);
}
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index bfe9efe937..62a0e5c141 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -2526,6 +2526,7 @@ serve(async (req: Request) => {
supplierProcesses,
configurationRules,
quote,
+ ownedQuoteLine,
] = await Promise.all([
client
.from("activeMakeMethods")
@@ -2555,8 +2556,26 @@ serve(async (req: Request) => {
.eq("id", quoteId)
.eq("companyId", companyId)
.single(),
+ client
+ .from("quoteLine")
+ .select("id")
+ .eq("id", quoteLineId)
+ .eq("quoteId", quoteId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
]);
+ // requirePermissions proved the CALLER may act in companyId; it proves
+ // nothing about the quote line in the body. The quoteMakeMethod lookup
+ // is scoped, but a miss INSERTS one and then rewrites the line's
+ // materials and operations by quoteLineId alone.
+ if (ownedQuoteLine.error) {
+ throw new Error("Failed to get quote line");
+ }
+ if (!ownedQuoteLine.data) {
+ return errorResponse("Quote line not found", 404);
+ }
+
const configurationCodeByField = configurationRules?.data?.reduce<
Record<string, string>
>((acc, rule) => {
@@ -6652,6 +6671,11 @@ serve(async (req: Request) => {
});
throw new Error("Failed to get target quote make method");
}
+ // targetQuoteId is written onto new rows and priced below; bind it to
+ // the verified target line rather than trusting the body.
+ if (targetQuoteMakeMethod.data.quoteId !== targetQuoteId) {
+ return errorResponse("Quote line not found", 404);
+ }
if (
sourceQuoteMakeMethod.error ||
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 169ac8311a..cfa9a3c4a7 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -59,6 +59,233 @@ const importCsvValidator = z.object({
const EXTERNAL_ID_KEY = "csv";
+type ImportTable = z.infer<typeof importCsvValidator>["table"];
+
+// The module whose `update` permission each import needs — the same map the
+// ERP's import route checks (`importPermissions` in `imports.models.ts`).
+const IMPORT_PERMISSIONS: Record<ImportTable, string> = {
+ customer: "sales",
+ customerContact: "sales",
+ supplier: "purchasing",
+ supplierContact: "purchasing",
+ part: "parts",
+ material: "parts",
+ bom: "parts",
+ operations: "parts",
+ partWithMethod: "parts",
+ tool: "parts",
+ fixture: "parts",
+ consumable: "parts",
+ workCenter: "production",
+ process: "production",
+ storageUnit: "inventory",
+ service: "parts",
+ unitOfMeasure: "parts",
+ itemPostingGroup: "accounting",
+ storageType: "parts",
+ scrapReason: "production",
+ department: "people",
+ materialSubstance: "parts",
+ materialForm: "parts",
+ materialFinish: "parts",
+ materialGrade: "parts",
+ materialType: "parts",
+ materialDimension: "parts",
+};
+
+// The columns each importer may write from a CSV row. Kysely here runs as the
+// service role, so spreading a row into an INSERT/UPDATE would let a crafted
+// mapping write `id`, `createdBy`, `intercompanyCompanyId`, or any other
+// column. These mirror `fieldMappings` / `importSchemas` in the ERP's
+// `imports.models.ts`; columns the importer derives itself (rates, flags,
+// side-table fields) are handled explicitly at the call site.
+type Tables = Database["public"]["Tables"];
+type InsertColumns<T extends keyof Tables> = readonly (keyof Tables[T]["Insert"] &
+ string)[];
+
+const CUSTOMER_COLUMNS = [
+ "name",
+ "accountManagerId",
+ "customerStatusId",
+ "customerTypeId",
+ "phone",
+ "fax",
+ "currencyCode",
+ "website",
+] as const satisfies InsertColumns<"customer">;
+const SUPPLIER_COLUMNS = [
+ "name",
+ "accountManagerId",
+ "supplierStatus",
+ "supplierTypeId",
+ "phone",
+ "fax",
+ "currencyCode",
+ "website",
+] as const satisfies InsertColumns<"supplier">;
+const CONTACT_COLUMNS = [
+ "firstName",
+ "lastName",
+ "email",
+ "title",
+ "mobilePhone",
+ "workPhone",
+ "homePhone",
+ "fax",
+ "notes",
+] as const satisfies InsertColumns<"contact">;
+const WORK_CENTER_COLUMNS = [
+ "name",
+ "description",
+ "defaultStandardFactor",
+ "locationId",
+] as const satisfies InsertColumns<"workCenter">;
+const PROCESS_COLUMNS = [
+ "name",
+ "defaultStandardFactor",
+] as const satisfies InsertColumns<"process">;
+
+/**
+ * The allow-listed columns of a CSV row, typed as `table`'s own columns. CSV
+ * cells are strings; the enum and numeric columns among them are checked by
+ * Postgres on write, as they were before the allow-list.
+ */
+function pickColumns<T extends keyof Tables, K extends keyof Tables[T]["Insert"] & string>(
+ _table: T,
+ record: Partial<Record<string, string>>,
+ columns: readonly K[]
+): Partial<Pick<Tables[T]["Insert"], K>> {
+ const out: Partial<Record<K, string>> = {};
+ for (const column of columns) {
+ if (column in record) out[column] = record[column];
+ }
+ return out as unknown as Partial<Pick<Tables[T]["Insert"], K>>;
+}
+
+// Tables a CSV row may reference by id. The material taxonomy has global
+// system rows (companyId IS NULL) that every company may use.
+type ReferencedTable =
+ | "employee"
+ | "customerStatus"
+ | "customerType"
+ | "supplierType"
+ | "paymentTerm"
+ | "shippingMethod"
+ | "supplier"
+ | "location"
+ | "materialSubstance"
+ | "materialForm"
+ | "materialFinish"
+ | "materialGrade"
+ | "materialDimension";
+
+const GLOBAL_REFERENCED_TABLES = new Set<ReferencedTable>([
+ "materialSubstance",
+ "materialForm",
+ "materialFinish",
+ "materialGrade",
+ "materialDimension",
+]);
+
+type ReferenceSpec = { column: string; table: ReferencedTable; label: string };
+
+const itemReferences: ReferenceSpec[] = [
+ { column: "supplierId", table: "supplier", label: "Supplier" },
+];
+
+// Id-valued columns per import. The wizard resolves these through
+// company-scoped fetchers, but the ids arrive in the request body, so each is
+// re-checked against the caller's company before anything is written.
+const REFERENCES: Partial<Record<ImportTable, ReferenceSpec[]>> = {
+ customer: [
+ { column: "accountManagerId", table: "employee", label: "Account Manager" },
+ { column: "customerStatusId", table: "customerStatus", label: "Status" },
+ { column: "customerTypeId", table: "customerType", label: "Type" },
+ { column: "paymentTermId", table: "paymentTerm", label: "Payment Term" },
+ ],
+ supplier: [
+ { column: "accountManagerId", table: "employee", label: "Account Manager" },
+ { column: "supplierTypeId", table: "supplierType", label: "Type" },
+ { column: "paymentTermId", table: "paymentTerm", label: "Payment Term" },
+ {
+ column: "shippingMethodId",
+ table: "shippingMethod",
+ label: "Shipping Method",
+ },
+ ],
+ part: itemReferences,
+ tool: itemReferences,
+ fixture: itemReferences,
+ consumable: itemReferences,
+ service: itemReferences,
+ material: [
+ ...itemReferences,
+ {
+ column: "materialSubstanceId",
+ table: "materialSubstance",
+ label: "Substance",
+ },
+ { column: "materialFormId", table: "materialForm", label: "Form" },
+ { column: "finishId", table: "materialFinish", label: "Finish" },
+ { column: "gradeId", table: "materialGrade", label: "Grade" },
+ { column: "dimensionId", table: "materialDimension", label: "Dimensions" },
+ ],
+ workCenter: [{ column: "locationId", table: "location", label: "Location" }],
+ storageUnit: [{ column: "locationId", table: "location", label: "Location" }],
+};
+
+type CsvRecord = Record<string, string>;
+
+/**
+ * Report every row that references a record outside the caller's company, and
+ * return the other rows as `[rowIndex, record]` pairs (the index is the CSV row
+ * the summary reports). One query per referenced column, run together.
+ */
+async function rejectForeignReferences(
+ table: ImportTable,
+ records: CsvRecord[],
+ cId: string,
+ errors: Array<{ row: number; reason: string }>
+): Promise<Array<[number, CsvRecord]>> {
+ const ownedBySpec = await Promise.all(
+ (REFERENCES[table] ?? []).map(async (spec) => {
+ const ids = [
+ ...new Set(records.map((r) => r[spec.column]).filter((v) => !!v)),
+ ];
+ if (ids.length === 0) return { spec, owned: new Set<string>() };
+ const scope = GLOBAL_REFERENCED_TABLES.has(spec.table)
+ ? sql<boolean>`("companyId" = ${cId} OR "companyId" IS NULL)`
+ : sql<boolean>`"companyId" = ${cId}`;
+ // Every referenced table has an `id` and a `companyId`; the cast only
+ // narrows the union for Kysely's types.
+ const rows = await db
+ .selectFrom(spec.table as "location")
+ .select(["id"])
+ .where("id", "in", ids)
+ .where(scope)
+ .execute();
+ return { spec, owned: new Set(rows.map((r) => r.id)) };
+ })
+ );
+
+ const accepted: Array<[number, CsvRecord]> = [];
+ for (const [rowIndex, record] of records.entries()) {
+ const foreign = ownedBySpec.find(
+ ({ spec, owned }) =>
+ !!record[spec.column] && !owned.has(record[spec.column])
+ );
+ if (foreign) {
+ errors.push({
+ row: rowIndex,
+ reason: `${foreign.spec.label} "${record[foreign.spec.column]}" was not found in this company`,
+ });
+ } else {
+ accepted.push([rowIndex, record]);
+ }
+ }
+ return accepted;
+}
+
/**
* Fallback CSV parser used when std/csv rejects a row-length mismatch.
* Handles RFC-4180 quoting but tolerates uneven row widths (extra cells
@@ -966,7 +1193,9 @@ serve(async (req: Request) => {
logger.info({ table, filePath, columnMappings, enumMappings, companyId, userId });
- const client = await requirePermissions(req, companyId, userId, { create: "resources" });
+ const client = await requirePermissions(req, companyId, userId, {
+ update: IMPORT_PERMISSIONS[table],
+ });
// The client is service-role and the legacy bucket is shared across
// tenants, so the `${companyId}/` key prefix is the tenant boundary on the
@@ -1042,6 +1271,13 @@ serve(async (req: Request) => {
skipped: [] as Array<{ row: number; reason: string }>,
};
+ const acceptedRows = await rejectForeignReferences(
+ table,
+ mappedRecords,
+ companyId,
+ summary.errors
+ );
+
switch (table) {
case "customer": {
const externalIdMap = await getCsvExternalIdMap("customer", companyId);
@@ -1088,7 +1324,7 @@ serve(async (req: Request) => {
ext: PartnerExtensionData;
}> = [];
- for (const [rowIndex, record] of mappedRecords.entries()) {
+ for (const [rowIndex, record] of acceptedRows) {
const ext = extractPartnerExtensions(record);
const {
id,
@@ -1130,7 +1366,7 @@ serve(async (req: Request) => {
customerUpdates.push({
id: decision.entityId,
data: {
- ...nullifyEmptyStrings(rest),
+ ...nullifyEmptyStrings(pickColumns("customer", rest, CUSTOMER_COLUMNS)),
updatedAt: new Date().toISOString(),
updatedBy: userId,
},
@@ -1146,7 +1382,7 @@ serve(async (req: Request) => {
}
} else {
customerInserts.push({
- ...nullifyEmptyStrings(rest),
+ ...nullifyEmptyStrings(pickColumns("customer", rest, CUSTOMER_COLUMNS)),
readableId: id || null,
companyId,
createdAt: new Date().toISOString(),
@@ -1289,7 +1525,7 @@ serve(async (req: Request) => {
ext: PartnerExtensionData;
}> = [];
- for (const [rowIndex, record] of mappedRecords.entries()) {
+ for (const [rowIndex, record] of acceptedRows) {
const ext = extractPartnerExtensions(record);
const {
id,
@@ -1331,7 +1567,9 @@ serve(async (req: Request) => {
supplierUpdates.push({
id: decision.entityId,
data: {
- ...nullifyEmptyStrings(rest),
+ ...nullifyEmptyStrings(
+ pickColumns("supplier", rest, SUPPLIER_COLUMNS)
+ ),
updatedAt: new Date().toISOString(),
updatedBy: userId,
},
@@ -1347,7 +1585,7 @@ serve(async (req: Request) => {
}
} else {
supplierInserts.push({
- ...nullifyEmptyStrings(rest),
+ ...nullifyEmptyStrings(pickColumns("supplier", rest, SUPPLIER_COLUMNS)),
readableId: id || null,
companyId,
createdAt: new Date().toISOString(),
@@ -1581,7 +1819,10 @@ serve(async (req: Request) => {
const dimensionPairs: Array<{ scopeId: string; name: string }> =
[];
- for (const record of mappedRecords) {
+ // Rejected rows are left out: one may name another company's
+ // substance or form, and resolving it would create taxonomy rows
+ // under that parent.
+ for (const [, record] of acceptedRows) {
const substanceId = record.materialSubstanceId;
const formId = record.materialFormId;
// An explicit *Id (possible via direct invocation) wins over the
@@ -1690,7 +1931,7 @@ serve(async (req: Request) => {
}
}
- for (const [rowIndex, record] of mappedRecords.entries()) {
+ for (const [rowIndex, record] of acceptedRows) {
const item = itemValidator.safeParse(record);
if (!item.success) {
@@ -2134,7 +2375,7 @@ serve(async (req: Request) => {
[];
const isContactValid = (
- record: Record<string, string>
+ record: { email?: string | null }
): record is {
email: string;
} => {
@@ -2144,7 +2385,10 @@ serve(async (req: Request) => {
};
for (const [rowIndex, record] of mappedRecords.entries()) {
- const { id, companyId: customerId, ...contactData } = record;
+ // `companyId` here is the parent's External Company ID; only
+ // contact columns are written.
+ const { id, companyId: customerId } = record;
+ const contactData = pickColumns("contact", record, CONTACT_COLUMNS);
if (externalContactIdMap.has(id)) {
const existingEntityId = externalContactIdMap.get(id)!;
@@ -2255,7 +2499,7 @@ serve(async (req: Request) => {
[];
const isContactValid = (
- record: Record<string, string>
+ record: { email?: string | null }
): record is {
email: string;
} => {
@@ -2265,7 +2509,10 @@ serve(async (req: Request) => {
};
for (const [rowIndex, record] of mappedRecords.entries()) {
- const { id, companyId: supplierId, ...contactData } = record;
+ // `companyId` here is the parent's External Company ID; only
+ // contact columns are written.
+ const { id, companyId: supplierId } = record;
+ const contactData = pickColumns("contact", record, CONTACT_COLUMNS);
if (externalContactIdMap.has(id)) {
const existingEntityId = externalContactIdMap.get(id)!;
@@ -2380,7 +2627,7 @@ serve(async (req: Request) => {
);
};
- for (const record of mappedRecords) {
+ for (const [, record] of acceptedRows) {
const { id, ...rest } = record;
if (externalIdMap.has(id)) {
const existingEntityId = externalIdMap.get(id)!;
@@ -2389,7 +2636,7 @@ serve(async (req: Request) => {
workCenterUpdates.push({
id: existingEntityId,
data: {
- ...rest,
+ ...pickColumns("workCenter", rest, WORK_CENTER_COLUMNS),
laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,
machineRate: rest.machineRate
? parseFloat(rest.machineRate)
@@ -2405,7 +2652,7 @@ serve(async (req: Request) => {
} else if (isWorkCenterValid(rest) && !workCenterIds.has(id)) {
workCenterIds.add(id);
workCenterInserts.push({
- ...rest,
+ ...pickColumns("workCenter", rest, WORK_CENTER_COLUMNS),
laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,
machineRate: rest.machineRate
? parseFloat(rest.machineRate)
@@ -2506,7 +2753,7 @@ serve(async (req: Request) => {
processUpdates.push({
id: existingEntityId,
data: {
- ...rest,
+ ...pickColumns("process", rest, PROCESS_COLUMNS),
processType: normalizeProcessType(rest.processType),
completeAllOnScan:
rest.completeAllOnScan?.toLowerCase() === "true" ?? false,
@@ -2518,7 +2765,7 @@ serve(async (req: Request) => {
} else if (isProcessValid(rest) && !processIds.has(id)) {
processIds.add(id);
processInserts.push({
- ...rest,
+ ...pickColumns("process", rest, PROCESS_COLUMNS),
processType: normalizeProcessType(rest.processType),
completeAllOnScan:
rest.completeAllOnScan?.toLowerCase() === "true" ?? false,
@@ -2702,7 +2949,7 @@ serve(async (req: Request) => {
return ids;
};
- for (const [rowIndex, record] of mappedRecords.entries()) {
+ for (const [rowIndex, record] of acceptedRows) {
const id = record.id ?? "";
const name = (record.name ?? "").trim();
const locationId = (record.locationId ?? "").trim();
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 96e96f22b8..a21b3f190a 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -4,6 +4,7 @@ import { sql, Transaction } from "kysely";
import { z } from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { assertCompanyRecords, RecordNotFoundError } from "../lib/company-records.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
@@ -152,6 +153,7 @@ async function issueJobOperationMaterials(
const materialsToIssue = await trx
.selectFrom("jobMaterial")
.where("jobOperationId", "=", jobOperationId)
+ .where("companyId", "=", companyId)
.where("itemType", "in", ["Material", "Part", "Consumable"])
.where("methodType", "!=", "Make to Order")
.where("estimatedQuantity", ">", 0)
@@ -163,6 +165,7 @@ async function issueJobOperationMaterials(
const kittedChildren = await trx
.selectFrom("jobMaterialWithMakeMethodId")
.where("jobOperationId", "=", jobOperationId)
+ .where("companyId", "=", companyId)
.where("itemType", "in", ["Material", "Part", "Consumable"])
.where("methodType", "=", "Make to Order")
.where("kit", "=", true)
@@ -1085,6 +1088,40 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
+// The production-event and inspection links a completion/scrap payload carries
+// are written verbatim into productionQuantity, whose single-column FKs accept
+// any company's row — re-read them under companyId first (one query per table).
+async function assertProductionQuantityLinks(
+ companyId: string,
+ links: {
+ laborProductionEventId?: string;
+ machineProductionEventId?: string;
+ setupProductionEventId?: string;
+ inspectionId?: string;
+ inspectionSampleId?: string;
+ }
+) {
+ await assertCompanyRecords(
+ db,
+ "productionEvent",
+ [
+ links.laborProductionEventId,
+ links.machineProductionEventId,
+ links.setupProductionEventId,
+ ],
+ companyId,
+ "Production event"
+ );
+ await assertCompanyRecords(db, "inspection", [links.inspectionId], companyId, "Inspection");
+ await assertCompanyRecords(
+ db,
+ "inspectionSample",
+ [links.inspectionSampleId],
+ companyId,
+ "Inspection sample"
+ );
+}
+
// Shared accounting context for the tracked-consumption paths (the per-op and
// per-batch cases): whether accounting is enabled, the posting-group defaults,
// and the active dimension map.
@@ -1192,6 +1229,7 @@ async function consumeTrackedEntitiesIntoOperation(
"in",
children.map((child) => child.trackedEntityId)
)
+ .where("companyId", "=", companyId)
.selectAll()
.execute();
@@ -1243,6 +1281,7 @@ async function consumeTrackedEntitiesIntoOperation(
jobMaterial = await trx
.selectFrom("jobMaterial")
.where("id", "=", materialId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirst();
@@ -1297,6 +1336,7 @@ async function consumeTrackedEntitiesIntoOperation(
const jobOperation = await trx
.selectFrom("jobOperation")
.where("id", "=", jobOperationId)
+ .where("companyId", "=", companyId)
.select(["jobId", "jobMakeMethodId"])
.executeTakeFirst();
@@ -1307,6 +1347,7 @@ async function consumeTrackedEntitiesIntoOperation(
const item = await trx
.selectFrom("item")
.where("id", "=", itemId)
+ .where("companyId", "=", companyId)
.select(["name", "type", "itemTrackingType", "defaultMethodType"])
.executeTakeFirst();
@@ -1389,6 +1430,7 @@ async function consumeTrackedEntitiesIntoOperation(
const parentTrackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", parentTrackedEntityId)
+ .where("companyId", "=", companyId)
.select([
"id",
"sourceDocumentId",
@@ -1838,17 +1880,20 @@ serve(async (req: Request) => {
case "jobOperationBatchComplete": {
const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ await assertProductionQuantityLinks(companyId, row);
const [jobOperation, productionQuantities] = await Promise.all([
client
.from("jobOperation")
.select("*")
.eq("id", row.jobOperationId)
+ .eq("companyId", companyId)
.single(),
client
.from("productionQuantity")
.select("*")
.eq("jobOperationId", row.jobOperationId)
+ .eq("companyId", companyId)
.eq("type", "Production"),
]);
@@ -1922,6 +1967,7 @@ serve(async (req: Request) => {
.from("productionQuantity")
.select("quantity")
.eq("jobOperationId", jobOperationId)
+ .eq("companyId", companyId)
.eq("type", "Production"),
]);
if (entity.error || !entity.data) {
@@ -1978,11 +2024,13 @@ serve(async (req: Request) => {
case "jobOperationSerialComplete": {
const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ await assertProductionQuantityLinks(companyId, row);
const jobOperation = await client
.from("jobOperation")
.select("*")
.eq("id", row.jobOperationId)
+ .eq("companyId", companyId)
.single();
if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {
throw new Error("Job operation not found");
@@ -2053,6 +2101,7 @@ serve(async (req: Request) => {
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirst();
@@ -2205,6 +2254,14 @@ serve(async (req: Request) => {
const client = await requirePermissions(req, companyId, userId, {
update: "production",
});
+ // Lands on productionQuantity, the Scrap activity and the journal's
+ // ScrapReason dimension — all this company's rows.
+ await assertCompanyRecords(db, "scrapReason", [scrapReasonId], companyId, "Scrap reason");
+ await assertProductionQuantityLinks(companyId, {
+ laborProductionEventId,
+ machineProductionEventId,
+ setupProductionEventId,
+ });
const operationRes = await client
.from("jobOperation")
@@ -2676,6 +2733,14 @@ serve(async (req: Request) => {
} = validatedPayload;
const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ // Written into jobMaterialStep for an unplanned part (no companyId there).
+ await assertCompanyRecords(
+ db,
+ "jobOperationStep",
+ [jobOperationStepId],
+ companyId,
+ "Job operation step"
+ );
const [accountingSettings, companyRecord] = await Promise.all([
client
@@ -2715,8 +2780,10 @@ serve(async (req: Request) => {
const jobOperation = await trx
.selectFrom("jobOperation")
.where("id", "=", id)
+ .where("companyId", "=", companyId)
.select(["jobId", "jobMakeMethodId"])
.executeTakeFirst();
+ if (!jobOperation) throw new RecordNotFoundError("Job operation not found");
const [job, item] = await Promise.all([
trx
@@ -2727,6 +2794,7 @@ serve(async (req: Request) => {
trx
.selectFrom("item")
.where("id", "=", itemId)
+ .where("companyId", "=", companyId)
.select([
"id",
"itemTrackingType",
@@ -2741,8 +2809,10 @@ serve(async (req: Request) => {
const material = await trx
.selectFrom("jobMaterial")
.where("id", "=", materialId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirst();
+ if (!material) throw new RecordNotFoundError("Job material not found");
let storageUnitId: string | null | undefined;
// Prioritize material.storageUnitId if available
@@ -3013,6 +3083,16 @@ serve(async (req: Request) => {
const client = await requirePermissions(req, companyId, userId, {
update: "production",
});
+ // The parent lands in trackedActivityOutput and the reason on the ledger,
+ // the activity and the journal dimension — both must be this company's.
+ await assertCompanyRecords(
+ db,
+ "trackedEntity",
+ [parentTrackedEntityId],
+ companyId,
+ "Parent tracked entity"
+ );
+ await assertCompanyRecords(db, "scrapReason", [scrapReasonId], companyId, "Scrap reason");
const [trackedEntity, jobMaterial] = await Promise.all([
client
@@ -3541,6 +3621,14 @@ serve(async (req: Request) => {
}
const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ // Stamped on the Consume activity and written into jobMaterialStep.
+ await assertCompanyRecords(
+ db,
+ "jobOperationStep",
+ [jobOperationStepId],
+ companyId,
+ "Job operation step"
+ );
const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));
const accounting = await loadConsumeAccountingContext(client, companyId);
@@ -3989,6 +4077,7 @@ serve(async (req: Request) => {
"in",
children.map((child) => child.trackedEntityId)
)
+ .where("companyId", "=", companyId)
.selectAll()
.execute();
@@ -4014,8 +4103,10 @@ serve(async (req: Request) => {
const jobMaterial = await trx
.selectFrom("jobMaterial")
.where("id", "=", materialId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirst();
+ if (!jobMaterial) throw new RecordNotFoundError("Job material not found");
// Get item details
const item = await trx
@@ -4035,6 +4126,7 @@ serve(async (req: Request) => {
const parentTrackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", parentTrackedEntityId)
+ .where("companyId", "=", companyId)
.select([
"id",
"sourceDocumentId",
@@ -4205,10 +4297,14 @@ serve(async (req: Request) => {
const { trackedEntityId, newRevision, quantity, companyId, userId } =
validatedPayload;
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ await requirePermissions(req, companyId, userId, { update: "inventory" });
+
const convertedEntity = await db.transaction().execute(async (trx) => {
const trackedEntity = await trx
.selectFrom("trackedEntity")
.where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirstOrThrow();
@@ -4452,11 +4548,15 @@ serve(async (req: Request) => {
userId,
} = validatedPayload;
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ await requirePermissions(req, companyId, userId, { update: "resources" });
+
await db.transaction().execute(async (trx) => {
// Get the maintenance dispatch to find the location
const dispatch = await trx
.selectFrom("maintenanceDispatch")
.where("id", "=", maintenanceDispatchId)
+ .where("companyId", "=", companyId)
.select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])
.executeTakeFirstOrThrow();
@@ -4466,6 +4566,7 @@ serve(async (req: Request) => {
const item = await trx
.selectFrom("item")
.where("id", "=", itemId)
+ .where("companyId", "=", companyId)
.select(["id", "itemTrackingType"])
.executeTakeFirstOrThrow();
@@ -4541,6 +4642,9 @@ serve(async (req: Request) => {
userId,
} = validatedPayload;
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ await requirePermissions(req, companyId, userId, { update: "resources" });
+
if (children.length === 0) {
throw new Error("At least one tracked entity is required");
}
@@ -4553,6 +4657,7 @@ serve(async (req: Request) => {
const dispatch = await trx
.selectFrom("maintenanceDispatch")
.where("id", "=", maintenanceDispatchId)
+ .where("companyId", "=", companyId)
.select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])
.executeTakeFirstOrThrow();
@@ -4586,6 +4691,7 @@ serve(async (req: Request) => {
"in",
children.map((child) => child.trackedEntityId)
)
+ .where("companyId", "=", companyId)
.selectAll()
.execute();
@@ -4631,6 +4737,7 @@ serve(async (req: Request) => {
const item = await trx
.selectFrom("item")
.where("id", "=", itemId)
+ .where("companyId", "=", companyId)
.select(["id", "readableIdWithRevision"])
.executeTakeFirstOrThrow();
@@ -4873,6 +4980,9 @@ serve(async (req: Request) => {
const { maintenanceDispatchItemId, children, companyId, userId } =
validatedPayload;
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ await requirePermissions(req, companyId, userId, { update: "resources" });
+
if (children.length === 0) {
throw new Error("At least one tracked entity is required");
}
@@ -4882,6 +4992,7 @@ serve(async (req: Request) => {
const dispatchItem = await trx
.selectFrom("maintenanceDispatchItem")
.where("id", "=", maintenanceDispatchItemId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirstOrThrow();
@@ -4902,6 +5013,7 @@ serve(async (req: Request) => {
"in",
children.map((child) => child.trackedEntityId)
)
+ .where("companyId", "=", companyId)
.selectAll()
.execute();
@@ -5068,11 +5180,15 @@ serve(async (req: Request) => {
const { maintenanceDispatchItemId, companyId, userId } =
validatedPayload;
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ await requirePermissions(req, companyId, userId, { update: "resources" });
+
await db.transaction().execute(async (trx) => {
// Get the maintenance dispatch item
const dispatchItem = await trx
.selectFrom("maintenanceDispatchItem")
.where("id", "=", maintenanceDispatchItemId)
+ .where("companyId", "=", companyId)
.selectAll()
.executeTakeFirstOrThrow();
diff --git a/packages/database/supabase/functions/lib/company-records.ts b/packages/database/supabase/functions/lib/company-records.ts
new file mode 100644
index 0000000000..6ca2c6a502
--- /dev/null
+++ b/packages/database/supabase/functions/lib/company-records.ts
@@ -0,0 +1,53 @@
+import type { Kysely } from "kysely";
+import type { DB } from "./database.ts";
+
+// Record ids in a payload come straight from the caller and prove nothing about
+// tenancy: requirePermissions authorizes the CALLER for companyId, not the ids it
+// sends. Several of these ids are only ever written as references into the
+// caller's own rows (a ledger's locationId, an activity's trackedEntityId), and
+// their single-column FKs accept a row from any company — so nothing downstream
+// refuses a foreign id. Re-read them under companyId before writing.
+export class RecordNotFoundError extends Error {
+ readonly status = 404;
+}
+
+type CompanyScopedTable =
+ | "inspection"
+ | "inspectionSample"
+ | "jobOperationStep"
+ | "location"
+ | "nonConformance"
+ | "productionEvent"
+ | "purchaseOrder"
+ | "scrapReason"
+ | "storageUnit"
+ | "trackedEntity";
+
+/**
+ * Throws `RecordNotFoundError` unless every provided id is a row of `table` in
+ * `companyId`. Null / undefined / duplicate ids are ignored, so optional payload
+ * fields stay optional. One query per call — collect the ids first.
+ */
+export async function assertCompanyRecords(
+ db: Kysely<DB>,
+ table: CompanyScopedTable,
+ ids: Iterable<string | null | undefined>,
+ companyId: string,
+ label: string
+): Promise<void> {
+ const unique = [
+ ...new Set([...ids].filter((id): id is string => typeof id === "string")),
+ ];
+ if (unique.length === 0) return;
+
+ const rows = await db
+ .selectFrom(table)
+ .select("id")
+ .where("id", "in", unique)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ if (rows.length !== unique.length) {
+ throw new RecordNotFoundError(`${label} not found`);
+ }
+}
diff --git a/packages/database/supabase/functions/lib/response.test.ts b/packages/database/supabase/functions/lib/response.test.ts
index 3df5834221..284366cbbc 100644
--- a/packages/database/supabase/functions/lib/response.test.ts
+++ b/packages/database/supabase/functions/lib/response.test.ts
@@ -177,3 +177,23 @@ Deno.test("isDataLayerError returns false for non-data-layer values", () => {
assertEquals(isDataLayerError(input), false);
}
});
+
+Deno.test("errorResponse uses a numeric 4xx/5xx err.status over the passed status", async () => {
+ // Shaped like lib/company-records.ts' RecordNotFoundError.
+ class NotFoundError extends Error {
+ readonly status = 404;
+ }
+ const res = errorResponse(new NotFoundError("Receipt not found"), 500);
+ assertEquals(res.status, 404);
+ assertEquals(await res.json(), { message: "Receipt not found" });
+
+ const limited = Object.assign(new Error("Rate limit exceeded"), { status: 429 });
+ assertEquals(errorResponse(limited, 401).status, 429);
+});
+
+Deno.test("errorResponse ignores a non-HTTP err.status", () => {
+ for (const status of [200, 302, 700, "404", 404.5]) {
+ const err = Object.assign(new Error("x"), { status });
+ assertEquals(errorResponse(err, 400).status, 400);
+ }
+});
diff --git a/packages/database/supabase/functions/lib/response.ts b/packages/database/supabase/functions/lib/response.ts
index eb42ad3acb..25719fd9dd 100644
--- a/packages/database/supabase/functions/lib/response.ts
+++ b/packages/database/supabase/functions/lib/response.ts
@@ -116,6 +116,8 @@ function zodIssueSummary(err: unknown): string | null {
* - `extra` merges additional top-level keys — currently only `invalidLineIds` from
* `post-inventory-count`. `undefined` values are dropped so callers can pass optionals
* without conditional spreads.
+ * - A numeric 4xx/5xx `err.status` (e.g. `RecordNotFoundError`'s 404, a rate-limit 429)
+ * wins over `status`, so a catch block needn't map each error class itself.
*/
export function errorResponse(
err: unknown,
@@ -124,6 +126,16 @@ export function errorResponse(
): Response {
console.error(err);
+ const errStatus = (err as { status?: unknown } | null | undefined)?.status;
+ if (
+ typeof errStatus === "number" &&
+ Number.isInteger(errStatus) &&
+ errStatus >= 400 &&
+ errStatus <= 599
+ ) {
+ status = errStatus;
+ }
+
const raw =
typeof err === "string"
? err
diff --git a/packages/database/supabase/functions/lib/supabase.ts b/packages/database/supabase/functions/lib/supabase.ts
index e61a057779..a488704fe7 100644
--- a/packages/database/supabase/functions/lib/supabase.ts
+++ b/packages/database/supabase/functions/lib/supabase.ts
@@ -124,10 +124,17 @@ export const getSupabase = (authorizationHeader: string | null) => {
);
};
+/**
+ * Service-role client for a trusted server bearer or a company API key. Pass
+ * `requiredPermissions` whenever the function acts on company data: an API
+ * key is then held to the same scopes `requirePermissions` would demand, not
+ * just to belonging to the company.
+ */
export const getSupabaseServiceRole = async (
authorizationHeader: string | null,
apiKeyHeader?: string | null,
- companyId?: string
+ companyId?: string,
+ requiredPermissions?: RequiredPermissions
) => {
if (!authorizationHeader && !apiKeyHeader) {
throw new Error("Authorization header or API key header is required");
@@ -148,7 +155,7 @@ export const getSupabaseServiceRole = async (
const keyHash = hashApiKey(apiKeyHeader);
const { data, error } = await serviceRole
.from("apiKey")
- .select("id, companyId, rateLimit, rateLimitWindow, expiresAt")
+ .select("id, companyId, scopes, rateLimit, rateLimitWindow, expiresAt")
.eq("keyHash" as any, keyHash)
.eq("companyId", companyId)
.single();
@@ -179,6 +186,10 @@ export const getSupabaseServiceRole = async (
throw new Error("Rate limit exceeded");
}
+ if (requiredPermissions) {
+ assertApiKeyScopes(row.scopes ?? {}, requiredPermissions, companyId);
+ }
+
return serviceRole;
}
@@ -236,6 +247,24 @@ function parseClaimsPermissions(
return { permissions, role };
}
+/** An API key's scopes are `<module>_<action>` → company ids, like claims. */
+function assertApiKeyScopes(
+ scopes: Record<string, string[]>,
+ required: RequiredPermissions,
+ companyId: string
+): void {
+ for (const [action, modules] of Object.entries(required)) {
+ const moduleList =
+ typeof modules === "string" ? [modules] : (modules as string[]);
+ for (const mod of moduleList) {
+ const scopeKey = `${mod}_${action}`;
+ if (!(scopeKey in scopes) || !scopes[scopeKey]?.includes(companyId)) {
+ throw new Error("API key lacks required permissions");
+ }
+ }
+ }
+}
+
function checkPermissions(
claims: Record<string, Permission>,
companyId: string,
@@ -299,9 +328,14 @@ export async function requireCaller(req: Request): Promise<void> {
throw new Error("Sign in or use an API key");
}
+/** True when the request carries the service role key (jobs, other edge functions). */
+export function isServiceRoleRequest(req: Request): boolean {
+ return isTrustedBearer(req.headers.get("Authorization"));
+}
+
/** For functions only servers call (jobs, other edge functions): the service role key or nothing. */
export function requireServiceRole(req: Request): void {
- if (!isTrustedBearer(req.headers.get("Authorization"))) {
+ if (!isServiceRoleRequest(req)) {
throw new Error("Service role only");
}
}
@@ -356,18 +390,7 @@ export async function requirePermissions(
throw new Error("Rate limit exceeded");
}
- // Check API key scopes against required permissions
- const scopes: Record<string, string[]> = row.scopes ?? {};
- for (const [action, modules] of Object.entries(permissions)) {
- const moduleList =
- typeof modules === "string" ? [modules] : (modules as string[]);
- for (const mod of moduleList) {
- const scopeKey = `${mod}_${action}`;
- if (!(scopeKey in scopes) || !scopes[scopeKey]?.includes(companyId)) {
- throw new Error("API key lacks required permissions");
- }
- }
- }
+ assertApiKeyScopes(row.scopes ?? {}, permissions, companyId);
return serviceRole;
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 56a0f29b7f..65c0f4f7ed 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -14010,21 +14010,18 @@ export type Database = {
companyId: string
employeeTypeId: string
id: string
- pin: string | null
}
Insert: {
active?: boolean
companyId: string
employeeTypeId: string
id?: string
- pin?: string | null
}
Update: {
active?: boolean
companyId?: string
employeeTypeId?: string
id?: string
- pin?: string | null
}
Relationships: [
{
@@ -14376,6 +14373,101 @@ export type Database = {
}
]
}
+ employeePin: {
+ Row: {
+ companyId: string
+ employeeId: string
+ pinHash: string
+ updatedAt: string
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ employeeId: string
+ pinHash: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ employeeId?: string
+ pinHash?: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_employee_fkey"
+ columns: ["employeeId", "companyId"]
+ isOneToOne: true
+ referencedRelation: "employee"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeePin_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ }
+ ]
+ }
employeeShift: {
Row: {
companyId: string
@@ -84398,6 +84490,15 @@ export type Database = {
Args: { p_company_id: string }
Returns: undefined
}
+ set_employee_pin: {
+ Args: {
+ p_company_id: string
+ p_employee_id: string
+ p_pin: string
+ p_updated_by: string
+ }
+ Returns: undefined
+ }
set_shelf_life_for_operation: {
Args: {
p_event: Database["public"]["Enums"]["shelfLifeTriggerTiming"]
@@ -84790,6 +84891,10 @@ export type Database = {
}
uuid_generate_v4: { Args: never; Returns: string }
uuid_to_base58: { Args: { _uuid: string }; Returns: string }
+ verify_employee_pin: {
+ Args: { p_company_id: string; p_employee_id: string; p_pin: string }
+ Returns: boolean
+ }
workflow_merge_custom_fields: {
Args: {
p_company_id: string
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
index 594348fef3..04b550a1b8 100644
--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -5,6 +5,10 @@ import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { Transaction } from "kysely";
import { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import {
+ assertCompanyRecords,
+ RecordNotFoundError,
+} from "../lib/company-records.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
@@ -133,6 +137,39 @@ serve(async (req: Request) => {
update: "inventory",
});
+ // The service-role client proves the caller may act in companyId, not that
+ // the ids below belong to it — each lands on this company's ledger rows or
+ // journal dimensions, and their single-column FKs accept any company's row.
+ await assertCompanyRecords(db, "location", [locationId], companyId, "Location");
+ await assertCompanyRecords(
+ db,
+ "storageUnit",
+ [storageUnitId, originalStorageUnitId],
+ companyId,
+ "Storage unit"
+ );
+ await assertCompanyRecords(
+ db,
+ "scrapReason",
+ [scrapReasonId],
+ companyId,
+ "Scrap reason"
+ );
+ // A trackedEntityId that exists nowhere is legitimate: the app mints the id
+ // (nanoid) for a NEW serial/batch and this function inserts it. One that
+ // belongs to another company is not — the paths below would write ledger
+ // rows pointing at it (the insert only fails by accident of the id-only PK).
+ if (trackedEntityId) {
+ const existing = await db
+ .selectFrom("trackedEntity")
+ .select("companyId")
+ .where("id", "=", trackedEntityId)
+ .executeTakeFirst();
+ if (existing && existing.companyId !== companyId) {
+ throw new RecordNotFoundError("Tracked entity not found");
+ }
+ }
+
const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();
const nowIso = new Date().toISOString();
diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.ts
index 3ffa2e25b7..8ba8700bb0 100644
--- a/packages/database/supabase/functions/post-memo/index.ts
+++ b/packages/database/supabase/functions/post-memo/index.ts
@@ -30,10 +30,12 @@ serve(async (req: Request) => {
logger.info({ type, memoId, userId, companyId });
+ // An API key must carry the scope the ERP's post/void routes require.
const client = await getSupabaseServiceRole(
req.headers.get("Authorization"),
req.headers.get("carbon-key") ?? "",
companyId,
+ { update: "invoicing" },
);
const today = datetime.today(await getCompanyTimeZone(client, companyId))
.toString();
diff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.ts
index b4c15b5d68..15aab41bf3 100644
--- a/packages/database/supabase/functions/post-nonconformance/index.ts
+++ b/packages/database/supabase/functions/post-nonconformance/index.ts
@@ -1,6 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { assertCompanyRecords } from "../lib/company-records.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
@@ -79,6 +80,31 @@ serve(async (req: Request) => {
return jsonResponse({ success: true, journalId: null });
}
+ // The service-role client proves the caller may act in companyId, not that
+ // the document or the movements' location / tracked entity belong to it —
+ // all three land on this company's ledger rows.
+ await assertCompanyRecords(
+ db,
+ documentType === "Inbound Inspection" ? "inspection" : "nonConformance",
+ [documentId],
+ companyId,
+ documentType === "Inbound Inspection" ? "Inspection" : "Non-conformance"
+ );
+ await assertCompanyRecords(
+ db,
+ "location",
+ effectiveMovements.map((m) => m.locationId),
+ companyId,
+ "Location"
+ );
+ await assertCompanyRecords(
+ db,
+ "trackedEntity",
+ effectiveMovements.map((m) => m.trackedEntityId),
+ companyId,
+ "Tracked entity"
+ );
+
const itemIds = [...new Set(effectiveMovements.map((m) => m.itemId))];
const [itemsResult, itemCostsResult, accountingSettings] =
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index 3980cfbca0..1eefe3d1d8 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -43,10 +43,12 @@ serve(async (req: Request) => {
logger.info({ type, paymentId, userId, companyId });
+ // An API key must carry the scope the ERP's post/void routes require.
const client = await getSupabaseServiceRole(
req.headers.get("Authorization"),
req.headers.get("carbon-key") ?? "",
companyId,
+ { update: "invoicing" },
);
const today = datetime.today(await getCompanyTimeZone(client, companyId))
.toString();
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index 4edba98dfa..c4712d0a8a 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -3,6 +3,7 @@ import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { sql } from "kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { assertCompanyRecords, RecordNotFoundError } from "../lib/company-records.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
@@ -139,6 +140,38 @@ serve(async (req: Request) => {
return errorResponse(err, 401);
}
+ // requirePermissions proves the caller may act in companyId, not that the
+ // body's ids belong to it. Every line-scoped case writes pickingListId as the
+ // ledger/activity documentId and locationId / fromStorageUnitId /
+ // trackedEntityId onto this company's ledger rows, so all of them are
+ // re-read under companyId — and the line must be on the list the body names.
+ if ("pickingListLineId" in validatedPayload) {
+ const { companyId, pickingListId, pickingListLineId, locationId } = validatedPayload;
+ const line = await db
+ .selectFrom("pickingListLine")
+ .select("id")
+ .where("id", "=", pickingListLineId)
+ .where("pickingListId", "=", pickingListId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!line) throw new RecordNotFoundError("Picking list line not found");
+ await assertCompanyRecords(db, "location", [locationId], companyId, "Location");
+ await assertCompanyRecords(
+ db,
+ "storageUnit",
+ ["fromStorageUnitId" in validatedPayload ? validatedPayload.fromStorageUnitId : null],
+ companyId,
+ "Storage unit"
+ );
+ await assertCompanyRecords(
+ db,
+ "trackedEntity",
+ ["trackedEntityId" in validatedPayload ? validatedPayload.trackedEntityId : null],
+ companyId,
+ "Tracked entity"
+ );
+ }
+
const today = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId)).toString();
let splitEntityId: string | undefined;
diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.ts
index 1b7263ca54..1b3a02b681 100644
--- a/packages/database/supabase/functions/post-production-event/index.ts
+++ b/packages/database/supabase/functions/post-production-event/index.ts
@@ -63,7 +63,8 @@ serve(async (req: Request) => {
.from("productionEvent")
.select("*, jobOperation!inner(jobId, processId)")
.eq("id", productionEventId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
getDefaultPostingGroup(client, companyId),
client
.from("dimension")
@@ -74,6 +75,10 @@ serve(async (req: Request) => {
]);
if (productionEvent.error) throw new Error("Failed to fetch production event");
+ // Service-role client: a production event outside companyId is a 404.
+ if (!productionEvent.data) {
+ return errorResponse("Production event not found", 404);
+ }
if (accountDefaults?.error || !accountDefaults?.data) {
throw new Error("Error getting account defaults");
}
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 1476e74a7e..b4a908389d 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -64,12 +64,16 @@ serve(async (req: Request) => {
.then((r) => r.data?.accountingEnabled ?? false);
if (type === "void") {
+ // The client is service-role: requirePermissions proved the caller may
+ // act in companyId, not that invoiceId belongs to it.
const invoice = await client
.from("purchaseInvoice")
.select("*")
.eq("id", invoiceId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
if (invoice.error) throw new Error("Failed to fetch purchaseInvoice");
+ if (!invoice.data) return errorResponse("Purchase invoice not found", 404);
if (!invoice.data.postingDate) {
throw new Error("Can only void posted purchase invoices");
@@ -511,11 +515,18 @@ serve(async (req: Request) => {
const [purchaseInvoice, purchaseInvoiceLines, purchaseInvoiceDelivery, dimensions] =
await Promise.all([
- client.from("purchaseInvoice").select("*").eq("id", invoiceId).single(),
+ // Scoped for the same reason as the void path's read.
+ client
+ .from("purchaseInvoice")
+ .select("*")
+ .eq("id", invoiceId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("purchaseInvoiceLine")
.select("*")
- .eq("invoiceId", invoiceId),
+ .eq("invoiceId", invoiceId)
+ .eq("companyId", companyId),
client
.from("purchaseInvoiceDelivery")
.select("supplierShippingCost")
@@ -541,6 +552,8 @@ serve(async (req: Request) => {
if (purchaseInvoice.error)
throw new Error("Failed to fetch purchaseInvoice");
+ if (!purchaseInvoice.data)
+ return errorResponse("Purchase invoice not found", 404);
if (purchaseInvoiceLines.error)
throw new Error("Failed to fetch receipt lines");
if (purchaseInvoiceDelivery.error)
@@ -2226,7 +2239,8 @@ serve(async (req: Request) => {
await client
.from("purchaseInvoice")
.update({ status: "Draft" })
- .eq("id", payload.invoiceId);
+ .eq("id", payload.invoiceId)
+ .eq("companyId", payload.companyId);
}
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index cdfd203504..28c2ab02e2 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -81,12 +81,24 @@ serve(async (req: Request) => {
const [receipt, receiptLines, receiptLineTracking, dimensions] =
await Promise.all([
- client.from("receipt").select("*").eq("id", receiptId).single(),
- client.from("receiptLine").select("*").eq("receiptId", receiptId),
+ // The client is service-role: requirePermissions proved the caller may
+ // act in companyId, not that receiptId belongs to it.
+ client
+ .from("receipt")
+ .select("*")
+ .eq("id", receiptId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("receiptLine")
+ .select("*")
+ .eq("receiptId", receiptId)
+ .eq("companyId", companyId),
client
.from("trackedEntity")
.select("*")
- .eq("attributes->> Receipt", receiptId),
+ .eq("attributes->> Receipt", receiptId)
+ .eq("companyId", companyId),
client
.from("dimension")
.select("id, entityType")
@@ -96,6 +108,7 @@ serve(async (req: Request) => {
]);
if (receipt.error) throw new Error("Failed to fetch receipt");
+ if (!receipt.data) return errorResponse("Receipt not found", 404);
if (receiptLines.error) throw new Error("Failed to fetch receipt lines");
if (dimensions.error) {
console.error("Failed to fetch dimensions", dimensions.error);
@@ -3198,7 +3211,8 @@ serve(async (req: Request) => {
await client
.from("receipt")
.update({ status: "Draft" })
- .eq("id", payload.receiptId);
+ .eq("id", payload.receiptId)
+ .eq("companyId", payload.companyId);
}
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index c86269d375..35f876b3f0 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -77,8 +77,19 @@ serve(async (req: Request) => {
const [salesInvoice, salesInvoiceLines, salesInvoiceShipment] =
await Promise.all([
- client.from("salesInvoice").select("*").eq("id", invoiceId).single(),
- client.from("salesInvoiceLine").select("*").eq("invoiceId", invoiceId),
+ // The client is service-role: requirePermissions proved the caller may
+ // act in companyId, not that invoiceId belongs to it.
+ client
+ .from("salesInvoice")
+ .select("*")
+ .eq("id", invoiceId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("salesInvoiceLine")
+ .select("*")
+ .eq("invoiceId", invoiceId)
+ .eq("companyId", companyId),
client
.from("salesInvoiceShipment")
.select("shippingCost, shippingMethodId")
@@ -87,6 +98,7 @@ serve(async (req: Request) => {
]);
if (salesInvoice.error) throw new Error("Failed to fetch salesInvoice");
+ if (!salesInvoice.data) return errorResponse("Sales invoice not found", 404);
if (salesInvoiceLines.error)
throw new Error("Failed to fetch shipment lines");
if (salesInvoiceShipment.error)
@@ -1348,12 +1360,17 @@ serve(async (req: Request) => {
logger.error("post-sales-invoice failed", {
error: String((err as Error)?.stack ?? err),
});
- if ("invoiceId" in payload) {
+ // A failed VOID must not touch status: the invoice is still Posted and its
+ // ledger/journal rows still stand, so forcing it to Draft would contradict
+ // the books and let it be edited and posted a second time. Same guard
+ // post-receipt, post-shipment and post-purchase-invoice carry.
+ if (payload.type !== "void" && "invoiceId" in payload) {
const client = await requirePermissions(req, payload.companyId, payload.userId, { update: "invoicing" });
await client
.from("salesInvoice")
.update({ status: "Draft" })
- .eq("id", payload.invoiceId);
+ .eq("id", payload.invoiceId)
+ .eq("companyId", payload.companyId);
}
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index e41600441e..099b9b0ef9 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -53,18 +53,28 @@ serve(async (req: Request) => {
const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();
const [shipment, shipmentLines, shipmentLineTracking] = await Promise.all([
- client.from("shipment").select("*").eq("id", shipmentId).single(),
+ // The client is service-role: requirePermissions proved the caller may
+ // act in companyId, not that shipmentId belongs to it.
+ client
+ .from("shipment")
+ .select("*")
+ .eq("id", shipmentId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("shipmentLine")
.select("*, fulfillment(*)")
- .eq("shipmentId", shipmentId),
+ .eq("shipmentId", shipmentId)
+ .eq("companyId", companyId),
client
.from("trackedEntity")
.select("*")
- .eq("attributes->> Shipment", shipmentId),
+ .eq("attributes->> Shipment", shipmentId)
+ .eq("companyId", companyId),
]);
if (shipment.error) throw new Error("Failed to fetch shipment");
+ if (!shipment.data) return errorResponse("Shipment not found", 404);
if (shipmentLines.error) throw new Error("Failed to fetch shipment lines");
const itemIds = shipmentLines.data.reduce<string[]>((acc, shipmentLine) => {
@@ -4490,7 +4500,8 @@ serve(async (req: Request) => {
await client
.from("shipment")
.update({ status: "Draft" })
- .eq("id", payload.shipmentId);
+ .eq("id", payload.shipmentId)
+ .eq("companyId", payload.companyId);
}
return errorResponse(err, 500);
}
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index 8961e75a6d..cd59e503db 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -4,6 +4,7 @@ import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { sql } from "kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { assertCompanyRecords, RecordNotFoundError } from "../lib/company-records.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
@@ -145,6 +146,32 @@ serve(async (req: Request) => {
return errorResponse(err, 401);
}
+ // requirePermissions proves the caller may act in companyId, not that the
+ // body's ids belong to it. Every case writes stockTransferId as the
+ // ledger/activity documentId and locationId / fromStorageUnitId onto this
+ // company's ledger rows, so they are re-read under companyId — and the line
+ // must be on the transfer the body names.
+ {
+ const { companyId, stockTransferId, stockTransferLineId, locationId } =
+ validatedPayload;
+ const line = await db
+ .selectFrom("stockTransferLine")
+ .select("id")
+ .where("id", "=", stockTransferLineId)
+ .where("stockTransferId", "=", stockTransferId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!line) throw new RecordNotFoundError("Stock transfer line not found");
+ await assertCompanyRecords(db, "location", [locationId], companyId, "Location");
+ await assertCompanyRecords(
+ db,
+ "storageUnit",
+ ["fromStorageUnitId" in validatedPayload ? validatedPayload.fromStorageUnitId : null],
+ companyId,
+ "Storage unit"
+ );
+ }
+
const companyToday = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId));
const today = companyToday.toString();
let expiredWarning: string | undefined;
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index b662e4dc01..ae2a4d45e7 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -46,7 +46,8 @@ serve(async (req: Request) => {
.from("jobMakeMethod")
.select("*")
.eq("id", jobMakeMethodId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
]);
if (jobMakeMethod.error) {
@@ -54,6 +55,10 @@ serve(async (req: Request) => {
`Failed to get job makeMethod: ${jobMakeMethod.error.message}`
);
}
+ // Service-role client: a make method outside companyId is a 404.
+ if (!jobMakeMethod.data) {
+ return errorResponse("Job make method not found", 404);
+ }
let parentQuantity = 1;
if (jobMakeMethod.data.parentMaterialId) {
@@ -127,15 +132,24 @@ serve(async (req: Request) => {
case "jobRequirements": {
const jobId = id;
const [job, jobMakeMethod] = await Promise.all([
- client.from("job").select("*").eq("id", jobId).single(),
+ client
+ .from("job")
+ .select("*")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("jobMakeMethod")
.select("*")
.eq("jobId", jobId)
+ .eq("companyId", companyId)
.is("parentMaterialId", null)
.single(),
]);
+ // Service-role client: a job outside companyId is a 404.
+ if (!job.data) return errorResponse("Job not found", 404);
+
if (jobMakeMethod.error) {
throw new Error(
`Failed to get job make method: ${jobMakeMethod.error.message}`
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index bcfaf7157e..a142395d93 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -25,7 +25,7 @@ import {
sequences,
unitOfMeasures,
} from "../lib/seed.ts";
-import { getSupabaseServiceRole } from "../lib/supabase.ts";
+import { getSupabaseServiceRole, requireServiceRole } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { resolveShippingDefault } from "./shipping-default.ts";
@@ -35,6 +35,17 @@ const db = getDatabaseClient<DB>(pool);
serve(async (req: Request) => {
const preflight = corsPreflight(req);
if (preflight) return preflight;
+
+ // Only servers seed a company (company.new, companies.new and onboarding, all
+ // with the service role). A company API key must not reach it: the body's
+ // userId becomes the company's Admin and parentCompanyId picks the group it
+ // joins — companies.new checks that parent against the caller's group first.
+ try {
+ requireServiceRole(req);
+ } catch (err) {
+ return errorResponse(err, 401);
+ }
+
const { companyId: id, userId, parentCompanyId, identityOnly } =
await req.json();
@@ -51,11 +62,7 @@ serve(async (req: Request) => {
if (!userId) throw new Error("Payload is missing userId");
const companyId = id as string;
- const client = await getSupabaseServiceRole(
- req.headers.get("Authorization"),
- req.headers.get("carbon-key") ?? "",
- companyId
- );
+ const client = await getSupabaseServiceRole(req.headers.get("Authorization"));
const company = await client
.from("company")
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
index 449d93ad7c..719ef7bf9f 100644
--- a/packages/database/supabase/functions/sync/index.ts
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -186,7 +186,39 @@ serve(async (req: Request) => {
.from("makeMethod")
.select("id, itemId, version, status")
.eq("id", makeMethodId)
- .single();
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ // Service-role client: a make method outside companyId is a 404.
+ if (!topLevelMakeMethod.data) {
+ return errorResponse("Make method not found", 404);
+ }
+
+ const existingItemIds = new Set(
+ data.map((item: { id?: string }) => item.id).filter(Boolean)
+ );
+
+ const existingItems = await client
+ .from("item")
+ .select(
+ "id, readableId, readableIdWithRevision, unitOfMeasureCode, type, revision"
+ )
+ .eq("companyId", companyId)
+ .in("id", Array.from(existingItemIds));
+ if (existingItems.error) return errorResponse("Failed to fetch items", 500);
+
+ const existingItemsByItemId = new Map(
+ existingItems.data?.map((item) => [item.id, item]) ?? []
+ );
+
+ // Every item id in the body is updated by id alone below, so each must
+ // have come back from the companyId-scoped read above. Checked before
+ // anything is written (the Draft make method below).
+ for (const itemId of existingItemIds) {
+ if (!existingItemsByItemId.has(itemId as string)) {
+ return errorResponse("Item not found", 404);
+ }
+ }
let activeMakeMethodId = makeMethodId;
let topLevelSourceMakeMethodId: string | null = null;
@@ -246,24 +278,15 @@ serve(async (req: Request) => {
}
}
- const existingItemIds = new Set(
- data.map((item: { id?: string }) => item.id).filter(Boolean)
- );
-
- const [existingMakeMethods, existingItems] = await Promise.all([
- client
- .from("activeMakeMethods")
- .select("id, itemId, version, status")
- .eq("companyId", companyId)
- .in("itemId", Array.from(existingItemIds)),
- client
- .from("item")
- .select(
- "id, readableId, readableIdWithRevision, unitOfMeasureCode, type, revision"
- )
- .eq("companyId", companyId)
- .in("id", Array.from(existingItemIds)),
- ]);
+ // Read after the Draft above may have been created, as before.
+ const existingMakeMethods = await client
+ .from("activeMakeMethods")
+ .select("id, itemId, version, status")
+ .eq("companyId", companyId)
+ .in("itemId", Array.from(existingItemIds));
+ if (existingMakeMethods.error) {
+ return errorResponse("Failed to fetch make methods", 500);
+ }
logger.info({
action: "fetched_active_make_methods",
@@ -283,10 +306,6 @@ serve(async (req: Request) => {
]) ?? []
);
- const existingItemsByItemId = new Map(
- existingItems.data?.map((item) => [item.id, item]) ?? []
- );
-
try {
interface TreeNode {
data: z.infer<typeof onShapeDataValidator>;
diff --git a/packages/database/supabase/functions/trigger-rework/index.ts b/packages/database/supabase/functions/trigger-rework/index.ts
index 54e3804d9e..7090d88ef5 100644
--- a/packages/database/supabase/functions/trigger-rework/index.ts
+++ b/packages/database/supabase/functions/trigger-rework/index.ts
@@ -2,6 +2,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";
import type { Transaction } from "kysely";
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import z from "npm:zod@^4.5.4";
+import { assertCompanyRecords } from "../lib/company-records.ts";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
@@ -460,6 +461,41 @@ serve(async (req) => {
return errorResponse("Job not found in this company", 404);
}
+ // The same holds for the two operation ids: triggerRework reads, clones and
+ // writes productionQuantity against them by id alone, so both must be
+ // operations of this job (the job is already proven to be this company's).
+ const operationIds = [
+ ...new Set([body.triggeredAtJobOperationId, body.targetJobOperationId]),
+ ];
+ const operations = await db
+ .selectFrom("jobOperation")
+ .select("id")
+ .where("id", "in", operationIds)
+ .where("jobId", "=", body.jobId)
+ .where("companyId", "=", body.companyId)
+ .execute();
+ if (operations.length !== operationIds.length) {
+ return errorResponse("Job operation not found in this company", 404);
+ }
+
+ await assertCompanyRecords(
+ db,
+ "trackedEntity",
+ body.trackedEntityIds ?? [],
+ body.companyId,
+ "Tracked entity"
+ );
+
+ // Written as productionQuantity.inspectionId, whose FK accepts any company's
+ // inspection.
+ await assertCompanyRecords(
+ db,
+ "inspection",
+ [body.inspectionId],
+ body.companyId,
+ "Inspection"
+ );
+
logger.info(
`🔰 Starting rework for job ${body.jobId}: go back to ${body.targetJobOperationId} from ${body.triggeredAtJobOperationId}`
);
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index e5d74bc945..cec3713646 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -5,6 +5,7 @@ import z from "npm:zod@^4.5.4";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { getFunctionLogger } from "../lib/logging.ts";
+import { RecordNotFoundError } from "../lib/company-records.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -84,15 +85,19 @@ serve(async (req: Request) => {
.from("purchaseOrder")
.select("*")
.eq("id", purchaseOrderId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("purchaseOrderLine")
.select("*")
- .eq("purchaseOrderId", purchaseOrderId),
+ .eq("purchaseOrderId", purchaseOrderId)
+ .eq("companyId", companyId),
]);
if (purchaseOrder.error)
throw new Error("Failed to fetch purchaseOrder");
+ if (!purchaseOrder.data)
+ throw new RecordNotFoundError("Purchase order not found");
if (purchaseOrderLines.error)
throw new Error("Failed to fetch purchase order lines");
if (!purchaseOrder.data.supplierId)
@@ -163,15 +168,19 @@ serve(async (req: Request) => {
.from("purchaseInvoice")
.select("*")
.eq("id", invoiceId)
- .single(),
+ .eq("companyId", companyId)
+ .maybeSingle(),
client
.from("purchaseInvoiceLine")
.select("*")
- .eq("invoiceId", invoiceId),
+ .eq("invoiceId", invoiceId)
+ .eq("companyId", companyId),
]);
if (purchaseInvoice.error)
throw new Error("Failed to fetch purchaseInvoice");
+ if (!purchaseInvoice.data)
+ throw new RecordNotFoundError("Purchase invoice not found");
if (purchaseInvoiceLines.error)
throw new Error("Failed to fetch invoice lines");
if (!purchaseInvoice.data.supplierId)
@@ -501,6 +510,7 @@ serve(async (req: Request) => {
.updateTable("supplierPart")
.set(supplierPartUpdate)
.where("id", "=", supplierPartUpdate.id!)
+ .where("companyId", "=", companyId)
.execute();
}
}
@@ -511,6 +521,7 @@ serve(async (req: Request) => {
.updateTable("itemReplenishment")
.set(itemReplenishmentUpdate)
.where("itemId", "=", itemReplenishmentUpdate.itemId!)
+ .where("companyId", "=", companyId)
.execute();
}
}
diff --git a/packages/database/supabase/migrations/20260926093417_open-job-material-lines-invoker.sql b/packages/database/supabase/migrations/20260926093417_open-job-material-lines-invoker.sql
new file mode 100644
index 0000000000..39440020bd
--- /dev/null
+++ b/packages/database/supabase/migrations/20260926093417_open-job-material-lines-invoker.sql
@@ -0,0 +1,56 @@
+-- openJobMaterialLines runs as the caller again.
+--
+-- A view without security_invoker runs as its owner, so the RLS on the tables
+-- underneath never sees the querying role. Every view in "public" is a
+-- PostgREST endpoint, reachable with the anon key the apps publish, so this
+-- view served every company's open job material lines to anyone
+-- (reported by two independent researchers against production).
+--
+-- The clause was added in 20250616011758, dropped in 20250616131548, restored
+-- by the RLS audit (20250716061055), then dropped by omission in
+-- 20260321143847, 20260417000300, 20260811123619 and 20260908211552 — each
+-- recreated the view from a copy that lacked it. The no-view-without-invoker
+-- check in @carbon/checks now fails a CREATE VIEW that does not state
+-- security_invoker, and the view-without-security-invoker invariant checks the
+-- live catalog.
+--
+-- The joins now also match on companyId, so the view is tenant-consistent on
+-- its own and the joins can use the ("id", "companyId") primary keys. Rows are
+-- unchanged: a job, make method or item always shares its material's company.
+
+CREATE OR REPLACE VIEW "openJobMaterialLines" WITH (security_invoker = true) AS (
+ SELECT
+ jm."id",
+ jm."jobId",
+ jmm."parentMaterialId",
+ jm."jobMakeMethodId",
+ j."jobId" as "jobReadableId",
+ jm."itemId",
+ jm."quantityToIssue",
+ jm."unitOfMeasureCode",
+ jm."companyId",
+ i1."replenishmentSystem",
+ i1."itemTrackingType",
+ ir."leadTime" AS "leadTime",
+ j."locationId",
+ j."dueDate",
+ jm."quantity" AS "quantityPerParent"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j
+ ON jm."jobId" = j."id" AND j."companyId" = jm."companyId"
+ INNER JOIN "jobMakeMethod" jmm
+ ON jm."jobMakeMethodId" = jmm."id" AND jmm."companyId" = jm."companyId"
+ INNER JOIN "item" i1
+ ON jm."itemId" = i1."id" AND i1."companyId" = jm."companyId"
+ INNER JOIN "item" i2
+ ON j."itemId" = i2."id" AND i2."companyId" = jm."companyId"
+ INNER JOIN "itemReplenishment" ir
+ ON i2."id" = ir."itemId" AND ir."companyId" = jm."companyId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+);
diff --git a/packages/database/supabase/migrations/20260926141957_employee-pin.sql b/packages/database/supabase/migrations/20260926141957_employee-pin.sql
new file mode 100644
index 0000000000..cc07f28026
--- /dev/null
+++ b/packages/database/supabase/migrations/20260926141957_employee-pin.sql
@@ -0,0 +1,140 @@
+-- Console PINs out of the API's reach, and console mode out of the REST API's
+-- write path.
+--
+-- 1. `employee.pin` held every console PIN in PLAINTEXT, and `employee` is
+-- readable by every member of the company and every API key through
+-- PostgREST — anyone could read a colleague's PIN and pin in as them at a
+-- shared MES terminal. The PIN moves to "employeePin" as a bcrypt hash, on a
+-- table with RLS enabled and NO policies (and no API-role privileges), so no
+-- anon/authenticated/API-key request can read or write it. Only the servers'
+-- direct Kysely connection (and service_role) reach it, through
+-- set_employee_pin / verify_employee_pin.
+--
+-- 2. `companySettings.consoleEnabled` gates a commercial feature, but the
+-- table's UPDATE policy lets any `settings_update` holder PATCH it over REST
+-- and skip the entitlement lock in `@carbon/ee` updateConsoleSetting. A
+-- trigger refuses the change when it arrives through the API roles.
+
+-- ── 1. employeePin ─────────────────────────────────────────────────────────
+
+CREATE TABLE "employeePin" (
+ "employeeId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "pinHash" TEXT NOT NULL,
+ "updatedBy" TEXT REFERENCES "user"("id") ON DELETE SET NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "employeePin_pkey" PRIMARY KEY ("employeeId", "companyId"),
+ CONSTRAINT "employeePin_employee_fkey" FOREIGN KEY ("employeeId", "companyId")
+ REFERENCES "employee"("id", "companyId") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "employeePin_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
+
+CREATE INDEX "employeePin_companyId_idx" ON "employeePin" ("companyId");
+CREATE INDEX "employeePin_updatedBy_idx" ON "employeePin" ("updatedBy");
+
+-- RLS on with NO policies: an API role sees zero rows and every write fails.
+-- The table privileges go too, so the refusal is a plain "permission denied"
+-- (a table privilege revoke is an ordinary error on this image — it is only
+-- REVOKE EXECUTE on a function that crashes the backend, see .ai/lessons.md).
+ALTER TABLE "employeePin" ENABLE ROW LEVEL SECURITY;
+REVOKE ALL ON TABLE "public"."employeePin" FROM anon, authenticated;
+
+-- Both functions are SECURITY INVOKER on purpose: through /rest/v1/rpc they run
+-- as the API role and can touch nothing, while the servers' direct connection
+-- (table owner) runs them normally. No SECURITY DEFINER, so there is no caller
+-- to authorize (public-definer-function-authorizes-caller).
+CREATE OR REPLACE FUNCTION public.set_employee_pin(
+ p_employee_id TEXT,
+ p_company_id TEXT,
+ p_pin TEXT,
+ p_updated_by TEXT
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = public, extensions
+AS $$
+BEGIN
+ IF p_pin IS NULL OR p_pin !~ '^[0-9]{4}$' THEN
+ RAISE EXCEPTION 'PIN must be 4 digits' USING ERRCODE = 'check_violation';
+ END IF;
+
+ INSERT INTO "employeePin" ("employeeId", "companyId", "pinHash", "updatedBy", "updatedAt")
+ VALUES (
+ p_employee_id,
+ p_company_id,
+ extensions.crypt(p_pin, extensions.gen_salt('bf')),
+ p_updated_by,
+ NOW()
+ )
+ ON CONFLICT ("employeeId", "companyId") DO UPDATE SET
+ "pinHash" = EXCLUDED."pinHash",
+ "updatedBy" = EXCLUDED."updatedBy",
+ "updatedAt" = EXCLUDED."updatedAt";
+END;
+$$;
+
+-- False for a wrong PIN, a NULL PIN, and an employee with no PIN alike.
+CREATE OR REPLACE FUNCTION public.verify_employee_pin(
+ p_employee_id TEXT,
+ p_company_id TEXT,
+ p_pin TEXT
+)
+RETURNS BOOLEAN
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public, extensions
+AS $$
+ SELECT COALESCE((
+ SELECT ep."pinHash" = extensions.crypt(p_pin, ep."pinHash")
+ FROM "employeePin" ep
+ WHERE ep."employeeId" = p_employee_id
+ AND ep."companyId" = p_company_id
+ ), false);
+$$;
+
+-- Carry every existing PIN over, hashed, then drop the plaintext column.
+-- (gen_salt is volatile, so each row gets its own salt.)
+INSERT INTO "employeePin" ("employeeId", "companyId", "pinHash", "updatedAt")
+SELECT
+ "id",
+ "companyId",
+ extensions.crypt("pin", extensions.gen_salt('bf')),
+ NOW()
+FROM "employee"
+WHERE "pin" IS NOT NULL AND "pin" <> '';
+
+ALTER TABLE "employee" DROP COLUMN "pin";
+
+-- ── 2. companySettings.consoleEnabled is server-only ──────────────────────
+
+-- Modelled on guard_user_identity_columns. Reads the request ROLE rather than
+-- current_user, so the refusal also holds inside a SECURITY DEFINER function a
+-- PostgREST request reaches. The servers' direct connection has role 'none' and
+-- service_role is neither API role, so updateConsoleSetting (which writes over
+-- Kysely after its requireEntitlement lock) is unaffected. Other columns of
+-- companySettings stay writable over REST exactly as before.
+CREATE OR REPLACE FUNCTION public.guard_company_settings_console_enabled()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SET search_path = public
+AS $$
+BEGIN
+ IF NEW."consoleEnabled" IS DISTINCT FROM OLD."consoleEnabled"
+ AND current_setting('role', true) IN ('anon', 'authenticated') THEN
+ RAISE EXCEPTION 'Console mode can only be changed by the server'
+ USING ERRCODE = 'insufficient_privilege';
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+DROP TRIGGER IF EXISTS "guard_company_settings_console_enabled" ON "public"."companySettings";
+CREATE TRIGGER "guard_company_settings_console_enabled"
+BEFORE UPDATE ON "public"."companySettings"
+FOR EACH ROW
+EXECUTE FUNCTION public.guard_company_settings_console_enabled();
diff --git a/packages/database/supabase/tests/rpc-privileges.test.sql b/packages/database/supabase/tests/rpc-privileges.test.sql
index 58d98a8bb5..caf6cbeac4 100644
--- a/packages/database/supabase/tests/rpc-privileges.test.sql
+++ b/packages/database/supabase/tests/rpc-privileges.test.sql
@@ -1,4 +1,5 @@
--- Tenant isolation for functions reachable at /rest/v1/rpc (20260925121735_rpc-function-guards).
+-- Tenant isolation for functions reachable at /rest/v1/rpc (20260925121735_rpc-function-guards),
+-- and console PINs out of the API's reach (20260926141957_employee-pin).
-- Run from the repository root against an existing local database:
-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/rpc-privileges.test.sql
-- All fixtures and role changes are confined to the rolled-back transaction.
@@ -205,5 +206,156 @@ END;
$$;
RESET ROLE;
+-- Console PINs (20260926141957_employee-pin). "employeePin" holds bcrypt
+-- hashes that no API role may read or write, even through the two SECURITY
+-- INVOKER functions; companySettings."consoleEnabled" changes only over the
+-- servers' direct connection. user_a gets settings_update here so the trigger,
+-- not the UPDATE policy, is what refuses the console flag.
+SET LOCAL "app.sync_in_progress" = 'true';
+DO $pin_fixtures$
+DECLARE
+ company_a text := current_setting('test.company_a');
+ user_a text := current_setting('test.user_a');
+ user_c text := current_setting('test.user_c');
+ employee_type text;
+BEGIN
+ -- The company's all-employees group, which the employeeType interceptor joins.
+ INSERT INTO "group" (id, name, "companyId")
+ VALUES ('00000000-0000-' || substring(company_a, 1, 4) || '-' || substring(company_a, 5, 4) || '-' || substring(company_a, 9, 12),
+ 'RPC privileges employees', company_a)
+ ON CONFLICT (id) DO NOTHING;
+ INSERT INTO "employeeType" (name, "companyId") VALUES ('RPC privileges', company_a) RETURNING id INTO employee_type;
+ INSERT INTO "employee" (id, "companyId", "employeeTypeId", active) VALUES
+ (user_a, company_a, employee_type, true), (user_c, company_a, employee_type, true);
+ INSERT INTO "companySettings" (id, "consoleEnabled") VALUES (company_a, false)
+ ON CONFLICT (id) DO UPDATE SET "consoleEnabled" = false;
+ UPDATE "userPermission"
+ SET permissions = permissions || jsonb_build_object('settings_update', jsonb_build_array(company_a))
+ WHERE id = user_a;
+
+ -- The owner (the servers' direct connection) sets and verifies.
+ PERFORM set_employee_pin(user_a, company_a, '4821', user_a);
+ IF NOT verify_employee_pin(user_a, company_a, '4821') THEN
+ RAISE EXCEPTION 'FAIL: the owner cannot verify a PIN it set';
+ END IF;
+ IF verify_employee_pin(user_a, company_a, '0000') THEN
+ RAISE EXCEPTION 'FAIL: a wrong PIN verified';
+ END IF;
+ IF verify_employee_pin(user_c, company_a, '4821') THEN
+ RAISE EXCEPTION 'FAIL: an employee with no PIN verified';
+ END IF;
+ IF (SELECT "pinHash" FROM "employeePin" WHERE "employeeId" = user_a AND "companyId" = company_a) = '4821' THEN
+ RAISE EXCEPTION 'FAIL: the PIN is stored in plaintext';
+ END IF;
+END;
+$pin_fixtures$;
+
+SELECT set_config('request.jwt.claims', '{}', true);
+SET LOCAL ROLE anon;
+DO $$
+BEGIN
+ BEGIN
+ PERFORM 1 FROM "employeePin";
+ RAISE EXCEPTION 'FAIL: anon read employeePin';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ IF verify_employee_pin(current_setting('test.user_a'), current_setting('test.company_a'), '4821') THEN
+ RAISE EXCEPTION 'FAIL: anon verified an employee''s PIN';
+ END IF;
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ PERFORM set_employee_pin(current_setting('test.user_a'), current_setting('test.company_a'), '1111', NULL);
+ RAISE EXCEPTION 'FAIL: anon set an employee''s PIN';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ UPDATE "companySettings" SET "consoleEnabled" = true WHERE id = current_setting('test.company_a');
+ IF FOUND THEN
+ RAISE EXCEPTION 'FAIL: anon switched console mode on';
+ END IF;
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+END;
+$$;
+RESET ROLE;
+
+-- The employee themself, holding settings_update in company A.
+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_a'), 'role', 'authenticated')::text, true);
+SET LOCAL ROLE authenticated;
+DO $$
+DECLARE
+ updated integer;
+BEGIN
+ BEGIN
+ PERFORM 1 FROM "employeePin";
+ RAISE EXCEPTION 'FAIL: an employee read employeePin';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ INSERT INTO "employeePin" ("employeeId", "companyId", "pinHash")
+ VALUES (current_setting('test.user_c'), current_setting('test.company_a'), 'forged');
+ RAISE EXCEPTION 'FAIL: an employee wrote employeePin directly';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ IF verify_employee_pin(current_setting('test.user_a'), current_setting('test.company_a'), '4821') THEN
+ RAISE EXCEPTION 'FAIL: an employee verified a PIN through the API';
+ END IF;
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ PERFORM set_employee_pin(current_setting('test.user_c'), current_setting('test.company_a'), '1111', current_setting('test.user_a'));
+ RAISE EXCEPTION 'FAIL: an employee set a colleague''s PIN through the API';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ UPDATE "companySettings" SET "consoleEnabled" = true WHERE id = current_setting('test.company_a');
+ RAISE EXCEPTION 'FAIL: a settings_update holder switched console mode on over the API';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ -- Every other column stays writable, and sending consoleEnabled unchanged is fine.
+ UPDATE "companySettings"
+ SET "digitalQuoteEnabled" = NOT "digitalQuoteEnabled", "consoleEnabled" = "consoleEnabled"
+ WHERE id = current_setting('test.company_a');
+ GET DIAGNOSTICS updated = ROW_COUNT;
+ IF updated <> 1 THEN
+ RAISE EXCEPTION 'FAIL: a settings_update holder could not update another companySettings column (% rows)', updated;
+ END IF;
+END;
+$$;
+RESET ROLE;
+SELECT set_config('request.jwt.claims', '{}', true);
+
+-- Nothing the API roles tried landed, and the server can still flip the flag.
+DO $$
+DECLARE
+ company_a text := current_setting('test.company_a');
+BEGIN
+ IF NOT verify_employee_pin(current_setting('test.user_a'), company_a, '4821')
+ OR verify_employee_pin(current_setting('test.user_a'), company_a, '1111')
+ OR EXISTS (SELECT 1 FROM "employeePin" WHERE "employeeId" = current_setting('test.user_c') AND "companyId" = company_a) THEN
+ RAISE EXCEPTION 'FAIL: an API role changed a PIN';
+ END IF;
+ IF (SELECT "consoleEnabled" FROM "companySettings" WHERE id = company_a) THEN
+ RAISE EXCEPTION 'FAIL: an API role switched console mode on';
+ END IF;
+
+ UPDATE "companySettings" SET "consoleEnabled" = true WHERE id = company_a;
+ IF NOT (SELECT "consoleEnabled" FROM "companySettings" WHERE id = company_a) THEN
+ RAISE EXCEPTION 'FAIL: the server cannot switch console mode on';
+ END IF;
+END;
+$$;
+
SELECT 'rpc-privileges: all checks passed' AS result;
ROLLBACK;
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 8264fbef1f..1686d7a446 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -62,7 +62,7 @@ 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.
+- **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(client, db, companyId, enabled, userId?)` → `{ error, pin, pinError }` writes `companySettings.consoleEnabled` over `db` (a trigger refuses API-role writes) behind `requireEntitlement("PERMISSIONS")`, provisions the protected "Console Operator" employee type and a PIN for the enabling user (returned once as `pin`; `pinError` when it could not be created); `isConsoleModeEnabledForCompany(client, companyId, { consoleEnabled? })` is the runtime DEGRADE gate (flag AND entitlement; `null` when the settings read failed — never tear a live console session down on `null`); `generateConsolePin`, `setEmployeePin(db, …)`, `verifyEmployeePin(db, …)` → `{ hasPin, valid }` work on the bcrypt `employeePin` table, reachable only over the server's Kysely connection.
- **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`, `./audit.server` (the audit-log engine — `enableAuditLog` embeds `requireEntitlement("AUDIT_LOG")`, skipped under `CONTROLLED_ENVIRONMENT` where audit is mandatory; `auditConfig`/types stay client-safe in `@carbon/database`), `./email-notifications.server` (`emailNotificationsEnabled` — the EMAIL notification-channel gate, runtime DEGRADE; `sendEmail` transactional transport stays ungated in `@carbon/lib`), `./backups.server` (`requireBackupsEntitlement(companyId)` — embedded at the top of the Inngest backup/restore/import durable functions in `@carbon/jobs`, `IS_LOCAL_DEV`-exempt; the engine is Inngest-coupled and stays in jobs), 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
diff --git a/packages/ee/src/accounting/core/account-mapping.ts b/packages/ee/src/accounting/core/account-mapping.ts
index fc773c5a74..a1f800b3ec 100644
--- a/packages/ee/src/accounting/core/account-mapping.ts
+++ b/packages/ee/src/accounting/core/account-mapping.ts
@@ -90,7 +90,7 @@ function toErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
-async function getCompanyGroupId(
+export async function getCompanyGroupId(
db: Db,
companyId: string
): Promise<string | null> {
@@ -330,6 +330,23 @@ export async function upsertAccountMapping(
args: UpsertAccountMappingInput
): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {
try {
+ // The account id comes from the caller (a form field on the mapping tab),
+ // and this Kysely client bypasses RLS. Accounts are company-group scoped:
+ // refuse one from outside the caller's group, whose number and name the
+ // mapping list would otherwise display.
+ const companyGroupId = await getCompanyGroupId(db, args.companyId);
+ const account = companyGroupId
+ ? await db
+ .selectFrom("account")
+ .select("id")
+ .where("id", "=", args.accountId)
+ .where("companyGroupId", "=", companyGroupId)
+ .executeTakeFirst()
+ : undefined;
+ if (!account) {
+ return { data: null, error: `Account ${args.accountId} not found` };
+ }
+
const mappingService = createMappingService(db, args.companyId);
await mappingService.link(
diff --git a/packages/ee/src/accounting/core/dimension-mapping.ts b/packages/ee/src/accounting/core/dimension-mapping.ts
index b34065eaa6..8dfdbe79dc 100644
--- a/packages/ee/src/accounting/core/dimension-mapping.ts
+++ b/packages/ee/src/accounting/core/dimension-mapping.ts
@@ -1,4 +1,5 @@
import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import { getCompanyGroupId } from "./account-mapping";
import type { ExternalIntegrationMapping } from "./external-mapping";
import { createMappingService } from "./external-mapping";
import type { PostingSyncDimensionSlot } from "./models";
@@ -158,6 +159,79 @@ export function buildDimensionValueMappingLookup(
return lookup;
}
+/**
+ * The dimension when it belongs to the company's group, else null.
+ * Dimensions are company-group scoped.
+ */
+async function getGroupDimension(
+ db: Db,
+ args: { companyId: string; dimensionId: string }
+): Promise<{ entityType: string; companyGroupId: string } | null> {
+ const companyGroupId = await getCompanyGroupId(db, args.companyId);
+ if (!companyGroupId) return null;
+ const dimension = await db
+ .selectFrom("dimension")
+ .select("entityType")
+ .where("id", "=", args.dimensionId)
+ .where("companyGroupId", "=", companyGroupId)
+ .executeTakeFirst();
+ return dimension
+ ? { entityType: String(dimension.entityType), companyGroupId }
+ : null;
+}
+
+/**
+ * Does the value belong to the company's group? Custom values are
+ * group-scoped `dimensionValue` rows of this dimension; entity-typed values
+ * are company-scoped rows of the dimension's source table, accepted for any
+ * company in the group (and unowned rows with a null companyId). An entity
+ * type with no known source table is not checked.
+ */
+async function isGroupDimensionValue(
+ db: Db,
+ args: {
+ companyGroupId: string;
+ dimensionId: string;
+ entityType: string;
+ valueId: string;
+ }
+): Promise<boolean> {
+ const { companyGroupId } = args;
+
+ if (args.entityType === "Custom") {
+ const value = await db
+ .selectFrom("dimensionValue")
+ .select("id")
+ .where("id", "=", args.valueId)
+ .where("dimensionId", "=", args.dimensionId)
+ .where("companyGroupId", "=", companyGroupId)
+ .executeTakeFirst();
+ return !!value;
+ }
+
+ const source = DIMENSION_LABEL_SOURCES[args.entityType];
+ if (!source) return true;
+
+ const rows = await (db as Kysely<KyselyDatabase>)
+ .selectFrom(source.table as never)
+ .select(`${source.table}.companyId` as never)
+ .where(`${source.table}.id` as never, "=" as never, args.valueId as never)
+ .execute();
+ if (rows.length === 0) return false;
+
+ const groupCompanies = await db
+ .selectFrom("company")
+ .select("id")
+ .where("companyGroupId", "=", companyGroupId)
+ .execute();
+ const inGroup = new Set(groupCompanies.map((company) => company.id));
+
+ return (rows as Array<Record<string, unknown>>).some((row) => {
+ const owner = row.companyId;
+ return owner === null || (typeof owner === "string" && inGroup.has(owner));
+ });
+}
+
/**
* Upsert a dimension-value mapping (`<dimensionId>:<valueId>` → provider
* option id). Several Carbon values may legitimately share one provider
@@ -177,6 +251,26 @@ export async function upsertDimensionValueMapping(
}
): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {
try {
+ // dimensionId/valueId can come from a form field, and this Kysely client
+ // bypasses RLS: refuse a dimension or value from outside the caller's
+ // group, whose label the mapping tab would otherwise resolve and show.
+ const dimension = await getGroupDimension(db, args);
+ if (!dimension) {
+ return { data: null, error: `Dimension ${args.dimensionId} not found` };
+ }
+ if (
+ !(await isGroupDimensionValue(db, {
+ ...dimension,
+ dimensionId: args.dimensionId,
+ valueId: args.valueId
+ }))
+ ) {
+ return {
+ data: null,
+ error: `Dimension value ${args.valueId} not found`
+ };
+ }
+
const mappingService = createMappingService(db, args.companyId);
const entityId = buildDimensionValueMappingEntityId(
args.dimensionId,
@@ -283,6 +377,10 @@ export async function upsertDimensionMapping(
}
): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {
try {
+ if (!(await getGroupDimension(db, args))) {
+ return { data: null, error: `Dimension ${args.dimensionId} not found` };
+ }
+
const mappingService = createMappingService(db, args.companyId);
await mappingService.link(
diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.ts
index 886d07aceb..d8a0c86550 100644
--- a/packages/ee/src/accounting/core/service.ts
+++ b/packages/ee/src/accounting/core/service.ts
@@ -87,21 +87,85 @@ export function resolveSyncConfig(metadata: unknown): GlobalSyncConfig {
const logger = getLogger("ee", "accounting");
-export const getAccountingIntegration = async <T extends ProviderID>(
+type CompanyIntegrationRow =
+ Database["public"]["Tables"]["companyIntegration"]["Row"];
+
+// Credentials written before the providerMetadata shape kept tenantId at the
+// top level — match both paths so legacy rows stay resolvable.
+const TENANT_ID_PATHS = [
+ "metadata->credentials->>tenantId",
+ "metadata->credentials->providerMetadata->>tenantId"
+] as const;
+
+/**
+ * Resolve a provider's `companyIntegration` row by company id OR by the
+ * provider tenant id stored in its credentials. Each lookup is a separate,
+ * parameterised `.eq()` — the id is caller-supplied (a webhook's tenantId, a
+ * URL segment), so it must never be interpolated into a PostgREST filter
+ * string, where a `,` or `)` would add filter clauses of the caller's choosing.
+ *
+ * A company match wins (the PK is `(id, companyId)`, so it is unique).
+ * Otherwise exactly one row must match a tenant path — two companies
+ * connected to the same tenant is ambiguous and resolves to nothing, as the
+ * old single `.or().single()` query did.
+ */
+async function findIntegrationByCompanyOrTenant(
client: SupabaseClient<Database>,
companyOrTenantId: string,
- provider: T
-) => {
- const integration = await client
+ provider: ProviderID
+): Promise<{ data: CompanyIntegrationRow | null; error: unknown }> {
+ const byCompany = await client
.from("companyIntegration")
.select("*")
.eq("id", provider)
- .or(
- // Credentials written before the providerMetadata shape kept tenantId
- // at the top level — match both paths so legacy rows stay resolvable
- `companyId.eq.${companyOrTenantId},metadata->credentials->>tenantId.eq.${companyOrTenantId},metadata->credentials->providerMetadata->>tenantId.eq.${companyOrTenantId}`
+ .eq("companyId", companyOrTenantId)
+ .maybeSingle();
+
+ if (byCompany.error) return { data: null, error: byCompany.error };
+ if (byCompany.data) return { data: byCompany.data, error: null };
+
+ const byTenant = await Promise.all(
+ TENANT_ID_PATHS.map((path) =>
+ client
+ .from("companyIntegration")
+ .select("*")
+ .eq("id", provider)
+ .eq(path, companyOrTenantId)
+ .limit(2)
)
- .single();
+ );
+
+ const failed = byTenant.find((result) => result.error);
+ if (failed) return { data: null, error: failed.error };
+
+ const matches = new Map<string, CompanyIntegrationRow>();
+ for (const result of byTenant) {
+ for (const row of result.data ?? []) matches.set(row.companyId, row);
+ }
+
+ if (matches.size !== 1) {
+ return {
+ data: null,
+ error:
+ matches.size === 0
+ ? "no matching integration"
+ : "tenant id matches more than one company"
+ };
+ }
+
+ return { data: [...matches.values()][0]!, error: null };
+}
+
+export const getAccountingIntegration = async <T extends ProviderID>(
+ client: SupabaseClient<Database>,
+ companyOrTenantId: string,
+ provider: T
+) => {
+ const integration = await findIntegrationByCompanyOrTenant(
+ client,
+ companyOrTenantId,
+ provider
+ );
logger.info("Fetched integration", {
provider,
@@ -117,7 +181,7 @@ export const getAccountingIntegration = async <T extends ProviderID>(
// Merge vaulted secret material (accessToken/refreshToken) back into the
// metadata before parsing, so provider construction reads credentials the same
- // as before. The tenantId/realmId used by the `.or(...)` filter above are NOT
+ // as before. The tenantId/realmId used by the tenant lookup above are NOT
// secret and remain in the plaintext column, so that lookup is unaffected.
// Vault RPCs require the service-role client.
const { getCarbonServiceRole } = await import("@carbon/auth/client.server");
diff --git a/packages/ee/src/approvals/service.ts b/packages/ee/src/approvals/service.ts
index ffd435e101..63d317d5d9 100644
--- a/packages/ee/src/approvals/service.ts
+++ b/packages/ee/src/approvals/service.ts
@@ -50,7 +50,10 @@ export async function approveRequest(
};
}
- const { documentType, documentId } = approvalRequest;
+ // Document ids on an approval request are caller-supplied at creation, and
+ // Kysely bypasses RLS: every document write below is also pinned to the
+ // request's own company so a foreign id can never be approved into state.
+ const { documentType, documentId, companyId } = approvalRequest;
const now = new Date().toISOString();
try {
@@ -81,6 +84,7 @@ export async function approveRequest(
"receivedComplete"
])
.where("purchaseOrderId", "=", documentId)
+ .where("companyId", "=", companyId)
.execute();
const { status: calculatedStatus } = getPurchaseOrderStatus(lines);
@@ -94,6 +98,7 @@ export async function approveRequest(
updatedAt: now
})
.where("id", "=", documentId)
+ .where("companyId", "=", companyId)
.where("status", "=", "Needs Approval")
.returning(["id"])
.executeTakeFirst();
@@ -112,6 +117,7 @@ export async function approveRequest(
updatedAt: now
})
.where("id", "=", documentId)
+ .where("companyId", "=", companyId)
.returning(["id"])
.executeTakeFirst();
@@ -127,6 +133,7 @@ export async function approveRequest(
updatedAt: now
})
.where("id", "=", documentId)
+ .where("companyId", "=", companyId)
.returning(["id"])
.executeTakeFirst();
@@ -814,7 +821,7 @@ export async function rejectRequest(
// Pre-flight check: verify approval request exists and is pending
const approvalRequest = await db
.selectFrom("approvalRequest")
- .select(["id", "status", "documentType", "documentId"])
+ .select(["id", "status", "documentType", "documentId", "companyId"])
.where("id", "=", id)
.executeTakeFirst();
@@ -829,7 +836,8 @@ export async function rejectRequest(
};
}
- const { documentType, documentId } = approvalRequest;
+ // Pinned to the request's own company — see approveRequest.
+ const { documentType, documentId, companyId } = approvalRequest;
const now = new Date().toISOString();
try {
@@ -859,6 +867,7 @@ export async function rejectRequest(
updatedAt: now
})
.where("id", "=", documentId)
+ .where("companyId", "=", companyId)
.where("status", "=", "Needs Approval")
.returning(["id"])
.executeTakeFirst();
@@ -880,6 +889,7 @@ export async function rejectRequest(
updatedAt: now
})
.where("id", "=", documentId)
+ .where("companyId", "=", companyId)
.returning(["id"])
.executeTakeFirst();
@@ -904,6 +914,52 @@ export async function rejectRequest(
}
}
+// Approvers are user or group ids from the form, and the callers write with the
+// service role: prove each one is a member / group of the rule's company, or a
+// rule could name another tenant's users as approvers of this company's
+// documents. `approverGroupIds` mixes groups and individuals.
+async function approversBelongToCompany(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ rule: {
+ approverGroupIds?: string[] | null;
+ defaultApproverId?: string | null;
+ }
+): Promise<boolean> {
+ const approverIds = [...new Set(rule.approverGroupIds ?? [])];
+ const userIds = [
+ ...new Set(
+ [...approverIds, rule.defaultApproverId].filter(
+ (id): id is string => typeof id === "string" && id.length > 0
+ )
+ )
+ ];
+ if (userIds.length === 0) return true;
+
+ const [groups, employees] = await Promise.all([
+ approverIds.length > 0
+ ? client
+ .from("group")
+ .select("id")
+ .in("id", approverIds)
+ .eq("companyId", companyId)
+ : Promise.resolve({ data: [] as { id: string }[], error: null }),
+ client
+ .from("employee")
+ .select("id")
+ .in("id", userIds)
+ .eq("companyId", companyId)
+ ]);
+ if (groups.error || employees.error) return false;
+
+ const groupIds = new Set((groups.data ?? []).map((g) => g.id));
+ const employeeIds = new Set((employees.data ?? []).map((e) => e.id));
+ return (
+ approverIds.every((id) => groupIds.has(id) || employeeIds.has(id)) &&
+ (!rule.defaultApproverId || employeeIds.has(rule.defaultApproverId))
+ );
+}
+
export async function upsertApprovalRule(
client: SupabaseClient<Database>,
rule: UpsertApprovalRuleInput
@@ -924,6 +980,16 @@ export async function upsertApprovalRule(
await requireEntitlement(client, existing.data.companyId, "APPROVAL_RULES");
+ if (
+ !(await approversBelongToCompany(client, existing.data.companyId, rule))
+ ) {
+ logger.error("Approval rule names approvers outside the company", {
+ companyId: existing.data.companyId,
+ ruleId: rule.id
+ });
+ return { data: null, error: { message: "Approver not found" } };
+ }
+
return client
.from("approvalRule")
.update(sanitize(rule))
@@ -935,5 +1001,12 @@ export async function upsertApprovalRule(
await requireEntitlement(client, rule.companyId, "APPROVAL_RULES");
+ if (!(await approversBelongToCompany(client, rule.companyId, rule))) {
+ logger.error("Approval rule names approvers outside the company", {
+ companyId: rule.companyId
+ });
+ return { data: null, error: { message: "Approver not found" } };
+ }
+
return client.from("approvalRule").insert([rule]).select("id").single();
}
diff --git a/packages/ee/src/audit/audit.ts b/packages/ee/src/audit/audit.ts
index 6bd463c8d8..4850847c5f 100644
--- a/packages/ee/src/audit/audit.ts
+++ b/packages/ee/src/audit/audit.ts
@@ -365,23 +365,24 @@ export async function getAuditLogArchives(
*/
export async function getArchiveDownloadUrl(
client: SupabaseClient,
- archiveId: string
+ archiveId: string,
+ companyId: string
): Promise<string> {
- // First get the archive record to get the path
+ // First get the archive record to get the path. The id comes from the
+ // caller and `client` is the service role, so scope it to the caller's
+ // company — otherwise any archive id signs another tenant's audit log.
const { data: archive, error: fetchError } = await client
.from("auditLogArchive")
.select("archivePath, companyId")
.eq("id", archiveId)
+ .eq("companyId", companyId)
.single();
if (fetchError || !archive) {
throw new Error(`Archive not found: ${fetchError?.message}`);
}
- const { archivePath, companyId } = archive as {
- archivePath: string;
- companyId: string;
- };
+ const { archivePath } = archive as { archivePath: string };
// Generate signed URL (1 hour expiry). New archives live in the company's
// own private bucket (bucket id = companyId); pre-migration archives live in
diff --git a/packages/ee/src/console.server.ts b/packages/ee/src/console.server.ts
index 789446b6a9..d197fca5e9 100644
--- a/packages/ee/src/console.server.ts
+++ b/packages/ee/src/console.server.ts
@@ -1,8 +1,117 @@
import { randomInt } from "node:crypto";
import type { Database } from "@carbon/database";
-import { sanitize } from "@carbon/utils";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { sql } from "kysely";
import { requireEntitlement } from "./entitlements.server";
+import { companyHasFeature } from "./plan.server";
+
+const logger = getLogger("ee", "console");
+
+/**
+ * RUNTIME gate for console (kiosk) mode — the DEGRADE counterpart of the
+ * `requireEntitlement` lock in `updateConsoleSetting`. Console mode is on for a
+ * company only when BOTH its `companySettings.consoleEnabled` flag is set AND the
+ * company is entitled to the `PERMISSIONS` feature.
+ *
+ * The flag alone is not enough: it outlives the entitlement (a plan downgrade
+ * leaves it set), and it predates the trigger that now keeps API roles from
+ * writing it. Every MES path that enters or honours console mode must ask this
+ * instead of reading the flag.
+ *
+ * `true` / `false` are definite answers. `null` means the settings row could
+ * not be read: a caller that would ENTER console mode treats it as false
+ * (`!result`), but one that would tear a live console session down must not —
+ * a transient read error is not the company switching console mode off.
+ *
+ * Pass `consoleEnabled` when the caller already read the flag, to skip the read.
+ */
+export async function isConsoleModeEnabledForCompany(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ options: { consoleEnabled?: boolean } = {}
+): Promise<boolean | null> {
+ let consoleEnabled = options.consoleEnabled;
+ if (consoleEnabled === undefined) {
+ const settings = await client
+ .from("companySettings")
+ .select("consoleEnabled")
+ .eq("id", companyId)
+ .maybeSingle();
+
+ if (settings.error) {
+ logger.error("Failed to read console mode setting", {
+ companyId,
+ error: settings.error
+ });
+ return null;
+ }
+ consoleEnabled = settings.data?.consoleEnabled ?? false;
+ }
+
+ if (!consoleEnabled) return false;
+ return companyHasFeature(client, companyId, { feature: "PERMISSIONS" });
+}
+
+/**
+ * Console PINs live in `employeePin` as a bcrypt hash (migration
+ * `20260926141957_employee-pin`). That table has RLS on with no policies and no
+ * API-role privileges, so it is reachable only over the server's direct Kysely
+ * connection — never through a Supabase client, which is why these take `db`.
+ * The plaintext PIN exists only in the request that creates it: it is
+ * generated here, on the server, and shown to the admin once.
+ */
+export function generateConsolePin(): string {
+ return randomInt(0, 10000).toString().padStart(4, "0");
+}
+
+export async function setEmployeePin(
+ db: Kysely<KyselyDatabase>,
+ {
+ employeeId,
+ companyId,
+ pin,
+ updatedBy
+ }: {
+ employeeId: string;
+ companyId: string;
+ pin: string;
+ updatedBy: string;
+ }
+): Promise<void> {
+ await sql`SELECT set_employee_pin(${employeeId}, ${companyId}, ${pin}, ${updatedBy})`.execute(
+ db
+ );
+}
+
+/**
+ * `hasPin` is false when the employee has no PIN at all; `valid` is false for
+ * a wrong PIN and for no PIN alike. Without a `pin` only `hasPin` is asked.
+ */
+export async function verifyEmployeePin(
+ db: Kysely<KyselyDatabase>,
+ {
+ employeeId,
+ companyId,
+ pin
+ }: { employeeId: string; companyId: string; pin?: string }
+): Promise<{ hasPin: boolean; valid: boolean }> {
+ const result = await sql<{ hasPin: boolean; valid: boolean }>`
+ SELECT
+ EXISTS (
+ SELECT 1 FROM "employeePin"
+ WHERE "employeeId" = ${employeeId} AND "companyId" = ${companyId}
+ ) AS "hasPin",
+ ${
+ pin === undefined
+ ? sql`false`
+ : sql`verify_employee_pin(${employeeId}, ${companyId}, ${pin})`
+ } AS "valid"
+ `.execute(db);
+ const row = result.rows[0];
+ return { hasPin: row?.hasPin === true, valid: row?.valid === true };
+}
/**
* Commercial (Enterprise) console / kiosk mode. Enabling it provisions the
@@ -12,18 +121,47 @@ import { requireEntitlement } from "./entitlements.server";
* (`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).
+ *
+ * `companySettings.consoleEnabled` is written over `db` (the server's direct
+ * connection): a DB trigger refuses changes to it from the API roles, so the
+ * flag can only move through this function and its entitlement lock.
+ *
+ * Returns the PIN it generated for `userId` (only when that user had none) so
+ * the caller can show it ONCE — it cannot be read back later. `pinError` is
+ * set when that PIN could not be created; console mode is enabled regardless.
*/
export async function updateConsoleSetting(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
companyId: string,
consoleEnabled: boolean,
userId?: string
-) {
+): Promise<{
+ error: { message: string } | null;
+ pin: string | null;
+ pinError: string | null;
+}> {
await requireEntitlement(client, companyId, "PERMISSIONS");
- const update = await client
- .from("companySettings")
- .update(sanitize({ consoleEnabled }) as any)
- .eq("id", companyId);
+
+ try {
+ await db
+ .updateTable("companySettings")
+ .set({ consoleEnabled })
+ .where("id", "=", companyId)
+ .execute();
+ } catch (err) {
+ return {
+ error: {
+ message:
+ err instanceof Error ? err.message : "Failed to update console mode"
+ },
+ pin: null,
+ pinError: null
+ };
+ }
+
+ let generatedPin: string | null = null;
+ let pinError: string | null = null;
// When enabling, create "Console Operator" employee type if it doesn't exist
if (consoleEnabled) {
@@ -108,25 +246,33 @@ export async function updateConsoleSetting(
}
// 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);
+ // (a user with no employee row in this company fails the FK and gets none,
+ // as before).
+ if (
+ userId &&
+ !(await verifyEmployeePin(db, { employeeId: userId, companyId })).hasPin
+ ) {
+ const pin = generateConsolePin();
+ try {
+ await setEmployeePin(db, {
+ employeeId: userId,
+ companyId,
+ pin,
+ updatedBy: userId
+ });
+ generatedPin = pin;
+ } catch (err) {
+ // Console mode is on either way; the enabling user just has no PIN
+ // yet (e.g. no employee row in this company) and needs one reset.
+ logger.error("Failed to generate a console PIN for the enabling user", {
+ companyId,
+ userId,
+ error: err
+ });
+ pinError = "A PIN could not be generated for you";
}
}
}
- return update;
+ return { error: null, pin: generatedPin, pinError };
}
diff --git a/packages/ee/src/integrations/secrets.ts b/packages/ee/src/integrations/secrets.ts
index e3c611ac13..c125933546 100644
--- a/packages/ee/src/integrations/secrets.ts
+++ b/packages/ee/src/integrations/secrets.ts
@@ -22,9 +22,13 @@ import type { SupabaseClient } from "@supabase/supabase-js";
* as non-secret leaks — keep this map exhaustive and reviewed.
*/
export const SECRET_KEYS: Record<string, string[]> = {
- linear: ["apiKey"],
+ linear: ["apiKey", "webhookSigningSecret"],
slack: ["access_token"],
- jira: ["credentials.accessToken", "credentials.refreshToken"],
+ jira: [
+ "credentials.accessToken",
+ "credentials.refreshToken",
+ "webhookSigningSecret"
+ ],
onshape: ["credentials.accessToken", "credentials.refreshToken"],
xero: ["credentials.accessToken", "credentials.refreshToken"],
quickbooks: ["credentials.accessToken", "credentials.refreshToken"],
@@ -42,6 +46,14 @@ export const SECRET_KEYS: Record<string, string[]> = {
email: ["apiKey", "password"]
};
+/**
+ * Metadata key of the OPTIONAL inbound-webhook signing secret for integrations
+ * whose webhook the customer creates by hand in the provider (Linear, Jira).
+ * Optional so existing unsigned installs keep working: when it is set, the
+ * webhook route rejects any delivery without a valid signature.
+ */
+export const WEBHOOK_SIGNING_SECRET_KEY = "webhookSigningSecret";
+
/** Thrown when a secret is expected in the vault but cannot be read (fail-closed). */
export class IntegrationSecretUnavailableError extends Error {
constructor(companyId: string, integrationId: string) {
@@ -268,3 +280,29 @@ export async function resolveIntegrationSecrets(
}
return base;
}
+
+/**
+ * Read an integration's optional webhook signing secret from the vault.
+ * Returns null when none is configured (the webhook stays unsigned). Throws
+ * `IntegrationSecretUnavailableError` when the vault cannot be read — callers
+ * must fail closed, since "no secret" cannot be told apart from "unreadable".
+ * Requires a SERVICE-ROLE client.
+ */
+export async function getWebhookSigningSecret(
+ serviceClient: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: string,
+ row: { metadata: unknown; secretRef?: string | null }
+): Promise<string | null> {
+ const resolved = await resolveIntegrationSecrets(
+ serviceClient,
+ companyId,
+ integrationId,
+ row.metadata,
+ row.secretRef
+ );
+ const secret = getPath(resolved, WEBHOOK_SIGNING_SECRET_KEY);
+ return typeof secret === "string" && secret.trim().length > 0
+ ? secret.trim()
+ : null;
+}
diff --git a/packages/ee/src/integrations/webhook-signature.ts b/packages/ee/src/integrations/webhook-signature.ts
new file mode 100644
index 0000000000..bc1c043f3d
--- /dev/null
+++ b/packages/ee/src/integrations/webhook-signature.ts
@@ -0,0 +1,55 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+const HEX = /^[0-9a-f]*$/i;
+const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
+
+/**
+ * Constant-time check of an HMAC-SHA256 webhook signature over the RAW request
+ * body. Shared by every provider that signs the body alone (Ramp: base64;
+ * Linear and Jira: hex) — providers that sign a composite payload (Rillet,
+ * Paperless Parts) build their own input.
+ *
+ * Fail-closed: an empty signature or secret, an undecodable signature, or a
+ * length mismatch returns false. The length check runs BEFORE
+ * `timingSafeEqual`, which throws on unequal lengths.
+ */
+export function verifyHmacSha256Signature(args: {
+ signature: string;
+ body: string;
+ secret: string;
+ encoding: "hex" | "base64";
+}): boolean {
+ const { body, secret, encoding } = args;
+ const signature = args.signature?.trim();
+ if (!signature || !secret) return false;
+
+ // Buffer.from silently skips characters outside the alphabet ("hex" stops at
+ // the first one, "base64" drops them), so a valid digest padded with junk
+ // would decode to the valid digest. Refuse anything outside the alphabet.
+ if (!(encoding === "hex" ? HEX : BASE64).test(signature)) return false;
+
+ let expected: Buffer;
+ let provided: Buffer;
+ try {
+ expected = createHmac("sha256", secret).update(body).digest();
+ provided = Buffer.from(signature, encoding);
+ } catch {
+ return false;
+ }
+
+ return (
+ provided.length === expected.length && timingSafeEqual(provided, expected)
+ );
+}
+
+/** Outcome of verifying one signed webhook delivery. `reason` is for logs only. */
+export type WebhookVerification =
+ | { ok: true }
+ | {
+ ok: false;
+ reason:
+ | "missing-signature"
+ | "invalid-signature"
+ | "missing-timestamp"
+ | "stale-timestamp";
+ };
diff --git a/packages/ee/src/jira/config.tsx b/packages/ee/src/jira/config.tsx
index 8db0b8572f..151972f170 100644
--- a/packages/ee/src/jira/config.tsx
+++ b/packages/ee/src/jira/config.tsx
@@ -17,7 +17,17 @@ export const Jira = defineIntegration({
"Sync quality issues and change notices from Carbon to Jira.",
setupInstructions: SetupInstructions,
images: [],
- settings: [],
+ settings: [
+ {
+ name: "webhookSigningSecret",
+ label: "Webhook Secret",
+ description:
+ "Optional. When set, Carbon rejects webhook requests that are not signed with this secret.",
+ type: "secret",
+ required: false,
+ value: ""
+ }
+ ],
oauth: {
authUrl: "https://auth.atlassian.com/authorize",
clientId: JIRA_CLIENT_ID!,
@@ -30,7 +40,11 @@ export const Jira = defineIntegration({
],
tokenUrl: "https://auth.atlassian.com/oauth/token"
},
- schema: z.object({})
+ schema: z.object({
+ // Optional, vaulted (empty keeps the stored value). When set, the webhook
+ // route requires a valid `X-Hub-Signature` on every delivery.
+ webhookSigningSecret: z.string().optional()
+ })
});
function SetupInstructions({ companyId }: { companyId: string }) {
@@ -58,6 +72,11 @@ function SetupInstructions({ companyId }: { companyId: string }) {
<p className="text-sm text-muted-foreground">
Select the following events: Issue updated, Issue deleted.
</p>
+ <p className="text-sm text-muted-foreground">
+ In the webhook's "Secret" field, enter a long random value (or let Jira
+ generate one), then paste the same value into the "Webhook Secret" field
+ below so Carbon only accepts requests that Jira has signed.
+ </p>
</>
);
}
diff --git a/packages/ee/src/jira/lib/index.server.ts b/packages/ee/src/jira/lib/index.server.ts
index fe4bbfd4b1..beaa77d953 100644
--- a/packages/ee/src/jira/lib/index.server.ts
+++ b/packages/ee/src/jira/lib/index.server.ts
@@ -3,3 +3,4 @@ export * from "./richtext";
export * from "./service";
export * from "./types";
export * from "./utils";
+export * from "./webhook";
diff --git a/packages/ee/src/jira/lib/webhook.ts b/packages/ee/src/jira/lib/webhook.ts
new file mode 100644
index 0000000000..615d5faaa5
--- /dev/null
+++ b/packages/ee/src/jira/lib/webhook.ts
@@ -0,0 +1,41 @@
+import {
+ verifyHmacSha256Signature,
+ type WebhookVerification
+} from "../../integrations/webhook-signature";
+
+/**
+ * Verify a Jira Cloud admin-webhook delivery against the "Secret" entered on
+ * the webhook in Jira (System → WebHooks).
+ *
+ * Scheme (https://developer.atlassian.com/cloud/jira/platform/webhooks/,
+ * "Secure admin webhooks"): `X-Hub-Signature` is `method=signature`, e.g.
+ * `sha256=<hex HMAC-SHA256 of the raw body keyed by the secret>`. Only
+ * `sha256` is accepted. Jira sends no timestamp header and the payload's
+ * `timestamp` is not a documented freshness guarantee, so there is no replay
+ * window — the sync job re-fetches the issue from Jira, so a replayed
+ * delivery can only re-apply Jira's current state.
+ */
+export function verifyJiraWebhook(args: {
+ signature: string | null;
+ body: string;
+ secret: string;
+}): WebhookVerification {
+ const { signature, body, secret } = args;
+ if (!signature) return { ok: false, reason: "missing-signature" };
+
+ const separator = signature.indexOf("=");
+ const method = signature.slice(0, separator).trim().toLowerCase();
+ const digest = signature.slice(separator + 1);
+ if (separator < 1 || method !== "sha256") {
+ return { ok: false, reason: "invalid-signature" };
+ }
+
+ return verifyHmacSha256Signature({
+ signature: digest,
+ body,
+ secret,
+ encoding: "hex"
+ })
+ ? { ok: true }
+ : { ok: false, reason: "invalid-signature" };
+}
diff --git a/packages/ee/src/linear/config.tsx b/packages/ee/src/linear/config.tsx
index acd36ba308..f217648c51 100644
--- a/packages/ee/src/linear/config.tsx
+++ b/packages/ee/src/linear/config.tsx
@@ -21,6 +21,15 @@ export const Linear = defineIntegration({
type: "secret",
required: true,
value: ""
+ },
+ {
+ name: "webhookSigningSecret",
+ label: "Webhook Signing Secret",
+ description:
+ "Optional. When set, Carbon rejects webhook requests that are not signed with this secret.",
+ type: "secret",
+ required: false,
+ value: ""
}
],
schema: z.object({
@@ -31,7 +40,10 @@ export const Linear = defineIntegration({
.string()
.refine((val) => val === "" || val.startsWith("lin_api"), {
message: "Linear API Key must start with 'lin_api'"
- })
+ }),
+ // Optional, vaulted like apiKey (empty keeps the stored value). When set,
+ // the webhook route requires a valid `Linear-Signature` on every delivery.
+ webhookSigningSecret: z.string().optional()
})
});
@@ -60,6 +72,12 @@ function SetupInstructions({ companyId }: { companyId: string }) {
</InputRightElement>
</InputGroup>
+ <p className="text-sm text-muted-foreground">
+ After you save the webhook, Linear shows a signing secret on the
+ webhook's detail page. Copy it into the "Webhook Signing Secret" field
+ below so Carbon only accepts requests that Linear has signed.
+ </p>
+
<p className="text-sm text-muted-foreground">
Next, from the sidebar go to "Security and access" page and generate a
new API key. Copy the generated API key and paste it into the "API Key"
diff --git a/packages/ee/src/linear/lib/index.server.ts b/packages/ee/src/linear/lib/index.server.ts
index fe4bbfd4b1..beaa77d953 100644
--- a/packages/ee/src/linear/lib/index.server.ts
+++ b/packages/ee/src/linear/lib/index.server.ts
@@ -3,3 +3,4 @@ export * from "./richtext";
export * from "./service";
export * from "./types";
export * from "./utils";
+export * from "./webhook";
diff --git a/packages/ee/src/linear/lib/webhook.ts b/packages/ee/src/linear/lib/webhook.ts
new file mode 100644
index 0000000000..4798a88a8f
--- /dev/null
+++ b/packages/ee/src/linear/lib/webhook.ts
@@ -0,0 +1,57 @@
+import {
+ verifyHmacSha256Signature,
+ type WebhookVerification
+} from "../../integrations/webhook-signature";
+
+/** Linear's documented replay window: reject deliveries older than 60 s. */
+export const LINEAR_WEBHOOK_TOLERANCE_MS = 60_000;
+
+/**
+ * Verify a Linear webhook delivery against the webhook's signing secret
+ * (shown on the webhook's detail page in Linear).
+ *
+ * Scheme (https://linear.app/developers/webhooks, "Securing webhooks"):
+ * `Linear-Signature` is the hex HMAC-SHA256 of the RAW request body keyed by
+ * the signing secret. The JSON body carries `webhookTimestamp` (UNIX ms); a
+ * delivery more than 60 s from now is rejected so a captured request cannot
+ * be replayed. The timestamp is inside the signed body, so it cannot be
+ * altered without breaking the signature.
+ */
+export function verifyLinearWebhook(args: {
+ signature: string | null;
+ body: string;
+ secret: string;
+ now?: number;
+}): WebhookVerification {
+ const { signature, body, secret } = args;
+ if (!signature) return { ok: false, reason: "missing-signature" };
+
+ if (
+ !verifyHmacSha256Signature({ signature, body, secret, encoding: "hex" })
+ ) {
+ return { ok: false, reason: "invalid-signature" };
+ }
+
+ const timestamp = readWebhookTimestamp(body);
+ if (timestamp === null) return { ok: false, reason: "missing-timestamp" };
+
+ const now = args.now ?? Date.now();
+ if (Math.abs(now - timestamp) > LINEAR_WEBHOOK_TOLERANCE_MS) {
+ return { ok: false, reason: "stale-timestamp" };
+ }
+
+ return { ok: true };
+}
+
+function readWebhookTimestamp(body: string): number | null {
+ try {
+ const parsed: unknown = JSON.parse(body);
+ const value =
+ parsed && typeof parsed === "object"
+ ? (parsed as { webhookTimestamp?: unknown }).webhookTimestamp
+ : undefined;
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/ee/src/permissions.server.ts b/packages/ee/src/permissions.server.ts
index 8439b0ac8a..27e3516328 100644
--- a/packages/ee/src/permissions.server.ts
+++ b/packages/ee/src/permissions.server.ts
@@ -263,6 +263,23 @@ export function makeCompanyPermissionsFromEmployeeType(
// The write path — builds and persists the flattened permission object
// ---------------------------------------------------------------------------
+// The target user id comes from the caller's form (and the bulk path runs as
+// the service role), so prove it is an employee of the company whose
+// permissions are being written before touching the user's grants. Read via
+// the service role: the membership fact must not depend on the caller's RLS.
+async function isCompanyEmployee(
+ userId: string,
+ companyId: string
+): Promise<boolean> {
+ const employee = await getCarbonServiceRole()
+ .from("employee")
+ .select("id")
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ return !employee.error && !!employee.data;
+}
+
export async function updateEmployee(
client: SupabaseClient<Database>,
{
@@ -282,6 +299,24 @@ export async function updateEmployee(
}
): Promise<Result> {
await requireEntitlement(client, companyId, "PERMISSIONS");
+ if (!(await isCompanyEmployee(id, companyId))) {
+ // error() logs the context when it is non-null.
+ return error({ companyId, userId: id }, "Employee not found");
+ }
+ // The employee type comes from the form and employee.employeeTypeId has a
+ // single-column foreign key, so another company's type would be accepted.
+ const ownType = await getCarbonServiceRole()
+ .from("employeeType")
+ .select("id")
+ .eq("id", employeeType)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (ownType.error || !ownType.data) {
+ return error(
+ { companyId, employeeTypeId: employeeType, error: ownType.error },
+ "Employee type not found"
+ );
+ }
const updateEmployeeEmployeeType = await client
.from("employee")
.upsert([{ id, companyId, employeeTypeId: employeeType }]);
@@ -317,6 +352,10 @@ export async function updatePermissions(
}
): Promise<Result> {
await requireEntitlement(client, companyId, "PERMISSIONS");
+ if (!(await isCompanyEmployee(id, companyId))) {
+ // error() logs the context when it is non-null.
+ return error({ companyId, userId: id }, "Employee not found");
+ }
const claimsAdmin = await client.rpc("is_claims_admin", {
company: companyId
});
diff --git a/packages/ee/src/ramp/lib/webhook.ts b/packages/ee/src/ramp/lib/webhook.ts
index fafa61464a..c6658ee394 100644
--- a/packages/ee/src/ramp/lib/webhook.ts
+++ b/packages/ee/src/ramp/lib/webhook.ts
@@ -1,4 +1,4 @@
-import { createHmac, timingSafeEqual } from "node:crypto";
+import { verifyHmacSha256Signature } from "../../integrations/webhook-signature";
/**
* Verify a Ramp webhook delivery.
@@ -17,24 +17,5 @@ export function verifyRampWebhookSignature(args: {
body: string;
secret: string;
}): boolean {
- const { signature, body, secret } = args;
- if (!signature || !secret) return false;
-
- let expected: Buffer;
- try {
- expected = createHmac("sha256", secret).update(body).digest();
- } catch {
- return false;
- }
-
- let provided: Buffer;
- try {
- provided = Buffer.from(signature.trim(), "base64");
- } catch {
- return false;
- }
-
- return (
- provided.length === expected.length && timingSafeEqual(provided, expected)
- );
+ return verifyHmacSha256Signature({ ...args, encoding: "base64" });
}
diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.md
index 2a92598c90..5876e88a08 100644
--- a/packages/files/AGENTS.md
+++ b/packages/files/AGENTS.md
@@ -6,7 +6,7 @@ in the codebase, shared by the browser, Node, and the Supabase edge runtime.
| Subpath | Provides |
|---------|----------|
-| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id) with the legacy shared `private` bucket folded in — reads (`download` / `info` / `createSignedUrl`) fall back to it, `list` unions both, `remove` deletes from both, writes (`upload` / `move` / `copy` / `createSignedUploadUrl`) go to the company bucket only. Every key must sit under `${companyId}/` (under a service-role client that prefix is the ONLY tenant boundary on the shared legacy bucket); anything else gets `{ data: null, error }` without touching storage. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. All legacy-bucket fallback lives in `storage.ts` so removing it later is a one-file change; `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) |
+| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id) with the legacy shared `private` bucket folded in — reads (`download` / `info` / `createSignedUrl`) fall back to it, `list` unions both, `remove` deletes from both, writes (`upload` / `move` / `copy` / `createSignedUploadUrl`) go to the company bucket only. Every key must sit under `${companyId}/` (under a service-role client that prefix is the ONLY tenant boundary on the shared legacy bucket) and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. All legacy-bucket fallback lives in `storage.ts` so removing it later is a one-file change; `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) |
| `./csv` | `encodeCsv` (object rows) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection |
| `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` |
| `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). Touches `node:fs`: never import from client code |
diff --git a/packages/files/src/media/image.ts b/packages/files/src/media/image.ts
index 4ef0746395..db6e60d1ce 100644
--- a/packages/files/src/media/image.ts
+++ b/packages/files/src/media/image.ts
@@ -11,6 +11,7 @@ import {
processRawImage,
UnsupportedImageFormatError
} from "../../../database/supabase/functions/shared/image-pipeline.ts";
+import { isUnsafeStoragePath } from "../storage";
import { getFileExtension, isHeic } from "./media";
export * from "../../../database/supabase/functions/shared/image-pipeline.ts";
@@ -59,6 +60,11 @@ export async function transformImageViaStorage(
): Promise<Blob> {
const extension = file.name.split(".").pop() ?? "bin";
const tempPath = `${directory}/${nanoid()}.${extension}`;
+ // The directory is the caller's and the extension comes from the file name;
+ // neither may move the staged object out of the directory it names.
+ if (isUnsafeStoragePath(tempPath)) {
+ throw new Error(`Refused to stage an image at an unsafe path: ${tempPath}`);
+ }
const upload = await client.storage.from(bucket).upload(tempPath, file, {
upsert: true
diff --git a/packages/files/src/media/storage.ts b/packages/files/src/media/storage.ts
index 8a792247a6..ee27cc4a92 100644
--- a/packages/files/src/media/storage.ts
+++ b/packages/files/src/media/storage.ts
@@ -1,4 +1,5 @@
import { getDatasetAssetUrl } from "@carbon/database/dataset-assets";
+import { isUnsafeStoragePath } from "../storage";
/**
* Preview URL for a stored private-bucket file. Demo-template artwork ships
@@ -43,7 +44,7 @@ export function parseJobFilePath(
const [companyId, kind, operationId, ...rest] = path.split("/");
if (kind !== "job" || !companyId || !operationId) return null;
if (rest.length !== 1 && rest.length !== 3) return null;
- if (rest.some((segment) => !segment || segment === "." || segment === ".."))
+ if (rest.some((segment) => !segment) || isUnsafeStoragePath(path))
return null;
return { companyId, operationId };
}
diff --git a/packages/files/src/storage.test.ts b/packages/files/src/storage.test.ts
index ac341f2d37..1b1a987951 100644
--- a/packages/files/src/storage.test.ts
+++ b/packages/files/src/storage.test.ts
@@ -3,8 +3,10 @@ import { describe, expect, it, vi } from "vitest";
import {
getCompanyPrivateBucket,
hasCompanyPrivateObjectPathPrefix,
+ isUnsafeStoragePath,
LEGACY_PRIVATE_BUCKET,
normalizeStorageSegment,
+ safeStorageFileName,
storage
} from "./storage";
@@ -79,6 +81,89 @@ describe("hasCompanyPrivateObjectPathPrefix", () => {
});
});
+describe("isUnsafeStoragePath", () => {
+ it.each([
+ ["a plain key", "co1/parts/item1/drawing.pdf"],
+ ["an encoded key (spaces)", "co1/parts/item1/My%20Drawing.pdf"],
+ ["a decoded key with spaces", "co1/parts/item1/My Drawing.pdf"],
+ ["dots inside a segment", "co1/parts/item1/a..b.v2.step"],
+ ["a trailing slash (list prefix)", "co1/parts/"],
+ ["a CAD raw", "co1/models/abc123/raw.step.zst"]
+ ])("allows %s", (_, path) => {
+ expect(isUnsafeStoragePath(path)).toBe(false);
+ });
+
+ it.each([
+ ["a parent segment", "co1/../co2/a.pdf"],
+ ["a current segment", "co1/./a.pdf"],
+ ["a leading parent segment", "../co2/a.pdf"],
+ ["a trailing parent segment", "co1/.."],
+ ["encoded parent segment", "co1/%2e%2e/co2/a.pdf"],
+ ["encoded parent segment, upper case", "co1/%2E%2E/co2/a.pdf"],
+ ["half-encoded parent segment", "co1/.%2e/co2/a.pdf"],
+ ["encoded current segment", "co1/%2e/a.pdf"],
+ ["encoded slash forming a parent segment", "co1/..%2fco2/a.pdf"],
+ ["double-encoded parent segment", "co1/%252e%252e/co2/a.pdf"],
+ ["double-encoded slash", "co1/..%252fco2/a.pdf"],
+ ["triple-encoded parent segment", "co1/%25252e%25252e/co2/a.pdf"],
+ ["a backslash", "co1\\..\\co2\\a.pdf"],
+ ["an encoded backslash", "co1/..%5c..%5cco2/a.pdf"],
+ ["a double-encoded backslash", "co1/..%255cco2/a.pdf"],
+ ["a query", "co1/a.pdf?download=1"],
+ ["an encoded query", "co1/a.pdf%3Fx"],
+ ["a fragment", "co1/a.pdf#x"],
+ ["a double-encoded fragment", "co1/a.pdf%2523x"],
+ ["a tab", "co1/a\t.pdf"],
+ ["a newline", "co1/.\n./co2/a.pdf"],
+ ["a NUL", "co1/a\u0000.pdf"],
+ ["DEL", "co1/a\u007f.pdf"],
+ ["an encoded tab", "co1/.%09./co2/a.pdf"],
+ ["an encoded NUL", "co1/a%00.pdf"],
+ ["a double-encoded newline", "co1/a%250a.pdf"],
+ ["a malformed escape", "co1/a%zz.pdf"],
+ ["a malformed escape one layer down", "co1/a%25zz.pdf"]
+ ])("refuses %s", (_, path) => {
+ expect(isUnsafeStoragePath(path)).toBe(true);
+ });
+
+ it("refuses a key that keeps decoding past the pass limit", () => {
+ let path = "co1/../co2/a.pdf";
+ for (let i = 0; i < 8; i++) path = encodeURIComponent(path);
+ expect(isUnsafeStoragePath(path)).toBe(true);
+ });
+});
+
+describe("safeStorageFileName", () => {
+ it("keeps an ordinary file name", () => {
+ expect(safeStorageFileName("PO 1234.pdf")).toBe("PO 1234.pdf");
+ expect(safeStorageFileName(" spaced.pdf ")).toBe("spaced.pdf");
+ });
+
+ it("keeps only the basename", () => {
+ expect(safeStorageFileName("../../co2/evil.pdf")).toBe("evil.pdf");
+ expect(safeStorageFileName("..\\..\\co2\\evil.pdf")).toBe("evil.pdf");
+ });
+
+ it.each([
+ ["a fragment", "Drawing #3.pdf", "Drawing 3.pdf"],
+ ["a query", "what?.pdf", "what.pdf"],
+ ["a percent sign", "50%.pdf", "50.pdf"],
+ ["an encoded dot-dot", "%2e%2e", "2e2e"]
+ ])("keeps a name with %s usable", (_, name, safe) => {
+ expect(safeStorageFileName(name)).toBe(safe);
+ });
+
+ it.each([
+ ["an empty name", ""],
+ ["a trailing slash", "dir/"],
+ ["a dot", "."],
+ ["a dot-dot", ".."],
+ ["a control character", "a\u0001.pdf"]
+ ])("refuses %s", (_, name) => {
+ expect(safeStorageFileName(name)).toBeNull();
+ });
+});
+
describe("storage(client).from", () => {
it("is the plain supabase bucket", () => {
const client = makeClient({});
@@ -96,6 +181,11 @@ describe("storage(client).company", () => {
describe("writes go to the company bucket only", () => {
it.each([
["upload", (b: Bucket) => b.upload("co1/docs/a.pdf", new Blob())],
+ // A `#` only truncates the key inside the company prefix, as it always has.
+ [
+ "upload",
+ (b: Bucket) => b.upload("co1/docs/Drawing #3.pdf", new Blob())
+ ],
["update", (b: Bucket) => b.update("co1/docs/a.pdf", new Blob())],
[
"uploadToSignedUrl",
@@ -167,7 +257,16 @@ describe("storage(client).company", () => {
["list", () => bucket.list("co2/docs")],
["remove", () => bucket.remove(["co1/a.pdf", "co2/a.pdf"])],
["a prefix-lookalike", () => bucket.download("co12/a.pdf")],
- ["an empty key", () => bucket.download("")]
+ ["an empty key", () => bucket.download("")],
+ ["a parent segment", () => bucket.download("co1/../co2/a.pdf")],
+ ["an encoded parent segment", () => bucket.download("co1/%2e%2e/co2/a")],
+ [
+ "a double-encoded parent segment",
+ () => bucket.upload("co1/%252e%252e/co2/a.pdf", new Blob())
+ ],
+ ["a backslash", () => bucket.remove(["co1\\..\\co2\\a.pdf"])],
+ ["a control character", () => bucket.createSignedUrl("co1/a\n.pdf", 60)],
+ ["a list prefix that climbs out", () => bucket.list("co1/..")]
])("%s", async (_, call) => {
const result = await call();
// `exists` answers false rather than null — supabase's own shape.
@@ -178,6 +277,18 @@ describe("storage(client).company", () => {
expect(touched()).toBe(false);
});
+ it.each([
+ ["a traversal before a query", () => bucket.download("co1/../co2/a?x")],
+ ["a traversal before a fragment", () => bucket.download("co1/..#/a")]
+ ])("%s", async (_, call) => {
+ const result = await call();
+ expect(result.data).toBeFalsy();
+ expect(result.error?.message).toMatch(
+ /outside the "co1\/" storage prefix/
+ );
+ expect(touched()).toBe(false);
+ });
+
it("names only the offending keys", async () => {
const { error } = await bucket.remove(["co1/a.pdf", "co2/a.pdf"]);
expect(error?.message).toBe(
diff --git a/packages/files/src/storage.ts b/packages/files/src/storage.ts
index ad6d36049b..4a6343adf8 100644
--- a/packages/files/src/storage.ts
+++ b/packages/files/src/storage.ts
@@ -55,6 +55,68 @@ export const hasCompanyPrivateObjectPathPrefix = (
return bucket ? objectPath.startsWith(`${bucket}/`) : false;
};
+// A well-formed key stops changing after one decode (a key cannot hold a
+// literal `%`), so anything still decoding after this many passes is refused.
+const MAX_STORAGE_PATH_DECODES = 4;
+
+const isDotSegment = (segment: string) => segment === "." || segment === "..";
+
+const hasUnsafeStorageSyntax = (path: string) => {
+ if (/[\\?#]/.test(path)) return true;
+ for (const char of path) {
+ const code = char.charCodeAt(0);
+ if (code < 0x20 || code === 0x7f) return true;
+ }
+ return path.split("/").some(isDotSegment);
+};
+
+/**
+ * True when an object key could resolve somewhere other than where its text
+ * says. storage-js puts the key into the request URL UNENCODED, and the WHATWG
+ * URL parser resolves `.` / `..` segments (percent-encoded `%2e` too), reads
+ * `\` as `/`, strips tabs and newlines, and ends the path at `?` / `#`. Any of
+ * those lets a key pass a `${companyId}/` prefix check and then read or write
+ * another company's object — or another bucket.
+ *
+ * The key is checked as given and after every decode until it stops changing,
+ * so single- and double-encoded traversal (`%2e%2e`, `%252e%252e`) is caught
+ * wherever a caller sits in the decode chain. A malformed escape is refused:
+ * storage never accepts a key containing a literal `%`.
+ */
+export function isUnsafeStoragePath(path: string): boolean {
+ let current = path;
+ for (let pass = 0; pass <= MAX_STORAGE_PATH_DECODES; pass++) {
+ if (hasUnsafeStorageSyntax(current)) return true;
+ let decoded: string;
+ try {
+ decoded = decodeURIComponent(current);
+ } catch {
+ return true;
+ }
+ if (decoded === current) return false;
+ current = decoded;
+ }
+ return true;
+}
+
+/**
+ * A caller-supplied file name made safe to use as the LAST segment of an
+ * object key: the basename only (anything before a `/` or `\` is dropped),
+ * trimmed, with `?`, `#` and `%` removed ("Drawing #3.pdf" → "Drawing 3.pdf",
+ * the same result `stripSpecialCharacters` gives). Null when nothing usable is
+ * left or the name fails `isUnsafeStoragePath`.
+ */
+export function safeStorageFileName(name: string): string | null {
+ // `?` / `#` would end the key at that character and `%` would be decoded
+ // into a different key, so they are dropped rather than refusing the upload.
+ const base = (name.split(/[/\\]/).pop() ?? "")
+ .replace(/[?#%]/g, "")
+ .replace(/\s{2,}/g, " ")
+ .trim();
+ if (!base || isUnsafeStoragePath(base)) return null;
+ return base;
+}
+
type Bucket = ReturnType<StorageClient["from"]>;
/**
@@ -108,8 +170,18 @@ function companyBucket(
const own = storage.from(id);
const legacy = storage.from(LEGACY_PRIVATE_BUCKET);
- const owned = (path: string) =>
- hasCompanyPrivateObjectPathPrefix(companyId, path);
+ // The prefix is only a boundary if the key cannot climb out of it. Storage
+ // uses the key only up to the first `?` / `#` (the URL parser ends the path
+ // there), so that is the key checked: cutting a suffix off a key that starts
+ // with `${companyId}/` cannot leave the company, and a name like
+ // "Drawing #3.pdf" keeps uploading exactly as it always has.
+ const owned = (path: string) => {
+ const key = path.split(/[?#]/, 1)[0] ?? "";
+ return (
+ hasCompanyPrivateObjectPathPrefix(companyId, key) &&
+ !isUnsafeStoragePath(key)
+ );
+ };
const owns = (...paths: string[]) => paths.every(owned);
const refuse = (...paths: string[]) =>
Promise.resolve({
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 85e34aac2a..e3ffcb643b 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260925121735",
+ "schemaVersion": "20260926141957",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-25T14:21:00.020Z",
+ "exportedAt": "2026-09-26T15:44:17.303Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -38,83 +38,83 @@
"name": "accountDefault",
"rows": 0,
"columns": [
- "laborAbsorptionAccount",
- "updatedBy",
- "salesReturnsAccount",
- "laborAndMachineVarianceAccount",
- "rawMaterialsAccount",
- "workInProgressAccount",
- "overheadAbsorptionAccount",
- "purchaseTaxPayableAccount",
- "salesTaxPayableAccount",
- "deferredTaxLiabilityAccountId",
- "inventoryAdjustmentVarianceAccount",
- "deferredTaxExpenseAccountId",
- "companyId",
- "finishedGoodsAccount",
- "assetLossOnDisposalAccount",
- "materialVarianceAccount",
"bankForeignCurrencyAccount",
- "accumulatedDepreciationOnDisposalAccount",
+ "materialVarianceAccount",
"realizedExchangeGainAccount",
+ "accumulatedDepreciationOnDisposalAccount",
"purchaseVarianceAccount",
- "salesShippingRevenueAccount",
- "overheadVarianceAccount",
"realizedExchangeLossAccount",
- "prepaymentAccount",
+ "overheadVarianceAccount",
+ "salesShippingRevenueAccount",
"salesAccount",
- "maintenanceAccount",
+ "prepaymentAccount",
"retainedEarningsAccount",
- "goodsReceivedNotInvoicedAccount",
+ "maintenanceAccount",
"supplierWriteOffAccount",
+ "goodsReceivedNotInvoicedAccount",
"serviceChargeAccount",
- "interestAccount",
- "assetAquisitionCostAccount",
- "supplierPrepaymentAccount",
- "intercompanyPayablesAccount",
- "lotSizeVarianceAccount",
- "indirectCostAccount",
- "bankCashAccount",
- "roundingAccount",
- "scrapAccount",
- "assetAquisitionCostOnDisposalAccount",
- "subcontractingVarianceAccount",
+ "laborAbsorptionAccount",
+ "updatedBy",
+ "workInProgressAccount",
+ "rawMaterialsAccount",
+ "laborAndMachineVarianceAccount",
+ "salesReturnsAccount",
+ "salesTaxPayableAccount",
+ "purchaseTaxPayableAccount",
+ "overheadAbsorptionAccount",
+ "deferredTaxLiabilityAccountId",
+ "assetLossOnDisposalAccount",
+ "finishedGoodsAccount",
+ "companyId",
+ "deferredTaxExpenseAccountId",
+ "inventoryAdjustmentVarianceAccount",
"bankLocalCurrencyAccount",
"receivablesAccount",
- "payablesAccount",
- "intercompanyReceivablesAccount",
"accumulatedDepreciationAccount",
- "supplierPaymentDiscountAccount",
+ "intercompanyReceivablesAccount",
+ "payablesAccount",
"reverseChargeSalesTaxPayableAccount",
- "customerPaymentDiscountAccount",
+ "supplierPaymentDiscountAccount",
"currencyTranslationAccount",
- "assetGainOnDisposalAccount",
+ "customerPaymentDiscountAccount",
"customerWriteOffAccount",
- "salesDiscountAccount",
+ "assetGainOnDisposalAccount",
+ "costOfGoodsSoldAccount",
"assetDepreciationExpenseAccount",
- "costOfGoodsSoldAccount"
+ "salesDiscountAccount",
+ "interestAccount",
+ "supplierPrepaymentAccount",
+ "assetAquisitionCostAccount",
+ "intercompanyPayablesAccount",
+ "lotSizeVarianceAccount",
+ "roundingAccount",
+ "bankCashAccount",
+ "indirectCostAccount",
+ "subcontractingVarianceAccount",
+ "assetAquisitionCostOnDisposalAccount",
+ "scrapAccount"
]
},
{
"name": "accountingPeriod",
"rows": 0,
"columns": [
+ "companyId",
+ "closeStatus",
+ "lockedAt",
"status",
"periodNumber",
"endDate",
"closedBy",
- "closeStatus",
- "companyId",
- "lockedAt",
- "startDate",
- "fiscalYear",
- "lockedBy",
- "updatedBy",
- "createdBy",
- "updatedAt",
"id",
"createdAt",
- "closedAt"
+ "updatedAt",
+ "closedAt",
+ "lockedBy",
+ "fiscalYear",
+ "startDate",
+ "createdBy",
+ "updatedBy"
]
},
{
@@ -122,39 +122,39 @@
"rows": 0,
"columns": [
"endingBalance",
- "accountingPeriodId",
- "accountId",
"createdBy",
- "updatedBy",
- "id",
+ "accountId",
+ "accountingPeriodId",
"endingBalanceDate",
- "companyId",
+ "id",
+ "updatedBy",
"updatedAt",
- "createdAt"
+ "createdAt",
+ "companyId"
]
},
{
"name": "accountingSyncOperation",
"rows": 0,
"columns": [
- "completedAt",
- "updatedAt",
"entityId",
- "createdBy",
+ "updatedAt",
+ "completedAt",
"externalId",
- "integration",
- "errorMessage",
+ "createdBy",
"entityType",
- "createdAt",
+ "errorMessage",
+ "integration",
"updatedBy",
+ "createdAt",
"trigger",
- "idempotencyKey",
"id",
+ "idempotencyKey",
"lastAttemptAt",
"direction",
"metadata",
- "companyId",
"errorCode",
+ "companyId",
"status",
"attemptCount"
]
@@ -163,25 +163,25 @@
"name": "accountingSyncTieOut",
"rows": 0,
"columns": [
- "docBackedAmount",
- "pendingAmount",
- "createdBy",
- "internalDelta",
- "companyId",
- "carbonPostedAmount",
- "excludedAmount",
- "id",
- "blockedAmount",
- "syncedAmount",
"integration",
"externalDelta",
"accountingPeriodId",
- "updatedAt",
"updatedBy",
- "computedAt",
- "createdAt",
+ "updatedAt",
+ "syncedAmount",
+ "providerAmount",
"accountId",
- "providerAmount"
+ "createdAt",
+ "computedAt",
+ "createdBy",
+ "companyId",
+ "internalDelta",
+ "docBackedAmount",
+ "pendingAmount",
+ "excludedAmount",
+ "id",
+ "blockedAmount",
+ "carbonPostedAmount"
]
},
{
@@ -204,60 +204,60 @@
"name": "agentThread",
"rows": 0,
"columns": [
- "title",
- "userId",
- "createdBy",
- "modelId",
"companyId",
- "updatedAt",
"createdAt",
- "id",
+ "updatedAt",
"updatedBy",
- "lastContext"
+ "id",
+ "lastContext",
+ "userId",
+ "title",
+ "createdBy",
+ "modelId"
]
},
{
"name": "agentMessage",
"rows": 0,
"columns": [
- "outputTokens",
- "finishReason",
- "updatedBy",
- "threadId",
- "feedback",
- "createdBy",
- "id",
- "inputTokens",
- "feedbackNote",
"role",
"companyId",
"updatedAt",
+ "feedbackNote",
+ "createdAt",
"context",
- "createdAt"
+ "threadId",
+ "updatedBy",
+ "finishReason",
+ "outputTokens",
+ "id",
+ "inputTokens",
+ "createdBy",
+ "feedback"
]
},
{
"name": "agentMessagePart",
"rows": 0,
"columns": [
+ "createdBy",
+ "updatedBy",
+ "type",
+ "toolState",
"toolName",
"updatedAt",
"errorMessage",
"companyId",
"orderIndex",
- "updatedBy",
- "createdBy",
- "toolState",
- "type",
- "toolInput",
- "toolClassification",
- "messageId",
- "toolDurationMs",
- "createdAt",
"textContent",
"toolOutput",
"toolCallId",
- "id"
+ "id",
+ "toolInput",
+ "toolClassification",
+ "toolDurationMs",
+ "messageId",
+ "createdAt"
]
},
{
@@ -269,11 +269,11 @@
"createdAt",
"status",
"updatedBy",
- "amount",
"companyId",
+ "amount",
"decisionAt",
- "createdBy",
"documentType",
+ "createdBy",
"updatedAt",
"requestedBy",
"decisionNotes",
@@ -287,44 +287,44 @@
"columns": [
"lowerBoundAmount",
"updatedBy",
- "createdBy",
"id",
+ "createdBy",
"createdAt",
"companyId",
"documentType",
"defaultApproverId",
"updatedAt",
"escalationDays",
- "enabled",
- "approverGroupIds"
+ "approverGroupIds",
+ "enabled"
]
},
{
"name": "auditLogArchive",
"rows": 0,
"columns": [
- "id",
"rowCount",
- "companyId",
+ "id",
"createdAt",
+ "companyId",
"endDate",
- "startDate",
+ "sizeBytes",
"archivePath",
- "sizeBytes"
+ "startDate"
]
},
{
"name": "changeOrderRequiredAction",
"rows": 0,
"columns": [
- "companyId",
"updatedAt",
- "id",
- "customFields",
+ "companyId",
"createdAt",
- "active",
- "name",
+ "customFields",
+ "id",
"updatedBy",
+ "name",
+ "active",
"createdBy"
]
},
@@ -332,137 +332,137 @@
"name": "changeOrderType",
"rows": 0,
"columns": [
- "companyId",
- "createdAt",
- "updatedBy",
- "createdBy",
- "name",
+ "updatedAt",
"id",
- "updatedAt"
+ "name",
+ "createdBy",
+ "updatedBy",
+ "createdAt",
+ "companyId"
]
},
{
"name": "companyAccountsPayableBillingAddress",
"rows": 0,
"columns": [
+ "postalCode",
+ "addressLine2",
+ "addressLine1",
+ "updatedAt",
+ "city",
"fax",
"countryCode",
- "updatedBy",
"name",
+ "updatedBy",
"state",
"email",
- "phone",
"id",
- "postalCode",
- "addressLine1",
- "addressLine2",
- "city",
- "updatedAt"
+ "phone"
]
},
{
"name": "companyAccountsReceivableBillingAddress",
"rows": 0,
"columns": [
- "postalCode",
- "addressLine2",
- "addressLine1",
- "city",
- "updatedAt",
+ "state",
+ "phone",
+ "id",
+ "email",
"countryCode",
"fax",
"updatedBy",
"name",
- "state",
- "id",
- "phone",
- "email"
- ]
- },
+ "city",
+ "updatedAt",
+ "postalCode",
+ "addressLine1",
+ "addressLine2"
+ ]
+ },
{
"name": "companySettings",
"rows": 0,
"columns": [
- "productLabelSize",
- "showCustomerReadableId",
- "plmReleaseControl",
- "includeOperationsOnTraveler",
- "id",
- "salesJobCompletedNotificationGroup",
- "autoStartOperationTimer",
+ "allowLowercaseItemIds",
+ "useMetric",
+ "accountsPayableEmail",
+ "showCurrencyTrailingZeros",
"enforceInspectionFourEyes",
- "requireMfa",
"updateLeadTimesOnReceipt",
- "accountsPayableEmail",
- "salesRuleNotificationGroup",
- "useMetric",
- "returnPickedMaterialTiming",
- "accountingEnabled",
- "accountsReceivableAddress",
- "inventoryJobCompletedNotificationGroup",
- "accountsPayableAddress",
- "includeMaterialsOnTraveler",
- "materialGeneratedIds",
- "qualityIssueTarget",
- "inventoryShelfLife",
- "incompletePickingListPolicy",
- "gaugeCalibrationExpiredNotificationGroup",
+ "autoStartOperationTimer",
+ "salesJobCompletedNotificationGroup",
+ "includeOperationsOnTraveler",
+ "id",
+ "plmReleaseControl",
+ "showCustomerReadableId",
+ "productLabelSize",
"digitalQuoteEnabled",
"consoleEnabled",
- "assetTaxDepreciationEnabled",
- "otherDispatchNotificationGroup",
- "allowLowercaseItemIds",
- "supplierQuoteNotificationGroup",
- "assetTaxRate",
- "defaultSupplierCc",
- "rfqReadyNotificationGroup",
- "operationsDispatchNotificationGroup",
+ "gaugeCalibrationExpiredNotificationGroup",
+ "inventoryShelfLife",
+ "incompletePickingListPolicy",
+ "materialGeneratedIds",
+ "qualityIssueTarget",
+ "includeMaterialsOnTraveler",
+ "accountsPayableAddress",
+ "accountsReceivableAddress",
+ "inventoryJobCompletedNotificationGroup",
+ "accountingEnabled",
+ "returnPickedMaterialTiming",
"kanbanOutput",
"quoteLineCategoryMarkups",
- "defaultCustomerCc",
- "printing",
- "showCurrencyTrailingZeros",
- "shelfLabelSize",
- "timeCardEnabled",
- "accountsReceivableEmail",
- "digitalQuoteIncludesPurchaseOrders",
+ "operationsDispatchNotificationGroup",
+ "rfqReadyNotificationGroup",
+ "assetTaxRate",
+ "defaultSupplierCc",
+ "otherDispatchNotificationGroup",
+ "supplierQuoteNotificationGroup",
+ "requireMfa",
+ "assetTaxDepreciationEnabled",
+ "maintenanceDispatchNotificationGroup",
+ "samplingStandard",
+ "qualityDispatchNotificationGroup",
+ "showSupplierReadableId",
+ "autoSelectMaterialWithoutPickingList",
"purchasePriceUpdateTiming",
"digitalQuoteNotificationGroup",
- "autoSelectMaterialWithoutPickingList",
- "showSupplierReadableId",
- "qualityDispatchNotificationGroup",
- "maintenanceDispatchNotificationGroup",
- "samplingStandard"
+ "digitalQuoteIncludesPurchaseOrders",
+ "accountsReceivableEmail",
+ "shelfLabelSize",
+ "timeCardEnabled",
+ "printing",
+ "defaultCustomerCc",
+ "salesRuleNotificationGroup"
]
},
{
"name": "companyUsage",
"rows": 0,
"columns": [
- "users",
- "updatedAt",
- "id",
"companyId",
- "aiTokens",
- "tasks",
+ "id",
+ "updatedAt",
+ "users",
+ "nextResetDatetime",
"createdAt",
- "nextResetDatetime"
+ "tasks",
+ "aiTokens"
]
},
{
"name": "consumable",
"rows": 0,
"columns": [
- "customFields",
"tags",
+ "customFields",
"approved",
"approvedBy",
"createdBy",
"updatedBy",
"id",
"companyId",
- "updatedAt",
- "createdAt"
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -487,16 +487,16 @@
"name": "costCenter",
"rows": 0,
"columns": [
+ "updatedAt",
+ "ownerId",
+ "name",
+ "createdAt",
"customFields",
"id",
- "createdAt",
- "name",
- "ownerId",
- "updatedAt",
- "createdBy",
+ "updatedBy",
"parentCostCenterId",
"companyId",
- "updatedBy"
+ "createdBy"
]
},
{
@@ -521,20 +521,20 @@
"name": "customField",
"rows": 0,
"columns": [
- "updatedBy",
- "dataTypeId",
"active",
- "sortOrder",
"required",
+ "sortOrder",
"table",
- "listOptions",
- "createdAt",
- "id",
- "updatedAt",
+ "updatedBy",
+ "dataTypeId",
"companyId",
"createdBy",
"name",
- "tags"
+ "tags",
+ "listOptions",
+ "createdAt",
+ "id",
+ "updatedAt"
]
},
{
@@ -588,76 +588,76 @@
"name": "depreciationRun",
"rows": 0,
"columns": [
- "companyId",
+ "id",
+ "createdBy",
+ "postedBy",
+ "depreciationRunId",
+ "updatedBy",
+ "createdAt",
+ "postedAt",
"status",
"periodEnd",
- "postedAt",
- "createdAt",
- "updatedBy",
- "depreciationRunId",
- "postedBy",
- "id",
- "createdBy"
+ "companyId"
]
},
{
"name": "dimension",
"rows": 0,
"columns": [
- "active",
- "createdBy",
- "entityType",
- "companyGroupId",
- "required",
- "updatedBy",
- "id",
- "updatedAt",
+ "name",
"createdAt",
- "name"
+ "updatedAt",
+ "id",
+ "updatedBy",
+ "required",
+ "companyGroupId",
+ "entityType",
+ "createdBy",
+ "active"
]
},
{
"name": "dimensionValue",
"rows": 0,
"columns": [
- "updatedBy",
- "companyGroupId",
- "name",
- "createdBy",
+ "createdAt",
+ "id",
"updatedAt",
"dimensionId",
- "createdAt",
- "id"
+ "createdBy",
+ "updatedBy",
+ "name",
+ "companyGroupId"
]
},
{
"name": "document",
"rows": 0,
"columns": [
+ "createdAt",
+ "path",
+ "sourceDocument",
+ "active",
+ "readGroups",
+ "companyId",
+ "id",
+ "writeGroups",
"description",
"name",
"updatedBy",
"type",
- "createdBy",
"size",
- "sourceDocumentId",
+ "createdBy",
"updatedAt",
- "sourceDocument",
- "path",
- "createdAt",
- "readGroups",
- "active",
- "id",
- "writeGroups",
- "companyId"
+ "sourceDocumentId"
]
},
{
"name": "documentExtraction",
"rows": 0,
"columns": [
- "storagePath",
"createdAt",
+ "storagePath",
"sourceDocument",
"updatedAt",
"sourceDocumentId",
@@ -666,8 +666,8 @@
"id",
"createdBy",
"documentType",
- "updatedBy",
"companyId",
+ "updatedBy",
"extractedData",
"error"
]
@@ -680,41 +680,41 @@
{
"name": "documentLabel",
"rows": 0,
- "columns": ["userId", "documentId", "companyId", "label"]
+ "columns": ["documentId", "userId", "companyId", "label"]
},
{
"name": "documentSection",
"rows": 0,
"columns": [
- "content",
- "placement",
"name",
+ "placement",
"createdBy",
- "id",
- "updatedBy",
- "config",
+ "content",
"companyId",
"updatedAt",
- "createdAt"
+ "createdAt",
+ "updatedBy",
+ "id",
+ "config"
]
},
{
"name": "documentTemplate",
"rows": 0,
"columns": [
+ "blocks",
+ "updatedBy",
"formatVersion",
"documentType",
"settings",
- "updatedBy",
- "blocks",
- "companyId",
- "updatedAt",
- "headerSectionId",
- "createdBy",
"id",
"footerSectionId",
"createdAt",
- "theme"
+ "theme",
+ "updatedAt",
+ "companyId",
+ "headerSectionId",
+ "createdBy"
]
},
{
@@ -745,166 +745,166 @@
{
"name": "employee",
"rows": 0,
- "columns": ["id", "companyId", "pin", "active", "employeeTypeId"]
+ "columns": ["id", "companyId", "active", "employeeTypeId"]
},
{
"name": "employeeTypePermission",
"rows": 0,
"columns": [
- "update",
- "create",
- "delete",
- "createdAt",
+ "module",
+ "updatedAt",
"employeeTypeId",
"view",
- "module",
- "updatedAt"
+ "delete",
+ "create",
+ "createdAt",
+ "update"
]
},
{
"name": "enforcementRule",
"rows": 0,
"columns": [
- "message",
- "appliesToAll",
- "id",
- "surfaces",
- "targetType",
"conditionAst",
- "companyId",
- "filteredItemGroupIds",
+ "targetType",
"createdBy",
- "createdAt",
- "active",
- "customFields",
- "filteredItemTypes",
- "description",
+ "filteredItemGroupIds",
+ "companyId",
+ "message",
+ "surfaces",
+ "id",
+ "appliesToAll",
"severity",
- "updatedBy",
- "updatedAt",
- "name",
+ "filteredItemMatchAll",
"family",
- "filteredItemMatchAll"
- ]
- },
- {
- "name": "enforcementRuleAcknowledgment",
+ "name",
+ "updatedAt",
+ "updatedBy",
+ "active",
+ "createdAt",
+ "description",
+ "filteredItemTypes",
+ "customFields"
+ ]
+ },
+ {
+ "name": "enforcementRuleAcknowledgment",
"rows": 0,
"columns": [
- "createdBy",
- "documentType",
- "documentLineId",
- "ruleName",
- "ruleId",
"updatedBy",
- "documentId",
- "id",
- "severity",
- "message",
- "itemId",
- "outcome",
+ "ruleId",
+ "ruleName",
+ "documentLineId",
+ "documentType",
+ "createdBy",
+ "createdAt",
"companyId",
- "createdAt"
+ "outcome",
+ "itemId",
+ "message",
+ "severity",
+ "id",
+ "documentId"
]
},
{
"name": "eventSystemSubscription",
"rows": 0,
"columns": [
- "handlerType",
- "table",
- "companyId",
- "operations",
- "active",
- "config",
- "name",
- "filter",
+ "id",
"createdAt",
- "id"
+ "filter",
+ "name",
+ "config",
+ "active",
+ "operations",
+ "companyId",
+ "table",
+ "handlerType"
]
},
{
"name": "exchangeRateOverride",
"rows": 0,
"columns": [
- "rate",
- "currencyCode",
- "updatedBy",
- "createdBy",
"companyId",
"updatedAt",
"id",
- "createdAt"
+ "createdAt",
+ "currencyCode",
+ "rate",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "externalIntegrationMapping",
"rows": 0,
"columns": [
- "entityId",
- "updatedBy",
- "integration",
- "metadata",
"externalId",
"createdBy",
- "companyId",
- "entityType",
- "createdAt",
- "lastSyncedAt",
- "updatedAt",
+ "metadata",
+ "updatedBy",
+ "entityId",
+ "integration",
+ "allowDuplicateExternalId",
"remoteUpdatedAt",
"id",
- "allowDuplicateExternalId"
+ "updatedAt",
+ "lastSyncedAt",
+ "createdAt",
+ "companyId",
+ "entityType"
]
},
{
"name": "fiscalYearSettings",
"rows": 0,
- "columns": ["startMonth", "companyId", "taxStartMonth", "updatedBy"]
+ "columns": ["updatedBy", "taxStartMonth", "companyId", "startMonth"]
},
{
"name": "fixedAssetClass",
"rows": 0,
"columns": [
- "updatedAt",
- "usefulLifeMonths",
"lossOnDisposalAccountId",
"createdAt",
+ "usefulLifeMonths",
+ "updatedAt",
+ "macrsConvention",
"taxResidualValuePercent",
"createdBy",
- "macrsConvention",
- "taxUsefulLifeMonths",
+ "bonusDepreciationPercent",
+ "companyId",
"description",
+ "taxUsefulLifeMonths",
"depreciationMethod",
- "companyId",
- "bonusDepreciationPercent",
"assetAccountId",
"updatedBy",
+ "writeDownAccountId",
"depreciationExpenseAccountId",
"id",
- "writeDownAccountId",
- "residualValuePercent",
"gainOnDisposalAccountId",
- "macrsPropertyClass",
- "taxDepreciationMethod",
+ "residualValuePercent",
"name",
- "accumulatedDepreciationAccountId",
+ "taxDepreciationMethod",
+ "macrsPropertyClass",
+ "writeOffAccountId",
"customFields",
- "writeOffAccountId"
+ "accumulatedDepreciationAccountId"
]
},
{
"name": "gaugeType",
"rows": 0,
"columns": [
- "customFields",
- "companyId",
- "updatedAt",
- "createdAt",
- "name",
- "updatedBy",
+ "createdBy",
"id",
- "createdBy"
+ "updatedBy",
+ "name",
+ "createdAt",
+ "updatedAt",
+ "companyId",
+ "customFields"
]
},
{
@@ -944,50 +944,55 @@
"name": "implementationCheckState",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "updatedAt",
"updatedBy",
"companyId",
- "value",
+ "createdBy",
+ "updatedAt",
+ "id",
"createdAt",
+ "itemKey",
"kind",
- "itemKey"
+ "value"
]
},
{
"name": "implementationFieldValue",
"rows": 0,
"columns": [
- "createdAt",
- "id",
- "updatedAt",
- "companyId",
- "createdBy",
- "updatedBy",
+ "fieldKey",
"value",
- "fieldKey"
+ "updatedBy",
+ "createdBy",
+ "companyId",
+ "updatedAt",
+ "id",
+ "createdAt"
]
},
{
"name": "implementationRow",
"rows": 0,
"columns": [
- "sortOrder",
- "createdAt",
- "collection",
- "payload",
"createdBy",
- "updatedAt",
"id",
+ "updatedAt",
"updatedBy",
- "companyId"
+ "companyId",
+ "sortOrder",
+ "createdAt",
+ "payload",
+ "collection"
]
},
{
"name": "invite",
"rows": 0,
"columns": [
+ "createdBy",
+ "permissions",
+ "email",
+ "role",
+ "attestedBy",
"revokedAt",
"createdAt",
"attestedAt",
@@ -995,35 +1000,30 @@
"companyId",
"updatedBy",
"id",
- "acceptedAt",
- "createdBy",
- "permissions",
- "email",
- "role",
- "attestedBy"
+ "acceptedAt"
]
},
{
"name": "itarCertification",
"rows": 0,
"columns": [
- "docVersion",
- "userAgent",
+ "fullLegalName",
+ "createdBy",
+ "type",
+ "userId",
"createdAt",
"updatedAt",
- "userId",
- "type",
- "createdBy",
- "fullLegalName",
- "id",
- "complianceContact",
- "ipAddress",
- "docHash",
- "updatedBy",
+ "docVersion",
+ "userAgent",
+ "certifiedAt",
+ "title",
"expiresAt",
"companyId",
- "title",
- "certifiedAt"
+ "updatedBy",
+ "docHash",
+ "ipAddress",
+ "complianceContact",
+ "id"
]
},
{
@@ -1046,57 +1046,57 @@
{
"name": "itemStockQuantities",
"rows": 0,
- "columns": ["locationId", "quantityOnHand", "itemId", "companyId"]
+ "columns": ["itemId", "companyId", "locationId", "quantityOnHand"]
},
{
"name": "journal",
"rows": 0,
"columns": [
- "postingDate",
- "reversalOfId",
- "postedBy",
- "updatedAt",
- "eliminationKind",
- "updatedBy",
- "postedAt",
- "accountingPeriodId",
- "companyId",
- "customFields",
- "sourceType",
- "journalEntryId",
- "id",
- "createdAt",
+ "createdBy",
"reversedById",
"description",
- "createdBy",
+ "tags",
"status",
- "tags"
+ "journalEntryId",
+ "id",
+ "sourceType",
+ "createdAt",
+ "accountingPeriodId",
+ "postedAt",
+ "companyId",
+ "eliminationKind",
+ "updatedBy",
+ "customFields",
+ "postingDate",
+ "reversalOfId",
+ "postedBy",
+ "updatedAt"
]
},
{
"name": "journalLine",
"rows": 0,
"columns": [
- "documentId",
- "journalLineReference",
- "tags",
- "companyId",
- "journalId",
- "quantity",
- "id",
- "externalDocumentId",
- "documentLineReference",
- "documentType",
+ "updatedAt",
+ "updatedBy",
"description",
"createdAt",
- "updatedBy",
- "updatedAt",
- "createdBy",
- "customFields",
- "accountId",
- "amount",
+ "documentType",
"intercompanyPartnerId",
- "accrual"
+ "accrual",
+ "amount",
+ "accountId",
+ "customFields",
+ "createdBy",
+ "journalId",
+ "companyId",
+ "tags",
+ "journalLineReference",
+ "documentId",
+ "documentLineReference",
+ "id",
+ "externalDocumentId",
+ "quantity"
]
},
{
@@ -1106,18 +1106,18 @@
"status",
"sourceJournalLineId",
"updatedAt",
- "targetCompanyId",
- "sourceCompanyId",
"createdAt",
+ "sourceCompanyId",
+ "targetCompanyId",
"amount",
- "id",
- "description",
"documentId",
+ "description",
+ "id",
"targetJournalLineId",
"companyGroupId",
"eliminationJournalId",
- "currencyCode",
- "documentType"
+ "documentType",
+ "currencyCode"
]
},
{
@@ -1143,12 +1143,12 @@
"name": "journalLineDimension",
"rows": 0,
"columns": [
- "createdAt",
- "id",
"journalLineId",
- "companyId",
+ "id",
+ "createdAt",
+ "valueId",
"dimensionId",
- "valueId"
+ "companyId"
]
},
{
@@ -1181,70 +1181,70 @@
"name": "fixedAsset",
"rows": 0,
"columns": [
- "disposalMethod",
- "serialNumber",
- "companyId",
- "taxDepreciationMethod",
- "id",
- "usefulLifeMonths",
- "disposalDate",
- "customFields",
- "residualValuePercent",
+ "bonusDepreciationPercent",
+ "taxResidualValuePercent",
+ "fixedAssetId",
"updatedAt",
"depreciationMethod",
"createdBy",
- "taxResidualValuePercent",
- "fixedAssetId",
- "bonusDepreciationPercent",
- "macrsConvention",
- "accumulatedTaxDepreciation",
- "saleProceeds",
- "acquisitionCost",
+ "disposalDate",
+ "customFields",
+ "residualValuePercent",
+ "id",
+ "usefulLifeMonths",
+ "companyId",
+ "taxDepreciationMethod",
+ "serialNumber",
+ "disposalMethod",
+ "name",
+ "macrsPropertyClass",
+ "fixedAssetClassId",
+ "depreciationStartDate",
+ "acquisitionDate",
+ "locationId",
+ "status",
+ "createdAt",
+ "notes",
+ "assetLifetimeUsage",
"description",
"accumulatedDepreciation",
"updatedBy",
"taxUsefulLifeMonths",
- "assetLifetimeUsage",
- "notes",
- "locationId",
- "status",
- "createdAt",
- "depreciationStartDate",
- "acquisitionDate",
- "name",
- "macrsPropertyClass",
- "fixedAssetClassId"
+ "macrsConvention",
+ "accumulatedTaxDepreciation",
+ "saleProceeds",
+ "acquisitionCost"
]
},
{
"name": "depreciationRunLine",
"rows": 0,
"columns": [
+ "depreciationRunId",
"journalId",
"id",
- "depreciationRunId",
- "taxAmount",
"companyId",
"fixedAssetId",
- "amount"
+ "amount",
+ "taxAmount"
]
},
{
"name": "fixedAssetDisposal",
"rows": 0,
"columns": [
- "gainLoss",
- "disposalDate",
- "disposalMethod",
- "updatedBy",
- "saleProceeds",
+ "fixedAssetId",
"journalId",
"createdAt",
- "fixedAssetId",
- "netBookValueAtDisposal",
- "id",
"companyId",
- "createdBy"
+ "id",
+ "createdBy",
+ "netBookValueAtDisposal",
+ "disposalMethod",
+ "disposalDate",
+ "gainLoss",
+ "saleProceeds",
+ "updatedBy"
]
},
{
@@ -1252,131 +1252,131 @@
"rows": 0,
"columns": [
"createdAt",
- "periodStart",
"periodEnd",
+ "periodStart",
"unitsProduced",
"createdBy",
"fixedAssetId",
"companyId",
- "updatedBy",
- "id"
+ "id",
+ "updatedBy"
]
},
{
"name": "inventoryCount",
"rows": 0,
"columns": [
- "locationId",
- "updatedBy",
- "inventoryCountId",
- "scope",
- "createdBy",
- "status",
- "updatedAt",
+ "isBlind",
+ "notes",
+ "id",
+ "postedAt",
+ "snapshotAt",
+ "postedBy",
+ "customFields",
"companyId",
"createdAt",
- "customFields",
- "postedBy",
- "snapshotAt",
- "postedAt",
- "id",
- "notes",
- "isBlind"
+ "updatedAt",
+ "createdBy",
+ "status",
+ "scope",
+ "updatedBy",
+ "inventoryCountId",
+ "locationId"
]
},
{
"name": "maintenanceFailureMode",
"rows": 0,
"columns": [
- "updatedBy",
- "id",
- "type",
"name",
- "createdAt",
- "updatedAt",
+ "type",
+ "id",
+ "updatedBy",
+ "companyId",
"createdBy",
- "companyId"
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "materialForm",
"rows": 0,
"columns": [
+ "createdBy",
"updatedBy",
"customFields",
"companyId",
- "createdBy",
- "code",
- "updatedAt",
- "name",
"createdAt",
"id",
- "tags"
+ "tags",
+ "updatedAt",
+ "code",
+ "name"
]
},
{
"name": "materialDimension",
"rows": 0,
- "columns": ["isMetric", "name", "companyId", "materialFormId", "id"]
+ "columns": ["id", "materialFormId", "companyId", "isMetric", "name"]
},
{
"name": "materialSubstance",
"rows": 0,
"columns": [
- "updatedBy",
- "customFields",
- "companyId",
- "createdBy",
+ "name",
"code",
"updatedAt",
- "name",
- "createdAt",
"id",
- "tags"
+ "tags",
+ "createdAt",
+ "customFields",
+ "companyId",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "materialFinish",
"rows": 0,
- "columns": ["companyId", "materialSubstanceId", "id", "name"]
+ "columns": ["name", "id", "materialSubstanceId", "companyId"]
},
{
"name": "materialGrade",
"rows": 0,
- "columns": ["id", "materialSubstanceId", "companyId", "name"]
+ "columns": ["companyId", "name", "materialSubstanceId", "id"]
},
{
"name": "materialType",
"rows": 0,
"columns": [
+ "name",
"id",
"companyId",
- "name",
- "materialFormId",
"code",
- "materialSubstanceId"
+ "materialSubstanceId",
+ "materialFormId"
]
},
{
"name": "material",
"rows": 0,
"columns": [
- "companyId",
- "approvedBy",
- "id",
- "createdAt",
- "customFields",
- "approved",
- "createdBy",
- "gradeId",
- "tags",
"updatedAt",
"materialTypeId",
- "dimensionId",
- "finishId",
- "materialFormId",
+ "tags",
+ "createdBy",
+ "gradeId",
"updatedBy",
- "materialSubstanceId"
+ "materialFormId",
+ "materialSubstanceId",
+ "finishId",
+ "dimensionId",
+ "approvedBy",
+ "id",
+ "companyId",
+ "approved",
+ "customFields",
+ "createdAt"
]
},
{
@@ -1388,231 +1388,231 @@
"name": "modelUpload",
"rows": 0,
"columns": [
- "processingError",
- "optimizeStatus",
- "originalPath",
- "graphPath",
- "optimizeError",
- "autodeskUrn",
- "optimizedModelPath",
- "optimizedAt",
- "companyId",
- "modelPath",
+ "glbPath",
+ "thumbnailPath",
+ "name",
+ "createdAt",
+ "optimizedSize",
+ "updatedAt",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "originalSize",
"size",
"processingStatus",
+ "modelPath",
"processedAt",
"componentCount",
- "originalSize",
- "id",
- "createdBy",
- "updatedBy",
- "createdAt",
- "optimizedSize",
- "updatedAt",
- "glbPath",
- "thumbnailPath",
- "name"
+ "companyId",
+ "optimizedAt",
+ "optimizeError",
+ "autodeskUrn",
+ "optimizedModelPath",
+ "processingError",
+ "optimizeStatus",
+ "graphPath",
+ "originalPath"
]
},
{
"name": "assemblyPlanJob",
"rows": 0,
"columns": [
- "modelUploadId",
- "createdAt",
- "companyId",
"updatedAt",
"id",
"createdBy",
"stats",
+ "modelUploadId",
+ "createdAt",
+ "companyId",
+ "planPath",
"status",
"kind",
- "error",
- "planPath"
+ "error"
]
},
{
"name": "noQuoteReason",
"rows": 0,
"columns": [
- "createdBy",
+ "updatedAt",
"createdAt",
"companyId",
- "updatedAt",
- "id",
- "updatedBy",
+ "createdBy",
+ "customFields",
"name",
- "customFields"
+ "updatedBy",
+ "id"
]
},
{
"name": "nonConformanceRequiredAction",
"rows": 0,
"columns": [
- "createdAt",
- "updatedAt",
- "name",
- "active",
"createdBy",
"systemType",
"id",
"updatedBy",
- "companyId"
+ "companyId",
+ "createdAt",
+ "updatedAt",
+ "name",
+ "active"
]
},
{
"name": "nonConformanceType",
"rows": 0,
"columns": [
- "id",
"updatedAt",
- "name",
+ "id",
"customFields",
+ "name",
"createdBy",
- "createdAt",
+ "updatedBy",
"companyId",
- "updatedBy"
+ "createdAt"
]
},
{
"name": "nonConformanceWorkflow",
"rows": 0,
"columns": [
- "priority",
- "companyId",
- "updatedAt",
- "content",
- "description",
"createdBy",
+ "description",
+ "content",
"requiredActionIds",
- "id",
- "approvalRequirements",
- "tags",
- "source",
+ "updatedAt",
+ "priority",
+ "companyId",
+ "active",
"updatedBy",
"createdAt",
"name",
- "active"
+ "source",
+ "approvalRequirements",
+ "id",
+ "tags"
]
},
{
"name": "nonConformance",
"rows": 0,
"columns": [
+ "description",
+ "nonConformanceTypeId",
+ "name",
+ "quantity",
+ "companyId",
+ "priority",
+ "tags",
"assignee",
"content",
"source",
- "tags",
"updatedAt",
"closeDate",
- "customFields",
"openDate",
- "quantity",
- "description",
- "nonConformanceTypeId",
- "name",
- "companyId",
- "priority",
- "updatedBy",
- "nonConformanceWorkflowId",
- "id",
- "createdBy",
- "status",
+ "customFields",
+ "dueDate",
"nonConformanceId",
"locationId",
- "dueDate",
+ "requiredActionIds",
"approvalRequirements",
"createdAt",
- "requiredActionIds"
+ "id",
+ "updatedBy",
+ "nonConformanceWorkflowId",
+ "status",
+ "createdBy"
]
},
{
"name": "changeOrder",
"rows": 0,
"columns": [
- "reasonForChange",
- "name",
- "approvalRequirements",
- "customFields",
- "tags",
- "updatedAt",
- "status",
- "createdBy",
- "companyId",
- "dueDate",
- "description",
"assignee",
- "createdAt",
"sourceType",
- "sourceId",
- "changeOrderId",
- "requiredActionIds",
- "priority",
+ "createdAt",
+ "dueDate",
+ "companyId",
+ "description",
+ "createdBy",
+ "status",
+ "updatedAt",
+ "customFields",
+ "tags",
+ "approvalRequirements",
+ "name",
+ "reasonForChange",
+ "type",
+ "openDate",
+ "changeOrderTypeId",
+ "id",
"nonConformanceId",
"updatedBy",
- "id",
- "changeOrderTypeId",
- "openDate",
- "type"
+ "priority",
+ "changeOrderId",
+ "requiredActionIds",
+ "sourceId"
]
},
{
"name": "changeOrderActionTask",
"rows": 0,
"columns": [
- "completedDate",
- "companyId",
- "id",
- "sortOrder",
+ "assignee",
+ "status",
+ "name",
+ "updatedAt",
+ "updatedBy",
+ "createdAt",
+ "dueDate",
"tags",
"notes",
- "createdBy",
"changeOrderId",
+ "createdBy",
"actionTypeId",
- "updatedBy",
- "dueDate",
- "createdAt",
- "assignee",
- "status",
- "updatedAt",
- "name"
+ "completedDate",
+ "companyId",
+ "id",
+ "sortOrder"
]
},
{
"name": "nonConformanceApprovalTask",
"rows": 0,
"columns": [
+ "assignee",
"status",
"updatedAt",
"approvalType",
- "assignee",
+ "updatedBy",
"createdAt",
"dueDate",
- "updatedBy",
- "nonConformanceId",
- "createdBy",
"tags",
"notes",
+ "nonConformanceId",
+ "createdBy",
+ "completedDate",
"companyId",
"id",
- "sortOrder",
- "completedDate"
+ "sortOrder"
]
},
{
"name": "nonConformanceReviewer",
"rows": 0,
"columns": [
- "title",
- "createdAt",
"updatedAt",
- "createdBy",
- "id",
- "updatedBy",
+ "createdAt",
+ "title",
"assignee",
- "status",
- "nonConformanceId",
+ "updatedBy",
+ "id",
+ "createdBy",
"companyId",
+ "nonConformanceId",
+ "status",
"notes",
"completedDate"
]
@@ -1637,49 +1637,49 @@
"name": "notification",
"rows": 0,
"columns": [
- "documentType",
+ "title",
"id",
+ "documentType",
"payload",
- "title",
- "seenAt",
- "userId",
"from",
"documentId",
- "event",
- "readAt",
+ "userId",
+ "seenAt",
"createdAt",
- "digestedInto",
- "companyId",
+ "readAt",
+ "event",
+ "description",
"topic",
- "description"
+ "companyId",
+ "digestedInto"
]
},
{
"name": "notificationDelivery",
"rows": 0,
"columns": [
- "documentId",
- "event",
- "userId",
- "lastDeliveryId",
"id",
"createdAt",
"successCount",
"companyId",
- "lastDeliveredAt"
+ "lastDeliveredAt",
+ "documentId",
+ "event",
+ "userId",
+ "lastDeliveryId"
]
},
{
"name": "notificationPreference",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "channel",
- "topic",
- "userId",
+ "id",
"enabled",
- "id"
+ "userId",
+ "topic",
+ "channel",
+ "companyId",
+ "updatedAt"
]
},
{
@@ -1687,11 +1687,11 @@
"rows": 0,
"columns": [
"redirectUri",
+ "scope",
"id",
"codeChallenge",
- "scope",
- "expiresAt",
"codeChallengeMethod",
+ "expiresAt",
"code",
"companyId",
"createdAt",
@@ -1721,83 +1721,83 @@
"name": "paymentTerm",
"rows": 0,
"columns": [
- "active",
- "tags",
+ "discountPercentage",
+ "updatedBy",
"daysDue",
+ "tags",
"daysDiscount",
- "updatedBy",
- "discountPercentage",
- "companyId",
- "createdBy",
- "name",
- "customFields",
- "calculationMethod",
+ "active",
"createdAt",
"id",
- "updatedAt"
+ "updatedAt",
+ "calculationMethod",
+ "customFields",
+ "name",
+ "companyId",
+ "createdBy"
]
},
{
"name": "periodCloseTaskDefinition",
"rows": 0,
"columns": [
- "severity",
- "isSystem",
+ "name",
+ "updatedBy",
+ "taskType",
+ "required",
+ "createdBy",
+ "autoCheckKey",
+ "updatedAt",
"customFields",
"companyId",
"createdAt",
- "sortOrder",
- "id",
+ "severity",
+ "isSystem",
"active",
+ "id",
"defaultAssigneeId",
- "required",
- "taskType",
- "name",
- "updatedBy",
- "updatedAt",
- "createdBy",
- "autoCheckKey"
+ "sortOrder"
]
},
{
"name": "periodCloseTask",
"rows": 0,
"columns": [
- "taskType",
- "status",
+ "evidenceJournalId",
+ "companyId",
+ "completedBy",
+ "sortOrder",
+ "severity",
"required",
"id",
- "severity",
- "sortOrder",
- "completedBy",
- "companyId",
- "evidenceJournalId",
- "updatedAt",
- "skippedReason",
- "notes",
- "name",
- "assigneeId",
- "updatedBy",
- "autoCheckKey",
- "createdAt",
- "createdBy",
+ "status",
+ "taskType",
"completedAt",
"accountingPeriodId",
- "definitionId"
+ "definitionId",
+ "createdBy",
+ "createdAt",
+ "autoCheckKey",
+ "assigneeId",
+ "updatedBy",
+ "name",
+ "notes",
+ "updatedAt",
+ "skippedReason"
]
},
{
"name": "pickingList",
"rows": 0,
"columns": [
- "createdAt",
"companyId",
+ "createdAt",
"customFields",
"pickingListId",
"dueDate",
- "updatedBy",
"id",
"createdBy",
+ "updatedBy",
"notes",
"locationId",
"status",
@@ -1809,90 +1809,90 @@
"name": "pricingRule",
"rows": 0,
"columns": [
- "itemIds",
- "customerIds",
- "id",
- "priority",
"validFrom",
"name",
- "customerTypeIds",
"maxQuantity",
+ "customerTypeIds",
+ "customerIds",
+ "id",
+ "itemIds",
+ "priority",
+ "validTo",
+ "ruleType",
+ "amountType",
+ "createdBy",
+ "companyId",
+ "minQuantity",
+ "updatedAt",
"amount",
"itemPostingGroupId",
"createdAt",
- "updatedAt",
"updatedBy",
- "active",
- "createdBy",
- "companyId",
- "validTo",
- "ruleType",
- "amountType",
- "minQuantity"
+ "active"
]
},
{
"name": "printJob",
"rows": 0,
"columns": [
- "attempts",
- "companyId",
- "updatedAt",
- "description",
- "sourceDocumentId",
- "origin",
- "sourceDocumentReadableId",
- "id",
- "printerUrl",
- "completedAt",
- "status",
- "createdBy",
- "contentType",
- "sourceDocument",
- "content",
"error",
+ "content",
+ "updatedBy",
"createdAt",
- "updatedBy"
+ "contentType",
+ "createdBy",
+ "status",
+ "completedAt",
+ "sourceDocument",
+ "id",
+ "sourceDocumentReadableId",
+ "origin",
+ "printerUrl",
+ "updatedAt",
+ "companyId",
+ "attempts",
+ "sourceDocumentId",
+ "description"
]
},
{
"name": "printerRoute",
"rows": 0,
"columns": [
+ "printerUrl",
"name",
"locationId",
- "printerUrl",
"format",
- "companyId",
"updatedAt",
"apiKey",
+ "companyId",
+ "mediaSizeId",
"templateId",
"id",
- "createdAt",
- "mediaSizeId"
+ "createdAt"
]
},
{
"name": "process",
"rows": 0,
"columns": [
- "active",
- "name",
"batchType",
- "processType",
+ "name",
+ "active",
"updatedBy",
- "tags",
+ "processType",
"updatedAt",
"id",
+ "tags",
"createdBy",
"defaultStandardFactor",
"requiresAbility",
"companyId",
"createdAt",
- "customFields",
"completeAllOnScan",
- "batchable",
- "batchRules"
+ "customFields",
+ "batchRules",
+ "batchable"
]
},
{
@@ -1916,12 +1916,12 @@
"name": "employeeAbility",
"rows": 0,
"columns": [
- "companyId",
- "employeeId",
+ "lastTrainingDate",
+ "abilityId",
"id",
"expiresAt",
- "abilityId",
- "lastTrainingDate"
+ "companyId",
+ "employeeId"
]
},
{
@@ -1936,11 +1936,11 @@
"updatedAt",
"updatedBy",
"name",
- "createdAt",
"assignee",
- "createdBy",
+ "createdAt",
"companyId",
"id",
+ "createdBy",
"status"
]
},
@@ -1948,15 +1948,15 @@
"name": "procedureParameter",
"rows": 0,
"columns": [
- "createdAt",
- "id",
- "updatedBy",
- "updatedAt",
- "procedureId",
- "companyId",
"createdBy",
+ "key",
"value",
- "key"
+ "companyId",
+ "updatedAt",
+ "procedureId",
+ "createdAt",
+ "updatedBy",
+ "id"
]
},
{
@@ -1964,14 +1964,14 @@
"rows": 0,
"columns": [
"active",
- "description",
- "name",
"createdAt",
- "id",
- "updatedAt",
+ "name",
+ "description",
"createdBy",
- "companyId",
- "updatedBy"
+ "updatedAt",
+ "id",
+ "updatedBy",
+ "companyId"
]
},
{
@@ -2000,54 +2000,54 @@
{
"name": "purchasingRfqFavorite",
"rows": 0,
- "columns": ["userId", "rfqId"]
+ "columns": ["rfqId", "userId"]
},
{
"name": "qualityDocument",
"rows": 0,
"columns": [
- "status",
- "updatedBy",
"assignee",
- "version",
"description",
- "content",
- "updatedAt",
- "id",
- "createdAt",
- "createdBy",
+ "version",
+ "updatedBy",
+ "status",
"companyId",
+ "createdBy",
+ "name",
"tags",
- "name"
+ "content",
+ "createdAt",
+ "id",
+ "updatedAt"
]
},
{
"name": "reportPin",
"rows": 0,
"columns": [
- "companyId",
- "pinned",
- "updatedBy",
- "createdBy",
"userId",
"updatedAt",
"reportKey",
- "createdAt"
+ "createdAt",
+ "pinned",
+ "companyId",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "reportView",
"rows": 0,
"columns": [
- "id",
"updatedBy",
+ "id",
"visibility",
"companyId",
- "updatedAt",
"createdAt",
+ "updatedAt",
"config",
- "name",
"reportKey",
+ "name",
"createdBy"
]
},
@@ -2055,69 +2055,69 @@
"name": "returnReason",
"rows": 0,
"columns": [
- "createdAt",
+ "createdBy",
+ "inventoryValueZero",
+ "companyId",
+ "updatedBy",
"customFields",
"id",
- "updatedAt",
+ "createdAt",
"name",
- "createdBy",
- "updatedBy",
- "inventoryValueZero",
- "companyId"
+ "updatedAt"
]
},
{
"name": "scrapReason",
"rows": 0,
"columns": [
- "updatedAt",
+ "createdBy",
"companyId",
"createdAt",
- "createdBy",
- "customFields",
- "name",
+ "updatedAt",
+ "id",
"updatedBy",
- "id"
+ "name",
+ "customFields"
]
},
{
"name": "searchIndexRegistry",
"rows": 0,
- "columns": ["lastRebuiltAt", "createdAt", "companyId"]
+ "columns": ["companyId", "createdAt", "lastRebuiltAt"]
},
{
"name": "sequence",
"rows": 0,
"columns": [
- "suffix",
- "size",
- "name",
"prefix",
- "next",
- "updatedBy",
- "companyId",
- "updatedAt",
+ "name",
+ "size",
+ "suffix",
+ "table",
"step",
- "table"
+ "updatedAt",
+ "companyId",
+ "updatedBy",
+ "next"
]
},
{
"name": "service",
"rows": 0,
"columns": [
- "approvedBy",
- "createdAt",
- "tags",
- "serviceType",
- "updatedAt",
- "approved",
- "toDate",
+ "updatedBy",
+ "companyId",
"createdBy",
"customFields",
"id",
"fromDate",
- "updatedBy",
- "companyId"
+ "serviceType",
+ "updatedAt",
+ "approved",
+ "toDate",
+ "approvedBy",
+ "createdAt",
+ "tags"
]
},
{
@@ -2173,81 +2173,81 @@
"name": "peopleAbsence",
"rows": 0,
"columns": [
- "shiftId",
- "employeeId",
- "date",
- "createdBy",
+ "companyId",
+ "updatedAt",
+ "createdAt",
"updatedBy",
"id",
"note",
- "companyId",
- "createdAt",
- "updatedAt"
+ "employeeId",
+ "date",
+ "createdBy",
+ "shiftId"
]
},
{
"name": "shippingMethod",
"rows": 0,
"columns": [
- "createdAt",
- "updatedAt",
- "name",
- "tags",
- "active",
"createdBy",
"id",
"updatedBy",
- "companyId",
+ "active",
+ "tags",
+ "name",
+ "createdAt",
+ "updatedAt",
+ "trackingUrl",
+ "customFields",
"carrier",
"carrierAccountId",
- "customFields",
- "trackingUrl"
+ "companyId"
]
},
{
"name": "shippingTerm",
"rows": 0,
"columns": [
- "createdAt",
- "updatedAt",
- "companyId",
- "active",
+ "updatedBy",
+ "name",
"createdBy",
- "id",
"tags",
- "updatedBy",
- "name"
+ "id",
+ "updatedAt",
+ "active",
+ "companyId",
+ "createdAt"
]
},
{
"name": "slackDocumentThread",
"rows": 0,
"columns": [
+ "channelId",
"createdAt",
"documentType",
"documentId",
- "channelId",
- "createdBy",
- "updatedBy",
- "companyId",
"threadTs",
"updatedAt",
- "id"
+ "id",
+ "updatedBy",
+ "createdBy",
+ "companyId"
]
},
{
"name": "ssoConnection",
"rows": 0,
"columns": [
- "metadataUrl",
"providerId",
+ "metadataUrl",
"requireSso",
"metadataXml",
"companyId",
"createdBy",
"updatedBy",
- "id",
"createdAt",
+ "id",
"updatedAt",
"active"
]
@@ -2256,66 +2256,66 @@
"name": "ssoDomain",
"rows": 0,
"columns": [
- "verifiedAt",
- "domain",
- "connectionId",
- "verificationToken",
+ "companyId",
"createdBy",
"updatedBy",
- "companyId",
- "status",
- "id",
"createdAt",
- "updatedAt"
+ "id",
+ "updatedAt",
+ "status",
+ "connectionId",
+ "domain",
+ "verifiedAt",
+ "verificationToken"
]
},
{
"name": "stockTransfer",
"rows": 0,
"columns": [
- "createdAt",
- "status",
- "tags",
- "locationId",
- "completedAt",
- "assignee",
"updatedBy",
"createdBy",
- "customFields",
"stockTransferId",
+ "customFields",
"companyId",
"notes",
"id",
- "updatedAt"
+ "updatedAt",
+ "createdAt",
+ "status",
+ "locationId",
+ "tags",
+ "assignee",
+ "completedAt"
]
},
{
"name": "storageType",
"rows": 0,
"columns": [
+ "createdAt",
"updatedAt",
- "createdBy",
"companyId",
- "createdAt",
- "customFields",
- "name",
+ "createdBy",
"updatedBy",
- "id"
+ "id",
+ "customFields",
+ "name"
]
},
{
"name": "suggestion",
"rows": 0,
"columns": [
+ "path",
+ "emoji",
+ "userId",
+ "attachmentPath",
"suggestion",
"companyId",
"id",
"createdAt",
- "tags",
- "path",
- "emoji",
- "userId",
- "attachmentPath"
+ "tags"
]
},
{
@@ -2338,60 +2338,60 @@
"name": "tableView",
"rows": 0,
"columns": [
- "sortOrder",
- "columnVisibility",
- "id",
- "sorts",
+ "name",
+ "createdAt",
"columnPinning",
"filters",
- "createdAt",
- "name",
- "updatedBy",
- "type",
- "companyId",
- "columnOrder",
+ "id",
+ "columnVisibility",
+ "sorts",
+ "sortOrder",
+ "description",
"table",
"createdBy",
- "description"
+ "columnOrder",
+ "companyId",
+ "type",
+ "updatedBy"
]
},
{
"name": "tag",
"rows": 0,
"columns": [
- "createdBy",
- "createdAt",
- "companyId",
+ "table",
"updatedBy",
"name",
- "table"
+ "createdAt",
+ "companyId",
+ "createdBy"
]
},
{
"name": "terms",
"rows": 0,
"columns": [
- "id",
- "purchasingTerms",
- "updatedBy",
"salesTerms",
- "updatedAt"
+ "updatedAt",
+ "updatedBy",
+ "purchasingTerms",
+ "id"
]
},
{
"name": "timeCardEntry",
"rows": 0,
"columns": [
- "createdAt",
"id",
+ "createdAt",
"updatedAt",
"note",
"employeeId",
"createdBy",
"updatedBy",
"clockOut",
- "companyId",
"clockIn",
+ "companyId",
"autoCloseShiftId"
]
},
@@ -2399,14 +2399,14 @@
"name": "tool",
"rows": 0,
"columns": [
- "customFields",
"tags",
+ "customFields",
+ "createdBy",
"approvedBy",
"approved",
- "createdBy",
+ "companyId",
"id",
"updatedBy",
- "companyId",
"createdAt",
"updatedAt"
]
@@ -2415,40 +2415,40 @@
"name": "trackedActivity",
"rows": 0,
"columns": [
- "id",
- "createdBy",
"attributes",
- "type",
- "createdAt",
+ "createdBy",
+ "id",
"updatedBy",
+ "createdAt",
+ "type",
"sourceDocumentReadableId",
- "sourceDocumentId",
+ "companyId",
"sourceDocument",
- "companyId"
+ "sourceDocumentId"
]
},
{
"name": "training",
"rows": 0,
"columns": [
- "id",
- "content",
- "tags",
- "status",
- "updatedAt",
- "name",
- "companyId",
- "type",
"estimatedDuration",
- "assignee",
- "processId",
- "updatedBy",
- "createdBy",
- "version",
- "createdAt",
- "description",
+ "type",
+ "companyId",
+ "name",
+ "updatedAt",
+ "status",
+ "tags",
+ "content",
+ "id",
+ "frequency",
"grantsAbilityId",
- "frequency"
+ "description",
+ "createdAt",
+ "version",
+ "createdBy",
+ "updatedBy",
+ "processId",
+ "assignee"
]
},
{
@@ -2460,8 +2460,8 @@
"trainingId",
"updatedBy",
"createdAt",
- "groupIds",
"companyId",
+ "groupIds",
"updatedAt"
]
},
@@ -2469,40 +2469,40 @@
"name": "trainingCompletion",
"rows": 0,
"columns": [
- "employeeId",
- "companyId",
- "createdAt",
- "completedAt",
"trainingAssignmentId",
"updatedBy",
"createdBy",
"period",
"updatedAt",
"id",
- "completedBy"
+ "completedBy",
+ "employeeId",
+ "companyId",
+ "createdAt",
+ "completedAt"
]
},
{
"name": "trainingQuestion",
"rows": 0,
"columns": [
- "type",
- "question",
- "createdAt",
- "options",
- "sortOrder",
- "tolerance",
- "createdBy",
- "updatedBy",
- "companyId",
+ "correctNumber",
+ "correctBoolean",
+ "id",
+ "required",
"trainingId",
+ "companyId",
"updatedAt",
"matchingPairs",
"correctAnswers",
- "correctNumber",
- "id",
- "correctBoolean",
- "required"
+ "tolerance",
+ "sortOrder",
+ "updatedBy",
+ "createdBy",
+ "question",
+ "createdAt",
+ "type",
+ "options"
]
},
{
@@ -2558,98 +2558,103 @@
"name": "assemblyComponentMapping",
"rows": 0,
"columns": [
- "confidence",
- "itemId",
- "geometryHash",
"createdBy",
- "id",
- "updatedBy",
- "companyId",
- "modelUploadId",
+ "geometryHash",
+ "itemId",
+ "confidence",
"updatedAt",
- "createdAt"
+ "createdAt",
+ "modelUploadId",
+ "companyId",
+ "updatedBy",
+ "id"
]
},
{
"name": "assemblyInstruction",
"rows": 0,
"columns": [
- "companyId",
- "publishedAt",
- "createdBy",
- "name",
- "updatedAt",
- "status",
+ "tags",
+ "assemblyPlanJobId",
+ "rootInstructionId",
+ "updatedBy",
+ "createdAt",
+ "modelUploadId",
+ "itemId",
+ "version",
"customFields",
- "id",
"settings",
- "version",
- "itemId",
- "modelUploadId",
- "createdAt",
- "updatedBy",
- "rootInstructionId",
- "assemblyPlanJobId",
- "tags"
+ "id",
+ "status",
+ "name",
+ "createdBy",
+ "updatedAt",
+ "companyId",
+ "publishedAt"
]
},
{
"name": "assemblyInstructionStep",
"rows": 0,
"columns": [
- "motion",
- "createdAt",
- "warnings",
- "notes",
+ "title",
+ "fastener",
"maxValue",
"rootStepId",
- "fastener",
- "title",
"planConfidence",
- "updatedAt",
- "description",
- "durationSeconds",
- "camera",
+ "warnings",
+ "notes",
+ "createdAt",
+ "motion",
"explode",
- "fileTypes",
- "parentStepId",
+ "camera",
"sortOrder",
- "createdBy",
- "type",
- "minValue",
+ "parentStepId",
+ "fileTypes",
+ "durationSeconds",
+ "description",
+ "updatedAt",
"updatedBy",
- "required",
+ "minValue",
"id",
- "unitOfMeasureCode",
+ "required",
+ "createdBy",
+ "type",
+ "listValues",
+ "assemblyInstructionId",
+ "componentNodeIds",
"companyId",
- "status",
- "buildWave",
+ "unitOfMeasureCode",
"instructionText",
- "assemblyInstructionId",
- "listValues",
- "componentNodeIds"
+ "buildWave",
+ "status"
]
},
{
"name": "assemblyInstructionStepMaterial",
"rows": 0,
"columns": [
- "sortOrder",
- "createdBy",
- "itemId",
- "quantity",
+ "updatedAt",
+ "createdAt",
+ "stepId",
"companyId",
- "updatedBy",
"id",
- "createdAt",
- "updatedAt",
- "stepId"
+ "updatedBy",
+ "createdBy",
+ "quantity",
+ "itemId",
+ "sortOrder"
]
},
{
"name": "assemblyInstructionStepSlide",
"rows": 0,
"columns": [
+ "modelUploadId",
+ "imagePath",
+ "size",
+ "caption",
+ "updatedBy",
"updatedAt",
"stepId",
"annotations",
@@ -2657,12 +2662,7 @@
"id",
"companyId",
"createdAt",
- "sortOrder",
- "modelUploadId",
- "imagePath",
- "size",
- "caption",
- "updatedBy"
+ "sortOrder"
]
},
{
@@ -2673,8 +2673,8 @@
"itemId",
"quantity",
"sortOrder",
- "createdAt",
"updatedAt",
+ "createdAt",
"stepId",
"companyId",
"updatedBy",
@@ -2685,52 +2685,52 @@
"name": "assemblyUnit",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "updatedBy",
- "sourceGroupId",
+ "name",
+ "componentNodeIds",
+ "createdBy",
+ "itemId",
+ "modelUploadId",
"createdAt",
"updatedAt",
- "modelUploadId",
- "itemId",
- "createdBy",
- "componentNodeIds",
- "name"
+ "updatedBy",
+ "id",
+ "sourceGroupId",
+ "companyId"
]
},
{
"name": "batchProperty",
"rows": 0,
"columns": [
+ "label",
+ "dataType",
+ "companyId",
+ "listOptions",
+ "itemId",
"createdAt",
"updatedAt",
- "itemId",
- "sortOrder",
"createdBy",
"id",
"updatedBy",
- "companyId",
- "label",
- "dataType",
- "listOptions"
+ "sortOrder"
]
},
{
"name": "changeOrderSupersession",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
- "changeOrderId",
- "discontinuationDate",
- "updatedAt",
- "id",
- "createdAt",
- "successorEffectivityDate",
"successorItemId",
"predecessorItemId",
+ "successorEffectivityDate",
"supersessionMode",
- "updatedBy"
+ "updatedBy",
+ "changeOrderId",
+ "companyId",
+ "createdBy",
+ "id",
+ "createdAt",
+ "updatedAt",
+ "discontinuationDate"
]
},
{
@@ -2738,8 +2738,8 @@
"rows": 0,
"columns": [
"itemId",
- "id",
"companyId",
+ "id",
"name",
"sortOrder",
"isUngrouped"
@@ -2749,19 +2749,19 @@
"name": "configurationParameter",
"rows": 0,
"columns": [
- "label",
"materialFormFilterId",
+ "label",
"key",
"configurationParameterGroupId",
- "updatedAt",
"dataType",
- "itemId",
+ "updatedAt",
"updatedBy",
- "sortOrder",
+ "itemId",
"createdAt",
+ "sortOrder",
+ "createdBy",
"companyId",
"id",
- "createdBy",
"listOptions"
]
},
@@ -2769,160 +2769,160 @@
"name": "configurationRule",
"rows": 0,
"columns": [
- "updatedBy",
- "itemId",
- "field",
- "updatedAt",
+ "code",
"companyId",
- "code"
+ "updatedAt",
+ "field",
+ "updatedBy",
+ "itemId"
]
},
{
"name": "demandForecast",
"rows": 0,
"columns": [
+ "createdAt",
+ "companyId",
+ "locationId",
"confidence",
+ "updatedAt",
"createdBy",
"itemId",
- "updatedAt",
- "companyId",
- "createdAt",
- "locationId",
- "updatedBy",
- "forecastMethod",
"notes",
"periodId",
- "forecastQuantity"
+ "forecastQuantity",
+ "forecastMethod",
+ "updatedBy"
]
},
{
"name": "demandProjection",
"rows": 0,
"columns": [
- "notes",
- "forecastQuantity",
- "periodId",
"forecastMethod",
"updatedBy",
+ "notes",
+ "periodId",
+ "forecastQuantity",
+ "confidence",
+ "createdBy",
+ "itemId",
+ "updatedAt",
"companyId",
"createdAt",
"id",
- "locationId",
- "confidence",
- "itemId",
- "createdBy",
- "updatedAt"
+ "locationId"
]
},
{
"name": "enforcementRuleItemAssignment",
"rows": 0,
"columns": [
+ "createdAt",
"createdBy",
"companyId",
- "createdAt",
- "ruleId",
"updatedBy",
- "itemId"
+ "itemId",
+ "ruleId"
]
},
{
"name": "inspectionDocument",
"rows": 0,
"columns": [
- "samplingSampleSize",
- "samplingSeverity",
- "updatedAt",
- "createdBy",
- "samplingInspectionLevel",
"version",
- "fileName",
- "samplingPercentage",
- "samplingAql",
- "updatedBy",
- "partId",
+ "samplingInspectionLevel",
+ "createdBy",
+ "updatedAt",
+ "samplingSeverity",
+ "samplingSampleSize",
"drawingNumber",
- "storagePath",
- "uploadedBy",
- "defaultPageWidth",
+ "partId",
+ "updatedBy",
+ "samplingAql",
+ "samplingPercentage",
+ "fileName",
"id",
- "defaultPageHeight",
- "pageCount",
- "companyId",
+ "defaultPageWidth",
+ "uploadedBy",
+ "storagePath",
+ "samplingPlanType",
"createdAt",
- "samplingPlanType"
+ "companyId",
+ "pageCount",
+ "defaultPageHeight"
]
},
{
"name": "inspectionFeature",
"rows": 0,
"columns": [
+ "nominalValue",
+ "samplingAql",
+ "samplingPercentage",
+ "companyId",
+ "updatedAt",
+ "pageNumber",
"type",
"samplingSeverity",
"samplingSampleSize",
"label",
- "samplingInspectionLevel",
"createdAt",
- "nominalValue",
- "samplingAql",
- "samplingPercentage",
- "pageNumber",
- "updatedAt",
- "companyId",
- "description",
- "createdBy",
- "id",
- "toleranceMinus",
+ "samplingInspectionLevel",
"unit",
"tolerancePlus",
"updatedBy",
"inspectionDocumentId",
- "samplingPlanType"
+ "samplingPlanType",
+ "description",
+ "createdBy",
+ "toleranceMinus",
+ "id"
]
},
{
"name": "balloon",
"rows": 0,
"columns": [
- "regionX",
+ "companyId",
+ "updatedBy",
+ "inspectionFeatureId",
+ "regionY",
+ "pageNumber",
+ "createdBy",
+ "updatedAt",
+ "createdAt",
+ "inspectionDocumentId",
+ "regionWidth",
+ "xCoordinate",
"regionHeight",
"id",
"yCoordinate",
- "regionWidth",
- "xCoordinate",
- "inspectionDocumentId",
- "createdAt",
- "updatedAt",
- "createdBy",
- "pageNumber",
- "regionY",
- "updatedBy",
- "companyId",
- "inspectionFeatureId"
+ "regionX"
]
},
{
"name": "inventoryCountLine",
"rows": 0,
"columns": [
- "id",
- "systemQuantity",
- "storageUnitId",
- "createdAt",
- "companyId",
- "countedAt",
- "readableId",
- "countedQuantity",
"countedBy",
"locationId",
"updatedBy",
"createdBy",
"itemId",
- "inventoryCountId",
"postedItemLedgerId",
+ "inventoryCountId",
"updatedAt",
"customFields",
- "trackedEntityId"
+ "trackedEntityId",
+ "id",
+ "systemQuantity",
+ "storageUnitId",
+ "createdAt",
+ "companyId",
+ "countedAt",
+ "readableId",
+ "countedQuantity"
]
},
{
@@ -2948,132 +2948,132 @@
"name": "itemInspectionDocumentAssignment",
"rows": 0,
"columns": [
- "inspectionDocumentId",
- "companyId",
- "updatedBy",
- "createdBy",
"usage",
"updatedAt",
"itemId",
- "createdAt"
+ "createdAt",
+ "companyId",
+ "inspectionDocumentId",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "itemPlanning",
"rows": 0,
"columns": [
- "companyId",
- "locationId",
- "minimumOrderQuantity",
- "reorderPoint",
- "demandAccumulationSafetyStock",
- "demandAccumulationIncludesInventory",
- "itemId",
- "reorderQuantity",
- "minimumReserveQuantity",
+ "demandAccumulationPeriod",
+ "maximumInventoryQuantity",
+ "updatedBy",
+ "createdAt",
"maximumOrderQuantity",
"reorderingPolicy",
"critical",
- "createdAt",
- "updatedBy",
- "demandAccumulationPeriod",
- "maximumInventoryQuantity",
- "tags",
- "updatedAt",
- "createdBy",
+ "customFields",
"orderMultiple",
- "customFields"
+ "createdBy",
+ "updatedAt",
+ "tags",
+ "demandAccumulationSafetyStock",
+ "reorderPoint",
+ "minimumOrderQuantity",
+ "locationId",
+ "companyId",
+ "minimumReserveQuantity",
+ "reorderQuantity",
+ "demandAccumulationIncludesInventory",
+ "itemId"
]
},
{
"name": "itemSerialSequence",
"rows": 0,
"columns": [
+ "prefix",
+ "itemId",
+ "size",
"updatedAt",
"suffix",
- "size",
- "itemId",
- "prefix",
- "next",
- "updatedBy",
- "createdBy",
- "id",
+ "companyId",
"createdAt",
"step",
- "companyId"
+ "updatedBy",
+ "id",
+ "createdBy",
+ "next"
]
},
{
"name": "itemShelfLife",
"rows": 0,
"columns": [
- "triggerTiming",
- "calculateFromBom",
- "days",
- "triggerProcessId",
- "createdBy",
"updatedBy",
"itemId",
"customFields",
"companyId",
"mode",
"createdAt",
- "updatedAt"
- ]
- },
- {
+ "updatedAt",
+ "triggerTiming",
+ "calculateFromBom",
+ "days",
+ "triggerProcessId",
+ "createdBy"
+ ]
+ },
+ {
"name": "itemSupersession",
"rows": 0,
"columns": [
- "successorEffectivityDate",
+ "discontinuationDate",
+ "supersessionMode",
+ "successorItemId",
+ "conversionFactor",
+ "updatedAt",
"createdAt",
"itemId",
- "updatedAt",
- "createdBy",
- "updatedBy",
+ "successorEffectivityDate",
"companyId",
- "discontinuationDate",
- "conversionFactor",
- "supersessionMode",
- "successorItemId"
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "itemUnitSalePrice",
"rows": 0,
"columns": [
- "allowInvoiceDiscount",
- "tags",
- "currencyCode",
- "salesUnitOfMeasureCode",
- "salesBlocked",
- "updatedAt",
- "companyId",
- "createdAt",
"customFields",
"unitSalePrice",
- "priceIncludesTax",
- "createdBy",
+ "companyId",
+ "createdAt",
"itemId",
- "updatedBy"
+ "createdBy",
+ "updatedBy",
+ "priceIncludesTax",
+ "salesUnitOfMeasureCode",
+ "currencyCode",
+ "tags",
+ "allowInvoiceDiscount",
+ "salesBlocked",
+ "updatedAt"
]
},
{
"name": "makeMethod",
"rows": 0,
"columns": [
- "updatedBy",
- "createdAt",
- "companyId",
- "createdBy",
- "changeOrderId",
- "customFields",
"version",
+ "customFields",
"itemId",
"updatedAt",
- "id",
+ "status",
"tags",
- "status"
+ "id",
+ "updatedBy",
+ "companyId",
+ "createdAt",
+ "changeOrderId",
+ "createdBy"
]
},
{
@@ -3084,18 +3084,18 @@
"createdAt",
"sortOrder",
"baseMakeMethodId",
- "changeSummary",
"changeType",
- "updatedBy",
+ "changeSummary",
"createdBy",
- "changeOrderId",
- "companyId",
+ "updatedBy",
"updatedAt",
- "successorEffectivityDate",
+ "companyId",
+ "changeOrderId",
"supersessionMode",
- "newItemId",
+ "successorEffectivityDate",
"discontinuationDate",
"id",
+ "newItemId",
"draftMakeMethodId"
]
},
@@ -3103,144 +3103,144 @@
"name": "nonConformanceItem",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "itemId",
- "createdAt",
+ "id",
+ "disposition",
+ "createdBy",
+ "nonConformanceId",
"updatedBy",
"quantity",
- "nonConformanceId",
- "createdBy",
- "id",
- "disposition"
+ "createdAt",
+ "companyId",
+ "itemId",
+ "updatedAt"
]
},
{
"name": "procedureStep",
"rows": 0,
"columns": [
- "maxValue",
- "unitOfMeasureCode",
- "companyId",
- "procedureId",
"updatedAt",
- "sortOrder",
- "listValues",
+ "procedureId",
+ "companyId",
+ "unitOfMeasureCode",
+ "maxValue",
"minValue",
"id",
- "type",
- "description",
+ "listValues",
+ "sortOrder",
"name",
"createdAt",
- "createdBy",
- "updatedBy",
+ "description",
+ "type",
+ "fileTypes",
"required",
- "fileTypes"
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "purchasingRfqLine",
"rows": 0,
"columns": [
- "order",
+ "createdBy",
+ "updatedBy",
+ "quantity",
+ "companyId",
+ "inventoryUnitOfMeasureCode",
+ "description",
+ "createdAt",
+ "itemId",
+ "purchaseUnitOfMeasureCode",
"id",
+ "order",
"externalNotes",
- "purchaseUnitOfMeasureCode",
- "updatedAt",
- "purchasingRfqId",
- "customFields",
"conversionFactor",
"internalNotes",
- "companyId",
- "quantity",
- "updatedBy",
- "createdBy",
- "createdAt",
- "itemId",
- "description",
- "inventoryUnitOfMeasureCode"
+ "updatedAt",
+ "customFields",
+ "purchasingRfqId"
]
},
{
"name": "qualityDocumentStep",
"rows": 0,
"columns": [
- "type",
"description",
- "createdAt",
"name",
- "updatedBy",
- "createdBy",
+ "createdAt",
+ "type",
"fileTypes",
"required",
- "unitOfMeasureCode",
- "maxValue",
+ "updatedBy",
+ "createdBy",
"updatedAt",
"qualityDocumentId",
"companyId",
- "sortOrder",
+ "unitOfMeasureCode",
+ "maxValue",
"id",
"minValue",
- "listValues"
+ "listValues",
+ "sortOrder"
]
},
{
"name": "riskRegister",
"rows": 0,
"columns": [
- "createdAt",
- "companyId",
- "type",
- "status",
- "likelihood",
- "assignee",
- "id",
- "itemId",
- "sourceId",
- "description",
+ "createdBy",
+ "source",
+ "updatedBy",
+ "notes",
"updatedAt",
"title",
+ "description",
"severity",
- "source",
- "createdBy",
- "notes",
- "updatedBy"
+ "assignee",
+ "itemId",
+ "id",
+ "sourceId",
+ "companyId",
+ "createdAt",
+ "type",
+ "status",
+ "likelihood"
]
},
{
"name": "trackedEntity",
"rows": 0,
"columns": [
- "attributes",
- "updatedBy",
- "status",
- "sourceDocument",
- "itemId",
- "sourceDocumentId",
- "createdBy",
- "companyId",
- "quantity",
"expirationDate",
- "sourceDocumentReadableId",
- "readableId",
+ "quantity",
+ "companyId",
+ "createdBy",
+ "id",
"createdAt",
- "id"
+ "readableId",
+ "sourceDocumentReadableId",
+ "sourceDocument",
+ "status",
+ "updatedBy",
+ "attributes",
+ "sourceDocumentId",
+ "itemId"
]
},
{
"name": "nonConformanceItemTrackedEntity",
"rows": 0,
"columns": [
+ "quantity",
+ "createdAt",
+ "nonConformanceId",
+ "trackedEntityId",
"companyId",
"updatedAt",
"id",
- "updatedBy",
"createdBy",
- "nonConformanceItemId",
- "quantity",
- "createdAt",
- "nonConformanceId",
- "trackedEntityId"
+ "updatedBy",
+ "nonConformanceItemId"
]
},
{
@@ -3252,8 +3252,8 @@
"createdBy",
"id",
"updatedAt",
- "companyId",
"trackedEntityId",
+ "companyId",
"createdAt"
]
},
@@ -3262,12 +3262,12 @@
"rows": 0,
"columns": [
"companyId",
- "quantity",
"createdBy",
- "trackedActivityId",
+ "quantity",
"createdAt",
- "trackedEntityId",
- "updatedBy"
+ "trackedActivityId",
+ "updatedBy",
+ "trackedEntityId"
]
},
{
@@ -3275,11 +3275,11 @@
"rows": 0,
"columns": [
"trackedEntityId",
- "createdBy",
"trackedActivityId",
- "updatedBy",
- "companyId",
+ "createdBy",
"quantity",
+ "companyId",
+ "updatedBy",
"createdAt"
]
},
@@ -3341,13 +3341,13 @@
"name": "userModulePreference",
"rows": 0,
"columns": [
- "id",
- "hidden",
"userId",
- "position",
- "module",
+ "hidden",
+ "id",
+ "updatedAt",
"companyId",
- "updatedAt"
+ "module",
+ "position"
]
},
{
@@ -3359,181 +3359,181 @@
"name": "warehouse",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "active",
- "requiresBin",
+ "requiresShipment",
+ "companyId",
"updatedBy",
"name",
- "companyId",
- "requiresShipment",
- "requiresPutAway",
- "createdAt",
+ "requiresBin",
+ "id",
+ "active",
+ "createdBy",
+ "requiresReceive",
"requiresPick",
"updatedAt",
"locationId",
- "requiresReceive"
+ "requiresPutAway",
+ "createdAt"
]
},
{
"name": "warehouseTransfer",
"rows": 0,
"columns": [
- "transferDate",
- "createdBy",
- "id",
- "reference",
- "companyId",
- "notes",
- "updatedBy",
- "transferId",
- "tags",
- "customFields",
"status",
"createdAt",
- "expectedReceiptDate",
- "toLocationId",
+ "customFields",
"fromLocationId",
- "updatedAt"
+ "updatedAt",
+ "toLocationId",
+ "expectedReceiptDate",
+ "reference",
+ "id",
+ "createdBy",
+ "transferDate",
+ "tags",
+ "updatedBy",
+ "transferId",
+ "notes",
+ "companyId"
]
},
{
"name": "workCenter",
"rows": 0,
"columns": [
- "companyId",
- "requiredAbilityId",
- "id",
- "active",
- "locationId",
- "createdBy",
- "name",
- "updatedAt",
- "alwaysOn",
- "updatedBy",
- "machineRate",
- "laborRate",
- "customFields",
- "departmentId",
- "batchCapacity",
- "defaultStandardFactor",
- "minimumBatchQuantity",
"tags",
"overheadRate",
"description",
- "createdAt"
+ "createdAt",
+ "minimumBatchQuantity",
+ "defaultStandardFactor",
+ "laborRate",
+ "departmentId",
+ "customFields",
+ "batchCapacity",
+ "updatedBy",
+ "alwaysOn",
+ "machineRate",
+ "createdBy",
+ "name",
+ "updatedAt",
+ "active",
+ "locationId",
+ "companyId",
+ "id",
+ "requiredAbilityId"
]
},
{
"name": "enforcementRuleWorkCenterAssignment",
"rows": 0,
"columns": [
- "createdBy",
- "companyId",
"createdAt",
- "ruleId",
+ "companyId",
+ "createdBy",
"updatedBy",
- "workCenterId"
+ "workCenterId",
+ "ruleId"
]
},
{
"name": "jobOperationBatch",
"rows": 0,
"columns": [
- "updatedAt",
- "readableId",
- "createdBy",
- "notes",
- "createdAt",
- "id",
- "customFields",
- "locationId",
+ "outputLotNumber",
+ "updatedBy",
+ "workCenterId",
+ "status",
"processId",
- "mergeOutput",
"companyId",
- "status",
- "workCenterId",
- "updatedBy",
- "outputLotNumber"
+ "mergeOutput",
+ "locationId",
+ "id",
+ "customFields",
+ "createdAt",
+ "notes",
+ "createdBy",
+ "readableId",
+ "updatedAt"
]
},
{
"name": "maintenanceSchedule",
"rows": 0,
"columns": [
- "updatedBy",
- "description",
- "workCenterId",
- "thursday",
- "wednesday",
"estimatedDuration",
"skipHolidays",
- "sunday",
- "frequency",
- "createdBy",
- "friday",
+ "thursday",
+ "wednesday",
+ "description",
+ "updatedBy",
+ "workCenterId",
"saturday",
"updatedAt",
"tuesday",
"takesWorkCenterOffline",
- "monday",
- "createdAt",
- "name",
- "active",
+ "frequency",
+ "createdBy",
+ "friday",
+ "sunday",
"locationId",
"nextDueAt",
- "lastGeneratedAt",
- "id",
- "companyId",
+ "active",
+ "createdAt",
+ "name",
+ "monday",
+ "procedureId",
"priority",
- "procedureId"
+ "companyId",
+ "lastGeneratedAt",
+ "id"
]
},
{
"name": "maintenanceDispatch",
"rows": 0,
"columns": [
- "assignee",
- "completedAt",
- "status",
- "content",
"actualStartTime",
- "updatedBy",
+ "content",
+ "status",
+ "completedAt",
+ "assignee",
"locationId",
- "priority",
- "companyId",
- "plannedStartTime",
+ "updatedBy",
"createdAt",
+ "plannedStartTime",
+ "companyId",
+ "priority",
+ "nonConformanceId",
"actualEndTime",
"createdBy",
- "nonConformanceId",
- "plannedEndTime",
"maintenanceDispatchId",
- "updatedAt",
- "suspectedFailureModeId",
- "workCenterId",
- "takesWorkCenterOffline",
+ "plannedEndTime",
"procedureId",
- "severity",
- "actualFailureModeId",
- "id",
+ "takesWorkCenterOffline",
+ "workCenterId",
+ "suspectedFailureModeId",
+ "updatedAt",
"maintenanceScheduleId",
- "oeeImpact",
- "source"
+ "id",
+ "actualFailureModeId",
+ "severity",
+ "source",
+ "oeeImpact"
]
},
{
"name": "maintenanceDispatchComment",
"rows": 0,
"columns": [
+ "createdBy",
"updatedBy",
"comment",
"companyId",
- "createdBy",
- "updatedAt",
- "maintenanceDispatchId",
"createdAt",
- "id"
+ "id",
+ "updatedAt",
+ "maintenanceDispatchId"
]
},
{
@@ -3541,163 +3541,163 @@
"rows": 0,
"columns": [
"createdBy",
- "updatedAt",
"maintenanceDispatchId",
+ "updatedAt",
"endTime",
- "createdAt",
"companyId",
"id",
+ "createdAt",
"notes",
"employeeId",
"workCenterId",
- "startTime",
- "updatedBy"
+ "updatedBy",
+ "startTime"
]
},
{
"name": "maintenanceDispatchItem",
"rows": 0,
"columns": [
+ "unitOfMeasureCode",
+ "updatedAt",
+ "itemId",
+ "quantity",
"updatedBy",
- "id",
"createdBy",
+ "id",
"unitCost",
"maintenanceDispatchId",
"createdAt",
- "companyId",
- "updatedAt",
- "unitOfMeasureCode",
- "quantity",
- "itemId"
+ "companyId"
]
},
{
"name": "maintenanceDispatchItemTrackedEntity",
"rows": 0,
"columns": [
- "companyId",
- "trackedEntityId",
- "quantity",
"createdAt",
- "updatedAt",
- "id",
- "createdBy",
+ "quantity",
+ "trackedEntityId",
+ "companyId",
+ "updatedBy",
"maintenanceDispatchItemId",
- "updatedBy"
+ "createdBy",
+ "id",
+ "updatedAt"
]
},
{
"name": "maintenanceDispatchWorkCenter",
"rows": 0,
"columns": [
- "companyId",
- "workCenterId",
- "updatedBy",
- "createdBy",
- "maintenanceDispatchId",
- "updatedAt",
+ "createdAt",
"id",
- "createdAt"
+ "updatedAt",
+ "maintenanceDispatchId",
+ "createdBy",
+ "updatedBy",
+ "companyId",
+ "workCenterId"
]
},
{
"name": "maintenanceScheduleItem",
"rows": 0,
"columns": [
- "maintenanceScheduleId",
- "createdAt",
- "updatedAt",
+ "companyId",
"updatedBy",
"id",
- "companyId",
- "itemId",
- "quantity",
+ "updatedAt",
+ "createdAt",
+ "maintenanceScheduleId",
+ "unitOfMeasureCode",
"createdBy",
- "unitOfMeasureCode"
+ "itemId",
+ "quantity"
]
},
{
"name": "peopleAssignment",
"rows": 0,
"columns": [
- "shiftId",
- "workCenterId",
- "hours",
- "locationId",
- "updatedAt",
- "employeeId",
- "note",
- "createdAt",
- "companyId",
"overtimeHours",
- "date",
+ "companyId",
+ "createdAt",
+ "note",
+ "updatedBy",
"id",
"createdBy",
- "updatedBy"
+ "date",
+ "workCenterId",
+ "locationId",
+ "hours",
+ "shiftId",
+ "employeeId",
+ "updatedAt"
]
},
{
"name": "storageUnit",
"rows": 0,
"columns": [
- "createdAt",
- "warehouseId",
- "storageTypeIds",
"active",
- "workCenterId",
+ "storageTypeIds",
+ "warehouseId",
+ "createdAt",
"companyId",
"tags",
- "updatedBy",
- "customFields",
- "isWorkCenterDefault",
+ "workCenterId",
"parentId",
"locationId",
- "createdBy",
- "updatedAt",
+ "isWorkCenterDefault",
+ "customFields",
+ "updatedBy",
+ "name",
"id",
- "name"
+ "updatedAt",
+ "createdBy"
]
},
{
"name": "itemLedger",
"rows": 0,
"columns": [
- "documentId",
- "id",
- "storageUnitId",
- "itemId",
- "scrapReasonId",
- "locationId",
- "documentLineId",
- "companyId",
- "entryNumber",
- "createdBy",
- "trackedEntityStatus",
- "updatedBy",
"documentType",
"comment",
"quantity",
- "correctionOfItemLedgerId",
- "externalDocumentId",
+ "updatedBy",
+ "trackedEntityStatus",
+ "createdBy",
+ "trackedEntityId",
"entryType",
- "createdAt",
"postingDate",
- "trackedEntityId"
+ "createdAt",
+ "correctionOfItemLedgerId",
+ "externalDocumentId",
+ "storageUnitId",
+ "id",
+ "documentId",
+ "companyId",
+ "entryNumber",
+ "documentLineId",
+ "scrapReasonId",
+ "locationId",
+ "itemId"
]
},
{
"name": "pickMethod",
"rows": 0,
"columns": [
- "locationId",
"updatedAt",
"sortMethod",
- "customFields",
- "itemId",
+ "locationId",
"createdAt",
- "defaultStorageUnitId",
- "companyId",
+ "itemId",
+ "customFields",
"updatedBy",
+ "companyId",
+ "defaultStorageUnitId",
"createdBy"
]
},
@@ -3743,83 +3743,83 @@
"rows": 0,
"columns": [
"unitOfMeasureCode",
+ "createdBy",
"itemId",
"quantity",
- "createdBy",
+ "companyId",
"updatedBy",
"id",
- "companyId",
- "workCenterId",
+ "updatedAt",
"createdAt",
- "updatedAt"
+ "workCenterId"
]
},
{
"name": "workCenterShift",
"rows": 0,
"columns": [
- "createdBy",
- "shiftId",
- "workCenterId",
"updatedBy",
- "id",
- "createdAt",
+ "workCenterId",
+ "shiftId",
+ "createdBy",
+ "updatedAt",
"companyId",
- "updatedAt"
+ "createdAt",
+ "id"
]
},
{
"name": "cardTransaction",
"rows": 0,
"columns": [
- "createdAt",
"integration",
- "updatedAt",
- "cardHolderName",
- "id",
+ "createdAt",
"supplierId",
+ "id",
+ "cardHolderName",
+ "updatedAt",
+ "offsetAccountId",
"merchantName",
"createdBy",
- "offsetAccountId",
+ "currencyCode",
"companyId",
"memo",
- "currencyCode",
- "updatedBy",
"exchangeRate",
- "postedBy",
+ "updatedBy",
"postingDate",
- "postedAt",
+ "postedBy",
+ "voidedAt",
"cardLast4",
+ "postedAt",
"status",
- "voidedAt",
"customFields",
- "voidedBy",
"cardAccountId",
- "amount",
- "journalId",
- "type",
+ "voidedBy",
+ "transactionDate",
"cardTransactionId",
- "transactionDate"
+ "type",
+ "amount",
+ "journalId"
]
},
{
"name": "cardTransactionLine",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "updatedBy",
- "description",
- "customFields",
- "companyId",
- "sequence",
- "createdAt",
- "costCenterId",
- "updatedAt",
+ "amount",
"projectId",
"cardTransactionId",
"accountId",
- "amount"
+ "updatedAt",
+ "costCenterId",
+ "createdAt",
+ "sequence",
+ "companyId",
+ "customFields",
+ "description",
+ "updatedBy",
+ "createdBy",
+ "id"
]
},
{
@@ -3854,24 +3854,24 @@
"name": "costLedger",
"rows": 0,
"columns": [
- "companyId",
- "supplierId",
- "costLedgerType",
"quantity",
- "documentType",
- "postingDate",
+ "costLedgerType",
+ "supplierId",
+ "companyId",
+ "remainingQuantity",
+ "appliesToCostLedgerId",
"nominalCost",
+ "postingDate",
"itemLedgerType",
- "appliesToCostLedgerId",
- "remainingQuantity",
- "adjustment",
+ "documentType",
"externalDocumentId",
"id",
- "documentId",
- "itemId",
- "createdAt",
+ "adjustment",
+ "entryNumber",
"cost",
- "entryNumber"
+ "createdAt",
+ "itemId",
+ "documentId"
]
},
{
@@ -3913,63 +3913,63 @@
"name": "customerBankAccount",
"rows": 0,
"columns": [
- "bankName",
- "bankCode",
- "currencyCode",
- "id",
- "accountNumber",
- "countryCode",
+ "createdBy",
"companyId",
"isPrimary",
- "createdBy",
- "createdAt",
- "notes",
- "tags",
+ "countryCode",
+ "accountNumber",
+ "currencyCode",
+ "id",
+ "bankCode",
+ "bankName",
+ "active",
+ "customerId",
+ "name",
+ "updatedBy",
+ "updatedAt",
+ "bankAddress",
"swiftBic",
"customFields",
"accountHolderName",
- "bankAddress",
- "updatedBy",
- "updatedAt",
- "active",
- "customerId",
- "name"
+ "createdAt",
+ "notes",
+ "tags"
]
},
{
"name": "customerItemPriceOverride",
"rows": 0,
"columns": [
+ "notes",
+ "createdAt",
"validTo",
- "itemId",
"updatedAt",
"customerTypeId",
- "notes",
- "createdAt",
- "companyId",
- "active",
- "updatedBy",
- "customerId",
+ "itemId",
"validFrom",
"createdBy",
+ "applyRulesOnTop",
"id",
- "applyRulesOnTop"
+ "companyId",
+ "active",
+ "updatedBy",
+ "customerId"
]
},
{
"name": "customerItemPriceOverrideBreak",
"rows": 0,
"columns": [
- "companyId",
+ "active",
+ "overridePrice",
+ "quantity",
+ "createdBy",
"id",
"updatedBy",
- "createdAt",
- "updatedAt",
+ "companyId",
"customerItemPriceOverrideId",
- "active",
- "createdBy",
- "overridePrice",
- "quantity"
+ "updatedAt",
+ "createdAt"
]
},
{
@@ -4003,42 +4003,42 @@
"name": "customerPartToItem",
"rows": 0,
"columns": [
- "customerPartId",
- "customerId",
- "id",
+ "companyId",
"itemId",
"customerPartRevision",
- "companyId"
+ "customerId",
+ "id",
+ "customerPartId"
]
},
{
"name": "customerPayment",
"rows": 0,
"columns": [
- "invoiceCustomerId",
- "updatedAt",
- "customerId",
- "updatedBy",
- "invoiceCustomerContactId",
+ "paymentTermId",
"invoiceCustomerLocationId",
+ "invoiceCustomerContactId",
"companyId",
- "paymentTermId"
+ "updatedBy",
+ "customerId",
+ "invoiceCustomerId",
+ "updatedAt"
]
},
{
"name": "customerShipping",
"rows": 0,
"columns": [
- "updatedAt",
- "incoterm",
"shippingCustomerId",
- "shippingMethodId",
- "customerId",
- "updatedBy",
+ "incoterm",
+ "updatedAt",
"incotermLocation",
- "companyId",
- "shippingCustomerContactId",
+ "updatedBy",
+ "customerId",
+ "shippingMethodId",
"shippingCustomerLocationId",
+ "shippingCustomerContactId",
+ "companyId",
"shippingTermId"
]
},
@@ -4046,318 +4046,318 @@
"name": "customerTax",
"rows": 0,
"columns": [
- "vatNumber",
- "eori",
- "taxExemptionCertificateNumber",
- "taxExempt",
- "taxId",
- "taxExemptionCertificatePath",
- "updatedAt",
+ "taxExemptionReason",
"companyId",
"customerId",
"updatedBy",
- "taxExemptionReason"
+ "taxExemptionCertificatePath",
+ "updatedAt",
+ "taxId",
+ "taxExempt",
+ "taxExemptionCertificateNumber",
+ "vatNumber",
+ "eori"
]
},
{
"name": "fixture",
"rows": 0,
"columns": [
- "createdBy",
+ "customFields",
+ "updatedAt",
+ "id",
+ "createdAt",
"updatedBy",
+ "createdBy",
"tags",
"itemId",
- "customFields",
- "createdAt",
- "id",
- "updatedAt",
+ "approvedBy",
"companyId",
- "customerId",
"approved",
- "approvedBy"
+ "customerId"
]
},
{
"name": "nonConformanceCustomer",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "customerId",
- "createdAt",
+ "createdBy",
+ "id",
"updatedBy",
"nonConformanceId",
- "createdBy",
- "id"
+ "createdAt",
+ "updatedAt",
+ "customerId",
+ "companyId"
]
},
{
"name": "opportunity",
"rows": 0,
"columns": [
- "requestForQuoteDocumentPath",
- "companyId",
"customerId",
"id",
- "purchaseOrderDocumentPath"
+ "purchaseOrderDocumentPath",
+ "companyId",
+ "requestForQuoteDocumentPath"
]
},
{
"name": "salesOrder",
"rows": 0,
"columns": [
- "customFields",
- "companyId",
- "salesOrderId",
- "completedDate",
- "customerEngineeringContactId",
- "customerId",
- "externalNotes",
- "customerContactId",
- "customerLocationId",
- "id",
- "customerReference",
- "sentCompleteDate",
- "internalNotes",
+ "opportunityId",
+ "exchangeRateUpdatedAt",
+ "currencyCode",
+ "createdBy",
+ "updatedAt",
+ "status",
"closedAt",
"revisionId",
- "status",
- "updatedAt",
- "createdBy",
- "currencyCode",
- "exchangeRateUpdatedAt",
- "opportunityId",
- "exchangeRate",
- "orderDate",
- "assignee",
- "updatedBy",
+ "salesPersonId",
+ "createdAt",
"locationId",
"closedBy",
- "createdAt",
- "salesPersonId"
+ "updatedBy",
+ "assignee",
+ "orderDate",
+ "exchangeRate",
+ "customerContactId",
+ "externalNotes",
+ "customerEngineeringContactId",
+ "customerId",
+ "completedDate",
+ "salesOrderId",
+ "companyId",
+ "customFields",
+ "internalNotes",
+ "sentCompleteDate",
+ "customerReference",
+ "id",
+ "customerLocationId"
]
},
{
"name": "salesOrderFavorite",
"rows": 0,
- "columns": ["userId", "salesOrderId"]
+ "columns": ["salesOrderId", "userId"]
},
{
"name": "salesOrderLine",
"rows": 0,
"columns": [
- "taxPercent",
- "priceTrace",
- "quantitySent",
- "customFields",
- "saleQuantity",
- "id",
- "sortOrder",
- "updatedAt",
- "externalNotes",
- "quantityInvoiced",
- "salesOrderId",
- "locationId",
+ "exchangeRate",
"sentDate",
"createdBy",
- "exchangeRate",
- "accountId",
"modelUploadId",
"promisedDate",
"description",
- "addOnCost",
- "invoicedComplete",
- "companyId",
- "unitOfMeasureCode",
- "pricingRuleId",
- "storageUnitId",
- "updatedBy",
- "sentComplete",
+ "accountId",
+ "salesOrderId",
+ "externalNotes",
+ "quantityInvoiced",
+ "locationId",
+ "updatedAt",
+ "priceTrace",
+ "quantitySent",
+ "customFields",
+ "taxPercent",
+ "saleQuantity",
+ "sortOrder",
+ "id",
+ "methodType",
+ "status",
+ "assetId",
+ "createdAt",
+ "shippingCost",
+ "nonTaxableAddOnCost",
"internalNotes",
"setupPrice",
+ "sentComplete",
"unitPrice",
"salesOrderLineType",
"itemId",
- "methodType",
- "assetId",
- "shippingCost",
- "createdAt",
- "nonTaxableAddOnCost",
- "status"
+ "storageUnitId",
+ "updatedBy",
+ "pricingRuleId",
+ "unitOfMeasureCode",
+ "addOnCost",
+ "invoicedComplete",
+ "companyId"
]
},
{
"name": "nonConformanceSalesOrderLine",
"rows": 0,
"columns": [
- "companyId",
- "updatedAt",
"id",
- "createdBy",
- "updatedBy",
+ "updatedAt",
+ "companyId",
"nonConformanceId",
+ "updatedBy",
+ "createdBy",
"salesOrderReadableId",
- "createdAt",
+ "salesOrderId",
"salesOrderLineId",
- "salesOrderId"
+ "createdAt"
]
},
{
"name": "salesOrderPayment",
"rows": 0,
"columns": [
- "invoiceCustomerId",
- "updatedBy",
- "companyId",
- "customFields",
"id",
"updatedAt",
+ "customFields",
"paymentComplete",
+ "invoiceCustomerId",
+ "companyId",
+ "updatedBy",
+ "paymentTermId",
"invoiceCustomerContactId",
- "invoiceCustomerLocationId",
- "paymentTermId"
+ "invoiceCustomerLocationId"
]
},
{
"name": "salesOrderShipment",
"rows": 0,
"columns": [
- "deliveryDate",
- "shippingTermId",
- "shippingMethodId",
- "supplierLocationId",
- "assignee",
- "customFields",
- "companyId",
"incoterm",
+ "companyId",
"updatedAt",
- "incotermLocation",
"receiptRequestedDate",
- "shippingCost",
"customerLocationId",
- "notes",
+ "shippingCost",
+ "incotermLocation",
+ "deliveryDate",
+ "assignee",
+ "customFields",
+ "supplierLocationId",
+ "shippingMethodId",
+ "shippingTermId",
+ "receiptPromisedDate",
+ "customerId",
+ "trackingNumber",
+ "id",
"dropShipment",
- "updatedBy",
+ "notes",
"supplierId",
"locationId",
- "receiptPromisedDate",
- "id",
- "trackingNumber",
- "customerId"
+ "updatedBy"
]
},
{
"name": "salesOrderStatusHistory",
"rows": 0,
"columns": [
- "salesOrderId",
- "id",
- "companyId",
+ "updatedBy",
"status",
"createdAt",
- "updatedBy",
- "createdBy"
+ "createdBy",
+ "salesOrderId",
+ "companyId",
+ "id"
]
},
{
"name": "salesOrderTransaction",
"rows": 0,
"columns": [
- "createdAt",
- "type",
- "userId",
+ "salesOrderId",
"companyId",
"id",
- "salesOrderId"
+ "type",
+ "userId",
+ "createdAt"
]
},
{
"name": "salesReturnOrder",
"rows": 0,
"columns": [
- "externalNotes",
- "salesReturnOrderId",
- "orderDate",
- "locationId",
- "replacementSalesOrderId",
- "id",
- "salesOrderId",
- "currencyCode",
- "customerContactId",
- "customerId",
- "expirationDate",
- "status",
- "companyId",
- "createdBy",
- "customFields",
- "customerReference",
"updatedAt",
- "createdAt",
"exchangeRate",
+ "createdAt",
"customerLocationId",
"assignee",
+ "updatedBy",
"internalNotes",
- "updatedBy"
+ "expirationDate",
+ "status",
+ "customerId",
+ "companyId",
+ "createdBy",
+ "customerReference",
+ "customFields",
+ "salesOrderId",
+ "id",
+ "currencyCode",
+ "customerContactId",
+ "externalNotes",
+ "salesReturnOrderId",
+ "orderDate",
+ "locationId",
+ "replacementSalesOrderId"
]
},
{
"name": "salesRfq",
"rows": 0,
"columns": [
+ "salesPersonId",
+ "customerId",
+ "noQuoteReasonId",
+ "id",
+ "rfqDate",
+ "expirationDate",
+ "internalNotes",
"customerEngineeringContactId",
"customerReference",
"completedDate",
- "internalNotes",
- "expirationDate",
- "customFields",
- "locationId",
"rfqId",
- "customerId",
- "salesPersonId",
- "id",
- "rfqDate",
- "noQuoteReasonId",
+ "locationId",
+ "customFields",
+ "tags",
+ "createdAt",
+ "companyId",
+ "customerLocationId",
+ "updatedBy",
+ "employeeId",
+ "opportunityId",
"externalNotes",
"customerContactId",
- "opportunityId",
+ "createdBy",
+ "updatedAt",
"status",
"assignee",
- "revisionId",
- "updatedAt",
- "createdBy",
- "companyId",
- "customerLocationId",
- "tags",
- "createdAt",
- "employeeId",
- "updatedBy"
+ "revisionId"
]
},
{
"name": "salesRfqFavorite",
"rows": 0,
- "columns": ["rfqId", "userId"]
+ "columns": ["userId", "rfqId"]
},
{
"name": "salesRfqLine",
"rows": 0,
"columns": [
- "unitOfMeasureCode",
"internalNotes",
- "updatedAt",
+ "unitOfMeasureCode",
"salesRfqId",
"customFields",
+ "updatedAt",
"description",
+ "externalNotes",
"id",
"order",
- "externalNotes",
"quantity",
- "createdAt",
"modelUploadId",
"customerPartId",
+ "createdAt",
"updatedBy",
- "tags",
"createdBy",
+ "tags",
"customerPartRevision",
"companyId",
"itemId"
@@ -4367,120 +4367,120 @@
"name": "externalLink",
"rows": 0,
"columns": [
- "createdAt",
- "companyId",
+ "documentType",
+ "supplierId",
+ "id",
+ "expiresAt",
"customerId",
"documentId",
- "expiresAt",
- "id",
- "supplierId",
- "documentType"
+ "companyId",
+ "createdAt"
]
},
{
"name": "quote",
"rows": 0,
"columns": [
- "customerId",
- "exchangeRateUpdatedAt",
+ "expirationDate",
+ "currencyCode",
"salesPersonId",
"id",
- "currencyCode",
- "expirationDate",
- "quoteId",
- "opportunityId",
- "customerContactId",
- "assignee",
- "digitalQuoteRejectedByEmail",
- "estimatorId",
- "internalNotes",
+ "customerId",
+ "exchangeRateUpdatedAt",
"digitalQuoteAcceptedBy",
"digitalQuoteAcceptedByEmail",
+ "internalNotes",
+ "digitalQuoteRejectedByEmail",
+ "estimatorId",
+ "assignee",
+ "customerContactId",
+ "quoteId",
+ "opportunityId",
+ "locationId",
+ "updatedAt",
+ "customFields",
+ "exchangeRate",
+ "updatedBy",
+ "dueDate",
"tags",
"customerLocationId",
"createdBy",
- "dueDate",
- "updatedBy",
- "customFields",
- "exchangeRate",
- "locationId",
- "updatedAt",
- "companyId",
- "createdAt",
- "customerReference",
- "revisionId",
- "digitalQuoteRejectedBy",
- "externalLinkId",
"completedDate",
"status",
"customerEngineeringContactId",
- "externalNotes"
+ "externalNotes",
+ "externalLinkId",
+ "digitalQuoteRejectedBy",
+ "customerReference",
+ "revisionId",
+ "createdAt",
+ "companyId"
]
},
{
"name": "job",
"rows": 0,
"columns": [
- "createdBy",
- "salesOrderLineId",
"notes",
"quantityReceivedToInventory",
- "assignee",
- "modelUploadId",
- "releasedDate",
+ "salesOrderLineId",
+ "createdBy",
"customerId",
- "updatedBy",
- "startDate",
- "customFields",
- "status",
+ "releasedDate",
+ "modelUploadId",
+ "assignee",
"completedDate",
- "unitOfMeasureCode",
- "itemId",
- "quantityShipped",
+ "status",
+ "customFields",
+ "startDate",
+ "updatedBy",
+ "quoteLineId",
"quoteId",
"projectedCompletionAt",
- "quoteLineId",
- "scheduleOutdatedAt",
- "locationId",
+ "itemId",
+ "quantityShipped",
+ "unitOfMeasureCode",
"createdAt",
- "id",
- "deadlineType",
- "updatedAt",
- "scrapQuantity",
+ "locationId",
+ "scheduleOutdatedAt",
"priority",
"storageUnitId",
- "dueDate",
- "configuration",
- "tags",
+ "scrapQuantity",
+ "updatedAt",
+ "deadlineType",
+ "id",
+ "companyId",
"quantity",
"estimatedTime",
- "companyId",
- "salesOrderId",
+ "tags",
+ "dueDate",
+ "configuration",
+ "quantityComplete",
+ "scheduleOutdatedReason",
"actualTime",
"jobId",
- "quantityComplete",
- "scheduleOutdatedReason"
+ "salesOrderId"
]
},
{
"name": "fulfillment",
"rows": 0,
"columns": [
- "salesOrderLineId",
"createdBy",
- "id",
- "updatedBy",
+ "salesOrderLineId",
"companyId",
- "quantity",
- "type",
+ "updatedBy",
+ "id",
"createdAt",
+ "type",
+ "quantity",
"jobId"
]
},
{
"name": "jobFavorite",
"rows": 0,
- "columns": ["jobId", "userId"]
+ "columns": ["userId", "jobId"]
},
{
"name": "quoteFavorite",
@@ -4491,484 +4491,484 @@
"name": "quoteLine",
"rows": 0,
"columns": [
- "taxPercent",
- "itemId",
- "unitPricePrecision",
- "customerPartRevision",
- "id",
- "description",
- "noQuoteReason",
"customerPartId",
- "itemType",
- "pricingRuleId",
+ "noQuoteReason",
"configuration",
- "unitOfMeasureCode",
+ "pricingRuleId",
+ "itemType",
"quoteId",
+ "unitOfMeasureCode",
"createdBy",
- "quantity",
- "companyId",
- "tags",
- "updatedAt",
- "estimatorId",
- "modelUploadId",
- "methodType",
- "priceTrace",
- "additionalCharges",
+ "taxPercent",
+ "itemId",
+ "customerPartRevision",
+ "unitPricePrecision",
+ "description",
+ "id",
"sortOrder",
- "locationId",
"externalNotes",
- "customFields",
+ "locationId",
"updatedBy",
- "status",
+ "customFields",
+ "internalNotes",
"quoteRevisionId",
- "internalNotes"
+ "status",
+ "updatedAt",
+ "tags",
+ "companyId",
+ "quantity",
+ "priceTrace",
+ "methodType",
+ "modelUploadId",
+ "estimatorId",
+ "additionalCharges"
]
},
{
"name": "quoteLinePrice",
"rows": 0,
"columns": [
- "priceSource",
- "createdAt",
"companyId",
"updatedBy",
"quoteId",
+ "priceSource",
+ "createdAt",
+ "createdBy",
"categoryMarkups",
"leadTime",
- "createdBy",
- "discountPercent",
"quantity",
"unitPrice",
"quoteLineId",
+ "discountPercent",
+ "updatedAt",
"shippingCost",
- "exchangeRate",
- "updatedAt"
+ "exchangeRate"
]
},
{
"name": "quotePayment",
"rows": 0,
"columns": [
- "updatedAt",
+ "companyId",
+ "invoiceCustomerLocationId",
+ "invoiceCustomerContactId",
+ "paymentTermId",
"customFields",
+ "updatedAt",
"invoiceCustomerId",
- "id",
"updatedBy",
- "companyId",
- "invoiceCustomerContactId",
- "invoiceCustomerLocationId",
- "paymentTermId"
+ "id"
]
},
{
"name": "quoteShipment",
"rows": 0,
"columns": [
- "updatedBy",
- "shippingTermId",
"shippingMethodId",
+ "shippingTermId",
+ "updatedBy",
"incotermLocation",
"receiptRequestedDate",
- "updatedAt",
"locationId",
- "companyId",
+ "updatedAt",
"incoterm",
+ "shippingCost",
"id",
- "shippingCost"
+ "companyId"
]
},
{
"name": "capacityReservation",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "workHours",
- "createdBy",
- "endAt",
+ "jobId",
"createdAt",
- "scenarioId",
"id",
- "jobId",
+ "scenarioId",
+ "createdBy",
+ "endAt",
+ "companyId",
+ "updatedAt",
+ "workHours",
+ "isPlaceholder",
+ "scheduleNote",
+ "updatedBy",
+ "operationId",
+ "startAt",
"jobOperationBatchId",
- "earliestStartAt",
- "resourceKind",
"resourceId",
- "startAt",
- "operationId",
- "updatedBy",
- "scheduleNote",
- "isPlaceholder"
+ "earliestStartAt",
+ "resourceKind"
]
},
{
"name": "gauge",
"rows": 0,
"columns": [
+ "createdBy",
+ "calibrationIntervalInMonths",
+ "serialNumber",
+ "updatedBy",
+ "companyId",
+ "locationId",
+ "updatedAt",
+ "customFields",
+ "createdAt",
+ "modelNumber",
+ "supplierId",
+ "nextCalibrationDate",
+ "lastCalibrationStatus",
+ "dateAcquired",
"gaugeRole",
- "gaugeCalibrationStatus",
"id",
+ "gaugeCalibrationStatus",
"description",
- "lastCalibrationDate",
"gaugeId",
+ "lastCalibrationDate",
"storageUnitId",
"gaugeStatus",
- "gaugeTypeId",
- "serialNumber",
- "calibrationIntervalInMonths",
- "createdBy",
- "updatedBy",
- "updatedAt",
- "locationId",
- "companyId",
- "createdAt",
- "customFields",
- "nextCalibrationDate",
- "supplierId",
- "modelNumber",
- "dateAcquired",
- "lastCalibrationStatus"
+ "gaugeTypeId"
]
},
{
"name": "gaugeCalibrationRecord",
"rows": 0,
"columns": [
- "calibrationAttempts",
- "createdBy",
- "requiresAction",
- "humidity",
- "supplierId",
- "inspectionStatus",
- "updatedBy",
- "dateCalibrated",
- "approvedBy",
- "measurementStandard",
- "requiresRepair",
- "id",
"customFields",
+ "id",
"createdAt",
"requiresAdjustment",
"temperature",
- "gaugeId",
"updatedAt",
+ "gaugeId",
"notes",
- "companyId"
+ "companyId",
+ "requiresAction",
+ "createdBy",
+ "calibrationAttempts",
+ "supplierId",
+ "humidity",
+ "updatedBy",
+ "dateCalibrated",
+ "inspectionStatus",
+ "measurementStandard",
+ "approvedBy",
+ "requiresRepair"
]
},
{
"name": "inspection",
"rows": 0,
"columns": [
- "updatedAt",
- "itemReadableId",
- "sampleSize",
- "inspectionDocumentId",
- "samplingStandard",
- "id",
+ "status",
+ "notes",
+ "aql",
+ "sourceDocument",
+ "createdAt",
+ "supplierId",
+ "dispositionedBy",
+ "acceptanceNumber",
+ "sourceDocumentReadableId",
+ "itemId",
+ "companyId",
+ "updatedBy",
+ "codeLetter",
+ "dispositionedAt",
+ "inspectionLevel",
+ "inspectionId",
+ "rejectionNumber",
+ "severity",
"samplingPlanType",
"createdBy",
- "sourceDocumentId",
"lotSize",
"sourceDocumentLineId",
- "inspectionId",
- "rejectionNumber",
- "severity",
- "codeLetter",
- "updatedBy",
- "inspectionLevel",
- "dispositionedAt",
- "sourceDocumentReadableId",
- "acceptanceNumber",
- "dispositionedBy",
- "itemId",
- "companyId",
- "sourceDocument",
- "supplierId",
- "createdAt",
- "status",
- "notes",
- "aql"
+ "sourceDocumentId",
+ "inspectionDocumentId",
+ "sampleSize",
+ "id",
+ "samplingStandard",
+ "updatedAt",
+ "itemReadableId"
]
},
{
"name": "inspectionSample",
"rows": 0,
"columns": [
- "notes",
- "updatedBy",
"inspectedAt",
- "status",
"trackedEntityId",
+ "status",
+ "notes",
+ "updatedBy",
+ "companyId",
+ "createdBy",
+ "inspectionId",
"inspectedBy",
- "updatedAt",
- "id",
"createdAt",
- "createdBy",
- "companyId",
- "inspectionId"
+ "id",
+ "updatedAt"
]
},
{
"name": "inspectionMeasurement",
"rows": 0,
"columns": [
- "createdAt",
- "value",
- "inspectionFeatureId",
"inspectionSampleId",
"updatedAt",
+ "inspectionFeatureId",
"notes",
- "createdBy",
- "id",
- "inspectedAt",
- "status",
- "inspectionId",
+ "value",
+ "createdAt",
"updatedBy",
+ "inspectionId",
+ "inspectedBy",
"companyId",
- "inspectedBy"
+ "inspectedAt",
+ "id",
+ "createdBy",
+ "status"
]
},
{
"name": "inspectionSamplingPlan",
"rows": 0,
"columns": [
- "companyId",
- "createdAt",
- "inspectionId",
+ "updatedAt",
+ "acceptanceNumber",
+ "codeLetter",
+ "sampleSize",
+ "inspectionFeatureId",
"rejectionNumber",
- "createdBy",
"id",
+ "createdBy",
"updatedBy",
- "codeLetter",
- "inspectionFeatureId",
- "sampleSize",
- "acceptanceNumber",
- "updatedAt"
+ "companyId",
+ "createdAt",
+ "inspectionId"
]
},
{
"name": "nonConformanceInspection",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "nonConformanceId",
"createdAt",
- "updatedBy",
"companyId",
- "inspectionId"
+ "inspectionId",
+ "updatedBy",
+ "id",
+ "createdBy",
+ "nonConformanceId"
]
},
{
"name": "inspectionHistory",
"rows": 0,
"columns": [
- "severity",
+ "outcome",
+ "samplingStandard",
+ "createdBy",
+ "supplierId",
+ "createdAt",
+ "itemId",
+ "inspectionLevel",
"id",
"lotSize",
"defectsFound",
- "aql",
- "sampleSize",
+ "severity",
"updatedBy",
- "companyId",
"inspectionId",
- "createdBy",
- "samplingStandard",
- "outcome",
- "inspectionLevel",
- "supplierId",
- "createdAt",
- "itemId"
+ "companyId",
+ "aql",
+ "sampleSize"
]
},
{
"name": "itemReplenishment",
"rows": 0,
"columns": [
- "purchasingUnitOfMeasureCode",
+ "createdBy",
+ "conversionFactor",
+ "scrapPercentage",
+ "updatedAt",
"updatedBy",
+ "purchasingUnitOfMeasureCode",
"tags",
"leadTime",
- "scrapPercentage",
- "updatedAt",
- "createdBy",
- "conversionFactor",
- "manufacturingBlocked",
- "lotSize",
+ "requiresConfiguration",
+ "itemId",
+ "companyId",
+ "purchasingBlocked",
"customFields",
"preferredSupplierId",
"createdAt",
- "purchasingBlocked",
- "itemId",
- "requiresConfiguration",
- "companyId"
+ "manufacturingBlocked",
+ "lotSize"
]
},
{
"name": "jobMakeMethod",
"rows": 0,
"columns": [
- "version",
- "trackedEntityId",
- "quantityPerParent",
- "createdAt",
- "itemId",
- "parentMaterialId",
- "requiresBatchTracking",
- "companyId",
"id",
"updatedAt",
"customFields",
- "createdBy",
- "updatedBy",
+ "companyId",
"itemScrapPercentage",
"jobId",
- "requiresSerialTracking"
+ "requiresSerialTracking",
+ "createdBy",
+ "updatedBy",
+ "trackedEntityId",
+ "quantityPerParent",
+ "version",
+ "itemId",
+ "requiresBatchTracking",
+ "parentMaterialId",
+ "createdAt"
]
},
{
"name": "jobMaterial",
"rows": 0,
"columns": [
+ "updatedAt",
+ "createdAt",
+ "jobOperationId",
"estimatedQuantity",
"itemScrapPercentage",
"unitOfMeasureCode",
"jobMakeMethodId",
"itemType",
- "updatedAt",
- "createdAt",
- "jobOperationId",
- "companyId",
- "itemId",
- "updatedBy",
- "customFields",
"requiresSerialTracking",
"order",
"defaultStorageUnit",
"substitutedFromItemId",
- "quantity",
- "id",
+ "companyId",
+ "itemId",
+ "updatedBy",
+ "customFields",
"methodType",
"quantityIssued",
- "createdBy",
- "jobId",
- "unitCost",
+ "quantity",
+ "id",
"requiresBatchTracking",
"kit",
"description",
"substitutionFactor",
"scrapQuantity",
- "storageUnitId"
+ "storageUnitId",
+ "createdBy",
+ "jobId",
+ "unitCost"
]
},
{
"name": "stockTransferLine",
"rows": 0,
"columns": [
+ "fromStorageUnitId",
"trackedEntityId",
- "pickedQuantity",
"id",
- "fromStorageUnitId",
+ "pickedQuantity",
+ "quantity",
"requiresSerialTracking",
"stockTransferId",
"createdBy",
- "quantity",
- "itemId",
- "requiresBatchTracking",
"createdAt",
"updatedAt",
+ "itemId",
+ "requiresBatchTracking",
+ "toStorageUnitId",
"updatedBy",
- "jobId",
- "companyId",
"jobMaterialId",
- "toStorageUnitId"
+ "companyId",
+ "jobId"
]
},
{
"name": "jobMaterialStep",
"rows": 0,
- "columns": ["quantity", "jobMaterialId", "jobOperationStepId"]
+ "columns": ["jobOperationStepId", "jobMaterialId", "quantity"]
},
{
"name": "jobOperation",
"rows": 0,
"columns": [
- "hasConflict",
- "workCenterId",
- "createdAt",
- "readyAt",
- "inspectionDocumentId",
- "id",
- "projectedCompletionAt",
- "setupUnit",
- "updatedAt",
- "laborUnit",
- "tags",
- "procedureId",
- "setupTime",
- "operationQuantity",
- "customFields",
- "targetQuantity",
- "quantityReworked",
- "laborTime",
- "companyId",
"conflictReason",
"overheadRate",
- "status",
"jobId",
+ "status",
"dueDate",
"machineUnit",
- "manuallyScheduled",
- "createdBy",
- "machineRate",
- "laborRate",
- "operationUnitCost",
- "operationSupplierProcessId",
- "reworkId",
- "operationLeadTime",
- "quantityComplete",
- "machineTime",
- "processId",
- "updatedBy",
- "assignee",
- "workInstruction",
- "priority",
- "description",
- "quantityScrapped",
+ "customFields",
+ "operationQuantity",
+ "setupTime",
+ "targetQuantity",
+ "quantityReworked",
+ "laborTime",
+ "companyId",
+ "inspectionDocumentId",
+ "setupUnit",
+ "projectedCompletionAt",
+ "id",
+ "laborUnit",
+ "updatedAt",
+ "tags",
+ "procedureId",
+ "workCenterId",
+ "hasConflict",
+ "createdAt",
+ "readyAt",
"jobOperationBatchId",
- "order",
- "jobMakeMethodId",
"operationOrder",
+ "jobMakeMethodId",
+ "order",
"startDate",
"operationType",
+ "operationMinimumCost",
"assemblyInstructionId",
- "operationMinimumCost"
+ "updatedBy",
+ "priority",
+ "description",
+ "workInstruction",
+ "assignee",
+ "quantityScrapped",
+ "reworkId",
+ "operationSupplierProcessId",
+ "quantityComplete",
+ "machineTime",
+ "operationLeadTime",
+ "processId",
+ "manuallyScheduled",
+ "machineRate",
+ "createdBy",
+ "laborRate",
+ "operationUnitCost"
]
},
{
"name": "jobOperationDependency",
"rows": 0,
"columns": [
- "dependsOnId",
- "operationId",
- "jobId",
+ "createdAt",
"companyId",
- "createdAt"
+ "jobId",
+ "operationId",
+ "dependsOnId"
]
},
{
"name": "jobOperationParameter",
"rows": 0,
"columns": [
- "updatedBy",
"id",
+ "updatedBy",
"createdAt",
"key",
"updatedAt",
"companyId",
- "value",
"operationId",
+ "value",
"createdBy"
]
},
@@ -4976,15 +4976,15 @@
"name": "jobOperationTool",
"rows": 0,
"columns": [
- "updatedBy",
- "id",
"createdAt",
- "operationId",
+ "id",
+ "updatedBy",
"updatedAt",
+ "operationId",
"companyId",
- "toolId",
+ "createdBy",
"quantity",
- "createdBy"
+ "toolId"
]
},
{
@@ -4992,36 +4992,36 @@
"rows": 0,
"columns": [
"jobReadableId",
- "jobId",
"jobOperationId",
+ "jobId",
"createdAt",
- "id",
"updatedAt",
+ "id",
"companyId",
"nonConformanceId",
- "createdBy",
- "updatedBy"
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "pickingListLine",
"rows": 0,
"columns": [
- "jobOperationId",
"status",
- "createdAt",
+ "jobOperationId",
"updatedAt",
- "quantityReturned",
+ "createdAt",
"customFields",
+ "quantityReturned",
+ "jobMaterialId",
"jobId",
"createdBy",
- "jobMaterialId",
"quantityToPick",
"toStorageUnitId",
"id",
"itemId",
- "companyId",
"pickingListId",
+ "companyId",
"updatedBy",
"storageUnitId",
"quantityPicked"
@@ -5042,138 +5042,138 @@
"name": "productionEvent",
"rows": 0,
"columns": [
+ "createdBy",
+ "companyId",
+ "id",
"createdAt",
"workCenterId",
"updatedBy",
"jobOperationId",
"postedToGL",
- "createdBy",
- "companyId",
- "id",
- "employeeId",
- "type",
- "startTime",
"notes",
"jobOperationBatchId",
"endTime",
- "updatedAt"
+ "updatedAt",
+ "employeeId",
+ "type",
+ "startTime"
]
},
{
"name": "productionQuantity",
"rows": 0,
"columns": [
- "quantity",
- "scrapReasonId",
- "type",
- "machineProductionEventId",
- "updatedAt",
- "setupProductionEventId",
- "inspectionId",
- "inspectionSampleId",
+ "laborProductionEventId",
+ "createdBy",
+ "companyId",
+ "id",
+ "createdAt",
+ "notes",
"jobOperationId",
"updatedBy",
- "notes",
- "createdAt",
- "id",
- "companyId",
- "createdBy",
- "laborProductionEventId"
+ "inspectionSampleId",
+ "inspectionId",
+ "updatedAt",
+ "setupProductionEventId",
+ "machineProductionEventId",
+ "type",
+ "scrapReasonId",
+ "quantity"
]
},
{
"name": "jobOperationNote",
"rows": 0,
"columns": [
- "companyId",
- "note",
- "updatedBy",
"createdAt",
- "jobOperationId",
- "updatedAt",
- "id",
+ "updatedBy",
+ "note",
+ "companyId",
+ "createdBy",
"productionQuantityId",
- "createdBy"
+ "id",
+ "updatedAt",
+ "jobOperationId"
]
},
{
"name": "rework",
"rows": 0,
"columns": [
- "targetJobOperationId",
- "triggeredAtJobOperationId",
- "updatedAt",
- "reason",
+ "jobId",
"companyId",
"requestedById",
- "jobId",
- "quantity",
"createdAt",
+ "completedAt",
"id",
- "completedAt"
+ "quantity",
+ "triggeredAtJobOperationId",
+ "targetJobOperationId",
+ "updatedAt",
+ "reason"
]
},
{
"name": "jobOperationStep",
"rows": 0,
"columns": [
- "nonConformanceInvestigationId",
- "operationId",
- "sortOrder",
- "updatedBy",
- "assemblyInstructionStepId",
- "createdBy",
- "description",
- "nonConformanceActionId",
- "required",
- "createdAt",
- "unitOfMeasureCode",
+ "type",
"fileTypes",
- "id",
"maxValue",
- "type",
+ "id",
+ "listValues",
+ "minValue",
"name",
"companyId",
"updatedAt",
- "listValues",
- "minValue"
+ "updatedBy",
+ "createdBy",
+ "assemblyInstructionStepId",
+ "operationId",
+ "nonConformanceInvestigationId",
+ "sortOrder",
+ "unitOfMeasureCode",
+ "description",
+ "nonConformanceActionId",
+ "createdAt",
+ "required"
]
},
{
"name": "jobOperationStepRecord",
"rows": 0,
"columns": [
+ "createdAt",
+ "booleanValue",
+ "numericValue",
+ "userValue",
+ "index",
"createdBy",
"updatedBy",
"value",
"companyId",
- "updatedAt",
"jobOperationStepId",
- "id",
- "createdAt",
- "numericValue",
- "booleanValue",
- "userValue",
- "index"
+ "updatedAt",
+ "id"
]
},
{
"name": "jobOperationStepSlide",
"rows": 0,
"columns": [
+ "annotations",
+ "sortOrder",
"caption",
"imagePath",
"createdBy",
- "sortOrder",
- "annotations",
- "modelUploadId",
- "stepId",
- "updatedAt",
- "createdAt",
- "size",
"id",
"updatedBy",
- "companyId"
+ "size",
+ "companyId",
+ "stepId",
+ "modelUploadId",
+ "createdAt",
+ "updatedAt"
]
},
{
@@ -5185,165 +5185,165 @@
"name": "kanban",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "conversionFactor",
- "storageUnitId",
- "itemId",
- "createdBy",
- "autoStartJob",
- "autoRelease",
- "purchaseUnitOfMeasureCode",
- "createdAt",
- "locationId",
"completedBarcodeOverride",
"updatedBy",
+ "createdAt",
+ "locationId",
+ "supplierId",
"jobId",
"fromStorageUnitId",
"quantity",
- "updatedAt",
"replenishmentSystem",
- "supplierId"
+ "updatedAt",
+ "storageUnitId",
+ "companyId",
+ "id",
+ "conversionFactor",
+ "autoRelease",
+ "purchaseUnitOfMeasureCode",
+ "itemId",
+ "createdBy",
+ "autoStartJob"
]
},
{
"name": "methodMaterial",
"rows": 0,
"columns": [
- "kit",
- "quantity",
- "methodOperationId",
- "scrapQuantity",
- "materialMakeMethodId",
- "methodType",
- "customFields",
- "order",
- "tags",
- "updatedAt",
- "itemType",
- "createdAt",
- "storageUnitIds",
- "unitOfMeasureCode",
"makeMethodId",
"updatedBy",
- "sourcingType",
- "itemId",
- "createdBy",
+ "unitOfMeasureCode",
+ "createdAt",
+ "storageUnitIds",
+ "companyId",
"id",
- "companyId"
+ "createdBy",
+ "itemId",
+ "sourcingType",
+ "customFields",
+ "methodType",
+ "materialMakeMethodId",
+ "methodOperationId",
+ "scrapQuantity",
+ "quantity",
+ "kit",
+ "updatedAt",
+ "itemType",
+ "order",
+ "tags"
]
},
{
"name": "methodMaterialStep",
"rows": 0,
- "columns": ["methodOperationStepId", "methodMaterialId", "quantity"]
+ "columns": ["quantity", "methodOperationStepId", "methodMaterialId"]
},
{
"name": "methodOperation",
"rows": 0,
"columns": [
- "customFields",
+ "companyId",
+ "workInstruction",
+ "id",
+ "operationType",
"createdBy",
"inspectionDocumentId",
"makeMethodId",
- "operationMinimumCost",
- "procedureId",
+ "customFields",
"machineUnit",
"assemblyInstructionId",
- "id",
- "workInstruction",
- "companyId",
- "operationType",
- "operationOrder",
- "order",
- "updatedAt",
- "setupTime",
- "workCenterId",
- "machineTime",
- "description",
- "tags",
- "operationUnitCost",
- "laborUnit",
- "setupUnit",
- "createdAt",
+ "procedureId",
+ "operationMinimumCost",
"operationLeadTime",
- "laborTime",
+ "createdAt",
+ "setupUnit",
+ "laborUnit",
"updatedBy",
+ "laborTime",
+ "processId",
"operationSupplierProcessId",
- "processId"
+ "setupTime",
+ "workCenterId",
+ "order",
+ "updatedAt",
+ "operationOrder",
+ "operationUnitCost",
+ "description",
+ "machineTime",
+ "tags"
]
},
{
"name": "methodOperationParameter",
"rows": 0,
"columns": [
- "key",
- "updatedAt",
"id",
"updatedBy",
"createdAt",
+ "key",
+ "updatedAt",
+ "companyId",
"operationId",
"value",
- "createdBy",
- "companyId"
+ "createdBy"
]
},
{
"name": "methodOperationStep",
"rows": 0,
"columns": [
- "assemblyInstructionStepId",
- "description",
+ "updatedAt",
+ "name",
+ "companyId",
+ "minValue",
+ "listValues",
+ "maxValue",
+ "id",
+ "fileTypes",
+ "type",
"createdAt",
"required",
+ "description",
+ "assemblyInstructionStepId",
"unitOfMeasureCode",
- "sortOrder",
"operationId",
- "createdBy",
+ "sortOrder",
"updatedBy",
- "companyId",
- "name",
- "updatedAt",
- "listValues",
- "minValue",
- "fileTypes",
- "maxValue",
- "id",
- "type"
+ "createdBy"
]
},
{
"name": "methodOperationStepSlide",
"rows": 0,
"columns": [
- "createdBy",
"imagePath",
"caption",
+ "createdBy",
"annotations",
"sortOrder",
- "updatedAt",
- "createdAt",
"stepId",
"modelUploadId",
- "companyId",
- "size",
+ "createdAt",
+ "updatedAt",
"updatedBy",
- "id"
+ "id",
+ "size",
+ "companyId"
]
},
{
"name": "methodOperationTool",
"rows": 0,
"columns": [
- "createdBy",
- "quantity",
- "toolId",
- "companyId",
- "updatedAt",
- "operationId",
- "createdAt",
+ "updatedBy",
"id",
- "updatedBy"
+ "createdAt",
+ "operationId",
+ "updatedAt",
+ "companyId",
+ "toolId",
+ "quantity",
+ "createdBy"
]
},
{
@@ -5355,84 +5355,84 @@
"name": "nonConformanceActionProcess",
"rows": 0,
"columns": [
- "createdAt",
+ "updatedBy",
+ "actionTaskId",
+ "createdBy",
+ "id",
"updatedAt",
"processId",
"companyId",
- "createdBy",
- "id",
- "updatedBy",
- "actionTaskId"
+ "createdAt"
]
},
{
"name": "nonConformanceActionTask",
"rows": 0,
"columns": [
+ "updatedBy",
+ "supplierId",
+ "dueDate",
+ "createdAt",
"assignee",
"updatedAt",
"status",
- "supplierId",
- "updatedBy",
- "createdAt",
- "dueDate",
- "tags",
- "notes",
- "nonConformanceId",
- "createdBy",
- "actionTypeId",
"completedDate",
- "companyId",
"sortOrder",
- "id"
+ "id",
+ "companyId",
+ "notes",
+ "tags",
+ "actionTypeId",
+ "createdBy",
+ "nonConformanceId"
]
},
{
"name": "nonConformancePurchaseReturnOrderLine",
"rows": 0,
"columns": [
- "id",
- "createdBy",
- "updatedBy",
- "quantity",
- "nonConformanceId",
+ "companyId",
+ "purchaseReturnOrderLineId",
+ "purchaseReturnOrderId",
+ "purchaseReturnOrderReadableId",
"createdAt",
"updatedAt",
- "purchaseReturnOrderReadableId",
- "purchaseReturnOrderId",
- "purchaseReturnOrderLineId",
- "companyId"
+ "nonConformanceId",
+ "quantity",
+ "createdBy",
+ "id",
+ "updatedBy"
]
},
{
"name": "nonConformanceSalesReturnOrderLine",
"rows": 0,
"columns": [
- "id",
- "updatedAt",
- "companyId",
"nonConformanceId",
- "updatedBy",
"createdBy",
- "salesReturnOrderReadableId",
- "salesReturnOrderId",
+ "updatedBy",
+ "updatedAt",
+ "id",
+ "companyId",
"salesReturnOrderLineId",
- "createdAt"
+ "salesReturnOrderId",
+ "createdAt",
+ "salesReturnOrderReadableId"
]
},
{
"name": "nonConformanceSupplier",
"rows": 0,
"columns": [
+ "supplierId",
+ "companyId",
+ "updatedAt",
+ "createdAt",
"nonConformanceId",
"updatedBy",
- "id",
"externalLinkId",
- "createdBy",
- "companyId",
- "supplierId",
- "updatedAt",
- "createdAt"
+ "id",
+ "createdBy"
]
},
{
@@ -5456,85 +5456,85 @@
"name": "payment",
"rows": 0,
"columns": [
- "postingDate",
- "exchangeRate",
- "updatedAt",
- "postedAt",
- "paymentId",
- "reference",
"supplierId",
"customFields",
- "currencyCode",
"id",
+ "currencyCode",
"totalAmount",
- "paymentDate",
+ "postingDate",
+ "updatedAt",
+ "exchangeRate",
+ "postedAt",
+ "reference",
+ "paymentId",
+ "createdBy",
+ "journalId",
+ "postedBy",
+ "createdAt",
+ "customerId",
+ "companyId",
+ "bankAccount",
"updatedBy",
+ "paymentDate",
+ "status",
"memo",
"paymentType",
- "status",
- "voidedAt",
"voidedBy",
- "postedBy",
- "journalId",
- "createdBy",
- "createdAt",
- "bankAccount",
- "companyId",
- "customerId"
+ "voidedAt"
]
},
{
"name": "purchaseInvoiceDelivery",
"rows": 0,
"columns": [
+ "locationId",
+ "updatedAt",
+ "incoterm",
"customFields",
"id",
"incotermLocation",
"companyId",
- "locationId",
- "updatedAt",
- "incoterm",
- "supplierShippingCost",
"shippingMethodId",
"shippingTermId",
- "updatedBy"
+ "updatedBy",
+ "supplierShippingCost"
]
},
{
"name": "purchaseInvoiceStatusHistory",
"rows": 0,
- "columns": ["createdAt", "companyId", "invoiceId", "id", "status"]
+ "columns": ["invoiceId", "id", "status", "createdAt", "companyId"]
},
{
"name": "purchaseOrderDelivery",
"rows": 0,
"columns": [
- "updatedAt",
- "tags",
"receiptRequestedDate",
- "customerLocationId",
"incotermLocation",
- "deliveryDate",
+ "customerLocationId",
+ "updatedAt",
+ "tags",
"incoterm",
"supplierShippingCost",
+ "shippingTermId",
"updatedBy",
"shippingMethodId",
- "shippingTermId",
- "receiptPromisedDate",
+ "deliveryDate",
"customerId",
- "trackingNumber",
"id",
- "dropShipment",
- "notes",
+ "trackingNumber",
+ "receiptPromisedDate",
"companyId",
"locationId",
- "customFields"
+ "customFields",
+ "dropShipment",
+ "notes"
]
},
{
"name": "purchaseOrderFavorite",
"rows": 0,
- "columns": ["userId", "purchaseOrderId"]
+ "columns": ["purchaseOrderId", "userId"]
},
{
"name": "purchaseOrderLine",
@@ -5542,13 +5542,13 @@
"columns": [
"conversionFactor",
"receivedDate",
- "tags",
"description",
+ "tags",
"externalNotes",
"createdAt",
"purchaseUnitOfMeasureCode",
- "purchaseOrderId",
"exchangeRate",
+ "purchaseOrderId",
"jobId",
"ownerId",
"quantityInvoiced",
@@ -5569,8 +5569,8 @@
"companyId",
"internalNotes",
"promisedDate",
- "supplierUnitPrice",
"purchaseOrderLineType",
+ "supplierUnitPrice",
"itemId",
"storageUnitId",
"setupPrice",
@@ -5579,8 +5579,8 @@
"quantityShipped",
"taxPercent",
"invoicedComplete",
- "costCenterId",
"inventoryUnitOfMeasureCode",
+ "costCenterId",
"jobOperationId",
"receivedComplete"
]
@@ -5589,16 +5589,16 @@
"name": "nonConformancePurchaseOrderLine",
"rows": 0,
"columns": [
- "companyId",
+ "nonConformanceId",
+ "createdBy",
+ "updatedBy",
"updatedAt",
"id",
- "updatedBy",
- "createdBy",
- "nonConformanceId",
- "purchaseOrderReadableId",
- "createdAt",
+ "companyId",
"purchaseOrderLineId",
- "purchaseOrderId"
+ "purchaseOrderId",
+ "createdAt",
+ "purchaseOrderReadableId"
]
},
{
@@ -5618,80 +5618,80 @@
"name": "purchaseOrderTransaction",
"rows": 0,
"columns": [
- "id",
- "companyId",
"purchaseOrderId",
- "createdAt",
+ "companyId",
+ "id",
+ "type",
"userId",
- "type"
+ "createdAt"
]
},
{
"name": "purchaseReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "createdAt",
- "purchaseReturnOrderLineId",
- "updatedAt",
- "trackedEntityId",
- "createdBy",
"updatedBy",
+ "companyId",
"quantity",
- "companyId"
+ "createdBy",
+ "updatedAt",
+ "trackedEntityId",
+ "createdAt",
+ "purchaseReturnOrderLineId"
]
},
{
"name": "purchasingRfqSupplier",
"rows": 0,
"columns": [
- "createdAt",
- "updatedBy",
- "companyId",
"supplierId",
- "createdBy",
+ "companyId",
+ "updatedBy",
+ "createdAt",
+ "purchasingRfqId",
"id",
- "purchasingRfqId"
+ "createdBy"
]
},
{
"name": "purchasingRfqToPurchaseOrder",
"rows": 0,
- "columns": ["purchasingRfqId", "purchaseOrderId", "companyId"]
+ "columns": ["companyId", "purchaseOrderId", "purchasingRfqId"]
},
{
"name": "purchasingRfqToSupplierQuote",
"rows": 0,
- "columns": ["purchasingRfqId", "supplierQuoteId", "companyId"]
+ "columns": ["companyId", "supplierQuoteId", "purchasingRfqId"]
},
{
"name": "quoteMakeMethod",
"rows": 0,
"columns": [
- "parentMaterialId",
- "quoteLineId",
- "version",
- "companyId",
- "itemId",
- "customFields",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "quantityPerParent",
"tags",
"quoteId",
"createdAt",
"updatedAt",
- "id",
- "createdBy",
- "updatedBy",
- "quantityPerParent"
+ "itemId",
+ "customFields",
+ "quoteLineId",
+ "version",
+ "parentMaterialId",
+ "companyId"
]
},
{
"name": "quoteMaterial",
"rows": 0,
"columns": [
+ "customFields",
+ "quoteMakeMethodId",
"quoteLineId",
"createdAt",
"itemId",
- "customFields",
- "quoteMakeMethodId",
"unitCostSource",
"methodType",
"tags",
@@ -5701,16 +5701,16 @@
"storageUnitId",
"scrapQuantity",
"createdBy",
- "updatedAt",
"quoteId",
"companyId",
- "order",
+ "updatedAt",
"quantity",
+ "order",
+ "unitOfMeasureCode",
"description",
"id",
- "unitOfMeasureCode",
- "itemType",
- "kit"
+ "kit",
+ "itemType"
]
},
{
@@ -5722,40 +5722,40 @@
"name": "quoteOperation",
"rows": 0,
"columns": [
- "quoteMakeMethodId",
- "quoteLineId",
- "laborRate",
+ "operationUnitCost",
+ "quoteId",
+ "inspectionDocumentId",
+ "companyId",
+ "operationLeadTime",
+ "setupTime",
+ "description",
+ "machineRate",
+ "machineUnit",
+ "laborUnit",
+ "tags",
+ "procedureId",
+ "id",
+ "setupUnit",
"assemblyInstructionId",
"createdBy",
"updatedAt",
+ "quoteMakeMethodId",
+ "quoteLineId",
+ "laborRate",
+ "operationMinimumCost",
"machineTime",
- "workCenterId",
"workInstruction",
+ "workCenterId",
"operationSupplierProcessId",
- "operationMinimumCost",
- "processId",
"updatedBy",
"operationType",
"operationOrder",
"order",
+ "processId",
"laborTime",
"createdAt",
"overheadRate",
- "customFields",
- "companyId",
- "operationUnitCost",
- "quoteId",
- "inspectionDocumentId",
- "description",
- "machineRate",
- "machineUnit",
- "operationLeadTime",
- "setupTime",
- "id",
- "laborUnit",
- "tags",
- "procedureId",
- "setupUnit"
+ "customFields"
]
},
{
@@ -5763,71 +5763,71 @@
"rows": 0,
"columns": [
"createdAt",
- "updatedBy",
"id",
+ "updatedBy",
"updatedAt",
"key",
"companyId",
"createdBy",
- "value",
- "operationId"
+ "operationId",
+ "value"
]
},
{
"name": "quoteOperationStep",
"rows": 0,
"columns": [
- "type",
- "fileTypes",
- "id",
- "maxValue",
- "listValues",
- "minValue",
- "name",
- "companyId",
- "updatedAt",
- "updatedBy",
- "createdBy",
- "operationId",
- "sortOrder",
- "unitOfMeasureCode",
- "description",
+ "createdAt",
"required",
- "createdAt"
+ "description",
+ "unitOfMeasureCode",
+ "sortOrder",
+ "operationId",
+ "createdBy",
+ "updatedBy",
+ "updatedAt",
+ "companyId",
+ "name",
+ "minValue",
+ "listValues",
+ "maxValue",
+ "id",
+ "fileTypes",
+ "type"
]
},
{
"name": "quoteOperationStepSlide",
"rows": 0,
"columns": [
- "createdBy",
- "caption",
- "imagePath",
- "annotations",
- "sortOrder",
- "updatedAt",
+ "companyId",
+ "id",
+ "updatedBy",
+ "size",
"createdAt",
+ "updatedAt",
"stepId",
"modelUploadId",
- "companyId",
- "size",
- "id",
- "updatedBy"
+ "annotations",
+ "sortOrder",
+ "createdBy",
+ "caption",
+ "imagePath"
]
},
{
"name": "quoteOperationTool",
"rows": 0,
"columns": [
- "operationId",
- "updatedAt",
- "id",
- "updatedBy",
- "createdAt",
- "quantity",
+ "companyId",
"toolId",
+ "quantity",
"createdBy",
- "companyId"
+ "updatedBy",
+ "id",
+ "createdAt",
+ "operationId",
+ "updatedAt"
]
},
{
@@ -5839,268 +5839,268 @@
"name": "receiptFixedAssetLine",
"rows": 0,
"columns": [
- "companyId",
- "id",
"updatedAt",
+ "id",
+ "companyId",
+ "receiptId",
"createdAt",
"updatedBy",
- "receiptId",
"serialNumber",
- "createdBy",
+ "purchaseOrderLineId",
"received",
- "purchaseOrderLineId"
+ "createdBy"
]
},
{
"name": "receiptLine",
"rows": 0,
"columns": [
- "receiptId",
- "companyId",
- "updatedAt",
- "storageUnitId",
- "receivedQuantity",
- "unitOfMeasure",
- "id",
- "locationId",
- "orderQuantity",
- "conversionFactor",
"requiresSerialTracking",
+ "conversionFactor",
"itemId",
- "createdAt",
"lineId",
+ "createdAt",
"outstandingQuantity",
"requiresBatchTracking",
"unitPrice",
+ "createdBy",
"updatedBy",
- "createdBy"
+ "companyId",
+ "receiptId",
+ "updatedAt",
+ "storageUnitId",
+ "receivedQuantity",
+ "unitOfMeasure",
+ "id",
+ "locationId",
+ "orderQuantity"
]
},
{
"name": "nonConformanceReceiptLine",
"rows": 0,
"columns": [
- "receiptLineId",
- "receiptId",
- "createdAt",
- "receiptReadableId",
- "nonConformanceId",
- "updatedBy",
"createdBy",
- "updatedAt",
+ "updatedBy",
+ "nonConformanceId",
+ "companyId",
"id",
- "companyId"
+ "updatedAt",
+ "createdAt",
+ "receiptId",
+ "receiptLineId",
+ "receiptReadableId"
]
},
{
"name": "salesInvoice",
"rows": 0,
"columns": [
- "currencyCode",
- "exchangeRate",
- "companyId",
- "totalDiscount",
"exchangeRateUpdatedAt",
- "customerReference",
- "createdAt",
"dateDue",
- "opportunityId",
- "invoiceCustomerLocationId",
- "internalNotes",
- "createdBy",
- "customerId",
- "locationId",
- "status",
- "totalTax",
+ "createdAt",
+ "customerReference",
+ "totalDiscount",
+ "companyId",
+ "exchangeRate",
+ "currencyCode",
+ "locationId",
+ "status",
+ "customerId",
"totalAmount",
- "invoiceCustomerId",
- "assignee",
- "id",
+ "totalTax",
+ "internalNotes",
+ "invoiceCustomerLocationId",
+ "opportunityId",
+ "createdBy",
"paymentTermId",
- "customFields",
+ "id",
"dateIssued",
+ "customFields",
+ "invoiceCustomerId",
+ "assignee",
+ "subtotal",
+ "invoiceId",
+ "updatedBy",
+ "datePaid",
+ "externalNotes",
"tags",
"invoiceCustomerContactId",
- "externalNotes",
- "shipmentId",
- "updatedAt",
"postingDate",
- "subtotal",
- "datePaid",
- "invoiceId",
- "updatedBy"
+ "updatedAt",
+ "shipmentId"
]
},
{
"name": "salesInvoiceLine",
"rows": 0,
"columns": [
- "nonTaxableAddOnCost",
- "opportunityId",
- "unitOfMeasureCode",
- "id",
- "assetId",
+ "addOnCost",
+ "modelUploadId",
+ "unitPrice",
+ "locationId",
+ "companyId",
+ "itemId",
+ "createdAt",
+ "salesOrderId",
+ "updatedBy",
+ "accountId",
+ "shippingCost",
+ "sortOrder",
+ "taxPercent",
+ "exchangeRate",
+ "invoiceLineType",
+ "description",
"internalNotes",
"methodType",
- "storageUnitId",
- "updatedAt",
- "invoiceId",
- "setupPrice",
- "externalNotes",
- "createdBy",
+ "unitOfMeasureCode",
+ "opportunityId",
+ "nonTaxableAddOnCost",
+ "assetId",
+ "id",
"quantity",
- "customFields",
+ "createdBy",
+ "externalNotes",
"salesOrderLineId",
- "itemId",
- "companyId",
- "locationId",
- "unitPrice",
- "modelUploadId",
- "addOnCost",
- "taxPercent",
- "sortOrder",
- "shippingCost",
- "description",
- "invoiceLineType",
- "exchangeRate",
- "createdAt",
- "accountId",
- "updatedBy",
- "salesOrderId"
+ "customFields",
+ "invoiceId",
+ "updatedAt",
+ "storageUnitId",
+ "setupPrice"
]
},
{
"name": "salesInvoiceShipment",
"rows": 0,
"columns": [
- "shippingCost",
- "incotermLocation",
- "createdAt",
- "updatedAt",
- "createdBy",
+ "customFields",
"id",
+ "createdBy",
"updatedBy",
- "customFields",
- "locationId",
- "shippingMethodId",
- "companyId",
+ "createdAt",
+ "updatedAt",
+ "incotermLocation",
+ "shippingCost",
+ "shippingTermId",
"incoterm",
- "shippingTermId"
+ "companyId",
+ "shippingMethodId",
+ "locationId"
]
},
{
"name": "salesReturnOrderLine",
"rows": 0,
"columns": [
- "unitOfMeasureCode",
- "createdAt",
- "updatedBy",
- "itemId",
- "disposition",
- "lineNumber",
+ "restockFeePercent",
+ "id",
+ "salesOrderLineId",
+ "quantityReceived",
+ "companyId",
+ "salesReturnOrderId",
+ "salesInvoiceLineId",
+ "unitPrice",
+ "returnReasonId",
+ "shipmentLineId",
+ "updatedAt",
+ "quantity",
"createdBy",
"customFields",
"closedComplete",
- "updatedAt",
- "shipmentLineId",
- "quantity",
- "returnReasonId",
- "unitPrice",
- "salesReturnOrderId",
- "salesInvoiceLineId",
- "companyId",
- "quantityReceived",
- "salesOrderLineId",
- "id",
- "restockFeePercent"
+ "disposition",
+ "lineNumber",
+ "itemId",
+ "createdAt",
+ "updatedBy",
+ "unitOfMeasureCode"
]
},
{
"name": "salesReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "quantity",
- "companyId",
- "updatedBy",
- "createdBy",
+ "salesReturnOrderLineId",
+ "createdAt",
"trackedEntityId",
"updatedAt",
- "salesReturnOrderLineId",
- "createdAt"
+ "createdBy",
+ "quantity",
+ "companyId",
+ "updatedBy"
]
},
{
"name": "salesReturnOrderCreditLine",
"rows": 0,
"columns": [
- "unitPrice",
- "salesReturnOrderLineId",
- "quantity",
- "companyId",
- "updatedAt",
- "createdAt",
"id",
+ "createdAt",
+ "updatedAt",
"restockFee",
"memoId",
+ "createdBy",
"updatedBy",
- "createdBy"
+ "unitPrice",
+ "quantity",
+ "salesReturnOrderLineId",
+ "companyId"
]
},
{
"name": "shipmentFixedAssetLine",
"rows": 0,
"columns": [
- "createdBy",
+ "serialNumber",
"salesOrderLineId",
"shipped",
- "serialNumber",
- "updatedBy",
- "createdAt",
- "shipmentId",
- "companyId",
+ "createdBy",
"updatedAt",
- "id"
+ "id",
+ "companyId",
+ "shipmentId",
+ "updatedBy",
+ "createdAt"
]
},
{
"name": "shipmentLine",
"rows": 0,
"columns": [
- "fulfillmentId",
- "unitPrice",
- "companyId",
- "createdBy",
+ "updatedBy",
+ "updatedAt",
"itemId",
"requiresBatchTracking",
"lineId",
- "updatedBy",
- "updatedAt",
"outstandingQuantity",
- "id",
- "locationId",
- "unitOfMeasure",
- "orderQuantity",
- "createdAt",
+ "fulfillmentId",
+ "unitPrice",
+ "companyId",
+ "createdBy",
"requiresSerialTracking",
"shipmentId",
+ "createdAt",
+ "storageUnitId",
"shippedQuantity",
- "storageUnitId"
+ "unitOfMeasure",
+ "id",
+ "locationId",
+ "orderQuantity"
]
},
{
"name": "nonConformanceShipmentLine",
"rows": 0,
"columns": [
- "shipmentReadableId",
+ "createdAt",
"shipmentLineId",
"shipmentId",
- "createdAt",
- "updatedAt",
- "id",
- "companyId",
- "nonConformanceId",
+ "shipmentReadableId",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "nonConformanceId",
+ "companyId",
+ "updatedAt",
+ "id"
]
},
{
@@ -6142,27 +6142,27 @@
"name": "supplierBankAccount",
"rows": 0,
"columns": [
- "customFields",
+ "bankCode",
+ "currencyCode",
+ "id",
+ "bankName",
+ "companyId",
+ "isPrimary",
+ "createdBy",
+ "accountNumber",
+ "countryCode",
"swiftBic",
+ "customFields",
"accountHolderName",
"createdAt",
"tags",
"notes",
- "name",
- "active",
- "supplierId",
"updatedBy",
"updatedAt",
- "bankAddress",
- "id",
- "currencyCode",
- "bankCode",
- "bankName",
- "createdBy",
- "companyId",
- "isPrimary",
- "countryCode",
- "accountNumber"
+ "active",
+ "supplierId",
+ "name",
+ "bankAddress"
]
},
{
@@ -6174,77 +6174,77 @@
"name": "receipt",
"rows": 0,
"columns": [
- "supplierId",
- "postingDate",
- "updatedAt",
- "companyId",
- "receiptId",
- "sourceDocumentReadableId",
- "status",
- "id",
- "invoiced",
- "externalDocumentId",
- "createdAt",
- "locationId",
- "sourceDocument",
- "tags",
- "customFields",
- "createdBy",
- "supplierInteractionId",
- "updatedBy",
"postedBy",
"sourceDocumentId",
+ "internalNotes",
"assignee",
- "internalNotes"
+ "supplierInteractionId",
+ "createdBy",
+ "updatedBy",
+ "sourceDocument",
+ "createdAt",
+ "locationId",
+ "tags",
+ "customFields",
+ "externalDocumentId",
+ "id",
+ "status",
+ "invoiced",
+ "sourceDocumentReadableId",
+ "updatedAt",
+ "companyId",
+ "receiptId",
+ "supplierId",
+ "postingDate"
]
},
{
"name": "shipment",
"rows": 0,
"columns": [
+ "customFields",
+ "status",
+ "trackingNumber",
+ "invoiced",
+ "shipmentId",
+ "externalNotes",
+ "supplierId",
+ "sourceDocumentReadableId",
+ "postingDate",
+ "externalDocumentId",
+ "customerId",
+ "id",
"shippingMethodId",
"tags",
- "locationId",
+ "createdAt",
+ "companyId",
"assignee",
+ "locationId",
"sourceDocument",
- "companyId",
- "createdAt",
+ "updatedAt",
+ "internalNotes",
"opportunityId",
"supplierInteractionId",
- "internalNotes",
- "updatedAt",
- "updatedBy",
+ "sourceDocumentId",
"postedBy",
"createdBy",
- "sourceDocumentId",
- "trackingNumber",
- "status",
- "customFields",
- "externalNotes",
- "shipmentId",
- "invoiced",
- "sourceDocumentReadableId",
- "supplierId",
- "customerId",
- "id",
- "postingDate",
- "externalDocumentId"
+ "updatedBy"
]
},
{
"name": "supplierLedger",
"rows": 0,
"columns": [
- "documentId",
+ "supplierId",
"postingDate",
"documentType",
- "supplierId",
- "companyId",
- "id",
- "externalDocumentId",
- "entryNumber",
+ "documentId",
+ "createdAt",
"amount",
- "createdAt"
+ "entryNumber",
+ "externalDocumentId",
+ "companyId",
+ "id"
]
},
{
@@ -6278,113 +6278,113 @@
"name": "purchaseInvoice",
"rows": 0,
"columns": [
- "invoiceSupplierContactId",
- "internalNotes",
- "supplierInteractionId",
- "createdBy",
- "currencyCode",
- "subtotal",
"dateIssued",
"status",
"invoiceId",
- "invoiceSupplierId",
- "createdAt",
- "id",
- "paymentTermId",
+ "subtotal",
+ "createdBy",
+ "currencyCode",
+ "invoiceSupplierContactId",
+ "internalNotes",
+ "supplierInteractionId",
"updatedAt",
"exchangeRate",
+ "id",
+ "paymentTermId",
+ "createdAt",
+ "invoiceSupplierId",
+ "totalTax",
+ "totalAmount",
+ "supplierId",
+ "dateDue",
+ "locationId",
"customFields",
"invoiceSupplierLocationId",
"tags",
- "locationId",
- "supplierId",
- "dateDue",
- "totalTax",
- "totalAmount",
- "datePaid",
- "assignee",
- "updatedBy",
- "totalDiscount",
- "companyId",
"supplierReference",
+ "postingDate",
"exchangeRateUpdatedAt",
- "postingDate"
+ "companyId",
+ "assignee",
+ "datePaid",
+ "updatedBy",
+ "totalDiscount"
]
},
{
"name": "purchaseOrder",
"rows": 0,
"columns": [
- "currencyCode",
- "closedBy",
+ "purchaseOrderType",
+ "exchangeRateUpdatedAt",
+ "createdBy",
+ "updatedAt",
+ "revisionId",
+ "closedAt",
"createdAt",
"externalNotes",
- "status",
+ "currencyCode",
+ "closedBy",
"assignee",
"updatedBy",
+ "status",
"exchangeRate",
- "exchangeRateUpdatedAt",
- "purchaseOrderType",
- "updatedAt",
- "createdBy",
- "revisionId",
- "closedAt",
- "internalNotes",
- "orderDate",
- "supplierReference",
- "supplierInteractionId",
- "supplierLocationId",
- "id",
- "tags",
"supplierContactId",
+ "tags",
"jobId",
"supplierId",
"jobReadableId",
- "companyId",
"purchaseOrderId",
- "customFields"
+ "companyId",
+ "customFields",
+ "internalNotes",
+ "orderDate",
+ "supplierReference",
+ "supplierInteractionId",
+ "supplierLocationId",
+ "id"
]
},
{
"name": "purchaseInvoiceLine",
"rows": 0,
"columns": [
- "costCenterId",
- "invoiceLineType",
- "quantity",
- "purchaseOrderId",
- "exchangeRate",
- "sortOrder",
- "inventoryUnitOfMeasureCode",
- "tags",
- "modelUploadId",
- "createdAt",
- "supplierTaxAmount",
- "taxPercent",
- "createdBy",
- "assetId",
- "purchaseUnitOfMeasureCode",
- "purchaseOrderLineId",
+ "itemId",
+ "updatedAt",
+ "locationId",
+ "id",
+ "conversionFactor",
+ "internalNotes",
+ "serviceId",
+ "storageUnitId",
+ "supplierShippingCost",
+ "updatedBy",
+ "requiredDate",
+ "invoiceId",
+ "projectId",
+ "description",
"jobOperationId",
"ownerId",
"customFields",
"accountId",
- "supplierUnitPrice",
"companyId",
- "requiredDate",
- "invoiceId",
- "projectId",
- "description",
- "internalNotes",
- "serviceId",
- "supplierShippingCost",
- "storageUnitId",
- "updatedBy",
- "locationId",
- "id",
- "conversionFactor",
- "itemId",
- "updatedAt"
+ "supplierUnitPrice",
+ "taxPercent",
+ "createdBy",
+ "assetId",
+ "purchaseUnitOfMeasureCode",
+ "purchaseOrderLineId",
+ "tags",
+ "modelUploadId",
+ "createdAt",
+ "supplierTaxAmount",
+ "costCenterId",
+ "quantity",
+ "invoiceLineType",
+ "purchaseOrderId",
+ "sortOrder",
+ "exchangeRate",
+ "inventoryUnitOfMeasureCode"
]
},
{
@@ -6406,188 +6406,188 @@
"name": "purchaseOrderPayment",
"rows": 0,
"columns": [
- "invoiceSupplierLocationId",
- "invoiceSupplierContactId",
"paymentTermId",
"tags",
- "invoiceSupplierId",
- "updatedBy",
- "companyId",
+ "invoiceSupplierContactId",
+ "invoiceSupplierLocationId",
"customFields",
- "updatedAt",
"id",
- "paymentComplete"
+ "updatedAt",
+ "paymentComplete",
+ "invoiceSupplierId",
+ "updatedBy",
+ "companyId"
]
},
{
"name": "purchaseReturnOrder",
"rows": 0,
"columns": [
- "orderDate",
- "purchaseReturnOrderId",
- "externalNotes",
- "replacementPurchaseOrderId",
- "locationId",
- "currencyCode",
- "id",
- "purchaseOrderId",
- "supplierContactId",
- "createdBy",
- "companyId",
- "supplierId",
+ "supplierReference",
+ "customFields",
"expirationDate",
"status",
- "customFields",
- "supplierReference",
- "supplierLocationId",
- "createdAt",
- "exchangeRate",
- "updatedAt",
- "internalNotes",
+ "supplierId",
+ "companyId",
+ "createdBy",
+ "assignee",
"updatedBy",
- "assignee"
+ "internalNotes",
+ "updatedAt",
+ "exchangeRate",
+ "createdAt",
+ "supplierLocationId",
+ "locationId",
+ "replacementPurchaseOrderId",
+ "externalNotes",
+ "purchaseReturnOrderId",
+ "orderDate",
+ "supplierContactId",
+ "purchaseOrderId",
+ "id",
+ "currencyCode"
]
},
{
"name": "memo",
"rows": 0,
"columns": [
- "voidedBy",
- "voidedAt",
- "status",
- "notes",
- "direction",
- "updatedBy",
- "memoDate",
+ "createdBy",
+ "journalId",
+ "salesReturnOrderId",
+ "postedBy",
"customerId",
"companyId",
"reasonAccount",
"createdAt",
- "journalId",
- "createdBy",
- "salesReturnOrderId",
- "postedBy",
- "reference",
- "memoId",
- "postedAt",
- "updatedAt",
- "exchangeRate",
- "postingDate",
+ "updatedBy",
+ "memoDate",
+ "voidedBy",
+ "voidedAt",
+ "status",
+ "direction",
+ "notes",
+ "customFields",
+ "supplierId",
"purchaseReturnOrderId",
"amount",
"id",
"currencyCode",
- "customFields",
- "supplierId"
+ "updatedAt",
+ "exchangeRate",
+ "postingDate",
+ "reference",
+ "memoId",
+ "postedAt"
]
},
{
"name": "invoiceSettlement",
"rows": 0,
"columns": [
- "discountAmount",
- "sourceExchangeRate",
- "createdAt",
- "appliedDate",
- "paymentId",
- "targetMemoId",
- "id",
- "writeOffAmount",
- "targetExchangeRate",
+ "appliedViaPaymentId",
+ "createdBy",
+ "fxGainLossAmount",
+ "sourceAmount",
+ "targetPurchaseInvoiceId",
"appliedAmount",
- "targetSalesInvoiceId",
+ "updatedBy",
+ "sourcePaymentId",
"companyId",
"memoId",
- "sourcePaymentId",
- "updatedBy",
- "createdBy",
- "appliedViaPaymentId",
- "targetPurchaseInvoiceId",
- "sourceAmount",
- "fxGainLossAmount"
+ "targetSalesInvoiceId",
+ "targetMemoId",
+ "targetExchangeRate",
+ "writeOffAmount",
+ "id",
+ "sourceExchangeRate",
+ "discountAmount",
+ "paymentId",
+ "appliedDate",
+ "createdAt"
]
},
{
"name": "purchaseReturnOrderLine",
"rows": 0,
"columns": [
- "returnReasonId",
- "unitPrice",
- "purchaseInvoiceLineId",
- "purchaseReturnOrderId",
"createdBy",
- "quantityShipped",
- "purchaseOrderLineId",
- "restockFeePercent",
+ "purchaseReturnOrderId",
+ "purchaseInvoiceLineId",
+ "unitPrice",
+ "returnReasonId",
"id",
- "unitOfMeasureCode",
- "updatedAt",
- "updatedBy",
- "closedComplete",
- "lineNumber",
+ "restockFeePercent",
+ "purchaseOrderLineId",
+ "quantityShipped",
"itemId",
- "companyId",
- "createdAt",
- "quantity",
+ "lineNumber",
+ "closedComplete",
+ "updatedBy",
+ "updatedAt",
+ "unitOfMeasureCode",
+ "customFields",
"receiptLineId",
- "customFields"
+ "quantity",
+ "createdAt",
+ "companyId"
]
},
{
"name": "purchaseReturnOrderCreditLine",
"rows": 0,
"columns": [
- "unitPrice",
- "companyId",
- "purchaseReturnOrderLineId",
- "quantity",
+ "createdBy",
+ "updatedBy",
+ "memoId",
"restockFee",
- "updatedAt",
"createdAt",
"id",
- "updatedBy",
- "createdBy",
- "memoId"
+ "updatedAt",
+ "companyId",
+ "purchaseReturnOrderLineId",
+ "quantity",
+ "unitPrice"
]
},
{
"name": "supplierPart",
"rows": 0,
"columns": [
- "supplierId",
- "customFields",
- "supplierPartId",
"conversionFactor",
- "supplierUnitOfMeasureCode",
- "updatedBy",
- "unitPrice",
+ "supplierPartId",
+ "customFields",
+ "supplierId",
"orderMultiple",
- "tags",
- "updatedAt",
- "itemId",
- "active",
+ "unitPrice",
+ "updatedBy",
+ "supplierUnitOfMeasureCode",
"createdBy",
- "companyId",
- "id",
+ "active",
+ "itemId",
+ "updatedAt",
+ "tags",
+ "minimumOrderQuantity",
"createdAt",
- "minimumOrderQuantity"
+ "id",
+ "companyId"
]
},
{
"name": "supplierPartPrice",
"rows": 0,
"columns": [
- "sourceDocumentId",
- "createdBy",
- "sourceType",
- "unitPrice",
- "companyId",
- "leadTime",
- "supplierPartId",
+ "sourceDocumentId",
+ "unitPrice",
+ "sourceType",
+ "createdBy",
"updatedBy",
- "updatedAt",
+ "supplierPartId",
+ "leadTime",
+ "companyId",
+ "quantity",
"createdAt",
- "quantity"
+ "updatedAt"
]
},
{
@@ -6598,62 +6598,62 @@
"invoiceSupplierContactId",
"invoiceSupplierLocationId",
"companyId",
+ "tags",
"supplierId",
"updatedBy",
- "tags",
"invoiceSupplierId",
- "updatedAt",
- "customFields"
+ "customFields",
+ "updatedAt"
]
},
{
"name": "supplierProcess",
"rows": 0,
"columns": [
+ "companyId",
+ "processId",
+ "minimumCost",
+ "updatedAt",
+ "customFields",
+ "createdAt",
"supplierId",
"tags",
- "createdAt",
- "customFields",
- "updatedBy",
+ "leadTime",
"createdBy",
"id",
- "leadTime",
- "processId",
- "minimumCost",
- "companyId",
- "updatedAt"
+ "updatedBy"
]
},
{
"name": "supplierQuote",
"rows": 0,
"columns": [
- "tags",
- "customFields",
- "quotedDate",
- "currencyCode",
- "revisionId",
- "updatedBy",
- "internalNotes",
- "expirationDate",
- "createdAt",
- "supplierReference",
- "updatedAt",
+ "status",
+ "supplierQuoteType",
+ "supplierId",
+ "id",
+ "supplierContactId",
+ "externalNotes",
+ "supplierInteractionId",
+ "supplierLocationId",
+ "exchangeRateUpdatedAt",
+ "assignee",
+ "supplierQuoteId",
"createdBy",
"exchangeRate",
- "externalLinkId",
"companyId",
- "assignee",
- "supplierQuoteId",
- "exchangeRateUpdatedAt",
- "supplierInteractionId",
- "supplierLocationId",
- "externalNotes",
- "supplierContactId",
- "id",
- "supplierId",
- "supplierQuoteType",
- "status"
+ "externalLinkId",
+ "updatedAt",
+ "expirationDate",
+ "supplierReference",
+ "createdAt",
+ "internalNotes",
+ "updatedBy",
+ "revisionId",
+ "currencyCode",
+ "quotedDate",
+ "tags",
+ "customFields"
]
},
{
@@ -6665,43 +6665,37 @@
"name": "supplierQuoteLine",
"rows": 0,
"columns": [
- "purchaseUnitOfMeasureCode",
- "ownerId",
- "supplierPartRevision",
- "id",
- "supplierQuoteLineType",
- "supplierQuoteId",
- "createdBy",
- "inventoryUnitOfMeasureCode",
- "accountId",
- "supplierPartId",
- "conversionFactor",
- "tags",
- "itemId",
"externalNotes",
- "updatedAt",
- "requiredDate",
- "internalNotes",
+ "itemId",
+ "tags",
+ "conversionFactor",
"companyId",
- "updatedBy",
- "customFields",
- "supplierQuoteRevisionId",
+ "internalNotes",
+ "requiredDate",
+ "updatedAt",
"quantity",
- "sortOrder",
+ "supplierQuoteRevisionId",
+ "customFields",
+ "updatedBy",
+ "costCenterId",
"description",
- "costCenterId"
+ "sortOrder",
+ "id",
+ "supplierPartRevision",
+ "ownerId",
+ "purchaseUnitOfMeasureCode",
+ "supplierQuoteLineType",
+ "createdBy",
+ "supplierQuoteId",
+ "supplierPartId",
+ "accountId",
+ "inventoryUnitOfMeasureCode"
]
},
{
"name": "supplierQuoteLinePrice",
"rows": 0,
"columns": [
- "leadTime",
- "quantity",
- "updatedAt",
- "createdAt",
- "supplierUnitPrice",
- "updatedBy",
"supplierQuoteLineId",
"createdBy",
"supplierTaxAmount",
@@ -6709,144 +6703,150 @@
"companyId",
"taxPercent",
"supplierQuoteId",
- "exchangeRate"
+ "exchangeRate",
+ "quantity",
+ "updatedAt",
+ "leadTime",
+ "createdAt",
+ "supplierUnitPrice",
+ "updatedBy"
]
},
{
"name": "supplierShipping",
"rows": 0,
"columns": [
- "supplierId",
- "updatedBy",
- "tags",
- "shippingMethodId",
- "incotermLocation",
- "shippingSupplierId",
- "updatedAt",
- "customFields",
- "shippingTermId",
- "incoterm",
+ "companyId",
"shippingSupplierContactId",
"shippingSupplierLocationId",
- "companyId"
+ "incoterm",
+ "shippingTermId",
+ "customFields",
+ "updatedAt",
+ "shippingSupplierId",
+ "incotermLocation",
+ "shippingMethodId",
+ "tags",
+ "supplierId",
+ "updatedBy"
]
},
{
"name": "supplierTax",
"rows": 0,
"columns": [
- "taxExemptionReason",
- "updatedBy",
+ "taxId",
+ "taxExemptionCertificatePath",
+ "updatedAt",
"supplierId",
"companyId",
- "updatedAt",
- "taxExemptionCertificatePath",
- "taxId",
- "taxExempt",
- "taxExemptionCertificateNumber",
+ "updatedBy",
+ "taxExemptionReason",
"eori",
- "vatNumber"
+ "vatNumber",
+ "taxExemptionCertificateNumber",
+ "taxExempt"
]
},
{
"name": "workflow",
"rows": 0,
"columns": [
- "companyId",
- "updatedAt",
- "nextRunAt",
- "createdBy",
+ "updatedBy",
+ "ownerId",
+ "publishedVersionId",
+ "name",
+ "description",
"canvasState",
"id",
"createdAt",
- "name",
- "description",
- "publishedVersionId",
- "updatedBy",
- "ownerId"
+ "nextRunAt",
+ "createdBy",
+ "companyId",
+ "updatedAt"
]
},
{
"name": "workflowVersion",
"rows": 0,
"columns": [
- "formatVersion",
- "edges",
- "workflowId",
- "versionNumber",
- "nodes",
- "updatedAt",
- "createdAt",
- "id",
+ "companyId",
"updatedBy",
"createdBy",
- "companyId"
+ "updatedAt",
+ "id",
+ "createdAt",
+ "nodes",
+ "versionNumber",
+ "workflowId",
+ "edges",
+ "formatVersion"
]
},
{
"name": "workflowRun",
"rows": 0,
"columns": [
- "workflowVersionId",
- "workflowId",
- "causedByRunId",
- "completedAt",
- "durationMs",
- "triggerTable",
- "createdAt",
- "error",
- "isTest",
- "eventId",
"startedAt",
"depth",
"compactedAt",
- "path",
- "companyId",
- "rootRunId",
- "triggerRecordId",
- "status",
+ "error",
+ "isTest",
+ "eventId",
+ "createdAt",
+ "triggerTable",
+ "completedAt",
+ "durationMs",
+ "workflowVersionId",
+ "causedByRunId",
+ "workflowId",
+ "sourceEventId",
+ "statusReason",
"id",
"ownerId",
- "statusReason",
- "sourceEventId"
+ "status",
+ "triggerRecordId",
+ "companyId",
+ "rootRunId",
+ "path"
]
},
{
"name": "workflowStepRun",
"rows": 0,
"columns": [
- "completedAt",
+ "branchTaken",
+ "nodeId",
+ "compactedAt",
+ "durationMs",
"runId",
+ "completedAt",
"sequence",
"createdAt",
"detail",
"itemKey",
- "branchTaken",
- "nodeId",
- "compactedAt",
- "durationMs",
+ "statusReason",
+ "id",
+ "output",
+ "nodeType",
"error",
"companyId",
"startedAt",
"status",
- "input",
- "statusReason",
- "id",
- "output",
- "nodeType"
+ "input"
]
},
{
"name": "workflowTriggerEvent",
"rows": 0,
"columns": [
+ "companyId",
"id",
"origin",
- "companyId",
- "eventId",
"workflowId",
"workflowVersionId",
- "createdAt"
+ "createdAt",
+ "eventId"
]
}
],
@@ -6855,6 +6855,7 @@
"apiKey",
"apiKeyRateLimit",
"companyIntegration",
+ "employeePin",
"oauthClient",
"oauthToken",
"webhook"
diff --git a/packages/jobs/src/backups/schema.ts b/packages/jobs/src/backups/schema.ts
index 00452aede5..088cab98c5 100644
--- a/packages/jobs/src/backups/schema.ts
+++ b/packages/jobs/src/backups/schema.ts
@@ -21,12 +21,16 @@ export const BACKUP_VERSION = 1;
* Tables whose contents must never travel in a backup — credentials,
* integration tokens and webhook targets stay with the source company.
* (`apiKeyRateLimit` dangles without its stripped `apiKey` and is an UNLOGGED
- * operational counter, never user data.)
+ * operational counter, never user data. `employeePin` holds console PIN
+ * hashes — a 4-digit PIN's bcrypt hash is brute-forced offline in minutes, so
+ * it is a credential; being secret also keeps an in-place restore from wiping
+ * every operator's PIN.)
*/
export const SECRET_TABLES = [
"apiKey",
"apiKeyRateLimit",
"companyIntegration",
+ "employeePin",
"webhook",
"oauthClient",
"oauthToken"
diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.ts
index f17a3ba6d9..99cd421b2f 100644
--- a/packages/jobs/src/inngest/functions/notifications/content.ts
+++ b/packages/jobs/src/inngest/functions/notifications/content.ts
@@ -11,6 +11,7 @@ import {
type NotificationDetail,
NotificationEvent
} from "@carbon/notifications";
+import { NonRetriableError } from "inngest";
type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];
@@ -116,6 +117,8 @@ export function buildDetails(
// to resolve per-document state.
type EventContentOptions = {
companyId: string;
+ // Which approvable document an Approval* event is about.
+ documentType?: ApprovalDocumentType;
documentIds?: string[];
userId?: string;
// Workflow-authored text, carried on the payload instead of read from a document.
@@ -123,6 +126,20 @@ type EventContentOptions = {
body?: string;
};
+// PGRST116: `.single()` matched no row — the document was deleted, or the id
+// does not belong to this company. Retrying cannot change either, so fail the
+// notify step for good instead of burning every Inngest retry on it. Any other
+// error (network, timeout) is returned unchanged and retried as before.
+function documentLookupError(error: { code?: string; message: string }) {
+ if (error.code === "PGRST116") {
+ return new NonRetriableError(
+ `Notification document not found in this company: ${error.message}`,
+ { cause: error }
+ );
+ }
+ return error;
+}
+
function changeNoticeStageDescription(
type: NotificationEvent,
readableId: string
@@ -141,8 +158,7 @@ async function buildEventContent(
client: ReturnType<typeof getCarbonServiceRole>,
type: NotificationEvent,
documentId: string,
- documentType?: ApprovalDocumentType,
- opts?: EventContentOptions
+ opts: EventContentOptions
): Promise<NotificationContent | null> {
switch (type) {
case NotificationEvent.SalesRfqReady:
@@ -151,11 +167,12 @@ async function buildEventContent(
.from("salesRfq")
.select("*, customer(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (salesRfq.error) {
console.error("Failed to get salesRfq", salesRfq.error);
- throw salesRfq.error;
+ throw documentLookupError(salesRfq.error);
}
const baseDetails = [
@@ -192,10 +209,11 @@ async function buildEventContent(
.from("quote")
.select("*, customer(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (quote.error) {
console.error("Failed to get quote", quote.error);
- throw quote.error;
+ throw documentLookupError(quote.error);
}
return {
description: `Quote ${quote?.data?.quoteId} assigned to you`,
@@ -217,10 +235,11 @@ async function buildEventContent(
.from("quote")
.select("*, customer(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (expiredQuote.error) {
console.error("Failed to get quote", expiredQuote.error);
- throw expiredQuote.error;
+ throw documentLookupError(expiredQuote.error);
}
return {
description: `Quote ${expiredQuote?.data?.quoteId} has expired`,
@@ -244,11 +263,12 @@ async function buildEventContent(
.from("salesOrder")
.select("*, customer(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (salesOrder.error) {
console.error("Failed to get salesOrder", salesOrder.error);
- throw salesOrder.error;
+ throw documentLookupError(salesOrder.error);
}
return {
@@ -274,6 +294,7 @@ async function buildEventContent(
.from("maintenanceDispatch")
.select("*, workCenter(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (maintenanceDispatchCreated.error) {
@@ -281,7 +302,7 @@ async function buildEventContent(
"Failed to get maintenanceDispatchCreated",
maintenanceDispatchCreated.error
);
- throw maintenanceDispatchCreated.error;
+ throw documentLookupError(maintenanceDispatchCreated.error);
}
return {
@@ -311,6 +332,7 @@ async function buildEventContent(
.from("maintenanceDispatch")
.select("*, workCenter(id, name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (maintenanceDispatch.error) {
@@ -318,7 +340,7 @@ async function buildEventContent(
"Failed to get maintenanceDispatch",
maintenanceDispatch.error
);
- throw maintenanceDispatch.error;
+ throw documentLookupError(maintenanceDispatch.error);
}
const workCenterName =
@@ -341,11 +363,12 @@ async function buildEventContent(
.from("nonConformance")
.select("*, location(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (nonConformance.error) {
console.error("Failed to get nonConformance", nonConformance.error);
- throw nonConformance.error;
+ throw documentLookupError(nonConformance.error);
}
return {
@@ -368,11 +391,12 @@ async function buildEventContent(
.from("job")
.select("*, customer(name), item(readableId, name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (job.error) {
console.error("Failed to get job", job.error);
- throw job.error;
+ throw documentLookupError(job.error);
}
return {
@@ -395,11 +419,12 @@ async function buildEventContent(
.from("job")
.select("*, customer(name), item(readableId, name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (completedJob.error) {
console.error("Failed to get job", completedJob.error);
- throw completedJob.error;
+ throw documentLookupError(completedJob.error);
}
return {
@@ -429,10 +454,11 @@ async function buildEventContent(
const jobs = await client
.from("job")
.select("id, jobId, dueDate, projectedCompletionAt")
- .in("id", ids);
+ .in("id", ids)
+ .eq("companyId", opts.companyId);
if (jobs.error) {
console.error("Failed to get jobs", jobs.error);
- throw jobs.error;
+ throw documentLookupError(jobs.error);
}
const rows = jobs.data ?? [];
if (rows.length === 0) return null;
@@ -460,11 +486,12 @@ async function buildEventContent(
.from("jobOperation")
.select("*, job(id, jobId), workCenter(name)")
.eq("id", operationId!)
+ .eq("companyId", opts.companyId)
.single();
if (jobOperation.error) {
console.error("Failed to get jobOperation", jobOperation.error);
- throw jobOperation.error;
+ throw documentLookupError(jobOperation.error);
}
const details = buildDetails([
@@ -499,11 +526,12 @@ async function buildEventContent(
.from("procedure")
.select("name, version, status, process(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (procedure.error) {
console.error("Failed to get procedure", procedure.error);
- throw procedure.error;
+ throw documentLookupError(procedure.error);
}
return {
@@ -528,11 +556,12 @@ async function buildEventContent(
.from("quote")
.select("*, customer(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (digitalQuote.error) {
console.error("Failed to get digital quote", digitalQuote.error);
- throw digitalQuote.error;
+ throw documentLookupError(digitalQuote.error);
}
// The email body renders the reference (quote id), so the outcome must
@@ -592,11 +621,12 @@ async function buildEventContent(
"gaugeId, description, gaugeCalibrationStatus, lastCalibrationDate, nextCalibrationDate"
)
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (gauge.error) {
console.error("Failed to get gauge", gauge.error);
- throw gauge.error;
+ throw documentLookupError(gauge.error);
}
return {
@@ -624,8 +654,7 @@ async function buildEventContent(
if (!docId) return null;
// Service-role lookups below — scope by companyId so a stale or
// mangled compound id can never surface another company's document.
- const companyId = opts?.companyId;
- if (!companyId) return null;
+ const { companyId } = opts;
const phrase =
outcome === "blocked"
@@ -645,7 +674,7 @@ async function buildEventContent(
if (salesInvoice.error) {
console.error("Failed to get salesInvoice", salesInvoice.error);
- throw salesInvoice.error;
+ throw documentLookupError(salesInvoice.error);
}
return {
@@ -668,7 +697,7 @@ async function buildEventContent(
if (salesOrder.error) {
console.error("Failed to get salesOrder", salesOrder.error);
- throw salesOrder.error;
+ throw documentLookupError(salesOrder.error);
}
return {
@@ -690,7 +719,7 @@ async function buildEventContent(
if (quote.error) {
console.error("Failed to get quote", quote.error);
- throw quote.error;
+ throw documentLookupError(quote.error);
}
return {
@@ -708,11 +737,12 @@ async function buildEventContent(
.from("stockTransfer")
.select("*, location(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (stockTransfer.error) {
console.error("Failed to get stockTransfer", stockTransfer.error);
- throw stockTransfer.error;
+ throw documentLookupError(stockTransfer.error);
}
// Number of line items to move — the header only has one location, so the
@@ -720,7 +750,8 @@ async function buildEventContent(
const { count: lineCount } = await client
.from("stockTransferLine")
.select("id", { count: "exact", head: true })
- .eq("stockTransferId", documentId);
+ .eq("stockTransferId", documentId)
+ .eq("companyId", opts.companyId);
return {
description: `Stock Transfer ${stockTransfer?.data?.stockTransferId} assigned to you`,
@@ -741,11 +772,12 @@ async function buildEventContent(
.from("pickingList")
.select("*, location(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (pickingList.error) {
console.error("Failed to get pickingList", pickingList.error);
- throw pickingList.error;
+ throw documentLookupError(pickingList.error);
}
return {
@@ -764,6 +796,7 @@ async function buildEventContent(
.from("trainingAssignment")
.select("*, training(id, name, type, frequency, estimatedDuration)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (trainingAssignment.error) {
@@ -771,7 +804,7 @@ async function buildEventContent(
"Failed to get trainingAssignment",
trainingAssignment.error
);
- throw trainingAssignment.error;
+ throw documentLookupError(trainingAssignment.error);
}
// Assigned-to-you training (vs ResourceTrainingAssignment, which
@@ -802,11 +835,12 @@ async function buildEventContent(
const assignments = await client
.from("trainingAssignment")
.select("id, training(id, name, type, frequency, estimatedDuration)")
- .in("id", ids);
+ .in("id", ids)
+ .eq("companyId", opts.companyId);
if (assignments.error) {
console.error("Failed to get trainingAssignments", assignments.error);
- throw assignments.error;
+ throw documentLookupError(assignments.error);
}
const rows = assignments.data ?? [];
if (rows.length === 0) return null;
@@ -868,13 +902,11 @@ async function buildEventContent(
period: periodByAssignment.get(assignment.id),
status: statusByAssignment.get(assignment.id),
title,
- url: opts?.companyId
- ? buildNotificationLink(
- NotificationEvent.TrainingReminder,
- assignment.id,
- opts.companyId
- )
- : undefined
+ url: buildNotificationLink(
+ NotificationEvent.TrainingReminder,
+ assignment.id,
+ opts.companyId
+ )
};
});
@@ -898,11 +930,12 @@ async function buildEventContent(
.from("training")
.select("name, type, status, version")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (training.error) {
console.error("Failed to get training", training.error);
- throw training.error;
+ throw documentLookupError(training.error);
}
// A newly available training (vs TrainingAssignment, which is a training
@@ -929,11 +962,12 @@ async function buildEventContent(
.from("purchaseOrder")
.select("*, supplier(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (purchaseOrder.error) {
console.error("Failed to get purchaseOrder", purchaseOrder.error);
- throw purchaseOrder.error;
+ throw documentLookupError(purchaseOrder.error);
}
return {
@@ -959,11 +993,12 @@ async function buildEventContent(
.from("purchaseInvoice")
.select("*, supplier!purchaseInvoice_supplierId_fkey(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (purchaseInvoice.error) {
console.error("Failed to get purchaseInvoice", purchaseInvoice.error);
- throw purchaseInvoice.error;
+ throw documentLookupError(purchaseInvoice.error);
}
return {
@@ -988,11 +1023,12 @@ async function buildEventContent(
.from("suggestion")
.select("*, user(id, fullName)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (suggestion.error) {
console.error("Failed to get suggestion", suggestion.error);
- throw suggestion.error;
+ throw documentLookupError(suggestion.error);
}
const submittedBy = suggestion.data.user?.fullName || "Anonymous";
@@ -1010,11 +1046,12 @@ async function buildEventContent(
.from("riskRegister")
.select("title, type, source, status, severity, likelihood")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (risk.error) {
console.error("Failed to get risk", risk.error);
- throw risk.error;
+ throw documentLookupError(risk.error);
}
return {
@@ -1045,11 +1082,12 @@ async function buildEventContent(
.from("purchasingRfq")
.select("*")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (purchasingRfq.error) {
console.error("Failed to get purchasing RFQ", purchasingRfq.error);
- throw purchasingRfq.error;
+ throw documentLookupError(purchasingRfq.error);
}
return {
@@ -1074,6 +1112,7 @@ async function buildEventContent(
.from("supplierQuote")
.select("*, supplier(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (supplierQuoteAssignment.error) {
@@ -1081,7 +1120,7 @@ async function buildEventContent(
"Failed to get supplier quote",
supplierQuoteAssignment.error
);
- throw supplierQuoteAssignment.error;
+ throw documentLookupError(supplierQuoteAssignment.error);
}
return {
@@ -1108,11 +1147,12 @@ async function buildEventContent(
.from("supplierQuote")
.select("*, supplier(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (supplierQuote.error) {
console.error("Failed to get supplier quote", supplierQuote.error);
- throw supplierQuote.error;
+ throw documentLookupError(supplierQuote.error);
}
const externalNotes = supplierQuote.data.externalNotes as Record<
@@ -1158,11 +1198,12 @@ async function buildEventContent(
outcome === "requested" ? "requires your approval" : `was ${outcome}`;
const docPhrase = poPhrase;
- if (documentType === "purchaseOrder") {
+ if (opts.documentType === "purchaseOrder") {
const po = await client
.from("purchaseOrder")
.select("purchaseOrderId, supplierReference, status, supplier(name)")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (po.error || !po.data) {
@@ -1187,11 +1228,12 @@ async function buildEventContent(
};
}
- if (documentType === "qualityDocument") {
+ if (opts.documentType === "qualityDocument") {
const qd = await client
.from("qualityDocument")
.select("name, status, version")
.eq("id", documentId)
+ .eq("companyId", opts.companyId)
.single();
if (qd.error || !qd.data) {
@@ -1232,12 +1274,7 @@ async function buildEventContent(
case NotificationEvent.ChangeNoticeImplementation:
case NotificationEvent.ChangeNoticeDone: {
// Company-scope both lookups: readable ids (ECO-…) repeat across tenants.
- const companyId = opts?.companyId;
- if (!companyId) {
- throw new Error(
- `companyId is required to resolve change notice ${documentId}`
- );
- }
+ const { companyId } = opts;
// documentId may be the row id (co_…) or the readable id (ECO-…) — try both.
const changeNoticeColumns =
@@ -1250,7 +1287,7 @@ async function buildEventContent(
.maybeSingle();
if (rowLookup.error) {
console.error("Failed to get changeOrder", rowLookup.error);
- throw rowLookup.error;
+ throw documentLookupError(rowLookup.error);
}
let changeNoticeData = rowLookup.data;
@@ -1263,13 +1300,15 @@ async function buildEventContent(
.maybeSingle();
if (readableIdLookup.error) {
console.error("Failed to get changeOrder", readableIdLookup.error);
- throw readableIdLookup.error;
+ throw documentLookupError(readableIdLookup.error);
}
changeNoticeData = readableIdLookup.data;
}
if (!changeNoticeData) {
- throw new Error(`Change notice not found for documentId ${documentId}`);
+ throw new NonRetriableError(
+ `Change notice not found for documentId ${documentId}`
+ );
}
const readableId = changeNoticeData.changeOrderId;
@@ -1374,16 +1413,9 @@ export async function getNotificationContent(
type: NotificationEvent,
documentId: string,
from: string | undefined,
- documentType?: ApprovalDocumentType,
- opts?: EventContentOptions
+ opts: EventContentOptions
): Promise<NotificationContent | null> {
- const content = await buildEventContent(
- client,
- type,
- documentId,
- documentType,
- opts
- );
+ const content = await buildEventContent(client, type, documentId, opts);
if (!content) return content;
const actorLabel = getActorLabel(type);
diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.ts
index 6968fc266c..b4dab8498c 100644
--- a/packages/jobs/src/inngest/functions/notifications/notify.ts
+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts
@@ -230,11 +230,11 @@ export const notifyFunction = inngest.createFunction(
payload.event,
primaryDocumentId,
payload.from,
- payload.documentType,
{
body: payload.body,
companyId: payload.companyId,
documentIds: payload.documentIds,
+ documentType: payload.documentType,
title: payload.title,
userId:
payload.recipient.type === "user"
diff --git a/packages/kv/AGENTS.md b/packages/kv/AGENTS.md
index 06ce15bd44..678ace2b22 100644
--- a/packages/kv/AGENTS.md
+++ b/packages/kv/AGENTS.md
@@ -32,7 +32,7 @@ pnpm --filter @carbon/kv typecheck
| Export | Provides |
|--------|----------|
| `redis` | Global ioredis singleton (lazy connect, 3 retries, offline queue), resilience-wrapped to fail soft when Redis is unreachable |
-| `Ratelimit` | Rate limiter class with `limit()`, `blockUntilReady()`, `getRemaining()`, `resetUsedTokens()` |
+| `Ratelimit` | Rate limiter class with `limit()`, `blockUntilReady()`, `getRemaining()`, `resetUsedTokens()`, `refund()` (sliding window only: give back a token `limit()` consumed, for consume-before-verify callers such as MES console pin-in) |
| `Ratelimit.fixedWindow(tokens, window)` | Fixed window algorithm (simple, low memory) |
| `Ratelimit.slidingWindow(tokens, window)` | Sliding window (smoother, prevents boundary bursts) |
| `Ratelimit.tokenBucket(refillRate, interval, maxTokens?)` | Token bucket (allows controlled bursts) |
diff --git a/packages/kv/src/ratelimit/ratelimit.test.ts b/packages/kv/src/ratelimit/ratelimit.test.ts
index 6af60665ec..414e1eb31a 100644
--- a/packages/kv/src/ratelimit/ratelimit.test.ts
+++ b/packages/kv/src/ratelimit/ratelimit.test.ts
@@ -1,4 +1,5 @@
import type { Redis } from "ioredis";
+import RedisMock from "ioredis-mock";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Ratelimit } from "./ratelimit";
@@ -541,3 +542,67 @@ describe("Ratelimit", () => {
});
});
});
+
+// These run the REAL Lua scripts (ioredis-mock executes them), so they pin what
+// Redis does with the counters rather than what a stubbed `eval` returns.
+describe("refund() against the real window scripts", () => {
+ beforeEach(async () => {
+ // Only the clock is faked — mid-window, so no test straddles a boundary.
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2024-01-01T00:30:00.000Z"));
+ // ioredis-mock instances share one keyspace; start every test empty.
+ await new RedisMock().flushall();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ const create = () =>
+ new Ratelimit({
+ redis: new RedisMock() as unknown as Redis,
+ limiter: Ratelimit.slidingWindow(2, "1 h"),
+ timeout: 0
+ });
+
+ it("a concurrent burst consumes at most the budget", async () => {
+ const ratelimit = create();
+ const results = await Promise.all(
+ Array.from({ length: 10 }, () => ratelimit.limit("terminal"))
+ );
+ expect(results.filter((r) => r.success)).toHaveLength(2);
+ });
+
+ it("returns a consumed token so the next call passes", async () => {
+ const ratelimit = create();
+ expect((await ratelimit.limit("terminal")).success).toBe(true);
+ expect((await ratelimit.limit("terminal")).success).toBe(true);
+ expect((await ratelimit.limit("terminal")).success).toBe(false);
+
+ await ratelimit.refund("terminal");
+
+ expect((await ratelimit.limit("terminal")).success).toBe(true);
+ expect((await ratelimit.limit("terminal")).success).toBe(false);
+ });
+
+ it("never banks credit below zero", async () => {
+ const ratelimit = create();
+ await ratelimit.refund("terminal");
+ await ratelimit.refund("terminal");
+
+ expect((await ratelimit.limit("terminal")).success).toBe(true);
+ expect((await ratelimit.limit("terminal")).success).toBe(true);
+ expect((await ratelimit.limit("terminal")).success).toBe(false);
+ });
+
+ it("only returns the identifier's own token", async () => {
+ const ratelimit = create();
+ await ratelimit.limit("a");
+ await ratelimit.limit("a");
+ await ratelimit.limit("b");
+
+ await ratelimit.refund("b");
+
+ expect((await ratelimit.limit("a")).success).toBe(false);
+ });
+});
diff --git a/packages/kv/src/ratelimit/ratelimit.ts b/packages/kv/src/ratelimit/ratelimit.ts
index bb0d465c17..616c4175c0 100644
--- a/packages/kv/src/ratelimit/ratelimit.ts
+++ b/packages/kv/src/ratelimit/ratelimit.ts
@@ -4,6 +4,7 @@ import { ms } from "./duration";
import {
fixedWindowRemainingScript,
fixedWindowScript,
+ slidingWindowRefundScript,
slidingWindowRemainingScript,
slidingWindowScript,
tokenBucketRemainingScript,
@@ -181,6 +182,23 @@ export class Ratelimit {
}
}
+ /**
+ * Give back one token a successful `limit()` consumed — for callers that
+ * must consume BEFORE doing the work (so a concurrent burst cannot all pass a
+ * read-only check) but only want some outcomes to count. Sliding window
+ * only: the fixed window counts rejected calls too, and a token bucket has no
+ * counter, so both keep the token. Never goes below zero.
+ * @param identifier - Unique identifier
+ */
+ async refund(identifier: string): Promise<void> {
+ const key = this.getKey(identifier);
+ try {
+ await this.limiter().refund?.(this.ctx, key);
+ } catch {
+ // Redis down: limit() failed open too, so there is nothing to give back.
+ }
+ }
+
private getKey(identifier: string): string {
return `${this.prefix}:${identifier}`;
}
@@ -336,6 +354,16 @@ export class Ratelimit {
const currentKey = `${key}:${currentWindow}`;
const previousKey = `${key}:${currentWindow - 1}`;
await ctx.redis.del(currentKey, previousKey);
+ },
+
+ async refund(ctx, key) {
+ const currentWindow = Math.floor(Date.now() / windowMs);
+ await ctx.redis.eval(
+ slidingWindowRefundScript,
+ 2,
+ `${key}:${currentWindow}`,
+ `${key}:${currentWindow - 1}`
+ );
}
});
}
diff --git a/packages/kv/src/ratelimit/scripts.ts b/packages/kv/src/ratelimit/scripts.ts
index 3b806d8d0a..a5bb2dd529 100644
--- a/packages/kv/src/ratelimit/scripts.ts
+++ b/packages/kv/src/ratelimit/scripts.ts
@@ -142,6 +142,29 @@ local usedTokens = requestsInPreviousWindow + requestsInCurrentWindow
return {tokens - usedTokens, tokens}
`;
+/**
+ * Sliding Window Refund — give back one token a successful `limit()` consumed
+ *
+ * Decrements the first of KEYS that holds a positive count, never below zero.
+ * Current window first, then previous, so a refund that lands just after a
+ * window boundary still returns the token to the window that took it.
+ *
+ * KEYS[1] = current window key
+ * KEYS[2] = previous window key
+ *
+ * Returns: 1 when a token was returned, 0 when there was nothing to return
+ */
+export const slidingWindowRefundScript = `
+for _, key in ipairs(KEYS) do
+ local value = redis.call("GET", key)
+ if value and tonumber(value) > 0 then
+ redis.call("DECRBY", key, 1)
+ return 1
+ end
+end
+return 0
+`;
+
/**
* Token Bucket Rate Limiting
*
diff --git a/packages/kv/src/ratelimit/types.ts b/packages/kv/src/ratelimit/types.ts
index 30d6d57a86..b2028ee297 100644
--- a/packages/kv/src/ratelimit/types.ts
+++ b/packages/kv/src/ratelimit/types.ts
@@ -53,6 +53,12 @@ export interface Algorithm {
* Reset the rate limit for a key
*/
resetTokens: (ctx: RatelimitContext, key: string) => Promise<void>;
+
+ /**
+ * Give back one token a successful `limit()` consumed. Sliding window only;
+ * the others leave the token spent.
+ */
+ refund?: (ctx: RatelimitContext, key: string) => Promise<void>;
}
/**
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 7da21654c3..9fbedde1d9 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} Werte"
msgid "{0} values missing"
msgstr "{0} Werte fehlen"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} wird als {name} gespeichert"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90 Tage"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Eine «muss übereinstimmen»-Regel für diesen Verfahren blockiert diese vor dem Teilen eines Los"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Eine 4-stellige PIN wird generiert, wenn ein Werker erstellt wird."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Ein Los benötigt mindestens einen Arbeitsgang. Um das ganze Los aufzulösen, nutzen Sie stattdessen Auflösen."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Eine von Carbon durchgeführte Datenmigration – Sie laden Ihre eigenen Daten"
@@ -1383,6 +1390,9 @@ msgstr "Unternehmen hinzufügen"
msgid "Add condition"
msgstr "Bedingung hinzufügen"
+msgid "Add Console Operator"
+msgstr "Konsolenbediener hinzufügen"
+
msgid "Add Contractor"
msgstr "Externen Mitarbeiter hinzufügen"
@@ -3286,6 +3296,10 @@ msgstr "Die einzige aktive Pause kann nicht deaktiviert werden. Fügen Sie statt
msgid "Can't download this file"
msgstr "Diese Datei kann nicht heruntergeladen werden"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Datei mit dem Namen {0} kann nicht hochgeladen werden"
+
msgid "Cancel"
msgstr "Abbrechen"
@@ -4101,6 +4115,9 @@ msgstr "Konsolenmodus ist aktiviert"
msgid "Console Operator"
msgstr "Konsolenbediener"
+msgid "Console Operator Created"
+msgstr "Konsolenbediener erstellt"
+
msgid "consumable"
msgstr "Verbrauchsmaterial"
@@ -4344,9 +4361,6 @@ msgstr "Teilenummer kopieren"
msgid "Copy part unique identifier"
msgstr "Eindeutige Teilkennung kopieren"
-msgid "Copy PIN"
-msgstr "PIN kopieren"
-
msgid "Copy previous day"
msgstr "Vorherigen Tag kopieren"
@@ -4668,6 +4682,9 @@ msgstr "Neu erstellen"
msgid "Create new rule"
msgstr "Neue Regel erstellen"
+msgid "Create Operator"
+msgstr "Werker erstellen"
+
msgid "Create PO Revision"
msgstr "Bestellungsrevision erstellen"
@@ -8087,8 +8104,8 @@ msgstr "Hauptbuch und Monatsabschluss"
msgid "Generate"
msgstr "Generieren"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Generieren Sie eine neue 4-stellige PIN. Teilen Sie sie dem Werker mit, damit er sich an MES-Terminals anmelden kann."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Generieren Sie eine neue 4-stellige PIN. Die aktuelle PIN des Werkers funktioniert sofort nicht mehr."
msgid "Generate and send customer invoices"
msgstr "Kundenrechnungen generieren und versenden"
@@ -8102,9 +8119,6 @@ msgstr "Geschäftsjahr generieren"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Generieren Sie Material-IDs und Beschreibungen basierend auf den Eigenschaften des Materials."
-msgid "Generate new PIN"
-msgstr "Neue PIN generieren"
-
msgid "Generate Picking List"
msgstr "Kommissionierliste generieren"
@@ -10902,9 +10916,6 @@ msgstr "Neue Zahlungsbedingung"
msgid "New Picking List"
msgstr "Neue Kommissionierliste"
-msgid "New PIN"
-msgstr "Neue PIN"
-
msgid "New PO"
msgstr "Neue Bestellung"
@@ -14118,9 +14129,6 @@ msgstr "Verbleibend"
msgid "Remaining after split stays on the original row."
msgstr "Verbleibende Menge bleibt in der ursprünglichen Zeile."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Merken Sie sich diese PIN. Sie benötigen sie, um den Konsolenmodus auf MES-Terminals zu beenden."
-
msgid "Remove"
msgstr "Entfernen"
@@ -14130,7 +14138,7 @@ msgstr "Entfernen {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "{0} aus Los entfernen"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Entfernen Sie {0} aus diesem Los? Sein Arbeitsgang kehrt zum Terminplan
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "{0} von {memberCount} Arbeitsgängen aus {1} entfernen?"
msgid "Remove {label}"
msgstr "Entfernen {label}"
@@ -14561,6 +14569,9 @@ msgstr "Rückgabegrund"
msgid "Return Reasons"
msgstr "Rückgabegründe"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Wechseln Sie zu Integrationen zurück und verbinden Sie Onshape erneut."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Kehren Sie zu „Integrationen“ zurück und verbinden Sie Ramp erneut."
@@ -15821,6 +15832,12 @@ msgstr "Link teilen"
msgid "Share Quote"
msgstr "Angebot teilen"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Teilen Sie diese PIN mit {name}, damit sie sich bei MES-Terminals anmelden können."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Teilen Sie diese PIN mit dem Werker, damit er sich bei MES-Terminals anmelden kann."
+
msgid "Shared"
msgstr "Geteilt"
@@ -17598,6 +17615,9 @@ msgstr "Die Anzahl der Monate, über die dieses Vermögen abgeschrieben wird."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Das Handbestandsniveau, das eine neue Auffüllungsbestellung gemäß den mengengestützten Richtlinien auslöst."
+msgid "The Onshape connection expired"
+msgstr "Die Onshape-Verbindung ist abgelaufen"
+
msgid "The operations and steps your parts move through"
msgstr "Die Arbeitsgänge und Schritte, die Ihre Teile durchlaufen"
@@ -18148,6 +18168,15 @@ msgstr "Dieser Pfad entscheidet nur darüber, was als nächstes ausgeführt wird
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Dieser Zeitraum hat keine gebuchten Buchungssätze und kann dauerhaft gelöscht werden. Dies kann nicht rückgängig gemacht werden."
+msgid "This PIN will not be shown again."
+msgstr "Diese PIN wird nicht mehr angezeigt."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Diese PIN wird nicht mehr angezeigt. Wenn Sie sie vergessen haben, setzen Sie sie in der Operatorliste zurück."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Diese PIN wird nicht mehr angezeigt. Sie benötigen sie, um den Konsolenmodus auf MES-Terminals zu beenden."
+
msgid "this purchase order"
msgstr "diese Bestellung"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 1c75694284..38dff3d42d 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} values"
msgid "{0} values missing"
msgstr "{0} values missing"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} will be saved as {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,6 +542,9 @@ msgstr "90D"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "A \"must match\" rule on this process blocks these from sharing a batch"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "A 4-digit PIN is generated when the operator is created."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
msgstr "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
@@ -1383,6 +1390,9 @@ msgstr "Add Company"
msgid "Add condition"
msgstr "Add condition"
+msgid "Add Console Operator"
+msgstr "Add Console Operator"
+
msgid "Add Contractor"
msgstr "Add Contractor"
@@ -3286,6 +3296,10 @@ msgstr "Can't disable the only active break. Add another break or toggle the ove
msgid "Can't download this file"
msgstr "Can't download this file"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Can't upload a file named {0}"
+
msgid "Cancel"
msgstr "Cancel"
@@ -4101,6 +4115,9 @@ msgstr "Console mode is enabled"
msgid "Console Operator"
msgstr "Console Operator"
+msgid "Console Operator Created"
+msgstr "Console Operator Created"
+
msgid "consumable"
msgstr "consumable"
@@ -4344,9 +4361,6 @@ msgstr "Copy part number"
msgid "Copy part unique identifier"
msgstr "Copy part unique identifier"
-msgid "Copy PIN"
-msgstr "Copy PIN"
-
msgid "Copy previous day"
msgstr "Copy previous day"
@@ -4668,6 +4682,9 @@ msgstr "Create New"
msgid "Create new rule"
msgstr "Create new rule"
+msgid "Create Operator"
+msgstr "Create Operator"
+
msgid "Create PO Revision"
msgstr "Create PO Revision"
@@ -8087,8 +8104,8 @@ msgstr "General Ledger and month-end close"
msgid "Generate"
msgstr "Generate"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
msgid "Generate and send customer invoices"
msgstr "Generate and send customer invoices"
@@ -8102,9 +8119,6 @@ msgstr "Generate Fiscal Year"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Generate material IDs and descriptions based on the properties of the material."
-msgid "Generate new PIN"
-msgstr "Generate new PIN"
-
msgid "Generate Picking List"
msgstr "Generate Picking List"
@@ -10902,9 +10916,6 @@ msgstr "New Payment Term"
msgid "New Picking List"
msgstr "New Picking List"
-msgid "New PIN"
-msgstr "New PIN"
-
msgid "New PO"
msgstr "New PO"
@@ -14118,9 +14129,6 @@ msgstr "Remaining"
msgid "Remaining after split stays on the original row."
msgstr "Remaining after split stays on the original row."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Remember this PIN. You will need it to exit console mode on MES terminals."
-
msgid "Remove"
msgstr "Remove"
@@ -14561,6 +14569,9 @@ msgstr "Return Reason"
msgid "Return Reasons"
msgstr "Return Reasons"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Return to Integrations and connect Onshape again."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Return to Integrations and connect Ramp again."
@@ -15821,6 +15832,12 @@ msgstr "Share Link"
msgid "Share Quote"
msgstr "Share Quote"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Share this PIN with {name} so they can pin in at MES terminals."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Share this PIN with the operator so they can pin in at MES terminals."
+
msgid "Shared"
msgstr "Shared"
@@ -17598,6 +17615,9 @@ msgstr "The number of months over which this asset will be depreciated."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "The on-hand level that triggers a new replenishment order under the quantity-based policies."
+msgid "The Onshape connection expired"
+msgstr "The Onshape connection expired"
+
msgid "The operations and steps your parts move through"
msgstr "The operations and steps your parts move through"
@@ -18148,6 +18168,15 @@ msgstr "This path only decides what runs next"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
+msgid "This PIN will not be shown again."
+msgstr "This PIN will not be shown again."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "This PIN will not be shown again. If it is lost, reset it from the operators list."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+
msgid "this purchase order"
msgstr "this purchase order"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 8294d243d1..72817595df 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} valores"
msgid "{0} values missing"
msgstr "{0} valores faltantes"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} se guardará como {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90 días"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Una regla \"debe coincidir\" en este proceso impide que estos compartan un lote de producción"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Se genera un PIN de 4 dígitos cuando se crea el operario."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Un lote de producción necesita al menos una operación. Para dividir el lote de producción completo, utilice Disolver en su lugar."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Una migración de datos ejecutada por Carbon — usted carga sus propios datos"
@@ -1383,6 +1390,9 @@ msgstr "Agregar Empresa"
msgid "Add condition"
msgstr "Agregar condición"
+msgid "Add Console Operator"
+msgstr "Agregar Operador de consola"
+
msgid "Add Contractor"
msgstr "Agregar Contratista"
@@ -3286,6 +3296,10 @@ msgstr "No puede desactivar el único descanso activo. Agregue otro descanso o c
msgid "Can't download this file"
msgstr "No se puede descargar este archivo"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "No se puede subir un archivo llamado {0}"
+
msgid "Cancel"
msgstr "Cancelar"
@@ -4101,6 +4115,9 @@ msgstr "El modo de consola está habilitado"
msgid "Console Operator"
msgstr "Operador de Consola"
+msgid "Console Operator Created"
+msgstr "Operador de consola creado"
+
msgid "consumable"
msgstr "consumible"
@@ -4344,9 +4361,6 @@ msgstr "Copiar número de parte"
msgid "Copy part unique identifier"
msgstr "Copiar identificador único de la pieza"
-msgid "Copy PIN"
-msgstr "Copiar PIN"
-
msgid "Copy previous day"
msgstr "Copiar día anterior"
@@ -4668,6 +4682,9 @@ msgstr "Crear nuevo"
msgid "Create new rule"
msgstr "Crear nueva regla"
+msgid "Create Operator"
+msgstr "Crear operario"
+
msgid "Create PO Revision"
msgstr "Crear Revisión de Orden de Compra"
@@ -8087,8 +8104,8 @@ msgstr "Libro Mayor y cierre de fin de mes"
msgid "Generate"
msgstr "Generar"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Generar un nuevo PIN de 4 dígitos. Compártelo con el operador para que pueda registrarse en los terminales MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Genere un nuevo PIN de 4 dígitos. El PIN actual del operario deja de funcionar inmediatamente."
msgid "Generate and send customer invoices"
msgstr "Generar y enviar facturas de cliente"
@@ -8102,9 +8119,6 @@ msgstr "Generar ejercicio fiscal"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Generar IDs de materiales y descripciones basadas en las propiedades del material."
-msgid "Generate new PIN"
-msgstr "Generar nuevo PIN"
-
msgid "Generate Picking List"
msgstr "Generar Lista de Picking"
@@ -10902,9 +10916,6 @@ msgstr "Nuevas condiciones de pago"
msgid "New Picking List"
msgstr "Nueva Lista de Picking"
-msgid "New PIN"
-msgstr "Nuevo PIN"
-
msgid "New PO"
msgstr "Nuevo PO"
@@ -14118,9 +14129,6 @@ msgstr "Restante"
msgid "Remaining after split stays on the original row."
msgstr "Lo restante después de dividir permanece en la fila original."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Recuerda este PIN. Lo necesitarás para salir del modo consola en terminales MES."
-
msgid "Remove"
msgstr "Quitar"
@@ -14130,7 +14138,7 @@ msgstr "Quitar {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Quitar {0} del lote de producción"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "¿Quitar {0} de este lote? Su operación vuelve al programa para ejecuta
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "¿Quitar {0} de {memberCount} operaciones de {1}?"
msgid "Remove {label}"
msgstr "Quitar {label}"
@@ -14561,6 +14569,9 @@ msgstr "Motivo de la devolución"
msgid "Return Reasons"
msgstr "Motivos de la devolución"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Volver a Integraciones y conectar Onshape nuevamente."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Vuelve a Integraciones y conecta Ramp de nuevo."
@@ -15821,6 +15832,12 @@ msgstr "Enlace compartido"
msgid "Share Quote"
msgstr "Compartir Cotización"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Comparta este PIN con {name} para que pueda acceder en terminales MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Comparta este PIN con el operario para que pueda acceder en terminales MES."
+
msgid "Shared"
msgstr "Compartido"
@@ -17598,6 +17615,9 @@ msgstr "El número de meses durante los cuales este activo será depreciado."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "El nivel de inventario en mano que activa un nuevo pedido de reabastecimiento según las políticas basadas en cantidad."
+msgid "The Onshape connection expired"
+msgstr "La conexión de Onshape venció"
+
msgid "The operations and steps your parts move through"
msgstr "Las operaciones y pasos por los que se mueven tus piezas"
@@ -18148,6 +18168,15 @@ msgstr "Esta ruta solo decide qué se ejecuta a continuación"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Este período no tiene asientos de diario registrados en él y puede eliminarse permanentemente. No se puede deshacer."
+msgid "This PIN will not be shown again."
+msgstr "Este PIN no se mostrará nuevamente."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Este PIN no se mostrará nuevamente. Si se pierde, restablézcalo desde la lista de operarios."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Este PIN no se mostrará nuevamente. Lo necesitará para salir del modo de consola en terminales MES."
+
msgid "this purchase order"
msgstr "esta orden de compra"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 4c3194c4e4..aca637d9fb 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} valeurs"
msgid "{0} values missing"
msgstr "{0} valeurs manquantes"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} sera enregistré en tant que {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}j"
@@ -538,8 +542,11 @@ msgstr "90 jours"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Une règle « doit correspondre » sur ce procédé empêche ces articles de partager un lot de production"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Un code PIN à 4 chiffres est généré lors de la création de l'opérateur."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Un lot de production a besoin d'au moins une opération. Pour diviser tout le lot, utilisez plutôt Dissoudre."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Une migration de données gérée par Carbon — vous chargez vos propres données"
@@ -1383,6 +1390,9 @@ msgstr "Ajouter Société"
msgid "Add condition"
msgstr "Ajouter une condition"
+msgid "Add Console Operator"
+msgstr "Ajouter un opérateur console"
+
msgid "Add Contractor"
msgstr "Ajouter Prestataire"
@@ -3286,6 +3296,10 @@ msgstr "Impossible de désactiver le seul palier actif. Ajoutez un autre palier
msgid "Can't download this file"
msgstr "Impossible de télécharger ce fichier"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Impossible de téléverser un fichier nommé {0}"
+
msgid "Cancel"
msgstr "Annuler"
@@ -4101,6 +4115,9 @@ msgstr "Le mode console est activé"
msgid "Console Operator"
msgstr "Opérateur Console"
+msgid "Console Operator Created"
+msgstr "Opérateur console créé"
+
msgid "consumable"
msgstr "consommable"
@@ -4344,9 +4361,6 @@ msgstr "Copier le numéro de pièce"
msgid "Copy part unique identifier"
msgstr "Copier l'identifiant unique de la pièce"
-msgid "Copy PIN"
-msgstr "Copier le PIN"
-
msgid "Copy previous day"
msgstr "Copier le jour précédent"
@@ -4668,6 +4682,9 @@ msgstr "Créer nouveau"
msgid "Create new rule"
msgstr "Créer une nouvelle règle"
+msgid "Create Operator"
+msgstr "Créer un opérateur"
+
msgid "Create PO Revision"
msgstr "Créer une révision de bon de commande"
@@ -8087,8 +8104,8 @@ msgstr "Grand livre et clôture de fin de mois"
msgid "Generate"
msgstr "Générer"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Générez un nouveau PIN à 4 chiffres. Partagez-le avec l'opérateur pour qu'il puisse se connecter aux terminaux MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Générer un nouveau code PIN à 4 chiffres. Le code PIN actuel de l'opérateur cessera de fonctionner immédiatement."
msgid "Generate and send customer invoices"
msgstr "Générer et envoyer les factures clients"
@@ -8102,9 +8119,6 @@ msgstr "Générer un exercice comptable"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Générer les IDs de matériaux et les descriptions en fonction des propriétés du matériau."
-msgid "Generate new PIN"
-msgstr "Générer un nouveau PIN"
-
msgid "Generate Picking List"
msgstr "Générer la liste de prélèvement"
@@ -10902,9 +10916,6 @@ msgstr "Nouvelles conditions de paiement"
msgid "New Picking List"
msgstr "Nouvelle Liste de Prélèvement"
-msgid "New PIN"
-msgstr "Nouveau PIN"
-
msgid "New PO"
msgstr "Nouveau BC"
@@ -14118,9 +14129,6 @@ msgstr "Restant"
msgid "Remaining after split stays on the original row."
msgstr "Le reste après la division reste sur la ligne d'origine."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Mémorisez ce code PIN. Vous en aurez besoin pour quitter le mode console sur les terminaux MES."
-
msgid "Remove"
msgstr "Retirer"
@@ -14130,7 +14138,7 @@ msgstr "Retirer {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Retirer {0} du lot de production"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Retirer {0} de ce lot de production ? Son opération retourne au plannin
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "Retirer {0} sur {memberCount} opérations de {1} ?"
msgid "Remove {label}"
msgstr "Retirer {label}"
@@ -14561,6 +14569,9 @@ msgstr "Motif de retour"
msgid "Return Reasons"
msgstr "Motifs de retour"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Retourner à Intégrations et reconnecter Onshape."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Retournez dans Intégrations et reconnectez Ramp."
@@ -15821,6 +15832,12 @@ msgstr "Lien de partage"
msgid "Share Quote"
msgstr "Partager le devis"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Partagez ce code PIN avec {name} pour qu'ils puissent se connecter sur les terminaux MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Partagez ce code PIN avec l'opérateur pour qu'il puisse se connecter sur les terminaux MES."
+
msgid "Shared"
msgstr "Partagé"
@@ -17598,6 +17615,9 @@ msgstr "Le nombre de mois sur lesquels cet actif sera amorti."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Le niveau d'inventaire en main qui déclenche un nouvel ordre de réapprovisionnement selon les politiques basées sur la quantité."
+msgid "The Onshape connection expired"
+msgstr "La connexion Onshape a expiré"
+
msgid "The operations and steps your parts move through"
msgstr "Les opérations et les étapes par lesquelles vos pièces passent"
@@ -18148,6 +18168,15 @@ msgstr "Ce chemin décide seulement de ce qui s'exécute ensuite"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Cette période n'a aucune écriture de journal comptabilisée et peut être supprimée définitivement. Cela ne peut pas être annulé."
+msgid "This PIN will not be shown again."
+msgstr "Ce code PIN ne sera plus affiché."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Ce code PIN ne sera plus affiché. Si vous l'avez oublié, réinitialisez-le à partir de la liste des opérateurs."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Ce code PIN ne sera plus affiché. Vous en aurez besoin pour quitter le mode console sur les terminaux MES."
+
msgid "this purchase order"
msgstr "ce bon de commande"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 5ab231a455..907424f05d 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} मान"
msgid "{0} values missing"
msgstr "{0} मान गायब हैं"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} को {name} के रूप में सहेजा जाएगा"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}द"
@@ -538,8 +542,11 @@ msgstr "90 दिन"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "इस प्रक्रिया पर एक \"मेल खाना चाहिए\" नियम इन्हें एक बैच साझा करने से रोकता है"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "ऑपरेटर बनाए जाने पर एक 4-अंकीय PIN बनाया जाता है।"
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "बैच को कम से कम एक ऑपरेशन की आवश्यकता है। पूरे बैच को विभाजित करने के लिए, इसके बजाय विघटन का उपयोग करें।"
msgid "A Carbon-run data migration — you load your own data"
msgstr "एक कार्बन-चलाया गया डेटा माइग्रेशन — आप अपना डेटा लोड करते हैं"
@@ -1383,6 +1390,9 @@ msgstr "कंपनी जोड़ें"
msgid "Add condition"
msgstr "शर्त जोड़ें"
+msgid "Add Console Operator"
+msgstr "कंसोल ऑपरेटर जोड़ें"
+
msgid "Add Contractor"
msgstr "ठेकेदार जोड़ें"
@@ -3286,6 +3296,10 @@ msgstr "केवल सक्रिय ब्रेक को अक्षम
msgid "Can't download this file"
msgstr "इस फ़ाइल को डाउनलोड नहीं कर सकते"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "{0} नाम की फ़ाइल अपलोड नहीं की जा सकती"
+
msgid "Cancel"
msgstr "रद्द करें"
@@ -4101,6 +4115,9 @@ msgstr "कंसोल मोड सक्षम है"
msgid "Console Operator"
msgstr "कंसोल ऑपरेटर"
+msgid "Console Operator Created"
+msgstr "कंसोल ऑपरेटर बनाया गया"
+
msgid "consumable"
msgstr "उपभोग्य सामग्री"
@@ -4344,9 +4361,6 @@ msgstr "भाग संख्या कॉपी करें"
msgid "Copy part unique identifier"
msgstr "भाग के अद्वितीय पहचानकर्ता की प्रतिलिपि बनाएं"
-msgid "Copy PIN"
-msgstr "PIN कॉपी करें"
-
msgid "Copy previous day"
msgstr "पिछले दिन से कॉपी करें"
@@ -4668,6 +4682,9 @@ msgstr "नया बनाएँ"
msgid "Create new rule"
msgstr "नया नियम बनाएं"
+msgid "Create Operator"
+msgstr "ऑपरेटर बनाएँ"
+
msgid "Create PO Revision"
msgstr "क्रय आदेश रिवीजन बनाएँ"
@@ -8087,8 +8104,8 @@ msgstr "सामान्य खाता बही और महीने क
msgid "Generate"
msgstr "उत्पन्न करें"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "एक नया 4-अंकीय PIN जेनरेट करें। इसे ऑपरेटर के साथ साझा करें ताकि वे MES टर्मिनल पर पिन इन कर सकें।"
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "एक नया 4-अंकीय PIN बनाएँ। ऑपरेटर का वर्तमान PIN तुरंत काम करना बंद कर देगा।"
msgid "Generate and send customer invoices"
msgstr "ग्राहक चालान उत्पन्न करें और भेजें"
@@ -8102,9 +8119,6 @@ msgstr "वित्तीय वर्ष उत्पन्न करें"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "सामग्री के गुणों के आधार पर सामग्री आईडी और विवरण उत्पन्न करें।"
-msgid "Generate new PIN"
-msgstr "नया PIN जेनरेट करें"
-
msgid "Generate Picking List"
msgstr "पिकिंग सूची जेनरेट करें"
@@ -10902,9 +10916,6 @@ msgstr "नई भुगतान शर्तें"
msgid "New Picking List"
msgstr "नई पिकिंग सूची"
-msgid "New PIN"
-msgstr "नया PIN"
-
msgid "New PO"
msgstr "नया PO"
@@ -14118,9 +14129,6 @@ msgstr "शेष"
msgid "Remaining after split stays on the original row."
msgstr "विभाजन के बाद शेष मूल पंक्ति पर रहता है।"
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "इस PIN को याद रखें। MES टर्मिनल पर कंसोल मोड से बाहर निकलने के लिए आपको इसकी आवश्यकता होगी।"
-
msgid "Remove"
msgstr "निकालें"
@@ -14130,7 +14138,7 @@ msgstr "निकालें {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "बैच से {0} निकालें"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "इस बैच से {0} को निकालें? इसका
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "क्या बैच {1} से {memberCount} में से {0} ऑपरेशन निकाले जाएँ?"
msgid "Remove {label}"
msgstr "निकालें {label}"
@@ -14561,6 +14569,9 @@ msgstr "रिटर्न कारण"
msgid "Return Reasons"
msgstr "रिटर्न कारण"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "एकीकरण पर वापस लौटें और Onshape को फिर से कनेक्ट करें।"
+
msgid "Return to Integrations and connect Ramp again."
msgstr "एकीकरण पर वापस जाएँ और Ramp को फिर से कनेक्ट करें।"
@@ -15821,6 +15832,12 @@ msgstr "लिंक साझा करें"
msgid "Share Quote"
msgstr "उद्धरण साझा करें"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "{name} के साथ यह PIN साझा करें ताकि वे MES टर्मिनल पर पिन इन कर सकें।"
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "इस PIN को ऑपरेटर के साथ साझा करें ताकि वे MES टर्मिनल पर पिन इन कर सकें।"
+
msgid "Shared"
msgstr "साझा"
@@ -17598,6 +17615,9 @@ msgstr "महीनों की संख्या जिसके दौर
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "हाथ पर रखी गई स्तर जो मात्रा-आधारित नीतियों के तहत एक नई पुनः भरण आदेश को ट्रिगर करता है।"
+msgid "The Onshape connection expired"
+msgstr "Onshape कनेक्शन समाप्त हो गया"
+
msgid "The operations and steps your parts move through"
msgstr "ऑपरेशन और चरण जिनके माध्यम से आपके पार्ट्स आगे बढ़ते हैं"
@@ -18148,6 +18168,15 @@ msgstr "यह path केवल यह तय करता है कि आग
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "इस अवधि में कोई जर्नल प्रविष्टि पोस्ट नहीं की गई है और इसे स्थायी रूप से हटाया जा सकता है। इसे पूर्ववत नहीं किया जा सकता।"
+msgid "This PIN will not be shown again."
+msgstr "यह PIN फिर से नहीं दिखाया जाएगा।"
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "यह PIN फिर से नहीं दिखाया जाएगा। यदि यह खो गया है, तो इसे ऑपरेटर सूची से रीसेट करें।"
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "यह PIN फिर से नहीं दिखाया जाएगा। MES टर्मिनल पर कंसोल मोड से बाहर निकलने के लिए आपको इसकी आवश्यकता होगी।"
+
msgid "this purchase order"
msgstr "यह क्रय आदेश"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 95f2070e6e..ee6aefd219 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} valori"
msgid "{0} values missing"
msgstr "{0} valori mancanti"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} verrà salvato come {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90 giorni"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Una regola \"devono corrispondere\" su questo processo impedisce a questi di condividere un lotto di produzione"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Un PIN a 4 cifre viene generato quando l'operatore viene creato."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Un lotto di produzione richiede almeno un'operazione. Per dividere l'intero lotto di produzione, utilizza Dissolvi."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Una migrazione dati gestita da Carbon — tu carichi i tuoi dati"
@@ -1383,6 +1390,9 @@ msgstr "Aggiungi Azienda"
msgid "Add condition"
msgstr "Aggiungi condizione"
+msgid "Add Console Operator"
+msgstr "Aggiungi Operatore console"
+
msgid "Add Contractor"
msgstr "Aggiungi un collaboratore esterno"
@@ -3286,6 +3296,10 @@ msgstr "Impossibile disabilitare l'unica pausa Attiva. Aggiungi un'altra pausa o
msgid "Can't download this file"
msgstr "Impossibile scaricare questo file"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Impossibile caricare un file denominato {0}"
+
msgid "Cancel"
msgstr "Annulla"
@@ -4101,6 +4115,9 @@ msgstr "La modalità console è abilitata"
msgid "Console Operator"
msgstr "Operatore Console"
+msgid "Console Operator Created"
+msgstr "Operatore console creato"
+
msgid "consumable"
msgstr "materiale di consumo"
@@ -4344,9 +4361,6 @@ msgstr "Copia numero parte"
msgid "Copy part unique identifier"
msgstr "Copia identificatore univoco della parte"
-msgid "Copy PIN"
-msgstr "Copia PIN"
-
msgid "Copy previous day"
msgstr "Copia giorno precedente"
@@ -4668,6 +4682,9 @@ msgstr "Crea nuovo"
msgid "Create new rule"
msgstr "Crea nuova regola"
+msgid "Create Operator"
+msgstr "Crea Operatore"
+
msgid "Create PO Revision"
msgstr "Crea Revisione PO"
@@ -8087,8 +8104,8 @@ msgstr "Contabilità generale e chiusura di fine mese"
msgid "Generate"
msgstr "Genera"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Genera un nuovo PIN a 4 cifre. Condividilo con l'operatore in modo che possa accedere ai terminali MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Genera un nuovo PIN a 4 cifre. Il PIN corrente dell'operatore smette di funzionare immediatamente."
msgid "Generate and send customer invoices"
msgstr "Genera e invia fatture ai clienti"
@@ -8102,9 +8119,6 @@ msgstr "Genera esercizio fiscale"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Genera ID materiali e descrizioni in base alle proprietà del materiale."
-msgid "Generate new PIN"
-msgstr "Genera nuovo PIN"
-
msgid "Generate Picking List"
msgstr "Genera Lista di Prelievo"
@@ -10902,9 +10916,6 @@ msgstr "Nuova Condizione di pagamento"
msgid "New Picking List"
msgstr "Nuova Lista di prelievo"
-msgid "New PIN"
-msgstr "Nuovo PIN"
-
msgid "New PO"
msgstr "Nuovo PO"
@@ -14118,9 +14129,6 @@ msgstr "Rimanente"
msgid "Remaining after split stays on the original row."
msgstr "La quantità rimanente dopo la divisione rimane sulla riga originale."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Ricorda questo PIN. Ne avrai bisogno per uscire dalla modalità console sui terminali MES."
-
msgid "Remove"
msgstr "Rimuovi"
@@ -14130,7 +14138,7 @@ msgstr "Rimuovi {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Rimuovi {0} dal lotto di produzione"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Rimuovere {0} da questo lotto di produzione? La sua operazione ritorna a
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "Rimuovi {0} su {memberCount} operazioni da {1}?"
msgid "Remove {label}"
msgstr "Rimuovi {label}"
@@ -14561,6 +14569,9 @@ msgstr "Motivo Reso"
msgid "Return Reasons"
msgstr "Motivi Reso"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Torna alle Integrazioni e connetti di nuovo Onshape."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Torna a Integrazioni e connetti nuovamente Ramp."
@@ -15821,6 +15832,12 @@ msgstr "Condividi Link"
msgid "Share Quote"
msgstr "Condividi Preventivo"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Condividi questo PIN con {name} affinché possano accedere ai terminali MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Condividi questo PIN con l'operatore affinché possa accedere ai terminali MES."
+
msgid "Shared"
msgstr "Condiviso"
@@ -17598,6 +17615,9 @@ msgstr "Il numero di mesi durante i quali questo asset sarà ammortizzato."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Il livello di inventario in mano che attiva un nuovo ordine di rifornimento secondo le politiche basate sulla quantità."
+msgid "The Onshape connection expired"
+msgstr "La connessione Onshape è scaduta"
+
msgid "The operations and steps your parts move through"
msgstr "Le operazioni e i passaggi attraverso cui si muovono i tuoi componenti"
@@ -18148,6 +18168,15 @@ msgstr "Questo percorso decide solo cosa viene eseguito dopo"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Questo periodo non ha voci di prima nota registrate e può essere eliminato permanentemente. Questa azione non può essere annullata."
+msgid "This PIN will not be shown again."
+msgstr "Questo PIN non verrà più visualizzato."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Questo PIN non verrà più visualizzato. Se viene smarrito, reimpostalo dall'elenco degli operatori."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Questo PIN non verrà più visualizzato. Ne avrai bisogno per uscire dalla modalità console sui terminali MES."
+
msgid "this purchase order"
msgstr "questo ordine di acquisto"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 6aba879db1..46ebfb1340 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -246,6 +246,10 @@ msgstr "{0}個の値"
msgid "{0} values missing"
msgstr "{0}個の値が見つかりません"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} は {name} として保存されます"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}日"
@@ -538,8 +542,11 @@ msgstr "90日"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "このプロセスの\"一致必須\"ルールにより、これらはバッチを共有できません"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "4 桁の PIN は、作業者が作成されるときに生成されます。"
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "バッチには少なくとも 1 つの工程が必要です。バッチ全体を分割するには、代わりに [分割] を使用してください。"
msgid "A Carbon-run data migration — you load your own data"
msgstr "Carbon実行のデータ移行 — あなたが自分のデータをロードします"
@@ -1383,6 +1390,9 @@ msgstr "会社を追加"
msgid "Add condition"
msgstr "条件を追加"
+msgid "Add Console Operator"
+msgstr "コンソールオペレーターを追加"
+
msgid "Add Contractor"
msgstr "外部作業者を追加"
@@ -3286,6 +3296,10 @@ msgstr "唯一の有効な休止を無効にすることはできません。別
msgid "Can't download this file"
msgstr "このファイルをダウンロードできません"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "名前が {0} のファイルはアップロードできません"
+
msgid "Cancel"
msgstr "キャンセル"
@@ -4101,6 +4115,9 @@ msgstr "コンソールモードが有効です"
msgid "Console Operator"
msgstr "コンソールオペレーター"
+msgid "Console Operator Created"
+msgstr "コンソールオペレーターが作成されました"
+
msgid "consumable"
msgstr "消耗品"
@@ -4344,9 +4361,6 @@ msgstr "部品番号をコピー"
msgid "Copy part unique identifier"
msgstr "部品の一意の識別子をコピー"
-msgid "Copy PIN"
-msgstr "PINをコピー"
-
msgid "Copy previous day"
msgstr "前日をコピー"
@@ -4668,6 +4682,9 @@ msgstr "新規作成"
msgid "Create new rule"
msgstr "新しいルールを作成"
+msgid "Create Operator"
+msgstr "作業者を作成"
+
msgid "Create PO Revision"
msgstr "発注書リビジョンを作成"
@@ -8087,8 +8104,8 @@ msgstr "総勘定元帳と月末決算"
msgid "Generate"
msgstr "生成"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "新しい4桁のPINを生成します。作業者に共有して、MES端末にサインインできるようにします。"
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "新しい 4 桁の PIN を生成します。作業者の現在の PIN は直ちに使用できなくなります。"
msgid "Generate and send customer invoices"
msgstr "得意先請求書を生成して送信する"
@@ -8102,9 +8119,6 @@ msgstr "会計年度を生成"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "材料のプロパティに基づいて材料IDと説明を生成します。"
-msgid "Generate new PIN"
-msgstr "新しいPINを生成"
-
msgid "Generate Picking List"
msgstr "ピッキングリストを生成"
@@ -10902,9 +10916,6 @@ msgstr "新規支払条件"
msgid "New Picking List"
msgstr "新しいピッキングリスト"
-msgid "New PIN"
-msgstr "新しいPIN"
-
msgid "New PO"
msgstr "新規PO"
@@ -14118,9 +14129,6 @@ msgstr "残高"
msgid "Remaining after split stays on the original row."
msgstr "分割後の残りは元の行に留まります。"
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "このPINを覚えておいてください。MES端末でコンソールモードを終了するために必要になります。"
-
msgid "Remove"
msgstr "除去"
@@ -14130,7 +14138,7 @@ msgstr "{0}を除去"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "バッチから {0} を除去"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "{0}をこのバッチから除去しますか?その工程はスケジ
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "{1} から {memberCount} 工程中 {0} 個を除去しますか?"
msgid "Remove {label}"
msgstr "{label}を除去"
@@ -14561,6 +14569,9 @@ msgstr "返品理由"
msgid "Return Reasons"
msgstr "返品理由一覧"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "連携に戻り、Onshape に再度接続してください。"
+
msgid "Return to Integrations and connect Ramp again."
msgstr "連携に戻り、Ramp にもう一度接続してください。"
@@ -15821,6 +15832,12 @@ msgstr "リンクを共有"
msgid "Share Quote"
msgstr "見積もりを共有"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "このPINを {name} と共有してください。これにより MES 端末でサインインできます。"
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "このPINを作業者と共有してください。これにより MES 端末でサインインできます。"
+
msgid "Shared"
msgstr "共有"
@@ -17598,6 +17615,9 @@ msgstr "このアセットが償却される月数。"
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "数量ベースのポリシーに基づいて新しい補充注文をトリガーするオンハンド在庫レベル。"
+msgid "The Onshape connection expired"
+msgstr "Onshape の接続が期限切れです"
+
msgid "The operations and steps your parts move through"
msgstr "部品が通過する工程とステップ。"
@@ -18148,6 +18168,15 @@ msgstr "このパスは次に何が実行されるかだけを決定します"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "この期間には転記された仕訳がなく、永久に削除できます。この処理は取り消せません。"
+msgid "This PIN will not be shown again."
+msgstr "このPINは再度表示されません。"
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "このPINは再度表示されません。紛失した場合は、作業者リストからリセットしてください。"
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "このPINは再度表示されません。MES 端末でコンソールモードを終了するときに必要です。"
+
msgid "this purchase order"
msgstr "この発注書"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 14ddecbb83..4655fac2f8 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -246,6 +246,10 @@ msgstr "{0}개 값"
msgid "{0} values missing"
msgstr "{0}개 값 누락"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0}이 {name}으로 저장됩니다"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90일"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "이 공정의 \"일치해야 함\" 규칙이 이들을 배치 공유에서 차단합니다"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "작업자를 생성할 때 4자리 PIN이 생성됩니다."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "배치는 최소한 하나의 공정이 필요합니다. 전체 배치를 분할하려면 대신 Dissolve를 사용하세요."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Carbon이 진행하는 데이터 마이그레이션 — 직접 데이터를 업로드"
@@ -1383,6 +1390,9 @@ msgstr "회사 추가"
msgid "Add condition"
msgstr "조건 추가"
+msgid "Add Console Operator"
+msgstr "콘솔 작업자 추가"
+
msgid "Add Contractor"
msgstr "외주 인력 추가"
@@ -3286,6 +3296,10 @@ msgstr "유일하게 활성화된 휴게시간은 비활성화할 수 없습니
msgid "Can't download this file"
msgstr "이 파일을 다운로드할 수 없습니다"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "{0}이라는 이름의 파일을 업로드할 수 없습니다"
+
msgid "Cancel"
msgstr "취소"
@@ -4101,6 +4115,9 @@ msgstr "콘솔 모드가 활성화됨"
msgid "Console Operator"
msgstr "콘솔 작업자"
+msgid "Console Operator Created"
+msgstr "콘솔 작업자가 생성되었습니다"
+
msgid "consumable"
msgstr "소모품"
@@ -4344,9 +4361,6 @@ msgstr "품목 번호 복사"
msgid "Copy part unique identifier"
msgstr "품목 고유 식별자 복사"
-msgid "Copy PIN"
-msgstr "PIN 복사"
-
msgid "Copy previous day"
msgstr "이전 날 복사"
@@ -4668,6 +4682,9 @@ msgstr "새로 생성"
msgid "Create new rule"
msgstr "새 규칙 생성"
+msgid "Create Operator"
+msgstr "작업자 생성"
+
msgid "Create PO Revision"
msgstr "구매주문 리비전 생성"
@@ -8087,8 +8104,8 @@ msgstr "총계정원장 및 월마감"
msgid "Generate"
msgstr "생성"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "새로운 4자리 PIN을 생성하세요. 작업자와 공유하여 MES 터미널에서 PIN으로 로그인할 수 있도록 하세요."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "새로운 4자리 PIN을 발급하세요. 작업자의 현재 PIN은 즉시 무효화됩니다."
msgid "Generate and send customer invoices"
msgstr "고객 송장 생성 및 발송"
@@ -8102,9 +8119,6 @@ msgstr "회계연도 생성"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "자재 속성을 기반으로 자재 ID와 설명을 생성합니다."
-msgid "Generate new PIN"
-msgstr "새 PIN 생성"
-
msgid "Generate Picking List"
msgstr "피킹 리스트 생성"
@@ -10902,9 +10916,6 @@ msgstr "신규 지불 조건"
msgid "New Picking List"
msgstr "새 피킹 리스트"
-msgid "New PIN"
-msgstr "새 PIN"
-
msgid "New PO"
msgstr "새 구매주문"
@@ -14118,9 +14129,6 @@ msgstr "남음"
msgid "Remaining after split stays on the original row."
msgstr "분할 후 남은 수량은 원래 행에 유지됩니다."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "이 PIN을 기억하세요. MES 터미널에서 콘솔 모드를 종료하려면 필요합니다."
-
msgid "Remove"
msgstr "제거"
@@ -14130,7 +14138,7 @@ msgstr "{0} 제거"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "배치에서 {0} 제거"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "{0}을(를) 이 배치에서 제거하시겠습니까? 그 공정은 일
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "{1}에서 {memberCount}개 공정 중 {0}개를 제거하시겠습니까?"
msgid "Remove {label}"
msgstr "제거 {label}"
@@ -14561,6 +14569,9 @@ msgstr "반품 사유"
msgid "Return Reasons"
msgstr "반품 사유"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "연동으로 돌아가서 Onshape를 다시 연결하세요."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "연동으로 돌아가 Ramp를 다시 연결하세요."
@@ -15821,6 +15832,12 @@ msgstr "링크 공유"
msgid "Share Quote"
msgstr "견적 공유"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "이 PIN을 {name}과 공유하면 MES 터미널에 로그인할 수 있습니다."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "이 PIN을 작업자와 공유하면 MES 터미널에 로그인할 수 있습니다."
+
msgid "Shared"
msgstr "공유됨"
@@ -17598,6 +17615,9 @@ msgstr "이 자산이 감가상각되는 개월 수입니다."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "수량 기반 정책에서 새 보충 주문을 발생시키는 보유 재고 수준입니다."
+msgid "The Onshape connection expired"
+msgstr "Onshape 연동이 만료되었습니다"
+
msgid "The operations and steps your parts move through"
msgstr "부품이 이동하는 공정 및 단계"
@@ -18148,6 +18168,15 @@ msgstr "이 경로는 다음에 실행할 작업만 결정합니다."
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "이 기간은 전기된 전표 항목이 없으며 영구적으로 삭제할 수 있습니다. 이를 취소할 수 없습니다."
+msgid "This PIN will not be shown again."
+msgstr "이 PIN은 다시 표시되지 않습니다."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "이 PIN은 다시 표시되지 않습니다. 분실한 경우 작업자 목록에서 재설정하세요."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "이 PIN은 다시 표시되지 않습니다. MES 터미널에서 콘솔 모드를 종료할 때 필요합니다."
+
msgid "this purchase order"
msgstr "이 발주서"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 6da27b1398..cc8729288d 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} wartości"
msgid "{0} values missing"
msgstr "{0} brakujących wartości"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} będzie zapisany jako {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90 dni"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Reguła \"muszą się zgadzać\" w tym procesie blokuje wspólne tworzenie partii produkcyjnej"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "4-cyfrowy PIN jest generowany podczas tworzenia operatora."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Partia produkcyjna wymaga co najmniej jednej operacji. Aby podzielić całą partię produkcyjną, użyj opcji Rozpuść."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Migracja danych prowadzona przez Carbon — ty ładujesz swoje dane"
@@ -1383,6 +1390,9 @@ msgstr "Dodaj firmę"
msgid "Add condition"
msgstr "Dodaj warunek"
+msgid "Add Console Operator"
+msgstr "Dodaj operatora konsoli"
+
msgid "Add Contractor"
msgstr "Dodaj Pracownika zewnętrznego"
@@ -3286,6 +3296,10 @@ msgstr "Nie można wyłączyć jedynej aktywnej przerwy. Dodaj kolejną przerwę
msgid "Can't download this file"
msgstr "Nie można pobrać tego pliku."
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Nie można przesłać pliku o nazwie {0}"
+
msgid "Cancel"
msgstr "Anuluj"
@@ -4101,6 +4115,9 @@ msgstr "Tryb konsoli jest włączony"
msgid "Console Operator"
msgstr "Operator Konsoli"
+msgid "Console Operator Created"
+msgstr "Operator konsoli utworzony"
+
msgid "consumable"
msgstr "materiał eksploatacyjny"
@@ -4344,9 +4361,6 @@ msgstr "Skopiuj numer części"
msgid "Copy part unique identifier"
msgstr "Skopiuj unikalny identyfikator części"
-msgid "Copy PIN"
-msgstr "Skopiuj PIN"
-
msgid "Copy previous day"
msgstr "Skopiuj poprzedni dzień"
@@ -4668,6 +4682,9 @@ msgstr "Utwórz nowy"
msgid "Create new rule"
msgstr "Utwórz nową regułę"
+msgid "Create Operator"
+msgstr "Utwórz operatora"
+
msgid "Create PO Revision"
msgstr "Utwórz rewizję zamówienia zakupu"
@@ -8087,8 +8104,8 @@ msgstr "Księga główna i zamknięcie na koniec miesiąca"
msgid "Generate"
msgstr "Generuj"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Wygeneruj nowy 4-cyfrowy PIN. Udostępnij go operatorowi, aby mógł się zalogować na terminalach MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Wygeneruj nowy 4-cyfrowy PIN. Obecny PIN operatora przestaje działać natychmiast."
msgid "Generate and send customer invoices"
msgstr "Generuj i wysyłaj faktury dla klientów"
@@ -8102,9 +8119,6 @@ msgstr "Generuj Rok obrotowy"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Generuj identyfikatory materiałów i opisy na podstawie właściwości materiału."
-msgid "Generate new PIN"
-msgstr "Wygeneruj nowy PIN"
-
msgid "Generate Picking List"
msgstr "Generuj Listę kompletacyjną"
@@ -10902,9 +10916,6 @@ msgstr "Nowe Warunki płatności"
msgid "New Picking List"
msgstr "Nowa Lista kompletacyjna"
-msgid "New PIN"
-msgstr "Nowy PIN"
-
msgid "New PO"
msgstr "Nowe ZO"
@@ -14118,9 +14129,6 @@ msgstr "Pozostało"
msgid "Remaining after split stays on the original row."
msgstr "Pozostała ilość po podziale pozostaje w oryginalnym wierszu."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Zapamiętaj ten PIN. Będziesz go potrzebować, aby wyjść z trybu konsoli na terminalach MES."
-
msgid "Remove"
msgstr "Usuń z listy"
@@ -14130,7 +14138,7 @@ msgstr "Usuń z listy {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Usuń z listy {0} z partii produkcyjnej"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Usunąć {0} z tej partii produkcyjnej? Jej operacja wraca do harmonogra
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "Usuń z listy {0} z {memberCount} operacji z {1}?"
msgid "Remove {label}"
msgstr "Usuń z listy {label}"
@@ -14561,6 +14569,9 @@ msgstr "Powód zwrotu"
msgid "Return Reasons"
msgstr "Powody zwrotu"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Wróć do Integracji i połącz Onshape ponownie."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Wróć do sekcji Integracje i ponownie połącz się z Ramp."
@@ -15821,6 +15832,12 @@ msgstr "Udostępnij Link"
msgid "Share Quote"
msgstr "Udostępnij Ofertę"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Udostępnij ten PIN użytkownikowi {name}, aby mógł zalogować się na terminalach MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Udostępnij ten PIN operatorowi, aby mógł zalogować się na terminalach MES."
+
msgid "Shared"
msgstr "Udostępnione"
@@ -17598,6 +17615,9 @@ msgstr "Liczba miesięcy, w ciągu których ten składnik aktywów będzie amort
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Poziom zapasu w ręku, który wyzwala nowy porządek uzupełniania zgodnie z zasadami opartymi na ilości."
+msgid "The Onshape connection expired"
+msgstr "Połączenie Onshape wygasło"
+
msgid "The operations and steps your parts move through"
msgstr "Operacje i kroki, przez które przechodzą Twoje części"
@@ -18148,6 +18168,15 @@ msgstr "Ta ścieżka decyduje tylko o tym, co uruchomi się dalej"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Ten okres nie ma zaksięgowanych dowodów księgowych i może być trwale usunięty. Nie można tego cofnąć."
+msgid "This PIN will not be shown again."
+msgstr "Ten PIN nie będzie już więcej wyświetlany."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Ten PIN nie będzie już więcej wyświetlany. Jeśli zostanie utracony, zresetuj go z listy operatorów."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Ten PIN nie będzie już więcej wyświetlany. Będzie ci potrzebny do wyjścia z trybu konsoli na terminalach MES."
+
msgid "this purchase order"
msgstr "to zamówienie zakupu"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 6eb237329f..d635a8b1eb 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} valores"
msgid "{0} values missing"
msgstr "{0} valores ausentes"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} será salvo como {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}d"
@@ -538,8 +542,11 @@ msgstr "90 dias"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Uma regra \"deve coincidir\" neste processo impede que estes compartilhem um lote de produção"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Um PIN de 4 dígitos é gerado quando o operador é criado."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Um lote de produção precisa de pelo menos uma operação. Para dividir o lote de produção inteiro, use Dissolver em vez disso."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Uma migração de dados executada pela Carbon — você carrega seus próprios dados"
@@ -1383,6 +1390,9 @@ msgstr "Adicionar Empresa"
msgid "Add condition"
msgstr "Adicionar condição"
+msgid "Add Console Operator"
+msgstr "Adicionar operador de console"
+
msgid "Add Contractor"
msgstr "Adicionar Terceirizado"
@@ -3286,6 +3296,10 @@ msgstr "Não é possível desabilitar o único intervalo ativo. Adicione outro i
msgid "Can't download this file"
msgstr "Não é possível baixar este arquivo"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Não é possível enviar arquivo nomeado {0}"
+
msgid "Cancel"
msgstr "Cancelar"
@@ -4101,6 +4115,9 @@ msgstr "O modo console está ativado"
msgid "Console Operator"
msgstr "Operador de Console"
+msgid "Console Operator Created"
+msgstr "Operador de console criado"
+
msgid "consumable"
msgstr "consumível"
@@ -4344,9 +4361,6 @@ msgstr "Copiar número da peça"
msgid "Copy part unique identifier"
msgstr "Copiar identificador único da peça"
-msgid "Copy PIN"
-msgstr "Copiar PIN"
-
msgid "Copy previous day"
msgstr "Copiar dia anterior"
@@ -4668,6 +4682,9 @@ msgstr "Criar novo"
msgid "Create new rule"
msgstr "Criar nova regra"
+msgid "Create Operator"
+msgstr "Criar operador"
+
msgid "Create PO Revision"
msgstr "Criar Revisão de PO"
@@ -8087,8 +8104,8 @@ msgstr "Livro razão e encerramento do período"
msgid "Generate"
msgstr "Gerar"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Gere um novo PIN de 4 dígitos. Compartilhe-o com o operador para que ele possa fazer login nos terminais MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Gerar um novo PIN de 4 dígitos. O PIN atual do operador deixa de funcionar imediatamente."
msgid "Generate and send customer invoices"
msgstr "Gerar e enviar faturas de cliente"
@@ -8102,9 +8119,6 @@ msgstr "Gerar Ano Fiscal"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Gerar IDs de material e descrições com base nas propriedades do material."
-msgid "Generate new PIN"
-msgstr "Gerar novo PIN"
-
msgid "Generate Picking List"
msgstr "Gerar lista de separação"
@@ -10902,9 +10916,6 @@ msgstr "Nova condição de pagamento"
msgid "New Picking List"
msgstr "Nova lista de separação"
-msgid "New PIN"
-msgstr "Novo PIN"
-
msgid "New PO"
msgstr "Novo PO"
@@ -14118,9 +14129,6 @@ msgstr "Restante"
msgid "Remaining after split stays on the original row."
msgstr "Restante após divisão permanece na linha original."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Lembre-se deste PIN. Você precisará dele para sair do modo console nos terminais MES."
-
msgid "Remove"
msgstr "Remover"
@@ -14130,7 +14138,7 @@ msgstr "Remover {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Remover {0} do lote de produção"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Remover {0} do lote de produção? Sua operação volta à programação
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "Remover {0} de {memberCount} operações de {1}?"
msgid "Remove {label}"
msgstr "Remover {label}"
@@ -14561,6 +14569,9 @@ msgstr "Motivo da Devolução"
msgid "Return Reasons"
msgstr "Motivos da Devolução"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Retornar a Integrações e conectar Onshape novamente."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Volte para Integrações e conecte o Ramp novamente."
@@ -15821,6 +15832,12 @@ msgstr "Compartilhar Link"
msgid "Share Quote"
msgstr "Compartilhar Cotação"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Compartilhe este PIN com {name} para que ele possa fazer login em terminais MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Compartilhe este PIN com o operador para que ele possa fazer login em terminais MES."
+
msgid "Shared"
msgstr "Compartilhado"
@@ -17598,6 +17615,9 @@ msgstr "O número de meses durante os quais este ativo será depreciado."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "O nível de inventário em mão que ativa um novo pedido de reabastecimento de acordo com as políticas baseadas em quantidade."
+msgid "The Onshape connection expired"
+msgstr "A conexão do Onshape venceu"
+
msgid "The operations and steps your parts move through"
msgstr "As operações e etapas pelas quais suas peças passam"
@@ -18148,6 +18168,15 @@ msgstr "Este caminho apenas decide o que é executado a seguir"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Este período não tem lançamentos de diário nele e pode ser deletado permanentemente. Isso não pode ser desfeito."
+msgid "This PIN will not be shown again."
+msgstr "Este PIN não será exibido novamente."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Este PIN não será exibido novamente. Se você o perdeu, redefina-o na lista de operadores."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Este PIN não será exibido novamente. Você precisará dele para sair do modo de console em terminais MES."
+
msgid "this purchase order"
msgstr "este pedido de compra"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 4d3d3f3ce2..1bb2a77782 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} значений"
msgid "{0} values missing"
msgstr "{0} значений отсутствует"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} будет сохранено как {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}д"
@@ -538,8 +542,11 @@ msgstr "90 дней"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Правило «должны совпадать» на этом процессе препятствует размещению в одной серии"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "4-значный PIN создается при создании оператора."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Серия должна содержать по крайней мере одну операцию. Чтобы разделить всю серию, используйте вместо этого «Растворить»."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Миграция данных, управляемая Carbon — вы загружаете свои собственные данные"
@@ -1383,6 +1390,9 @@ msgstr "Добавить организацию"
msgid "Add condition"
msgstr "Добавить условие"
+msgid "Add Console Operator"
+msgstr "Добавить оператора консоли"
+
msgid "Add Contractor"
msgstr "Добавить подрядчика"
@@ -3286,6 +3296,10 @@ msgstr "Невозможно отключить единственный акт
msgid "Can't download this file"
msgstr "Невозможно скачать этот файл"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "Невозможно загрузить файл с именем {0}"
+
msgid "Cancel"
msgstr "Отмена"
@@ -4101,6 +4115,9 @@ msgstr "Режим консоли включен"
msgid "Console Operator"
msgstr "Оператор консоли"
+msgid "Console Operator Created"
+msgstr "Оператор консоли создан"
+
msgid "consumable"
msgstr "расходный материал"
@@ -4344,9 +4361,6 @@ msgstr "Скопировать номер детали"
msgid "Copy part unique identifier"
msgstr "Скопировать уникальный идентификатор детали"
-msgid "Copy PIN"
-msgstr "Копировать PIN"
-
msgid "Copy previous day"
msgstr "Скопировать предыдущий день"
@@ -4668,6 +4682,9 @@ msgstr "Создать"
msgid "Create new rule"
msgstr "Создать новое правило"
+msgid "Create Operator"
+msgstr "Создать оператора"
+
msgid "Create PO Revision"
msgstr "Создать ревизию PO"
@@ -8087,8 +8104,8 @@ msgstr "Главная книга и закрытие месяца"
msgid "Generate"
msgstr "Генерировать"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Создайте новый 4-значный PIN-код. Поделитесь им с оператором, чтобы он мог войти на терминалы MES."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Создайте новый 4-значный PIN. Текущий PIN оператора перестанет работать немедленно."
msgid "Generate and send customer invoices"
msgstr "Создавать и отправлять счета-фактуры покупателей"
@@ -8102,9 +8119,6 @@ msgstr "Генерировать финансовый год"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Генерируйте идентификаторы материалов и описания на основе свойств материала."
-msgid "Generate new PIN"
-msgstr "Создать новый PIN"
-
msgid "Generate Picking List"
msgstr "Создать лист отбора"
@@ -10902,9 +10916,6 @@ msgstr "Новые условия оплаты"
msgid "New Picking List"
msgstr "Новый лист отбора"
-msgid "New PIN"
-msgstr "Новый PIN"
-
msgid "New PO"
msgstr "Новый ПО"
@@ -14118,9 +14129,6 @@ msgstr "Остаток"
msgid "Remaining after split stays on the original row."
msgstr "Остаток после разделения остается в исходной строке."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Запомните этот PIN-код. Он потребуется вам для выхода из режима консоли на терминалах MES."
-
msgid "Remove"
msgstr "Убрать"
@@ -14130,7 +14138,7 @@ msgstr "Убрать {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "Убрать {0} из серии"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "Убрать {0} из этой серии? Его операция ве
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "Убрать {0} из {memberCount} операций из {1}?"
msgid "Remove {label}"
msgstr "Убрать {label}"
@@ -14561,6 +14569,9 @@ msgstr "Причина возврата"
msgid "Return Reasons"
msgstr "Причины возврата"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Вернитесь в раздел «Интеграции» и снова подключитесь к Onshape."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Вернитесь в раздел «Интеграции» и снова подключите Ramp."
@@ -15821,6 +15832,12 @@ msgstr "Поделиться ссылкой"
msgid "Share Quote"
msgstr "Поделиться предложением"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Поделитесь этим PIN с {name}, чтобы они смогли войти на терминалы MES."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Поделитесь этим PIN с оператором, чтобы он смог войти на терминалы MES."
+
msgid "Shared"
msgstr "Общий доступ"
@@ -17598,6 +17615,9 @@ msgstr "Количество месяцев, в течение которых б
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Уровень наличного запаса, который запускает новый заказ на пополнение в соответствии с политиками на основе количества."
+msgid "The Onshape connection expired"
+msgstr "Подключение Onshape истекло"
+
msgid "The operations and steps your parts move through"
msgstr "Операции и шаги, через которые переходят ваши детали"
@@ -18148,6 +18168,15 @@ msgstr "Этот путь решает только, что будет запу
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Этот период не имеет проведенных операций и может быть безвозвратно удален. Это невозможно отменить."
+msgid "This PIN will not be shown again."
+msgstr "Этот PIN больше не будет показан."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Этот PIN больше не будет показан. Если он потеряется, сбросьте его из списка операторов."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Этот PIN больше не будет показан. Он вам понадобится для выхода из режима консоли на терминалах MES."
+
msgid "this purchase order"
msgstr "этот заказ поставщику"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b2cd56465f..f883964e3f 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} değer"
msgid "{0} values missing"
msgstr "{0} değeri eksik"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0}, {name} olarak kaydedilecek"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}g"
@@ -538,8 +542,11 @@ msgstr "90G"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "Bu operasyon üzerinde \"eşleşmeli\" kuralı bunların bir partide paylaşılmasını engeller"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "Operatör oluşturulduğunda bir 4 haneli PIN oluşturulur."
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "Bir parti en az bir operasyon gerektirir. Bütün partiyi ayırmak için bunun yerine Çöz'ü kullanın."
msgid "A Carbon-run data migration — you load your own data"
msgstr "Bir Carbon tarafından yönetilen veri taşıması — kendi verilerinizi yüklersiniz"
@@ -1383,6 +1390,9 @@ msgstr "Şirket Ekle"
msgid "Add condition"
msgstr "Koşul ekle"
+msgid "Add Console Operator"
+msgstr "Konsol operatörü ekle"
+
msgid "Add Contractor"
msgstr "Taşeron Ekle"
@@ -3286,6 +3296,10 @@ msgstr "Yalnızca aktif olan aralığı devre dışı bırakamazsınız. Başka
msgid "Can't download this file"
msgstr "Bu dosya indirilemiyor"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "{0} adlı bir dosya yüklenemiyor"
+
msgid "Cancel"
msgstr "İptal"
@@ -4101,6 +4115,9 @@ msgstr "Konsol modu etkinleştirildi"
msgid "Console Operator"
msgstr "Konsol Operatörü"
+msgid "Console Operator Created"
+msgstr "Konsol operatörü oluşturuldu"
+
msgid "consumable"
msgstr "sarf malzemesi"
@@ -4344,9 +4361,6 @@ msgstr "Parça numarasını kopyala"
msgid "Copy part unique identifier"
msgstr "Parça benzersiz tanımlayıcısını kopyala"
-msgid "Copy PIN"
-msgstr "PIN'i Kopyala"
-
msgid "Copy previous day"
msgstr "Önceki günü kopyala"
@@ -4668,6 +4682,9 @@ msgstr "Yeni oluştur"
msgid "Create new rule"
msgstr "Yeni kural oluştur"
+msgid "Create Operator"
+msgstr "Operatör oluştur"
+
msgid "Create PO Revision"
msgstr "PO Revizyonu Oluştur"
@@ -8087,8 +8104,8 @@ msgstr "Büyük defter ve dönem sonu kapanışı"
msgid "Generate"
msgstr "Oluştur"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "Yeni bir 4 haneli PIN oluşturun. Operatörün MES terminallerinde giriş yapabilmesi için bunu onunla paylaşın."
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "Yeni bir 4 haneli PIN oluştur. Operatörün mevcut PIN'i hemen çalışmayı durdurur."
msgid "Generate and send customer invoices"
msgstr "Müşteri faturalarını oluştur ve gönder"
@@ -8102,9 +8119,6 @@ msgstr "Mali Yıl Oluştur"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "Malzemenin özelliklerine göre malzeme kimlikleri ve açıklamaları oluşturun."
-msgid "Generate new PIN"
-msgstr "Yeni PIN oluştur"
-
msgid "Generate Picking List"
msgstr "Toplama listesi oluştur"
@@ -10902,9 +10916,6 @@ msgstr "Yeni ödeme koşulu"
msgid "New Picking List"
msgstr "Yeni Toplama Listesi"
-msgid "New PIN"
-msgstr "Yeni PIN"
-
msgid "New PO"
msgstr "Yeni Sipariş"
@@ -14118,9 +14129,6 @@ msgstr "Kalan"
msgid "Remaining after split stays on the original row."
msgstr "Bölme sonrası kalan orijinal satırda kalır."
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "Bu PIN'i hatırlayın. MES terminallerinde konsol modundan çıkmak için buna ihtiyacınız olacak."
-
msgid "Remove"
msgstr "Kaldır"
@@ -14130,7 +14138,7 @@ msgstr "Kaldır {0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "{0}'i partiden kaldır"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "{0} bu partiyi kaldırmak istiyor musunuz? Operasyonu çizelgeye geri d
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "{1}'den {memberCount} operasyondan {0}'ını kaldırılsın mı?"
msgid "Remove {label}"
msgstr "{label}'i Kaldır"
@@ -14561,6 +14569,9 @@ msgstr "İade Nedeni"
msgid "Return Reasons"
msgstr "İade Nedenleri"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "Entegrasyonlara dön ve Onshape'i tekrar bağla."
+
msgid "Return to Integrations and connect Ramp again."
msgstr "Entegrasyonlara geri dönün ve Ramp'i yeniden bağlayın."
@@ -15821,6 +15832,12 @@ msgstr "Paylaşım Bağlantısı"
msgid "Share Quote"
msgstr "Teklifi Paylaş"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "Bu PIN'i {name} ile paylaş, böylece MES terminal'lerine PIN ile giriş yapabilir."
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "Bu PIN'i operatörle paylaş, böylece MES terminal'lerine PIN ile giriş yapabilir."
+
msgid "Shared"
msgstr "Paylaşılan"
@@ -17598,6 +17615,9 @@ msgstr "Bu varlığın amort edileceği ay sayısı."
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "Miktar tabanlı politikler altında yeni bir yenileme siparişini tetikleyen eldeki envanter seviyesi."
+msgid "The Onshape connection expired"
+msgstr "Onshape bağlantısının süresi doldu"
+
msgid "The operations and steps your parts move through"
msgstr "Parçalarınızın geçtiği operasyonlar ve adımlar"
@@ -18148,6 +18168,15 @@ msgstr "Bu yol yalnızca sonra ne çalışacağını belirler"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "Bu dönem hiçbir muhasebe fişi içermez ve kalıcı olarak silinebilir. Bu işlem geri alınamaz."
+msgid "This PIN will not be shown again."
+msgstr "Bu PIN bir daha gösterilmeyecek."
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "Bu PIN bir daha gösterilmeyecek. Kaybolduysa, operatörler listesinden sıfırla."
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "Bu PIN bir daha gösterilmeyecek. MES terminal'lerinde konsol modundan çıkmak için gerekli olacak."
+
msgid "this purchase order"
msgstr "bu satın alma siparişi"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 0a89697b3e..48bb234c7c 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -246,6 +246,10 @@ msgstr "{0} 个值"
msgid "{0} values missing"
msgstr "{0} 个值缺失"
+#. placeholder {0}: file.name
+msgid "{0} will be saved as {name}"
+msgstr "{0} 将被保存为 {name}"
+
#. placeholder {0}: item.days
msgid "{0}d"
msgstr "{0}天"
@@ -538,8 +542,11 @@ msgstr "90天"
msgid "A \"must match\" rule on this process blocks these from sharing a batch"
msgstr "此工序上的 \"必须匹配\" 规则阻止这些共享一个生产批次"
+msgid "A 4-digit PIN is generated when the operator is created."
+msgstr "创建操作员时会生成4位数PIN。"
+
msgid "A batch needs at least one operation. To break up the whole batch, use Dissolve instead."
-msgstr ""
+msgstr "生产批次需要至少一个工序。要分解整个生产批次,请改用\"分解\"。"
msgid "A Carbon-run data migration — you load your own data"
msgstr "Carbon 运行的数据迁移 — 您加载自己的数据"
@@ -1383,6 +1390,9 @@ msgstr "添加公司"
msgid "Add condition"
msgstr "添加条件"
+msgid "Add Console Operator"
+msgstr "添加控制台操作员"
+
msgid "Add Contractor"
msgstr "添加外协人员"
@@ -3286,6 +3296,10 @@ msgstr "无法禁用唯一的启用休息时间。请添加另一个休息时间
msgid "Can't download this file"
msgstr "无法下载此文件"
+#. placeholder {0}: file.name
+msgid "Can't upload a file named {0}"
+msgstr "无法上传名为 {0} 的文件"
+
msgid "Cancel"
msgstr "取消"
@@ -4101,6 +4115,9 @@ msgstr "控制台模式已启用"
msgid "Console Operator"
msgstr "控制台操作员"
+msgid "Console Operator Created"
+msgstr "控制台操作员已创建"
+
msgid "consumable"
msgstr "耗材"
@@ -4344,9 +4361,6 @@ msgstr "复制零件号"
msgid "Copy part unique identifier"
msgstr "复制零件唯一标识符"
-msgid "Copy PIN"
-msgstr "复制PIN"
-
msgid "Copy previous day"
msgstr "复制前一天"
@@ -4668,6 +4682,9 @@ msgstr "新建"
msgid "Create new rule"
msgstr "创建新规则"
+msgid "Create Operator"
+msgstr "创建操作员"
+
msgid "Create PO Revision"
msgstr "创建采购订单修订版本"
@@ -8087,8 +8104,8 @@ msgstr "总账和月末结账"
msgid "Generate"
msgstr "生成"
-msgid "Generate a new 4-digit PIN. Share it with the operator so they can pin in at MES terminals."
-msgstr "生成新的4位PIN码。与操作员分享,以便他们可以在MES终端上登录。"
+msgid "Generate a new 4-digit PIN. The operator's current PIN stops working immediately."
+msgstr "生成新的4位数PIN。操作员的当前PIN将立即停止工作。"
msgid "Generate and send customer invoices"
msgstr "生成并发送客户发票"
@@ -8102,9 +8119,6 @@ msgstr "生成会计年度"
msgid "Generate material IDs and descriptions based on the properties of the material."
msgstr "根据原材料的属性生成原材料ID和描述。"
-msgid "Generate new PIN"
-msgstr "生成新PIN"
-
msgid "Generate Picking List"
msgstr "生成拣货单"
@@ -10902,9 +10916,6 @@ msgstr "新建付款条件"
msgid "New Picking List"
msgstr "新拣货单"
-msgid "New PIN"
-msgstr "新PIN"
-
msgid "New PO"
msgstr "新采购订单"
@@ -14118,9 +14129,6 @@ msgstr "剩余"
msgid "Remaining after split stays on the original row."
msgstr "拆分后的剩余部分保留在原始行上。"
-msgid "Remember this PIN. You will need it to exit console mode on MES terminals."
-msgstr "记住此PIN。您需要它来退出MES终端上的控制台模式。"
-
msgid "Remove"
msgstr "移除"
@@ -14130,7 +14138,7 @@ msgstr "移除{0}"
#. placeholder {0}: selectedIds.size
msgid "Remove {0} from batch"
-msgstr ""
+msgstr "从生产批次中移除 {0}"
#. placeholder {0}: removing.jobReadableId ?? "this operation"
msgid "Remove {0} from this batch? Its operation goes back to the schedule to run on its own."
@@ -14139,7 +14147,7 @@ msgstr "从此生产批次中移除 {0}?其工序回到排程以单独运行
#. placeholder {0}: selectedIds.size
#. placeholder {1}: batch.readableId
msgid "Remove {0} of {memberCount} operations from {1}?"
-msgstr ""
+msgstr "从 {1} 中移除 {0} 个(共 {memberCount} 个)工序?"
msgid "Remove {label}"
msgstr "移除 {label}"
@@ -14561,6 +14569,9 @@ msgstr "退货原因"
msgid "Return Reasons"
msgstr "退货原因"
+msgid "Return to Integrations and connect Onshape again."
+msgstr "返回集成并重新连接Onshape。"
+
msgid "Return to Integrations and connect Ramp again."
msgstr "返回集成页面并重新连接 Ramp。"
@@ -15821,6 +15832,12 @@ msgstr "分享链接"
msgid "Share Quote"
msgstr "分享报价"
+msgid "Share this PIN with {name} so they can pin in at MES terminals."
+msgstr "将此PIN与 {name} 分享,以便他们可以在MES终端登入。"
+
+msgid "Share this PIN with the operator so they can pin in at MES terminals."
+msgstr "将此PIN与操作员分享,以便他们可以在MES终端登入。"
+
msgid "Shared"
msgstr "共享"
@@ -17598,6 +17615,9 @@ msgstr "此资产将折旧的月数。"
msgid "The on-hand level that triggers a new replenishment order under the quantity-based policies."
msgstr "按数量触发新补充订单的库存水平根据基于数量的政策。"
+msgid "The Onshape connection expired"
+msgstr "Onshape连接已过期"
+
msgid "The operations and steps your parts move through"
msgstr "您的零件所经历的工序和步骤"
@@ -18148,6 +18168,15 @@ msgstr "此路径仅决定接下来运行什么"
msgid "This period has no journal entries posted to it and can be permanently deleted. This cannot be undone."
msgstr "此期间没有已过账的凭证,可以永久删除。此操作无法撤销。"
+msgid "This PIN will not be shown again."
+msgstr "此PIN将不再显示。"
+
+msgid "This PIN will not be shown again. If it is lost, reset it from the operators list."
+msgstr "此PIN将不再显示。如果丢失,可从操作员列表中重置。"
+
+msgid "This PIN will not be shown again. You will need it to exit console mode on MES terminals."
+msgstr "此PIN将不再显示。您需要它来在MES终端上退出控制台模式。"
+
msgid "this purchase order"
msgstr "此采购订单"
diff --git a/packages/utils/src/string.ts b/packages/utils/src/string.ts
index 0f4562c85d..a3d94ae676 100644
--- a/packages/utils/src/string.ts
+++ b/packages/utils/src/string.ts
@@ -38,6 +38,7 @@ export function pluralize(
}
export function stripSpecialCharacters(inputString: string) {
- // Keep only characters that are valid for S3 keys
- return inputString?.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,?]/g, "");
+ // Keep only characters that are valid for S3 keys. `?` is not: it ends the
+ // storage URL's path, so "what?.pdf" was stored as "what".
+ return inputString?.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,]/g, "");
}
diff --git a/scripts/lib/response-schema.ts b/scripts/lib/response-schema.ts
index d8f334ab79..94679fa95b 100644
--- a/scripts/lib/response-schema.ts
+++ b/scripts/lib/response-schema.ts
@@ -34,6 +34,21 @@ const MAX_DEPTH = 6;
/** A guard against pathological types, not a real limit — real rows sit well under. */
const MAX_PROPERTIES = 120;
+/**
+ * Collections `JSON.stringify` writes as `{}` — their members are methods and
+ * symbol-keyed slots, none of which reach the wire. Walking them emitted the
+ * checker's per-program symbol ids (`__@toStringTag@75448`) as property names,
+ * so an unrelated edit anywhere renumbered them and flipped the tool's digest.
+ */
+const JSON_OPAQUE_COLLECTIONS = new Set([
+ "Map",
+ "ReadonlyMap",
+ "WeakMap",
+ "Set",
+ "ReadonlySet",
+ "WeakSet"
+]);
+
/**
* Peel the layers between the declared return type and the payload a caller sees:
* `Promise<PostgrestSingleResponse<T>>` and the hand-rolled
@@ -116,6 +131,11 @@ export function typeToJsonSchema(
if (type.isUnion()) return unionToJsonSchema(type, at, depth, seen);
if (type.isObject()) {
+ const symbolName = type.getSymbol()?.getName();
+ if (symbolName && JSON_OPAQUE_COLLECTIONS.has(symbolName)) {
+ return { type: "object" };
+ }
+
const key = type.getText();
// Cycle: the type is already being expanded further up this branch.
if (seen.has(key)) return { type: "object" };
@@ -142,7 +162,11 @@ export function typeToJsonSchema(
};
}
- const properties = type.getProperties();
+ // Symbol-keyed members (`[Symbol.iterator]`, reported as `__@iterator@206`)
+ // are dropped by JSON.stringify, and their names carry unstable checker ids.
+ const properties = type
+ .getProperties()
+ .filter((property) => !property.getName().startsWith("__@"));
if (properties.length === 0) return { type: "object" };
if (properties.length > MAX_PROPERTIES) return { type: "object" };
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index 2fa5b47947..6040534e93 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -107,6 +107,23 @@ const INJECT_AUTH_OVERRIDES: Record<string, AuthField[]> = {
// authenticated creator for every replacement row.
invoicing_replaceInvoiceSettlements: ["companyId", "createdBy"],
invoicing_applyCreditsToInvoices: ["companyId", "createdBy"],
+ // Both read the caller's group-scoped currency with the payload's
+ // companyGroupId and write a memo, so it must come from the auth context —
+ // a caller-supplied group would resolve another group's currency rows.
+ purchasing_createPurchaseReturnOrderCredit: [
+ "companyId",
+ "companyGroupId",
+ "createdBy",
+ "updatedBy",
+ "userId",
+ ],
+ sales_createSalesReturnOrderCredit: [
+ "companyId",
+ "companyGroupId",
+ "createdBy",
+ "updatedBy",
+ "userId",
+ ],
};
// service-module → permission-module. `items` operations are gated by the `parts`