Skip to content

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

feat(onshape): push parts, assemblies and releases from a Carbon panel inside Onshape (#1764)

BettrCallRaul71387248000b
diff --git a/.ai/lessons.md b/.ai/lessons.md
index ba6b8cea18..07b5c489e9 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3700,6 +3700,60 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Applies to:** `membership` and its interceptors in `packages/database/src/event-system/handlers/`, and any unique key with a nullable column.
+---
+
+## Dev response caches must allow-list, never blanket-cache GETs
+
+**Context:** Caching Onshape API GETs in Redis during development (`ONSHAPE_DEV_CACHE=1`) to protect the annual API quota.
+
+**Problem:** Caching every GET poisoned the translation poll loop: `GET /translations/{id}` was cached while `requestState` was still `ACTIVE`, so `waitForTranslation` saw the same in-flight state forever and the export never completed. The failure looks like a hung job, not a cache bug.
+
+**Rule:** A dev-mode response cache must be an explicit allow-list of stable content reads (`DEV_CACHEABLE_PATHS` in `packages/ee/src/onshape/lib/client.ts`). Never add a polling or status endpoint. When adding a cacheable path, ask: can two reads of this URL legitimately differ within the TTL?
+
+**Applies to:** `packages/ee/src/onshape/lib/client.ts`, any dev-mode HTTP cache in front of a third-party API.
+
+## Inngest dev: an event fired before its function's first registration wedges the run
+
+**Context:** Adding a new Inngest function and firing its event from a route during local development.
+
+**Problem:** If the event fires before the dev server has registered the new function, the run sits "Running" forever — and per-key `concurrency` then queues every retry behind the wedged run, so nothing ever executes. The dev server's state is in-memory.
+
+**Rule:** After adding or renaming an Inngest function, reload the Inngest dev server (`crbn reload inngest`) before firing its event; if a run is already wedged, cancel it and re-fire. Check `http://localhost:<PORT_INNGEST>/runs` when a background job seems to do nothing.
+
+**Applies to:** `packages/jobs/src/inngest/`, local dev via `crbn up`.
+
+## Scripted source patches must assert their anchors
+
+**Context:** Applying code changes to large files via scripted string replacement (python/sed) instead of hand editing.
+
+**Problem:** A `.replace()` whose anchor doesn't match (e.g. after Biome reformatted the code) is a silent no-op: the script reports success, the file is unchanged, and the missing code later presents as an inexplicable runtime bug. One silent miss cost hours of "stale module" mis-debugging — the client genuinely lacked a branch the server had.
+
+**Rule:** Every scripted patch must assert the anchor's occurrence count before replacing (`assert s.count(old) == 1`) and fail loudly on a miss. Never chain a patch script with `&&` after an unasserted step.
+
+**Applies to:** Any agent or script editing source by string replacement, repo-wide.
+
+## One-shot stores: peek for validation, take only for the write
+
+**Context:** The Onshape panel's plan/apply split stores a reviewed plan in Redis and consumes it with GETDEL so a double-submitted apply cannot write twice.
+
+**Problem:** Taking the plan before validating the user's edits meant a 422 (one bad field) destroyed the review; the corrected retry hit 410 and forced a fresh Onshape read. The one-shot guarantee and the validation step were fighting over the same read.
+
+**Rule:** For any GETDEL-style one-shot record, validate against a peek (plain GET) and take the record only immediately before the first write. A rejected request must leave the record exactly as it was.
+
+**Applies to:** `packages/ee/src/onshape/lib/panel-plan-store.ts`, any Redis-backed one-shot token/plan/challenge consumed by a request that also validates input.
+
+## Never build PostgREST `.or()` filter strings from external values
+
+**Context:** Mapping-row deletes used `.or(`entityId.eq.${id},externalId.eq.${externalId}`)` where `externalId` embeds an Onshape part number.
+
+**Problem:** A part number containing `,` or `(` `)` changes the filter's meaning — the value is interpolated into PostgREST's filter grammar unquoted, so the delete can match other rows or fail. Every `.in()` / `.eq()` call passes values as parameters and is immune.
+
+**Rule:** Use `.eq()` / `.in()` instead of a hand-built `.or()` string whenever any operand comes from outside Carbon (CAD part numbers, external ids, user text). Chained filters on one query are AND-ed, so an OR across two columns ("remove mappings matching `entityId` OR `externalId`") becomes one parameterized statement PER COLUMN — two separate deletes — never both filters chained onto one delete, which removes only rows matching both and leaves the conflicting row that the next insert trips over.
+
+**Applies to:** every Supabase client call with `.or(` whose operands are not literals; `apps/erp/app/routes/api+/integrations.onshape.*`.
+
+---
+
## A docs heading is read by the in-app agent, and its length counts against a budget
**Context:** Adding a billing cycle to rental agreements lengthened two troubleshooting headings in `docs/content/docs/reference/rental-agreements.mdx`, each quoting every variant of an error message.
diff --git a/.ai/plans/2026-10-17-onshape-v2-own-oauth-client.md b/.ai/plans/2026-10-17-onshape-v2-own-oauth-client.md
new file mode 100644
index 0000000000..0b53136e97
--- /dev/null
+++ b/.ai/plans/2026-10-17-onshape-v2-own-oauth-client.md
@@ -0,0 +1,40 @@
+# Onshape V2 gets its own OAuth client
+
+The sync integration (`onshape`) and the panel (`onshape-v2`) are separate Onshape apps. Today both read `ONSHAPE_CLIENT_ID` / `ONSHAPE_CLIENT_SECRET`; only the redirect URL differs. After this change they share no variable.
+
+## Variables
+
+| Integration | Client id | Client secret | Redirect URL |
+| --- | --- | --- | --- |
+| `onshape` (sync) | `ONSHAPE_CLIENT_ID` | `ONSHAPE_CLIENT_SECRET` | `ONSHAPE_OAUTH_REDIRECT_URL` |
+| `onshape-v2` (panel) | `ONSHAPE_V2_CLIENT_ID` (new) | `ONSHAPE_V2_CLIENT_SECRET` (new) | `ONSHAPE_V2_OAUTH_REDIRECT_URL` |
+| `onshape-government` | integration settings | integration settings (Vault) | derived from `getAppUrl()` |
+
+- The sync integration keeps its names, so deployments that already set them are unchanged.
+- `ONSHAPE_V2_CLIENT_ID` is public (`browser: true`) like `ONSHAPE_CLIENT_ID`: `config-v2.tsx` is client-bundled and gates the card on it.
+- `ONSHAPE_DEV_CACHE` stays one local-dev switch; it is not app configuration.
+
+## Steps
+
+- [x] `packages/env/src/schema.ts`: new group `onshapeV2` (feature label "Onshape V2"); `ONSHAPE_V2_CLIENT_ID` (`browser`, `needed`), `ONSHAPE_V2_CLIENT_SECRET` (`secret`, `needed`); move `ONSHAPE_V2_OAUTH_REDIRECT_URL` into it. Then the startup report does not call a deployment with one integration half-configured.
+- [x] `packages/env/src/index.ts`: export both; add `ONSHAPE_V2_CLIENT_ID` to `getBrowserEnv()`; fix the "same Onshape app" comment.
+- [x] `apps/erp/app/root.tsx`: add `ONSHAPE_V2_CLIENT_ID` to the root loader's `env`.
+- [x] `packages/ee/src/onshape/lib/oauth.ts`: `getOnshapeOAuthConfig` takes client id, secret and redirect per integration id; unconfigured when any of the three is missing.
+- [x] `packages/ee/src/onshape/config-v2.tsx`: `active: !!ONSHAPE_V2_CLIENT_ID`.
+- [x] `packages/ee/src/onshape/lib/oauth.test.ts`: the panel uses its own client; each integration is unconfigured when only the other's variables are set.
+- [x] `sst.config.ts`: add the two variables to the ERP service.
+- [x] `ci/src/deploy.ts`: `onshape_v2_client_id`, `onshape_v2_client_secret` on `Workspace`, the destructure and the ERP env. The `workspaces` table needs these columns (with `onshape_v2_oauth_redirect_url`); that table is outside this repo.
+- [x] Docs: `docs/content/docs/integrations/cad.mdx` setup becomes two Onshape apps (sync: one redirect URI; panel: one redirect URI plus the Element right panel extension); `docs/content/docs/platform/self-hosting/environment-variables.mdx`.
+- [x] Rules and guides: `.claude/rules/onshape-panel.md` (OAuth bullet), `.claude/rules/environment-configuration.md`, `packages/ee/AGENTS.md`. The comment in `packages/ee/src/onshape/lib/connection.ts` names only the sync connections, so it stays as it is.
+- [x] Verify: `@carbon/ee` and `@carbon/env` tests, typecheck `erp` and `@carbon/ee`, Biome on changed files.
+
+## Not in this change
+
+- `packages/env/src/vercel-production.json` records what Vercel holds. Add the new names to it when someone adds them in Vercel.
+- The MES service in `sst.config.ts` already carries Onshape variables it does not use. This change does not touch them.
+- Token refresh still refuses without the redirect URL variable (`getOnshapeOAuthConfig`); separate fix.
+- The Redis API-call counter `onshape:api-calls:<year>` still counts every Onshape app together; separate fix.
+
+## Effect on existing connections
+
+A connection's refresh token belongs to the app that issued it. A panel connection made with the shared client keeps working only if `ONSHAPE_V2_CLIENT_*` hold that same client; otherwise it must reconnect. Production has no panel connections yet.
diff --git a/.ai/specs/2026-08-28-onshape-app.md b/.ai/specs/2026-08-28-onshape-app.md
new file mode 100644
index 0000000000..d515f60607
--- /dev/null
+++ b/.ai/specs/2026-08-28-onshape-app.md
@@ -0,0 +1,137 @@
+# Onshape panel: push CAD data into Carbon from inside Onshape
+
+> Status: in-progress (built on `feat/onshape-app`, PR #1764 open)
+> Author: Raul Soonawala
+> Date: 2026-08-28; rewritten 2026-10-12 to match the build
+
+## TLDR
+
+Carbon adds a panel to Onshape's element right panel. An engineer opens a Part Studio, an assembly or a drawing and sees which parts Carbon already has. The engineer then pushes parts, an assembly's BOM or a whole release into Carbon. Every push shows a review first and writes only when the engineer confirms it. The panel is its own integration, `onshape-v2`, beside the existing sync integrations. Carbon never pulls from Onshape on its own. Engineering detail: `.claude/rules/onshape-panel.md`. User docs: `docs/content/docs/integrations/cad.mdx`.
+
+## Overview diagram
+
+```mermaid
+flowchart LR
+ P["Panel in Onshape iframe"] -->|"Sign in (popup)"| A["onshape+/auth: mint cps_ token"]
+ P -->|"Bearer token"| S["status / releases routes"]
+ P -->|"Push"| PL["plan-* route: read Onshape + Carbon"]:::new
+ PL --> R[("Redis: plan, 15 min")]
+ R --> RV["Review in panel: 3 selects per row"]:::new
+ RV -->|"Confirm"| AP["push-* route: write Carbon, no Onshape call"]:::new
+ AP --> C[("item, part, makeMethod, methodMaterial, changeOrder, externalIntegrationMapping")]
+ AP --> J["onshape-panel-sync job: export model or PDF"]
+ classDef new stroke-dasharray:4 3
+```
+
+## Problem Statement
+
+Carbon's Onshape integration on main pulls from inside Carbon. The BoM Explorer imports a BOM, and a release webhook attaches models and drawings to items that already exist. The engineers who decide when CAD data is ready work in Onshape. They have no view there of what Carbon holds, and no control over when data goes in. Pulling also spends API quota on reads that nobody asked for.
+
+## Proposed Solution
+
+| Capability | What it does |
+|---|---|
+| Status | Shows each part or BOM line as Linked, Conflict, Unlinked or Released, and each release as In Carbon, Partial or Not in Carbon. |
+| Push a part | Creates or updates the item, links it to the Onshape part, and exports the model and thumbnail. |
+| Push an assembly | Creates missing items and writes the BOM into each make method, sub-assemblies included. An Active method gets a Draft version. |
+| Push a release | Creates a revision of each released item at the released letter, writes the released BOM, and stages the new revisions on one Draft change notice. Released drawings attach as PDF. |
+| Fields | Maps Onshape properties to six item fields and to part custom fields, and sets the push defaults for new items. |
+| Item page | One card on the part page: the Onshape link, the fields a push replaces, Open in Onshape and Detach. |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| Integration identity | Separate id `onshape-v2`, with its own grant, `companyIntegration` row and mapping namespace | A company can run the panel beside either sync connection. Disconnecting one never affects the other. |
+| Direction | Push only, started by a person in Onshape | The engineer decides when data is ready. No background reads spend quota. |
+| Write model | Two requests: PLAN stores a plan in Redis, APPLY writes it | The review shows exactly what the push writes. APPLY makes no Onshape call, and a double submit writes once. |
+| Panel credential | Opaque `cps_` token minted in a same-origin popup, held in Redis for 12 hours | The `SameSite=Lax` session cookie never reaches a cross-site iframe. The token holds identity only, never a Supabase token. |
+| Released methods | Never edited; the push writes into a Draft version | A push must not change what production uses. This matches a Version change in Carbon. |
+| Release revisions | New revisions are inactive on a Draft change notice | Carbon's change process decides when a revision becomes live. |
+| Field ownership | No field is locked. Each mapping is "Set at creation" or "Update on every push" | A linked item is a normal Carbon item. The mode decides what a later push overwrites. |
+| Property map location | The panel's Fields page | Onshape lists properties only from inside a document. |
+| Drawing record | The PDF document `<partNumber>-<revision>.pdf` on the model's item | No extra table. The Releases tab reads the drawing state back by file name. |
+| Item page footprint | One self-loading card, no Onshape fields on the form | Upstream changes to the item page stay free of merges. |
+| Write location | Route actions in `apps/erp` plus two server modules | Open: see Open Questions. Main's `sync` server function already writes items and BOMs for the BoM Explorer. |
+
+## Data Model Changes
+
+No new tables or columns.
+
+- Migration `20261016051650_onshape-v2-integration.sql` inserts the `onshape-v2` row into `integration`.
+- Migration `20261016051651_onshape-v2-vault-secrets.sql` moves plaintext tokens in `onshape-v2` metadata into Vault. `SECRET_KEYS["onshape-v2"]` names the access and refresh token.
+- `companyIntegration.metadata` for `onshape-v2` holds `credentials` (type, expiry), `propertyMap`, `descriptionModes` and five `default*` push-default keys.
+- `externalIntegrationMapping` rows with integration `onshape-v2` record identity:
+
+| Entity | `externalId` |
+|---|---|
+| Part item | `documentId:elementId:partId[:configuration]` |
+| Assembly item | `documentId:elementId:assembly[:configuration]` |
+| Release revision item | `release:<releaseId>:<partNumber>` |
+| BOM line the push wrote | entityType `methodMaterial` |
+| Draft the push made | entityType `makeMethod`, with the source Active method in metadata |
+
+## API / Service Changes
+
+All panel routes use `requireOnshapePanelPermissions` (bearer token, employees only, 401 or 403, no redirect).
+
+| Route | Method | Permission | Does |
+|---|---|---|---|
+| `api+/integrations.onshape.panel.status` | GET | parts view | Reads the element and its Carbon state |
+| `api+/integrations.onshape.panel.releases` | GET | parts view | Lists the 20 newest releases and their state |
+| `api+/integrations.onshape.panel.plan-part` | POST | parts create, update | Plans 1 to 50 parts |
+| `api+/integrations.onshape.panel.plan-assembly` | POST | parts create, update, delete | Plans an assembly at depth `all` (up to 1500 part numbers) or `top` |
+| `api+/integrations.onshape.panel.plan-release` | POST | parts create, update, delete | Plans one release |
+| `api+/integrations.onshape.panel.push-{part,assembly,release}` | POST | as the plan | Applies a stored plan |
+| `api+/integrations.onshape.panel.fields` | GET, POST | settings update | Reads and saves the property map and push defaults |
+| `api+/integrations.onshape.panel.me` | GET | employee | Returns the user, company and `canEditFields` |
+| `api+/integrations.onshape.panel.session` | DELETE | employee | Signs the panel out |
+| `api+/integrations.onshape.detach` | POST | parts update (cookie) | Removes the item's `onshape-v2` link |
+| `api+/integrations.onshape-v2.install`, `.oauth` | GET, POST | settings update | Starts and completes the OAuth grant |
+
+- Server modules: `modules/settings/onshape-push.server.ts` (field writers, BOM line writes, change notice staging) and `modules/settings/onshape-draft-method.server.ts` (Draft versions).
+- Background job: `onshape-panel-sync` exports a model, thumbnail or drawing PDF for one item.
+- `@carbon/kv` gains `acquireLease` and `withLease`. The Onshape token refresh uses them, because Onshape rotates refresh tokens.
+
+## UI Changes
+
+- Panel routes: `onshape+/panel` (framable by `*.onshape.com` only), `onshape+/auth` (sign-in popup), `onshape+/_layout` (owns the scroll and follows Onshape's theme).
+- Panel pages: the push page (Parts, Assembly or Push), Releases and Fields.
+- Settings → Integrations: an Onshape V2 card. Connect opens a popup for both Onshape connections; Reconnect goes to Onshape's consent page and back.
+- Part page: `ExternalSourceCard` after the CAD model.
+
+## Acceptance Criteria
+
+- [x] A part push creates the item with its model and thumbnail; a second push of an unchanged part writes nothing.
+- [x] Push all writes every numbered part of a Part Studio, with mapped item fields and custom fields.
+- [x] An assembly push writes the BOM into the assembly's make method.
+- [ ] An assembly push takes over matching manual lines and keeps the others (untested).
+- [ ] An assembly push with an Active method writes into a Draft version and reuses it on the next push (untested).
+- [x] A release push creates revisions at the released letters under one Draft change notice; a second push creates nothing.
+- [x] A release with a drawing attaches the PDF and reads In Carbon once the PDF lands.
+- [x] A user without settings view gets status and a review (checked over the API).
+- [x] Fields saves the map and push defaults; a push applies them.
+- [ ] A person signs in from inside Onshape's iframe by hand once (automation cannot complete the popup).
+- [ ] The write path has tests that run without Onshape.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| The write path (push routes, server modules, client) has no tests; 338 tests cover the pure modules only | High | Add module-boundary tests before the next live run. |
+| The push routes duplicate decisions that main's `sync` server function and the item page also make | High | Decide the write location (Open Questions). |
+| A private Onshape app bills the owner's yearly quota; a spent quota answers 402 | Medium | The panel names the cause. Dev mode caches stable reads. |
+| Onshape's panel is often under 768px wide, so Carbon inputs render at phone size | Low | Container-width styles in `@carbon/react`. |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [ ] Where do the writes live? Options: a thin panel over main's `sync` server function; landable slices of this branch; or this branch as is, with write-path tests first.
+- [ ] Which of the 19 open edge-case findings must be fixed before merge?
+- [ ] Can Onshape Government private apps host the panel, and from which domain?
+
+## Changelog
+
+- 2026-08-28: Created.
+- 2026-10-12: Rewritten to match the build. The field-mapping spec (`2026-10-07-onshape-standard-field-mapping.md`) is folded in and deleted.
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.md
index a6db6bc22a..f662d7f814 100644
--- a/.claude/rules/environment-configuration.md
+++ b/.claude/rules/environment-configuration.md
@@ -128,8 +128,12 @@ account notifications loader and the app shell loader (`pushPublicKey`), not
`getBrowserEnv()` for the authorize URL; `RAMP_CLIENT_SECRET`, server-only for code
exchange/token refresh), Slack (`SLACK_BOT_TOKEN`, `SLACK_CLIENT_ID`,
`SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET`, `SLACK_STATE_SECRET`,
-`SLACK_OAUTH_REDIRECT_URL`), OnShape (`ONSHAPE_CLIENT_ID/SECRET`,
-`ONSHAPE_OAUTH_REDIRECT_URL`), Xero, QuickBooks, Jira (each `*_CLIENT_ID/SECRET`,
+`SLACK_OAUTH_REDIRECT_URL`), Onshape (two Onshape apps, no shared variable:
+`ONSHAPE_CLIENT_ID/SECRET` + `ONSHAPE_OAUTH_REDIRECT_URL` for the `onshape` sync
+integration, `ONSHAPE_V2_CLIENT_ID/SECRET` + `ONSHAPE_V2_OAUTH_REDIRECT_URL` for the
+`onshape-v2` panel. `crbn up` writes `ONSHAPE_V2_OAUTH_REDIRECT_URL`
+into `.env.local` from the stack's `ERP_URL`, so each worktree host must be registered
+on the panel's Onshape app, or pinned in `.env` with `#force`), Xero, QuickBooks, Jira (each `*_CLIENT_ID/SECRET`,
plus webhook/redirect/state secrets), `EXCHANGE_RATES_API_KEY`,
`GOOGLE_PLACES_API_KEY`, AI keys `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`.
diff --git a/.claude/rules/onshape-panel.md b/.claude/rules/onshape-panel.md
new file mode 100644
index 0000000000..23403b36d3
--- /dev/null
+++ b/.claude/rules/onshape-panel.md
@@ -0,0 +1,137 @@
+paths:
+ - "packages/ee/src/onshape/**"
+ - "apps/erp/app/routes/onshape+/**"
+ - "apps/erp/app/routes/api+/integrations.onshape.panel.*"
+ - "apps/erp/app/routes/api+/integrations.onshape-v2.*"
+ - "apps/erp/app/routes/api+/integrations.onshape.detach.ts"
+ - "apps/erp/app/modules/settings/onshape-*.server.ts"
+ - "apps/erp/app/components/ExternalSource.tsx"
+ - "packages/jobs/src/inngest/functions/integrations/onshape-*"
+
+# Onshape panel (`onshape-v2`)
+
+A Carbon panel in Onshape's element right panel. Users push parts, assemblies and releases from Onshape; Carbon never pulls on its own. Spec: `.ai/specs/2026-08-28-onshape-app.md`. User docs: `docs/content/docs/integrations/cad.mdx`.
+
+## Connections
+
+- Three Onshape grants, each with its own `companyIntegration` row and mapping namespace: `onshape` and `onshape-government` (sync connections, `config.tsx`, one active per company) and `onshape-v2` (the panel, `config-v2.tsx`). A company can run the panel beside either sync connection.
+- `ONSHAPE_V2_INTEGRATION_ID` (`lib/integration-id.ts`): pass it to every panel read and write, e.g. `getOnshapeClient(…, ONSHAPE_V2_INTEGRATION_ID)`. Omitted, `getOnshapeClient` resolves the company's sync connection. A bare `"onshape"` literal in panel code is a bug.
+- `ONSHAPE_INTEGRATION_IDS`, `OnshapeIntegrationId`, `isOnshapeIntegrationId` and `getConflictingOnshapeIntegration` (`lib/connection.ts`) cover the two sync connections only. `OnshapeOAuthIntegrationId` covers all three.
+- Status, releases and the three plan routes read the connection with the service role. The `companyIntegration` SELECT policy needs settings view; through a parts-view user's client the row reads as absent and the panel says Onshape is not connected. The Fields route uses the user's client: it requires settings update anyway.
+- Only an `onshape-v2` item link means "the panel pushes to this item". A sync connection's item row is BOM-import bookkeeping for the BoM Explorer; the item card and Detach never read or delete it.
+- OAuth: the sync integration and the panel are two Onshape apps and share no variable. `onshape` reads `ONSHAPE_CLIENT_ID`, `ONSHAPE_CLIENT_SECRET`, `ONSHAPE_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape/oauth`); `onshape-v2` reads `ONSHAPE_V2_CLIENT_ID`, `ONSHAPE_V2_CLIENT_SECRET`, `ONSHAPE_V2_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape-v2/oauth`). Both ask for `OAuth2Read OAuth2Write`. Each card is `active` only when its own client id is set (`config.tsx`, `config-v2.tsx`); otherwise it reads Not Configured, Install is disabled and an installed connection's Details link goes nowhere; the env schema groups them as `onshape` and `onshapeV2`. Install routes call `beginOnshapeAuthorization`; callbacks call `completeOnshapeAuthorization` (`modules/settings/onshape-oauth.server.ts`); `getOnshapeOAuthConfig` picks the client and redirect per id and answers `not-configured` when one of that integration's three variables is missing. A connection's tokens belong to the app that issued them: changing an integration's client id means reconnecting. State is the cookie-bound one from `@carbon/auth/oauth-state.server`.
+- Connect opens a popup (`beginOAuthPopup`, `packages/ee/src/oauth-popup.ts`, opened inside the click). The callback renders `oauthPopupResponse`: it posts the outcome to the opener and closes, or lands on the integrations page with no opener. The drawer's Reconnect action POSTs to the install route and follows `{ redirectUrl }`.
+- Uninstall only sets `active = false` and keeps the tokens, so `getOnshapeClient` reads the `onshape-v2` row only while it is active: after an uninstall every panel read answers "not connected". A plan already stored can still be applied until it expires (15 min); APPLY makes no Onshape call.
+- `onshapeHealthcheck` (`hooks.server.ts`) builds the client (refreshing an expired token) and reads `/companies`; a revoked grant reads unhealthy.
+- Tokens live in Vault: `SECRET_KEYS["onshape-v2"]` (`integrations/secrets.ts`) names the access and refresh token. Migration `20261016051650_onshape-v2-integration.sql` seeds the `integration` row; `20261016051651_onshape-v2-vault-secrets.sql` moves any plaintext tokens already in `onshape-v2` metadata into Vault.
+
+## Integration metadata
+
+Several writers share `companyIntegration.metadata`: token refresh, the OAuth callback, the settings save, the webhook's Onshape company id and the Fields save. Each writes only its own keys. The others go through `patchIntegrationState` (row lock, dot-path patches) via the helpers in `lib/state.ts`; the Fields save is one Kysely UPDATE that writes `propertyMap` and `descriptionModes` with `jsonb_set` and merges the five `default*` push-default keys. Never write the whole column from an earlier read.
+
+## Token refresh
+
+`getOnshapeClient` refreshes within two minutes of expiry (a missing `expiresAt` counts as expired) and once more per client on a 401. Onshape rotates refresh tokens, so the refresh runs under a lease from `@carbon/kv` (`acquireLease` / `withLease`: Lua acquire that tells "held" from "Redis down", renewal during the exchange, compare-and-delete release). The lease key is `onshape-token-refresh:<companyId>:<integrationId>` (5 s, renewed every 2 s); waiters poll every 250 ms and give up after 20 s. With Redis down it refreshes without a lock. The holder re-reads the stored pair and adopts a token another caller already refreshed (`resolveOnshapeRefresh`, `lib/token-refresh.ts`). The token request times out after 15 s.
+
+## Panel auth
+
+The `carbon` cookie is `SameSite=Lax` and never reaches a cross-site iframe, so the panel has its own credential.
+
+- `onshape+/panel.tsx` loads without auth and is the only framable route: its `Content-Security-Policy: frame-ancestors https://onshape.com https://*.onshape.com` replaces the app's baseline directive.
+- `onshape+/auth.tsx` is a same-origin popup. It takes identity from the cookie session, refuses non-employees and console sessions, applies the app shell's account gates (MFA enrollment, ITAR attestation in a controlled environment), mints `cps_<32 base64url>` (Redis `panel-session:<token>`, `panel/session.server.ts`; 12 h, capped at the ERP session's absolute cap in a controlled environment) and posts it to the opener. The panel keeps it in sessionStorage (`carbon:onshape-panel-session`) and sends `Authorization: Bearer`; a 401 clears it.
+- A panel session holds identity only, never a Supabase token. Each request builds its client from a short-lived token signed for the user (`getUserScopedClient`). Copying the cookie session's refresh token would make the panel and the ERP tab rotate one chain, and GoTrue revokes the family on reuse.
+- Panel routes call `requireOnshapePanelPermissions` (`@carbon/ee/onshape/panel-session.server`), not `requirePermissions`. It applies the cookie path's session policy (`panelSessionRefusal`: absolute cap and idle lock in a controlled environment; a TOTP factor enrolled after minting everywhere), requires the `employee` role, then runs the same claims check. Denials are 401 or 403, never redirects. Activity is stamped only on an authorized request with `SET … KEEPTTL XX`, so a deleted session stays deleted.
+- Tokens never appear in URLs. postMessage targets `window.location.origin`.
+
+## Identity (`externalIntegrationMapping`, integration `onshape-v2`)
+
+| Entity | `externalId` |
+|---|---|
+| Part item | `documentId:elementId:partId[:configuration]` |
+| Assembly item | `documentId:elementId:assembly[:configuration]` |
+| Release revision item | `release:<releaseId>:<partNumber>` |
+| Onshape-written BOM line | entityType `methodMaterial`; `metadata.makeMethodId` names the method |
+| Draft the panel made | entityType `makeMethod` (`DRAFT_MARKER_ENTITY_TYPE`); `externalId` is the Draft id, `metadata.sourceMethodId` the Active method it copied |
+
+A non-default configuration is appended to the key (`normalizeConfiguration`, `externalIdFor*` in `panel/status.ts`).
+
+## Plan and apply
+
+Every push is two requests. PLAN (`api+/integrations.onshape.panel.plan-{part,assembly,release}`) reads Onshape and Carbon, builds the plan with the pure builders in `panel/plan.ts`, stores it and returns `{ planId, expiresAt, plan }`. APPLY (`push-{part,assembly,release}`) takes the stored plan and writes; it makes no Onshape call. A cancelled or expired review has spent its reads.
+
+- Store: `lib/panel-plan-store.ts`, Redis `panel-plan:cpp_<32 base64url>`, 15 min, bound to company and user. APPLY peeks to validate (a 422 leaves the plan in place) and takes it with GETDEL right before the first write. A plan Redis did not store answers 503 at PLAN; a missing, expired or foreign plan answers 410 at APPLY.
+- The review's only editors are three selects per row (`ItemFieldSelects.tsx`: replenishment, method type, tracking type). A choice is written to Carbon only. A create validates them with `mergeItemEdits`; an existing item with `mergeExistingItemEdits`, writing only what differs from `current`.
+- A part is `unchanged` when its microversion matches the one the last push recorded. If an "everyPush" value or description still differs, the row becomes an `update` flagged `cadUnchanged`: apply writes values and link and skips the model export.
+- APPLY re-resolves items by readableId before creating. Parts adopt with `pickAdoptTarget`: a Part at the same revision, else the latest Part (active rows first), never another item type with the same number. Revisions compare as `getNextRevision` counts them (`compareRevisions`, `panel/revision.ts`).
+- `plan-assembly` takes `depth`: `all`, or `top` (the root's method only, each sub-assembly a line pointing at its own method). With `all` it refuses more than `MAX_PLAN_PARTS` (1500) distinct part numbers with `code: "too-large"`, and the panel offers "Push this level only". A root with no part number is refused.
+- Pushing needs `wv` to be `w` or `v`; a microversion view shows status only. `plan-part` takes 1 to 50 part ids.
+
+## Item and BOM writes
+
+- New item fields follow one precedence (`proposeMappedItem`): the reviewer's choice, the mapped value, a BOM row with children is Make, a Standard content row is Buy, then the push defaults (`parsePushDefaults`, `panel/preferences.ts`: Make, Make to Order for Make, Pull from Inventory for Buy, Inventory tracking, and a unit that falls back to the configured one, then `EA`, then the company's first unit). An unparseable default falls back, and an illegal pair moves to an allowed method (`reconcilePushDefaults`). A mapped Replenishment with no mapped method takes the push default for it (`methodTypeForMake`, `methodTypeForBuy`) when the pair allows it. An empty name becomes the part number; an empty revision becomes `0`. "Show Assembly only" (`shownAsUnit`) decides structure only; "Purchasing Level" is not read.
+- No field is locked. A linked item is a Carbon item; a later push writes only "everyPush" values.
+- An assembly push links the root (unless it is released in Carbon: then only the children are linked) and links a child to its Onshape source only when neither is linked yet (`linkChildParts`); two items claiming one source are reported, not linked. Every reused item linked to its BOM row takes the "everyPush" values (`planExistingItem`); an item linked to another Onshape source takes none. Only description values Onshape gives are written (`assemblyTextChanges`): an empty cell never blanks Carbon's text. Item fields are written before BOM lines.
+- BOM lines take only Part, Material or Consumable items (`BOM_LINE_ITEM_TYPES`). The plan lists a part number Carbon holds as another type under `skipped`; apply reports it as an error.
+- Assembly BOM pushes are a diff. An owned line (one a previous push wrote, per its mapping row) is updated in place (`quantity`, `order`, `materialMakeMethodId`) or skipped when those match; owned lines Onshape no longer lists are deleted with their mappings. New lines and their mapping rows are inserted in one Kysely transaction (`insertOwnedMethodLines`, `modules/settings/onshape-push.server.ts`; a count mismatch rolls back).
+- A manual line for a part number Onshape also lists is taken over (`pairManualLines` in `plan.ts`, applied by `claimManualMethodLine`): Onshape's quantity, order and child method, its operation and scrap kept. Only a line whose `itemType` matches is taken over. Other manual lines are left alone.
+- Active make methods are never edited. An Active method whose lines already match Onshape's is left as is. The plan marks it `unchanged` when part numbers and quantities match in order with nothing taken over and no reusable Draft; apply decides again (`linesWouldChange`): owned lines paired by item id (FIFO), each with the same `quantity`, `order` and `materialMakeMethodId` (the child method apply resolves), and no owned line left over. Otherwise the push writes into a Draft (`ensureDraftMakeMethod`, `modules/settings/onshape-draft-method.server.ts`). It reuses a Draft only when the panel made it from the current Active method and no change notice holds it (`pickReusableDraft`); otherwise it makes version `max(version) + 1`, copies through `copyMakeMethod` and carries ownership with `pairOwnedCopiedLines`. The marker row is written last; if the copy, the carry or the marker fails, the service role deletes the new Draft (`externalIntegrationMapping` has no user DELETE policy). The assembly plan loads the reusable Draft (`loadReusableDrafts`), so the review names the Draft the push writes into.
+- With no Active method, `activeMakeMethods` returns the newest Draft, which can be a change notice's; `loadActiveMakeMethods` reads its `changeOrderId` from `makeMethod`. `loadMethodWriteRefusals` (`onshape-draft-method.server.ts`) refuses a change notice's Draft whatever the notice's stage, and a released (Production) revision when `plmReleaseControl` is `enforce` (`getLockVerdict`, the verdict `checkRevisionLock` gives the BOM editor). Plan drops those methods into `skipped` with the reason (`withRefusedMethods`; an `unchanged` Active method is not refused). Apply checks again before it makes a Draft and reports a refusal under `skipped`.
+- Every delete is scoped by `companyId`. Never build a PostgREST `.or()` string from CAD values.
+- Item page: one mount point, `ExternalSourceCard` in `x+/part+/$itemId.details.tsx`. It shows the fields a push replaces (`everyPushTargets`), last push time, Open in Onshape and Detach (`api+/integrations.onshape.detach` deletes the item's `onshape-v2` row only). A later push can link the item again by part number.
+
+## Property map
+
+One map per company: `metadata.propertyMap`, plus `metadata.descriptionModes` for Name and Description. Entry: `{ onshapePropertyId, onshapeName, valueType, target, mode, translations? }`; `target` is `{ kind: "customField", fieldId }` or `{ kind: "item", field }`. Pure logic in `panel/properties.ts` and `panel/standard-fields.ts`.
+
+- `STANDARD_FIELDS` is the only place an item field becomes mappable: `mpn`, `replenishmentSystem`, `defaultMethodType`, `sourcingType`, `itemTrackingType`, `unitOfMeasureCode`. Each names its writer key; `STANDARD_FIELD_WRITERS` (`onshape-push.server.ts`, a typed `Record`) holds one function per key: `itemMethod` (`updateItemMethodAndSourcing`, cascades onto Draft method materials), `itemTracking` (update plus `cascadeItemTrackingType`), `itemColumn` (`updateItemColumns`). There is no generic column write.
+- Translation: a list target carries rows `{ onshape, carbon | null }`, matched ignoring case and end spaces (`translateValue`). A unit also matches by code or name. `null` means "No value": the next precedence rule decides. An unmatched value is a review problem and is skipped.
+- Modes: `create` (default) writes only when the push creates the item; `everyPush` also writes to a linked existing item.
+- Existing items: "everyPush" values go through `interlockItemFields` in the item page's order: Replenishment (with the method `methodForReplenishment` gives: Make → Make to Order and Buy → Purchase to Order, as `deriveItemMethodUpdate` pins; Buy and Make keeps an allowed method and moves Make to Order to Pull from Inventory, since apply refuses that pair), method (refused when Replenishment does not allow it), Sourcing (Buy and Make only), then tracking, unit and MPN.
+- New items: every mapped value goes into the proposal. `upsertPart` takes neither MPN nor Sourcing, so apply writes those after the insert (`createdItemExtras`).
+- Values are read from part metadata (`readPartProperties`, one read at `depth=2`), the root's element metadata, BOM cells (matched by column id, then name) and released metadata at the released version. A list value is read as its option's label (`enumLabel`). A BOM cell "N/A" means the row lacks the property and reads as null. An empty map costs no extra reads.
+- `loadPlanMapping` and `loadPlanOptions` read with the service role, for the same settings-view reason as the connection.
+- The Fields page (`api+/integrations.onshape.panel.fields.ts`) lists the element's properties, the map, the modes, the push defaults, part custom fields and units; POST saves them. Both need settings update; `panel.me` returns `canEditFields`. The save refuses a value type the target does not take, a translation value outside the field's list, an Onshape value with two rows, two properties on one target, and deleted fields (422, per property). Limits: 100 entries, 100 translations each, 255-character values.
+- `MAPPABLE_VALUE_TYPES` for custom fields: STRING/ENUM/OBJECT → Text, BOOL → Yes/No, INT/DOUBLE → Numeric, DATE → Date. Nothing maps to a List custom field.
+- Custom field values land in `part.customFields` keyed by readableId, shared across revisions. Writes merge only mapped keys (`mergeCustomFieldValues`); an emptied "everyPush" value deletes the key. A Yes/No field stores the string `"on"` (`BOOLEAN_TRUE`).
+
+## Release push
+
+- Releases come from `GET /revisions/d/{did}`, grouped by releaseId (`panel/releases.ts`). An empty list triggers one `getCompanies()` call; with no Onshape company the route returns `releaseManagementAvailable: false`.
+- Each released model item gets an item at the released letter: `createRevision` from the newest revision below it, released or not (`pickRevisionBase`), else from the latest row; a fresh item only when Carbon has no row for the part number. Idempotent on part number and letter.
+- Each released assembly's BOM is read at its released version and configuration, keyed by `releaseBomKey` (element id, plus the normalized configuration when it is not the default), so two configurations of one element keep two BOMs.
+- BOM children that are not release items are resolved in one lookup and point at the revision the released BOM names, else the latest row (`pickBomChildRow`). A child that is a release item points only at the revision this push applied; a release item that was held back or failed is not created as a child, and its line is reported and not written.
+- The release items the push creates are staged under one Draft change notice: an open notice from an earlier push of the same release whose engineering content is editable and that is not waiting for approval (`findOpenReleaseNotice`: links matched on `metadata.releaseId`, item reads batched), else a new one inserted before the first item write (a failed insert writes nothing). `stageChangeNoticeItem` (`onshape-push.server.ts`) does what `createChangeNoticeDraftMethod` does, in one transaction: the item is inactive, it and its Draft method carry the notice id, and one affected row (Revision or New Part) names the base item and both methods. Releasing the notice activates them. `findOpenReleaseNotice` fails closed: a failed read refuses the plan or the push (nothing written) rather than opening a second notice; the push reads it before taking the plan. An item the notice cannot take is deleted again (service role, `deleteItem`) and reported, so it never sits outside change control. A notice this push inserted is deleted when nothing was created.
+- BOM children the release push creates are not staged on the notice. An assembly whose BOM was not read at review is not created, and any BOM read failure skips every BOM write.
+- With `createChangeNotice: false` (API only; the panel always sends the plan's notice) revisions are created active and, unless `makeDefault` is false, `updateDefaultRevision` makes each the default, repointing every BOM line that uses a revision of the part.
+- Release BOM lines: the push deletes the revision's copies of the base's Onshape lines and every `onshape-v2`-owned line on the target method (any earlier push's, not only this release's), then inserts one level per method in one transaction, with `releaseId` in the mapping metadata. The item link is `release:<releaseId>:<partNumber>` unless the reused revision is already linked to a part or assembly.
+- A released method in Carbon is not edited; its BOM is reported as skipped.
+- A reused revision held by a change notice whose engineering content is locked (Implementation onward, or awaiting approval; any of the item's make methods carries the notice id) takes neither field values nor BOM lines; it is reported as skipped with `requireChangeNoticeEditable`'s reason. A Draft held by an editable notice, the release's own included, stays writable.
+- Model exports carry the revision's `partId` and configuration (`releaseExportSelection`). A Part Studio item with no single `partId` is skipped.
+- A released drawing attaches to its model item as `<partNumber>-<revision>.pdf` (`releaseDrawingFileName`), its only record. The Releases tab reads it back by name, so a drawing-only release reads In Carbon once its PDFs land. A re-push re-exports onto the same path.
+
+## Batch every `.in()` sized by CAD data
+
+The gateway rejects a request line over 4,096 bytes, and a PostgREST `.in()` list rides in the URL; 55-character mapping keys fail at about 56 entries. Every panel `.in()` sized by a BOM, part studio or release goes through `selectInBatches` / `chunkFilterValues` (`lib/batched-filter.ts`), which split on encoded bytes. It also pages each batch past PostgREST's 1,000-row cap (`.range()` until a short page, `ORDER BY` the query's own order then `orderBy`, default `id`), so the factory is called once per page and must return a fresh builder. Batched rows arrive in batch order; re-sort after, with a unique tie-break (BOM lines sort by `order`, then `id`).
+
+## Onshape API facts
+
+- Root identity comes from element metadata ("Part number", "Name", "Description"); the BOM's top-level row (`includeTopLevelAssemblyRow=true`) is the fallback.
+- A Part Studio model export needs exactly one `partId`. The thumbnail endpoint cannot select a part or configuration, so only unconfigured assemblies take Onshape's thumbnail; others come from Carbon's model optimizer.
+- Unresolved action-URL placeholders arrive literally (`{$partNumber}`) and are read as null (`parsePanelContext`).
+- Extensions render only for users subscribed to the app; an OAuth grant alone shows nothing.
+- A linked document's BOM can report a different revision for a part than the source document's BOM at the same version.
+- A private app's calls bill the owner's yearly quota; public App Store apps are exempt. A spent quota answers 402, and `onshapeFailure` (`lib/onshape-failure.ts`) says so.
+
+## Background job and dev workflow
+
+- `onshape-panel-sync` (Inngest) does the slow work: export, poll, download, thumbnail, and released drawings as PDF. `elementKind` is `partstudio`, `assembly` or `drawing`; retries 1; concurrency 1 per item. Applies queue it with event id `<planId>:<itemId>:<elementId>`, so a retried apply exports once. A queue failure is reported and the writes stay; a part push then deletes the new link so the next push retries.
+- `ONSHAPE_DEV_CACHE=1` serves repeated GETs from a 10-minute Redis cache, only for `DEV_CACHEABLE_PATHS` in `lib/client.ts`; the key is the path alone, so every company shares entries. Never add a polling endpoint. Live calls are counted in Redis `onshape:api-calls:<year>`.
+
+## Panel UI
+
+- Pages: the push page (labelled Parts, Assembly, or Push on any other element, where it says there is nothing to push), Releases (needs a `documentId`) and Fields (settings update, on a Part Studio or assembly). The Carbon company and Sign out sit on the right.
+- The theme follows Onshape's `theme` action-URL parameter: the `onshape+` layout declares `handle.hostMode` and the root renders that mode. Missing means light.
+- Part badges: Linked, Conflict (same part number, not linked to this source; a push uses that item), Unlinked, and Released (released in Onshape; its Push is disabled because changes come through a release). Release states: In Carbon, Partial, Not in Carbon. The assembly BOM is the structured tree (`panel/bom-view.ts`).
+- Moving to another element clears a part or assembly review and the Fields state; a release review survives within the same document.
+- Every action is disabled while a read or write is in flight. `panelFetch` gives up after 60 s (`PanelTimeoutError`); applies pass no timeout, since a push keeps writing after the panel stops waiting.
+- `onshape+/_layout.tsx` owns the scroll (`h-dvh overflow-hidden`): a pinned header, one scrolling body (`min-h-0 flex-1 overflow-y-auto`) and a sticky action bar. The document must never scroll: under the app shell's `html.h-full` the root becomes a scroll container, and opening a Radix Select there snaps it to the top and closes the popup. Never add `min-h-screen` or `min-h-dvh` to the panel shell.
diff --git a/apps/erp/app/components/ExternalSource.tsx b/apps/erp/app/components/ExternalSource.tsx
new file mode 100644
index 0000000000..48a3d4e54a
--- /dev/null
+++ b/apps/erp/app/components/ExternalSource.tsx
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { useCarbon } from "@carbon/auth";
+import type { StandardFieldId } from "@carbon/ee";
+import { everyPushTargets } from "@carbon/ee";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useState } from "react";
+import { LuExternalLink, LuUnlink } from "react-icons/lu";
+import { Confirm } from "~/components/Modals";
+import { useDateFormatter, useUser } from "~/hooks";
+import { path } from "~/utils/path";
+
+type ExternalSourceMapping = {
+ externalId: string | null;
+ lastSyncedAt: string | null;
+ metadata: {
+ documentId?: string;
+ elementId?: string;
+ wv?: string;
+ wvId?: string;
+ partNumber?: string | null;
+ revision?: string | null;
+ pushedAt?: string;
+ } | null;
+};
+
+/**
+ * Self-loading card for the item's `onshape-v2` link: the fields a push
+ * replaces, last push time, Open in Onshape and Detach. Renders nothing when
+ * the item has no link.
+ */
+export function ExternalSourceCard({
+ itemId,
+ canDetach
+}: {
+ itemId: string;
+ canDetach: boolean;
+}) {
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const { t } = useLingui();
+ const { formatDateTime } = useDateFormatter();
+ const [mapping, setMapping] = useState<ExternalSourceMapping | null>(null);
+ const [confirmingDetach, setConfirmingDetach] = useState(false);
+ // Bumped after a detach: the card re-reads the link and goes once it is gone.
+ const [reload, setReload] = useState(0);
+ // Null until read, or when this user lacks settings view.
+ const [replaced, setReplaced] = useState<string[] | null>(null);
+ const itemFieldLabel: Record<StandardFieldId, string> = {
+ mpn: t`Manufacturer Part Number`,
+ replenishmentSystem: t`Replenishment`,
+ defaultMethodType: t`Default Method Type`,
+ sourcingType: t`Sourcing`,
+ itemTrackingType: t`Tracking Type`,
+ unitOfMeasureCode: t`Unit of Measure`
+ };
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reload re-reads the link
+ useEffect(() => {
+ if (!carbon) return;
+ let cancelled = false;
+ carbon
+ .from("externalIntegrationMapping")
+ .select("externalId, lastSyncedAt, metadata")
+ .eq("companyId", company.id)
+ .eq("entityType", "item")
+ .eq("entityId", itemId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .maybeSingle()
+ .then(({ data }) => {
+ if (cancelled) return;
+ setMapping((data as ExternalSourceMapping | null) ?? null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [carbon, company.id, itemId, reload]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the labels follow the locale, not the read
+ useEffect(() => {
+ if (!carbon || !mapping) return;
+ let cancelled = false;
+ void (async () => {
+ const integration = await carbon
+ .from("companyIntegration")
+ .select("metadata")
+ .eq("companyId", company.id)
+ .eq("id", ONSHAPE_V2_INTEGRATION_ID)
+ .maybeSingle();
+ if (cancelled) return;
+ if (!integration.data) {
+ setReplaced(null);
+ return;
+ }
+ const targets = everyPushTargets(integration.data.metadata);
+ const fieldNames = new Map<string, string>();
+ if (targets.customFieldIds.length > 0) {
+ const fields = await carbon
+ .from("customField")
+ .select("id, name")
+ .eq("companyId", company.id)
+ .in("id", targets.customFieldIds);
+ for (const field of fields.data ?? []) {
+ fieldNames.set(field.id, field.name);
+ }
+ }
+ if (cancelled) return;
+ setReplaced([
+ ...targets.descriptions.map((field) =>
+ field === "name" ? t`Short Description` : t`Long Description`
+ ),
+ ...targets.itemFields.map((field) => itemFieldLabel[field]),
+ ...targets.customFieldIds.flatMap((id) => {
+ const name = fieldNames.get(id);
+ return name ? [name] : [];
+ })
+ ]);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [carbon, company.id, mapping]);
+
+ if (!mapping) return null;
+
+ const meta = mapping.metadata ?? {};
+ // A child linked by an assembly push records no workspace, so it opens the
+ // document.
+ const onshapeUrl = !meta.documentId
+ ? null
+ : meta.wvId && meta.elementId
+ ? `https://cad.onshape.com/documents/${meta.documentId}/${meta.wv ?? "w"}/${meta.wvId}/e/${meta.elementId}`
+ : `https://cad.onshape.com/documents/${meta.documentId}`;
+ const pushedAt = meta.pushedAt ?? mapping.lastSyncedAt;
+ const lastPushed = pushedAt ? formatDateTime(pushedAt) : null;
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Onshape
+ <Badge variant="green">
+ <Trans>Linked</Trans>
+ </Badge>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-center justify-between gap-4">
+ <p className="text-sm text-muted-foreground">
+ {replaced === null ? (
+ <Trans>
+ Pushes replace only the fields that Onshape's Fields page sets
+ to Update on every push.
+ </Trans>
+ ) : replaced.length === 0 ? (
+ <Trans>
+ Pushes don't change this item's fields, so edits made here stay.
+ </Trans>
+ ) : (
+ <Trans>
+ Each push replaces: {replaced.join(", ")}. Other edits stay.
+ </Trans>
+ )}
+ {lastPushed ? (
+ <>
+ {" "}
+ <Trans>Last pushed {lastPushed}.</Trans>
+ </>
+ ) : null}
+ </p>
+ <HStack spacing={2} className="shrink-0">
+ {onshapeUrl ? (
+ <Button variant="secondary" leftIcon={<LuExternalLink />} asChild>
+ <a href={onshapeUrl} target="_blank" rel="noreferrer">
+ <Trans>Open in Onshape</Trans>
+ </a>
+ </Button>
+ ) : null}
+ {canDetach ? (
+ <Button
+ variant="ghost"
+ leftIcon={<LuUnlink />}
+ onClick={() => setConfirmingDetach(true)}
+ >
+ <Trans>Detach</Trans>
+ </Button>
+ ) : null}
+ </HStack>
+ </div>
+ </CardContent>
+ {confirmingDetach ? (
+ <Confirm
+ action={path.to.api.onShapeDetach}
+ title={t`Detach from Onshape?`}
+ text={t`Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back.`}
+ confirmText={t`Detach`}
+ onCancel={() => setConfirmingDetach(false)}
+ onSubmit={() => {
+ setConfirmingDetach(false);
+ setReload((n) => n + 1);
+ }}
+ >
+ <input type="hidden" name="itemId" value={itemId} />
+ </Confirm>
+ ) : null}
+ </Card>
+ );
+}
diff --git a/apps/erp/app/modules/settings/integration-errors.test.ts b/apps/erp/app/modules/settings/integration-errors.test.ts
new file mode 100644
index 0000000000..3886eb2446
--- /dev/null
+++ b/apps/erp/app/modules/settings/integration-errors.test.ts
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce(
+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),
+ ""
+ )
+}));
+
+import {
+ getIntegrationError,
+ integrationErrorSearch
+} from "./integration-errors";
+
+describe("integration error copy", () => {
+ it("resolves every code the Onshape callback can send for the panel", () => {
+ for (const code of [
+ "write-permission",
+ "denied",
+ "invalid-state",
+ "invalid-response",
+ "not-configured",
+ "token-exchange",
+ "save-failed",
+ "unexpected"
+ ] as const) {
+ expect(getIntegrationError("onshape-v2", code)).toBeDefined();
+ expect(integrationErrorSearch("onshape-v2", code)).toBe(
+ `?integration=onshape-v2&error=${code}`
+ );
+ }
+ });
+
+ it("gives the panel the public app's copy", () => {
+ expect(getIntegrationError("onshape-v2", "not-configured")).toBe(
+ getIntegrationError("onshape", "not-configured")
+ );
+ });
+
+ it("resolves nothing for an unknown integration or code", () => {
+ expect(getIntegrationError("onshape-v3", "denied")).toBeUndefined();
+ expect(getIntegrationError("onshape-v2", "no-such-code")).toBeUndefined();
+ });
+});
diff --git a/apps/erp/app/modules/settings/integration-errors.ts b/apps/erp/app/modules/settings/integration-errors.ts
index ebc51bac10..36490ee446 100644
--- a/apps/erp/app/modules/settings/integration-errors.ts
+++ b/apps/erp/app/modules/settings/integration-errors.ts
@@ -21,6 +21,54 @@ type IntegrationErrorMessage = {
description: MessageDescriptor;
};
+/**
+ * Shared by `onshape` and `onshape-v2`: one OAuth app, one callback handler.
+ * `onshape-v2` never answers `connection-conflict`.
+ */
+const onshapeErrors = {
+ // `invalid_scope` means the OAuth application isn't granted a scope we asked
+ // for. In practice that's `OAuth2Write`, so name the exact dev-portal
+ // permission instead of echoing Onshape's wording, which never says which
+ // scope is missing. The quoted label stays English in every locale — it's a
+ // literal string in Onshape's UI.
+ "write-permission": {
+ title: msg`Onshape denied the connection`,
+ description: msg`In Onshape, edit this OAuth application's permissions to include "Application can write to your documents", then connect again.`
+ },
+ denied: {
+ 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.`
+ },
+ "not-configured": {
+ title: msg`Onshape isn't configured`,
+ description: msg`This Carbon instance is missing its Onshape OAuth credentials. Ask an administrator to set them.`
+ },
+ "token-exchange": {
+ title: msg`Onshape rejected the authorization`,
+ description: msg`Exchanging the authorization code for an access token failed. Try connecting again.`
+ },
+ "save-failed": {
+ title: msg`Couldn't save the Onshape connection`,
+ description: msg`Onshape authorized the connection but saving it failed. Try connecting again.`
+ },
+ unexpected: {
+ title: msg`Couldn't complete the Onshape connection`,
+ description: msg`An unexpected error occurred while connecting to Onshape. Try connecting again.`
+ },
+ "connection-conflict": {
+ title: msg`Onshape Government is already connected`,
+ description: msg`A company connects to one Onshape at a time. Uninstall Onshape Government, then connect Onshape.`
+ }
+} satisfies Record<string, IntegrationErrorMessage>;
+
export const integrationErrors = {
ramp: {
denied: {
@@ -59,49 +107,8 @@ export const integrationErrors = {
description: msg`Ramp allows only one. Disconnect the other system in Ramp, or connect Carbon again choosing "Another system posts my ledger".`
}
},
- onshape: {
- // `invalid_scope` means the OAuth application isn't granted a scope we asked
- // for. In practice that's `OAuth2Write`, so name the exact dev-portal
- // permission instead of echoing Onshape's wording, which never says which
- // scope is missing. The quoted label stays English in every locale — it's a
- // literal string in Onshape's UI.
- "write-permission": {
- title: msg`Onshape denied the connection`,
- description: msg`In Onshape, edit this OAuth application's permissions to include "Application can write to your documents", then connect again.`
- },
- denied: {
- 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.`
- },
- "not-configured": {
- title: msg`Onshape isn't configured`,
- description: msg`This Carbon instance is missing its Onshape OAuth credentials. Ask an administrator to set them.`
- },
- "token-exchange": {
- title: msg`Onshape rejected the authorization`,
- description: msg`Exchanging the authorization code for an access token failed. Try connecting again.`
- },
- "save-failed": {
- title: msg`Couldn't save the Onshape connection`,
- description: msg`Onshape authorized the connection but saving it failed. Try connecting again.`
- },
- unexpected: {
- title: msg`Couldn't complete the Onshape connection`,
- description: msg`An unexpected error occurred while connecting to Onshape. Try connecting again.`
- },
- "connection-conflict": {
- title: msg`Onshape Government is already connected`,
- description: msg`A company connects to one Onshape at a time. Uninstall Onshape Government, then connect Onshape.`
- }
- },
+ onshape: onshapeErrors,
+ "onshape-v2": onshapeErrors,
// A Government customer's private OAuth app. Same codes as `onshape` — the two
// share one callback handler — but the fixes live in the customer's own
// Enterprise settings and in the Carbon integration settings, not in Carbon's
diff --git a/apps/erp/app/modules/settings/oauth-popup.server.test.ts b/apps/erp/app/modules/settings/oauth-popup.server.test.ts
new file mode 100644
index 0000000000..13d52cbcf8
--- /dev/null
+++ b/apps/erp/app/modules/settings/oauth-popup.server.test.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { OAUTH_POPUP_MESSAGE } from "./oauth-popup";
+import { oauthPopupResponse } from "./oauth-popup.server";
+
+describe("oauthPopupResponse", () => {
+ it("renders an html page carrying the result and the fallback url", async () => {
+ const response = oauthPopupResponse(
+ { integration: "onshape", ok: true },
+ "http://localhost:3000/x/settings/integrations"
+ );
+ const html = await response.text();
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toContain("text/html");
+ expect(response.headers.get("Cache-Control")).toBe("no-store");
+ expect(html).toContain(
+ JSON.stringify({
+ type: OAUTH_POPUP_MESSAGE,
+ integration: "onshape",
+ ok: true
+ })
+ );
+ expect(html).toContain('"http://localhost:3000/x/settings/integrations"');
+ expect(html).toContain(
+ "opener.postMessage(message, window.location.origin)"
+ );
+ expect(html).toContain("window.close()");
+ });
+
+ it("carries the error code on failure", async () => {
+ const response = oauthPopupResponse(
+ { integration: "onshape", ok: false, error: "denied" },
+ "http://localhost:3000/x/settings/integrations?integration=onshape&error=denied"
+ );
+ const html = await response.text();
+
+ expect(html).toContain('"ok":false');
+ expect(html).toContain('"error":"denied"');
+ expect(html).toContain("integration=onshape&error=denied");
+ });
+
+ it("cannot be broken out of with a closing script tag", async () => {
+ const response = oauthPopupResponse(
+ { integration: "onshape", ok: true },
+ "http://localhost:3000/</script><script>alert(1)</script>"
+ );
+ const html = await response.text();
+
+ expect(html).not.toContain("</script><script>alert(1)");
+ expect(html).toContain("\\u003c/script>");
+ });
+});
diff --git a/apps/erp/app/modules/settings/oauth-popup.server.ts b/apps/erp/app/modules/settings/oauth-popup.server.ts
new file mode 100644
index 0000000000..8c5176f01b
--- /dev/null
+++ b/apps/erp/app/modules/settings/oauth-popup.server.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { OAuthPopupOutcome, OAuthPopupResult } from "./oauth-popup";
+import { OAUTH_POPUP_MESSAGE } from "./oauth-popup";
+
+/**
+ * OAuth callback page: posts the outcome to the popup's opener and closes, or
+ * goes to `fallbackUrl` when there is no opener (popup blocked, callback opened
+ * directly). Only Carbon-authored values reach the page, never provider text.
+ */
+export function oauthPopupResponse(
+ outcome: OAuthPopupOutcome,
+ fallbackUrl: string
+) {
+ const message: OAuthPopupResult = { type: OAUTH_POPUP_MESSAGE, ...outcome };
+
+ const html = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="robots" content="noindex">
+<title>Carbon</title>
+</head>
+<body>
+<script>
+(function () {
+ var message = ${embed(message)};
+ var fallback = ${embed(fallbackUrl)};
+ var opener = window.opener;
+ var delivered = false;
+ try {
+ if (opener && !opener.closed) {
+ opener.postMessage(message, window.location.origin);
+ delivered = true;
+ }
+ } catch (_) {}
+ if (delivered) {
+ window.close();
+ }
+ // Still here: no opener, or the browser refused to close the window. Land
+ // where a plain redirect would have.
+ window.setTimeout(function () {
+ window.location.replace(fallback);
+ }, delivered ? 500 : 0);
+})();
+</script>
+<noscript><a href="${escapeAttribute(fallbackUrl)}">Continue</a></noscript>
+</body>
+</html>
+`;
+
+ return new Response(html, {
+ status: 200,
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Cache-Control": "no-store"
+ }
+ });
+}
+
+/** JSON that is safe inside a <script> element. */
+function embed(value: unknown) {
+ return JSON.stringify(value)
+ .replace(/</g, "\\u003c")
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+}
+
+function escapeAttribute(value: string) {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/"/g, "&quot;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+}
diff --git a/apps/erp/app/modules/settings/oauth-popup.ts b/apps/erp/app/modules/settings/oauth-popup.ts
new file mode 100644
index 0000000000..359ee65017
--- /dev/null
+++ b/apps/erp/app/modules/settings/oauth-popup.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The message an OAuth callback popup posts to the integrations page that
+// opened it. Client-safe: no server imports.
+
+export const OAUTH_POPUP_MESSAGE = "app_oauth_result" as const;
+
+/** What the callback decided; `error` is a code from `integration-errors`. */
+export type OAuthPopupOutcome = {
+ integration: string;
+} & ({ ok: true } | { ok: false; error: string });
+
+export type OAuthPopupResult = {
+ type: typeof OAUTH_POPUP_MESSAGE;
+} & OAuthPopupOutcome;
+
+export function isOAuthPopupResult(data: unknown): data is OAuthPopupResult {
+ if (typeof data !== "object" || data === null) return false;
+ const message = data as Record<string, unknown>;
+ return (
+ message.type === OAUTH_POPUP_MESSAGE &&
+ typeof message.integration === "string" &&
+ typeof message.ok === "boolean"
+ );
+}
diff --git a/apps/erp/app/modules/settings/onshape-draft-method.server.ts b/apps/erp/app/modules/settings/onshape-draft-method.server.ts
new file mode 100644
index 0000000000..9a360708d0
--- /dev/null
+++ b/apps/erp/app/modules/settings/onshape-draft-method.server.ts
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database, Json } from "@carbon/database";
+import type { DraftCandidate } from "@carbon/ee/onshape";
+import {
+ DRAFT_MARKER_ENTITY_TYPE,
+ loadReusableDrafts,
+ pairOwnedCopiedLines,
+ selectInBatches
+} from "@carbon/ee/onshape";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";
+import { getLogger } from "@carbon/logger";
+import { datetime } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { copyMakeMethod, upsertMakeMethodVersion } from "~/modules/items";
+import {
+ getLockVerdict,
+ type ReleaseControl
+} from "~/modules/items/items.server";
+import { getDatabaseClient } from "~/services/database.server";
+import { getCompanySettings } from "./settings.service";
+
+type Client = SupabaseClient<Database>;
+
+const logger = getLogger("erp", "onshape", "draft-method");
+
+type ItemRevisionStatus = Database["public"]["Enums"]["itemRevisionStatus"];
+
+/**
+ * Why the assembly push must not write a parent's BOM, per item id. A Draft a
+ * change notice holds is the notice's to change, whatever its stage. A
+ * released (Production) revision follows `plmReleaseControl` through
+ * `getLockVerdict`, as the BOM editor's `checkRevisionLock` does: `enforce`
+ * refuses, `warn` and `off` write. Two reads in all, not one per method.
+ */
+export async function loadMethodWriteRefusals(
+ client: Client,
+ companyId: string,
+ targets: Array<{
+ itemId: string;
+ method: { changeOrderId?: string | null };
+ revisionStatus: ItemRevisionStatus | null | undefined;
+ }>
+): Promise<Map<string, string>> {
+ const reasons = new Map<string, string>();
+ const changeOrderIds = [
+ ...new Set(
+ targets
+ .map((target) => target.method.changeOrderId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+ const anyProduction = targets.some(
+ (target) =>
+ !target.method.changeOrderId && target.revisionStatus === "Production"
+ );
+ const [notices, settings] = await Promise.all([
+ selectInBatches(changeOrderIds, (batch) =>
+ client
+ .from("changeOrder")
+ .select("id, changeOrderId")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ ),
+ anyProduction ? getCompanySettings(client, companyId) : null
+ ]);
+ // The notice's number is for the message only; the refusal stands without it.
+ const noticeNumber = new Map(
+ (notices.data ?? []).map((notice) => [notice.id, notice.changeOrderId])
+ );
+ const releaseControl = (settings?.data?.plmReleaseControl ??
+ "enforce") as ReleaseControl;
+ for (const target of targets) {
+ const changeOrderId = target.method.changeOrderId;
+ if (changeOrderId) {
+ const number = noticeNumber.get(changeOrderId);
+ reasons.set(
+ target.itemId,
+ `its make method is a Draft on ${number ? `change notice ${number}` : "a change notice"}. Change the BOM there.`
+ );
+ continue;
+ }
+ const verdict = getLockVerdict({
+ isLocked: target.revisionStatus === "Production",
+ releaseControl
+ });
+ if (!verdict.ok) reasons.set(target.itemId, verdict.message);
+ }
+ return reasons;
+}
+
+/**
+ * The Draft a push writes into when the item's method is Active: the one this
+ * integration made from that method (`pickReusableDraft`), else a new copy. The
+ * reusable marker is written last; a failure before it deletes the new Draft.
+ */
+export async function ensureDraftMakeMethod(
+ client: Client,
+ args: {
+ itemId: string;
+ activeMethodId: string;
+ companyId: string;
+ userId: string;
+ /** Preloaded with `loadReusableDrafts`; null when none, omitted to read it here. */
+ reusableDraft?: DraftCandidate | null;
+ }
+): Promise<
+ | { ok: true; id: string; created: boolean; version: number | null }
+ | { ok: false; error: string }
+> {
+ const { itemId, activeMethodId, companyId, userId } = args;
+ const serviceRole = getCarbonServiceRole();
+
+ let existing = args.reusableDraft;
+ if (existing === undefined) {
+ try {
+ const reusable = await loadReusableDrafts(
+ client,
+ serviceRole,
+ companyId,
+ new Map([[itemId, activeMethodId]])
+ );
+ existing = reusable.get(itemId) ?? null;
+ } catch (error) {
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : "could not read Drafts"
+ };
+ }
+ }
+ if (existing) {
+ return {
+ ok: true,
+ id: existing.id,
+ created: false,
+ version: existing.version
+ };
+ }
+
+ // max(version) + 1, not Active + 1: parallel Drafts collide on (itemId, version).
+ const highest = await client
+ .from("makeMethod")
+ .select("version")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .order("version", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (highest.error) {
+ return { ok: false, error: highest.error.message };
+ }
+ const version = (highest.data?.version ?? 0) + 1;
+
+ const draft = await upsertMakeMethodVersion(client, {
+ copyFromId: activeMethodId,
+ // No `activeVersionId`: it sets a version Active, and the push leaves live methods alone.
+ version,
+ companyId,
+ createdBy: userId
+ });
+ if (draft.error || !draft.data?.id) {
+ return {
+ ok: false,
+ error: draft.error?.message ?? "could not create a draft version"
+ };
+ }
+ const draftId = draft.data.id;
+
+ // `upsertMakeMethodVersion` copies only the method row; the BOM and routing come here.
+ const copied = await copyMakeMethod(client, getDatabaseClient(), {
+ sourceId: activeMethodId,
+ targetId: draftId,
+ companyId,
+ userId,
+ billOfMaterial: true,
+ billOfProcess: true,
+ parameters: true,
+ tools: true,
+ steps: true,
+ workInstructions: true
+ });
+ const failure = copied.error
+ ? `its method could not be copied (${copied.error.message})`
+ : await carryLineOwnership(client, serviceRole, {
+ sourceMethodId: activeMethodId,
+ targetMethodId: draftId,
+ companyId,
+ userId
+ });
+ const marked = failure
+ ? null
+ : await client.from("externalIntegrationMapping").insert({
+ entityType: DRAFT_MARKER_ENTITY_TYPE,
+ entityId: draftId,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ // Not the source id: two Drafts of one method would collide on the unique index.
+ externalId: draftId,
+ metadata: { sourceMethodId: activeMethodId, itemId } as Json,
+ lastSyncedAt: datetime.timestamp(),
+ companyId,
+ createdBy: userId
+ });
+ const problem =
+ failure ??
+ (marked?.error
+ ? `it could not be marked as Onshape's (${marked.error.message})`
+ : null);
+ if (!problem) {
+ return { ok: true, id: draftId, created: true, version };
+ }
+
+ // A half-built Draft, released, would ship without what failed to copy. Service
+ // role: line mappings have no user DELETE policy. The lines cascade.
+ const discarded = await discardDraft(serviceRole, {
+ draftId,
+ companyId
+ });
+ return {
+ ok: false,
+ error: discarded
+ ? `a draft version was created but ${problem}, so it was removed; push again`
+ : `a draft version was created but ${problem}, and it could not be removed — delete version ${version} before pushing again`
+ };
+}
+
+async function discardDraft(
+ serviceRole: Client,
+ args: { draftId: string; companyId: string }
+): Promise<boolean> {
+ const { draftId, companyId } = args;
+ const mappings = await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .eq("metadata->>makeMethodId", draftId);
+ const removed = await serviceRole
+ .from("makeMethod")
+ .delete()
+ .eq("id", draftId)
+ .eq("companyId", companyId);
+ const error = mappings.error ?? removed.error;
+ if (error) {
+ logger.error("Failed to discard a half-built Onshape Draft", {
+ companyId,
+ draftId,
+ error
+ });
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Copy this integration's line mappings onto the copied lines: ownership is
+ * keyed on line id, and unmapped copies would read as manual and be duplicated.
+ */
+async function carryLineOwnership(
+ client: Client,
+ serviceRole: Client,
+ args: {
+ sourceMethodId: string;
+ targetMethodId: string;
+ companyId: string;
+ userId: string;
+ }
+): Promise<string | null> {
+ const { sourceMethodId, targetMethodId, companyId, userId } = args;
+
+ const mappings = await serviceRole
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId, metadata, lastSyncedAt")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .eq("metadata->>makeMethodId", sourceMethodId);
+ if (mappings.error) return mappings.error.message;
+ if ((mappings.data ?? []).length === 0) return null;
+
+ const [sourceLines, targetLines] = await Promise.all([
+ client
+ .from("methodMaterial")
+ .select("id, itemId, order, quantity")
+ .eq("makeMethodId", sourceMethodId)
+ .eq("companyId", companyId),
+ client
+ .from("methodMaterial")
+ .select("id, itemId, order")
+ .eq("makeMethodId", targetMethodId)
+ .eq("companyId", companyId)
+ ]);
+ if (sourceLines.error) return sourceLines.error.message;
+ if (targetLines.error) return targetLines.error.message;
+
+ const owned = new Set((mappings.data ?? []).map((row) => row.entityId));
+ const paired = pairOwnedCopiedLines(
+ sourceLines.data ?? [],
+ targetLines.data ?? [],
+ owned
+ );
+
+ const inserts = [];
+ for (const mapping of mappings.data ?? []) {
+ const targetLineId = paired.get(mapping.entityId);
+ // Unpaired: left unmapped, so it reads as manual and is kept, not duplicated.
+ if (!targetLineId) continue;
+ const metadata = {
+ ...((mapping.metadata as Record<string, unknown> | null) ?? {}),
+ makeMethodId: targetMethodId
+ };
+ inserts.push({
+ entityType: "methodMaterial",
+ entityId: targetLineId,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ externalId: mapping.externalId,
+ metadata: metadata as Json,
+ lastSyncedAt: mapping.lastSyncedAt,
+ companyId,
+ createdBy: userId
+ });
+ }
+ if (inserts.length === 0) return null;
+
+ const written = await client
+ .from("externalIntegrationMapping")
+ .insert(inserts);
+ if (written.error) {
+ return `${inserts.length} of its lines could not be linked to Onshape (${written.error.message})`;
+ }
+ return null;
+}
diff --git a/apps/erp/app/modules/settings/onshape-oauth.server.ts b/apps/erp/app/modules/settings/onshape-oauth.server.ts
index 5c39f95c0a..70f914cb75 100644
--- a/apps/erp/app/modules/settings/onshape-oauth.server.ts
+++ b/apps/erp/app/modules/settings/onshape-oauth.server.ts
@@ -12,17 +12,23 @@ import {
import {
exchangeOnshapeAuthorizationCode,
getConflictingOnshapeIntegration,
+ isOnshapeIntegrationId,
ONSHAPE_OAUTH_SCOPES,
- type OnshapeIntegrationId
+ type OnshapeOAuthIntegrationId
} from "@carbon/ee/onshape";
-import { loadOnshapeOAuthConfig } from "@carbon/ee/onshape.server";
+import {
+ loadOnshapeOAuthConfig,
+ patchOnshapeOAuthGrant
+} from "@carbon/ee/onshape.server";
import { getLogger } from "@carbon/logger";
-import { redirectExternal } from "@carbon/utils";
+import { datetime } from "@carbon/utils";
+import { parseAbsolute } from "@internationalized/date";
import { oAuthCallbackSchema } from "~/modules/shared";
import { path } from "~/utils/path";
import type { IntegrationErrorCode } from "./integration-errors";
import { integrationErrorSearch } from "./integration-errors";
-import { upsertCompanyIntegration } from "./settings.server";
+import { oauthPopupResponse } from "./oauth-popup.server";
+import { clearCompanyIntegrationCache } from "./settings.server";
const logger = getLogger("erp", "onshape", "oauth");
@@ -38,14 +44,10 @@ function integrationsUrl(request: Request) {
}
/**
- * The OAuth callback for both Onshape integrations — the public app
- * (`/api/integrations/onshape/oauth`) and a Government customer's private app
- * (`/api/integrations/onshape-government/oauth`). Only where the client comes
- * from differs, and `loadOnshapeOAuthConfig` owns that.
- *
- * Onshape reaches this by redirecting the user's browser, so a failure has to
- * render as something they can act on: send them back to the integrations
- * page, which turns the code into a toast. Only a code crosses the URL;
+ * The OAuth callback for every Onshape grant (`onshape`, `onshape-government`,
+ * `onshape-v2`); `loadOnshapeOAuthConfig` picks the client. Onshape redirects
+ * the browser here, in the install popup or the whole tab, so the outcome
+ * renders through `oauthPopupResponse`. Only an error code crosses;
* `integrationErrors` owns the copy.
*/
export async function completeOnshapeAuthorization({
@@ -55,7 +57,7 @@ export async function completeOnshapeAuthorization({
companyId
}: {
request: Request;
- integrationId: OnshapeIntegrationId;
+ integrationId: OnshapeOAuthIntegrationId;
userId: string;
companyId: string;
}) {
@@ -73,13 +75,16 @@ export async function completeOnshapeAuthorization({
{ integrationId, userId, companyId }
);
- // Both integrations declare the same codes, each with its own copy.
+ // Every Onshape integration declares the same codes, each with its copy.
const connectionFailed = (
- reason: IntegrationErrorCode<OnshapeIntegrationId>
+ reason: IntegrationErrorCode<OnshapeOAuthIntegrationId>
) =>
- redirectExternal(
- `${integrationsUrl(request)}${integrationErrorSearch<OnshapeIntegrationId>(integrationId, reason)}`,
- { headers: { "Set-Cookie": consumedState.cookie } }
+ withCookie(
+ oauthPopupResponse(
+ { integration: integrationId, ok: false, error: reason },
+ `${integrationsUrl(request)}${integrationErrorSearch<OnshapeOAuthIntegrationId>(integrationId, reason)}`
+ ),
+ consumedState.cookie
);
if (!consumedState.valid) {
@@ -115,14 +120,16 @@ export async function completeOnshapeAuthorization({
const serviceRole = getCarbonServiceRole();
- // A company holds one Onshape connection at a time; two would leave every
- // background job guessing which tenant to talk to.
+ // A company holds one Onshape sync connection at a time; two would leave
+ // every background job guessing which tenant to talk to. The panel's grant
+ // is outside that rule.
if (
- await getConflictingOnshapeIntegration(
+ isOnshapeIntegrationId(integrationId) &&
+ (await getConflictingOnshapeIntegration(
serviceRole,
companyId,
integrationId
- )
+ ))
) {
return connectionFailed("connection-conflict");
}
@@ -149,57 +156,39 @@ export async function completeOnshapeAuthorization({
return connectionFailed("token-exchange");
}
- const existing = await serviceRole
- .from("companyIntegration")
- .select("metadata")
- .eq("id", integrationId)
- .eq("companyId", companyId)
- .maybeSingle();
- const existingMetadata = (existing.data?.metadata ?? {}) as Record<
- string,
- unknown
- >;
-
// The scope actually granted by this authorization. Onshape returns it on
// the token response; fall back to what we requested. A token minted
// without write can't export assets or manage the release webhook, and a
- // refresh can't widen it — so asset sync is switched off rather than left
- // on-but-broken.
+ // refresh can't widen it, so the grant patch turns asset sync off. The
+ // patch writes only the grant's keys, so settings survive a reconnect.
const scope = tokenData.scope ?? ONSHAPE_OAUTH_SCOPES.join(" ");
- const metadata: Record<string, unknown> = {
- ...existingMetadata,
- credentials: {
- type: "oauth2",
- accessToken: tokenData.access_token,
- refreshToken: tokenData.refresh_token,
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString()
- },
- scope,
- baseUrl: oauth.baseUrl
- };
- // Settings survive a reconnect (a Government app's client and tenant, the
- // asset-sync toggle), but the Onshape company is re-resolved from the new
- // token: it may belong to a different account or tenant.
- delete metadata.onshapeCompanyId;
- const canWrite = onshapeConnectionHasWriteScope(metadata);
- if (!canWrite) metadata.assetSyncEnabled = false;
-
- const saved = await upsertCompanyIntegration(serviceRole, {
- id: integrationId,
- active: true,
- // @ts-expect-error TS2322 - metadata is a JSON object
- metadata,
- updatedBy: userId,
- companyId
- });
-
- if (saved.error || !saved.data?.metadata) {
+ let saved: Awaited<ReturnType<typeof patchOnshapeOAuthGrant>>;
+ try {
+ saved = await patchOnshapeOAuthGrant(
+ serviceRole,
+ companyId,
+ integrationId,
+ {
+ accessToken: tokenData.access_token,
+ refreshToken: tokenData.refresh_token,
+ expiresAt: parseAbsolute(datetime.timestamp(), "UTC")
+ .add({ seconds: tokenData.expires_in ?? 3600 })
+ .toAbsoluteString(),
+ scope,
+ baseUrl: oauth.baseUrl,
+ canWrite: onshapeConnectionHasWriteScope({ scope }),
+ updatedBy: userId
+ }
+ );
+ } catch (error) {
logger.error("Failed to save Onshape integration", {
integrationId,
- error: saved.error
+ error
});
return connectionFailed("save-failed");
}
+ await clearCompanyIntegrationCache(companyId);
+ const metadata = (saved.metadata ?? {}) as Record<string, unknown>;
// A Government connection is configured BEFORE it is authorized, so asset
// sync may already be on: subscribe to releases now that there is a token.
@@ -214,11 +203,20 @@ export async function completeOnshapeAuthorization({
}
}
- return redirectExternal(integrationsUrl(request), {
- headers: { "Set-Cookie": consumedState.cookie }
- });
+ return withCookie(
+ oauthPopupResponse(
+ { integration: integrationId, ok: true },
+ integrationsUrl(request)
+ ),
+ consumedState.cookie
+ );
} catch (error) {
logger.error("Onshape OAuth Error", { integrationId, error });
return connectionFailed("unexpected");
}
}
+
+function withCookie(response: Response, cookie: string) {
+ response.headers.append("Set-Cookie", cookie);
+ return response;
+}
diff --git a/apps/erp/app/modules/settings/onshape-push.server.ts b/apps/erp/app/modules/settings/onshape-push.server.ts
new file mode 100644
index 0000000000..03f6b86433
--- /dev/null
+++ b/apps/erp/app/modules/settings/onshape-push.server.ts
@@ -0,0 +1,618 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database, Json } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import type {
+ ItemEdit,
+ ItemFieldSnapshot,
+ OwnedFieldChange,
+ StandardFieldWriter
+} from "@carbon/ee";
+import { mergeExistingItemEdits, standardField } from "@carbon/ee";
+import { selectInBatches } from "@carbon/ee/onshape";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";
+import { getLogger } from "@carbon/logger";
+import { datetime } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ canEditChangeNoticeEngineering,
+ cascadeItemTrackingType,
+ updateItemMethodAndSourcing
+} from "~/modules/items";
+
+const logger = getLogger("erp", "onshape", "push");
+
+type MethodMaterialInsert =
+ Database["public"]["Tables"]["methodMaterial"]["Insert"];
+
+export type OwnedMethodLine = {
+ row: Omit<MethodMaterialInsert, "companyId" | "createdBy">;
+ /** Ownership row metadata; `makeMethodId` names the line's method. */
+ metadata: Record<string, unknown>;
+};
+
+/**
+ * Replace an item's Onshape link in one transaction: delete any row for this
+ * item or this externalId, then insert. Both unique indexes need the deletes first.
+ */
+export async function swapItemMapping(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ itemId: string;
+ externalId: string;
+ metadata: Record<string, unknown>;
+ }
+): Promise<{ id: string; error: null } | { id: null; error: string }> {
+ const { companyId, userId, itemId, externalId } = args;
+ const now = datetime.timestamp();
+ try {
+ const inserted = await db.transaction().execute(async (trx) => {
+ await trx
+ .deleteFrom("externalIntegrationMapping")
+ .where("companyId", "=", companyId)
+ .where("integration", "=", ONSHAPE_V2_INTEGRATION_ID)
+ .where("entityType", "=", "item")
+ .where((eb) =>
+ eb.or([
+ eb("entityId", "=", itemId),
+ eb("externalId", "=", externalId)
+ ])
+ )
+ .execute();
+ return trx
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: "item",
+ entityId: itemId,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ externalId,
+ metadata: args.metadata as Json,
+ lastSyncedAt: now,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ });
+ return { id: inserted.id, error: null };
+ } catch (error) {
+ logger.error("Failed to link an item to Onshape", {
+ companyId,
+ itemId,
+ error
+ });
+ return {
+ id: null,
+ error: error instanceof Error ? error.message : "link failed"
+ };
+ }
+}
+
+/**
+ * Insert BOM lines and their ownership rows in one transaction. A line without
+ * its ownership row reads as manual, so the next push keeps it and adds a copy.
+ */
+export async function insertOwnedMethodLines(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ lines: OwnedMethodLine[];
+ }
+): Promise<
+ { mappingIds: string[]; error: null } | { mappingIds: null; error: string }
+> {
+ const { companyId, userId, lines } = args;
+ if (lines.length === 0) return { mappingIds: [], error: null };
+ const now = datetime.timestamp();
+ try {
+ const mappingIds = await db.transaction().execute(async (trx) => {
+ const inserted = await trx
+ .insertInto("methodMaterial")
+ .values(
+ lines.map((line) => ({
+ ...line.row,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ }))
+ )
+ .returning("id")
+ .execute();
+ // Mappings pair with lines by index (RETURNING follows VALUES order).
+ if (inserted.length !== lines.length) {
+ throw new Error(
+ `wrote ${inserted.length} of ${lines.length} lines; nothing was kept`
+ );
+ }
+ const mappings = await trx
+ .insertInto("externalIntegrationMapping")
+ .values(
+ lines.map((line, index) => ({
+ entityType: "methodMaterial",
+ entityId: inserted[index]!.id,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ metadata: line.metadata as Json,
+ lastSyncedAt: now,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ }))
+ )
+ .returning("id")
+ .execute();
+ return mappings.map((mapping) => mapping.id);
+ });
+ return { mappingIds, error: null };
+ } catch (error) {
+ logger.error("Failed to write Onshape BOM lines", {
+ companyId,
+ count: lines.length,
+ error
+ });
+ return {
+ mappingIds: null,
+ error: error instanceof Error ? error.message : "line insert failed"
+ };
+ }
+}
+
+/**
+ * Take over a manual line in one transaction: set the Onshape-owned columns and
+ * write its ownership row. Operation, scrap, tags and kit are kept.
+ */
+export async function claimManualMethodLine(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ lineId: string;
+ update: {
+ itemId: string;
+ quantity: number;
+ order: number;
+ materialMakeMethodId: string | null;
+ };
+ metadata: Record<string, unknown>;
+ }
+): Promise<
+ { mappingId: string; error: null } | { mappingId: null; error: string }
+> {
+ const { companyId, userId, lineId } = args;
+ const now = datetime.timestamp();
+ try {
+ const mappingId = await db.transaction().execute(async (trx) => {
+ const updated = await trx
+ .updateTable("methodMaterial")
+ .set({ ...args.update, updatedBy: userId, updatedAt: now })
+ .where("id", "=", lineId)
+ .where("companyId", "=", companyId)
+ .returning("id")
+ .executeTakeFirst();
+ if (!updated) throw new Error("the line no longer exists");
+ const mapping = await trx
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: "methodMaterial",
+ entityId: lineId,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ metadata: args.metadata as Json,
+ lastSyncedAt: now,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ return mapping.id;
+ });
+ return { mappingId, error: null };
+ } catch (error) {
+ logger.error("Failed to take over a BOM line for Onshape", {
+ companyId,
+ lineId,
+ error
+ });
+ return {
+ mappingId: null,
+ error: error instanceof Error ? error.message : "line takeover failed"
+ };
+ }
+}
+
+export type OpenReleaseNotice = {
+ id: string;
+ changeNoticeId: string;
+ affectedCount: number;
+};
+
+/**
+ * The notice an earlier push of this release made, while it still takes items:
+ * a release spanning two documents is pushed once per document into one notice.
+ * Fails closed: a read that fails is an error, never "no open notice", which
+ * would open a second notice for the release.
+ */
+export async function findOpenReleaseNotice(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ releaseId: string
+): Promise<
+ | { data: OpenReleaseNotice | null; error: null }
+ | { data: null; error: string }
+> {
+ const failed = (what: string, error: unknown) => {
+ logger.error("Could not read a release's earlier push", {
+ companyId,
+ releaseId,
+ read: what,
+ error
+ });
+ return {
+ data: null,
+ error: `Carbon couldn't read this release's earlier ${what}`
+ };
+ };
+
+ // Matched on the release id the link's metadata carries, not a LIKE on the
+ // key: a synthetic release id holds a part number, which may contain % or _.
+ const links = await client
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .like("externalId", "release:%")
+ .eq("metadata->>releaseId", releaseId);
+ if (links.error) return failed("links", links.error);
+ if (!links.data?.length) return { data: null, error: null };
+
+ const items = await selectInBatches(
+ links.data.map((link) => link.entityId),
+ (batch) =>
+ client
+ .from("item")
+ .select("changeOrderId")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ .not("changeOrderId", "is", null)
+ );
+ if (items.error) return failed("items", items.error);
+ const noticeIds = [
+ ...new Set(
+ items.data
+ .map((item) => item.changeOrderId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+ if (noticeIds.length === 0) return { data: null, error: null };
+
+ const notices = await selectInBatches(noticeIds, (batch) =>
+ client
+ .from("changeOrder")
+ .select(
+ "id, changeOrderId, status, createdAt, changeOrderAffectedItem(id)"
+ )
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (notices.error) return failed("change notices", notices.error);
+ // Batches arrive in batch order: the oldest open notice wins.
+ const editable = notices.data
+ .filter((notice) => canEditChangeNoticeEngineering(notice.status))
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
+ // A pending approval freezes the notice's engineering content; one can be
+ // pending only at Engineering Complete. approvalRequest is service-role only.
+ const awaitingIds = editable
+ .filter((notice) => notice.status === "Engineering Complete")
+ .map((notice) => notice.id);
+ const awaiting = new Set<string>();
+ if (awaitingIds.length > 0) {
+ const pending = await selectInBatches(awaitingIds, (batch) =>
+ getCarbonServiceRole()
+ .from("approvalRequest")
+ .select("documentId")
+ .eq("companyId", companyId)
+ .eq("documentType", "changeOrder")
+ .eq("status", "Pending")
+ .in("documentId", batch)
+ );
+ if (pending.error) return failed("change notice approvals", pending.error);
+ for (const row of pending.data) awaiting.add(row.documentId);
+ }
+ const open = editable.find((notice) => !awaiting.has(notice.id));
+ return {
+ data: open
+ ? {
+ id: open.id,
+ changeNoticeId: open.changeOrderId,
+ affectedCount: open.changeOrderAffectedItem?.length ?? 0
+ }
+ : null,
+ error: null
+ };
+}
+
+/**
+ * Stage a created item under a change notice as `createChangeNoticeDraftMethod`
+ * does: item inactive, item and Draft method stamped, one affected-item row.
+ */
+export async function stageChangeNoticeItem(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ /** `changeOrder.id`, not its readable id. */
+ changeOrderId: string;
+ companyId: string;
+ userId: string;
+ itemId: string;
+ /** The revision this one replaces; null for a New Part. */
+ baseItemId: string | null;
+ sortOrder: number;
+ }
+): Promise<{ error: string | null }> {
+ const { changeOrderId, companyId, userId, itemId, baseItemId } = args;
+ const now = datetime.timestamp();
+ try {
+ await db.transaction().execute(async (trx) => {
+ const draft = await trx
+ .selectFrom("makeMethod")
+ .select("id")
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .where("status", "=", "Draft")
+ .orderBy("version", "desc")
+ .executeTakeFirst();
+ // Release refuses an affected item with no Draft to activate.
+ if (!draft) throw new Error("the item has no Draft make method");
+ const base = baseItemId
+ ? await trx
+ .selectFrom("activeMakeMethods")
+ .select("id")
+ .where("itemId", "=", baseItemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : undefined;
+
+ await trx
+ .updateTable("item")
+ .set({
+ active: false,
+ changeOrderId,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .execute();
+ await trx
+ .updateTable("makeMethod")
+ .set({ changeOrderId, updatedBy: userId, updatedAt: now })
+ .where("id", "=", draft.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ await trx
+ .insertInto("changeOrderAffectedItem")
+ .values({
+ changeOrderId,
+ itemId: baseItemId ?? itemId,
+ changeType: baseItemId ? "Revision" : "New Part",
+ sortOrder: args.sortOrder,
+ draftMakeMethodId: draft.id,
+ baseMakeMethodId: base?.id ?? null,
+ newItemId: itemId,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+ });
+ return { error: null };
+ } catch (error) {
+ logger.error("Failed to stage an item under a change notice", {
+ companyId,
+ changeOrderId,
+ itemId,
+ error
+ });
+ return {
+ error: error instanceof Error ? error.message : "staging failed"
+ };
+ }
+}
+
+type ItemEnums = Database["public"]["Enums"];
+
+/** Item field values a push writes; an absent key is not written. */
+export type ItemFieldWrite = {
+ replenishmentSystem?: ItemEnums["itemReplenishmentSystem"];
+ defaultMethodType?: ItemEnums["methodType"];
+ sourcingType?: ItemEnums["sourcingType"];
+ itemTrackingType?: ItemEnums["itemTrackingType"];
+ unitOfMeasureCode?: string;
+ mpn?: string | null;
+};
+
+type WriterContext = {
+ client: SupabaseClient<Database>;
+ db: Kysely<KyselyDatabase>;
+ itemId: string;
+ companyId: string;
+ userId: string;
+};
+
+export async function updateItemColumns(
+ client: SupabaseClient<Database>,
+ args: {
+ itemId: string;
+ companyId: string;
+ userId: string;
+ values: Pick<ItemFieldWrite, "mpn" | "unitOfMeasureCode">;
+ }
+) {
+ return client
+ .from("item")
+ .update({
+ ...(args.values.mpn !== undefined ? { mpn: args.values.mpn } : {}),
+ ...(args.values.unitOfMeasureCode !== undefined
+ ? { unitOfMeasureCode: args.values.unitOfMeasureCode }
+ : {}),
+ updatedBy: args.userId,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", args.itemId)
+ .eq("companyId", args.companyId);
+}
+
+/**
+ * One writer per `StandardFieldWriter` key. Each writes as the item page does,
+ * so the cascades onto Draft method lines and open documents follow.
+ */
+const STANDARD_FIELD_WRITERS: Record<
+ StandardFieldWriter,
+ (ctx: WriterContext, write: ItemFieldWrite) => Promise<string | null>
+> = {
+ itemMethod: async (ctx, write) => {
+ const { replenishmentSystem, defaultMethodType, sourcingType } = write;
+ await updateItemMethodAndSourcing(ctx.db, {
+ itemIds: [ctx.itemId],
+ companyId: ctx.companyId,
+ userId: ctx.userId,
+ itemUpdate: { replenishmentSystem, defaultMethodType, sourcingType },
+ cascade: {
+ ...(defaultMethodType !== undefined
+ ? { methodType: defaultMethodType }
+ : {}),
+ ...(sourcingType !== undefined ? { sourcingType } : {})
+ }
+ });
+ return null;
+ },
+ itemTracking: async (ctx, write) => {
+ if (write.itemTrackingType === undefined) return null;
+ const updated = await ctx.client
+ .from("item")
+ .update({
+ itemTrackingType: write.itemTrackingType,
+ updatedBy: ctx.userId,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", ctx.itemId)
+ .eq("companyId", ctx.companyId);
+ if (updated.error) return updated.error.message;
+ await cascadeItemTrackingType(ctx.db, {
+ itemIds: [ctx.itemId],
+ companyId: ctx.companyId,
+ newType: write.itemTrackingType,
+ userId: ctx.userId
+ });
+ return null;
+ },
+ itemColumn: async (ctx, write) => {
+ const updated = await updateItemColumns(ctx.client, {
+ itemId: ctx.itemId,
+ companyId: ctx.companyId,
+ userId: ctx.userId,
+ values: write
+ });
+ return updated.error ? updated.error.message : null;
+ }
+};
+
+const WRITER_ORDER: StandardFieldWriter[] = [
+ "itemMethod",
+ "itemTracking",
+ "itemColumn"
+];
+
+/** Values must be final: this applies no interlock. Returns an error message, or null. */
+export async function applyItemFieldWrites(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ itemId: string;
+ companyId: string;
+ userId: string;
+ changed: ItemFieldWrite;
+ }
+): Promise<string | null> {
+ const { itemId, companyId, userId } = args;
+ const ctx: WriterContext = { client, db, itemId, companyId, userId };
+ try {
+ for (const writer of WRITER_ORDER) {
+ const write: ItemFieldWrite = {};
+ for (const [field, value] of Object.entries(args.changed)) {
+ if (value === undefined) continue;
+ if (standardField(field)?.writer !== writer) continue;
+ (write as Record<string, unknown>)[field] = value;
+ }
+ if (Object.keys(write).length === 0) continue;
+ const error = await STANDARD_FIELD_WRITERS[writer](ctx, write);
+ if (error) return error;
+ }
+ return null;
+ } catch (error) {
+ logger.error("Failed to write item fields from Onshape", {
+ companyId,
+ itemId,
+ error
+ });
+ return error instanceof Error ? error.message : "Failed to update the item";
+ }
+}
+
+/**
+ * Write to an item the push did not create: the "everyPush" descriptions, then
+ * the plan's target with the reviewer's edits on top. Returns the fields after
+ * the write, which a BOM line written later copies its method and unit from.
+ */
+export async function applyExistingItemFields(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ itemId: string;
+ companyId: string;
+ userId: string;
+ current: ItemFieldSnapshot | null | undefined;
+ target?: ItemFieldSnapshot;
+ edit?: ItemEdit;
+ descriptions?: OwnedFieldChange[];
+ }
+): Promise<{ values: ItemFieldSnapshot | null; error: string | null }> {
+ const { itemId, companyId, userId } = args;
+ const merged = args.current
+ ? mergeExistingItemEdits(args.current, args.edit, args.target)
+ : null;
+ if (merged && !merged.ok) {
+ return { values: null, error: merged.errors.join("; ") };
+ }
+
+ const text: { name?: string; description?: string } = {};
+ for (const change of args.descriptions ?? []) {
+ if (change.to !== null) text[change.field] = change.to;
+ }
+ if (Object.keys(text).length > 0) {
+ const updated = await client
+ .from("item")
+ .update({ ...text, updatedBy: userId, updatedAt: datetime.timestamp() })
+ .eq("id", itemId)
+ .eq("companyId", companyId);
+ if (updated.error) {
+ return { values: null, error: updated.error.message };
+ }
+ }
+
+ if (merged?.ok && Object.keys(merged.changed).length > 0) {
+ const error = await applyItemFieldWrites(client, db, {
+ itemId,
+ companyId,
+ userId,
+ changed: merged.changed
+ });
+ if (error) return { values: null, error };
+ }
+ return { values: merged?.ok ? merged.values : null, error: null };
+}
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index 4716b4a4c9..26c42daa38 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -15,6 +15,10 @@ import {
} from "@carbon/ee";
import { isAccountingSyncEnabled } from "@carbon/ee/accounting";
import { getIntegrationServerHooks } from "@carbon/ee/hooks.server";
+import {
+ isOnshapeOAuthIntegrationId,
+ patchOnshapeSettings
+} from "@carbon/ee/onshape.server";
import { patchRampSettings } from "@carbon/ee/ramp.server";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
@@ -375,6 +379,32 @@ export async function upsertCompanyIntegration(
}
}
+ // The Onshape rows are shared with the token refresh, the OAuth callback and
+ // the panel's property map, so a settings save patches only its own keys.
+ if (isOnshapeOAuthIntegrationId(update.id)) {
+ try {
+ const data = await patchOnshapeSettings(
+ getCarbonServiceRole(),
+ update.companyId,
+ update.id,
+ {
+ metadata: update.metadata as Record<string, unknown>,
+ active: update.active,
+ updatedBy: update.updatedBy
+ }
+ );
+ await clearCompanyIntegrationCache(update.companyId);
+ return { data, error: null };
+ } catch (error) {
+ logger.error("Failed to patch Onshape settings", {
+ error,
+ companyId: update.companyId,
+ integrationId: update.id
+ });
+ return { data: null, error };
+ }
+ }
+
// Split secret material out of the metadata: only the non-secret config is
// written to the column; the secrets go to Supabase Vault. The row is upserted
// FIRST (so it exists), then the vault RPC stamps `secretRef` onto it.
@@ -654,6 +684,21 @@ export async function updateIntegrationMetadata(
}
}
+ if (isOnshapeOAuthIntegrationId(integrationId)) {
+ try {
+ const data = await patchOnshapeSettings(
+ getCarbonServiceRole(),
+ companyId,
+ integrationId,
+ { metadata: metadata as Record<string, unknown>, updatedBy }
+ );
+ await clearCompanyIntegrationCache(companyId);
+ return { data, error: null };
+ } catch (error) {
+ return { data: null, error };
+ }
+ }
+
// Split secret material out to Supabase Vault; only the non-secret config is
// written to the column. The row already exists (this is an update), so vault
// FIRST (fail-closed: if the vault write fails, the plaintext is left intact
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
index e73a1a6501..962911c796 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
@@ -4,6 +4,8 @@
import type { Integration } from "@carbon/ee";
import { isIntegrationWhitelisted } from "@carbon/ee/plan";
+import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -16,16 +18,21 @@ import {
Tooltip,
TooltipContent,
TooltipTrigger,
+ toast,
useRouteData
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { LuLock } from "react-icons/lu";
import { Link, useFetcher, useNavigate } from "react-router";
import { usePlanGate } from "~/hooks/usePlanGate";
+import { getIntegrationError } from "~/modules/settings/integration-errors";
+import { isOAuthPopupResult } from "~/modules/settings/oauth-popup";
import { path } from "~/utils/path";
import { InstallModeDialog } from "./InstallModeDialog";
+const logger = getLogger("erp", "settings", "integrations");
+
/** Mirrors `IntegrationHealthStatus` in settings.server (not importable here). */
type IntegrationHealthStatus =
| "healthy"
@@ -57,6 +64,8 @@ export function IntegrationCard({
}) {
const fetcher = useFetcher<{}>();
const navigate = useNavigate();
+ const revalidator = useRevalidator();
+ const { i18n } = useLingui();
// The declared mode this install is in, if any. Undefined for every
// integration without modes, which then keeps its own description.
@@ -125,6 +134,32 @@ export function IntegrationCard({
const conflictsWith =
roleIncumbent && roleIncumbent !== integration.id ? roleIncumbent : null;
+ // An OAuth callback that ran inside the popup `onClientInstall` opened posts
+ // its outcome here and closes the popup (see oauth-popup.server.ts).
+ useEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ if (event.origin !== window.location.origin) return;
+ if (!isOAuthPopupResult(event.data)) return;
+ if (event.data.integration !== integration.id) return;
+
+ if (event.data.ok) {
+ revalidator.revalidate();
+ return;
+ }
+
+ const failure = getIntegrationError(integration.id, event.data.error);
+ if (failure) {
+ toast.error(i18n._(failure.title), {
+ id: `${integration.id}:${event.data.error}`,
+ description: i18n._(failure.description)
+ });
+ }
+ };
+
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, [integration.id, revalidator, i18n]);
+
const handleInstall = async () => {
if ("oauth" in integration && integration.oauth) {
// An integration declaring install MODES needs that question answered
@@ -140,7 +175,15 @@ export function IntegrationCard({
} else if (integration.settings.some((setting) => setting.required)) {
navigate(path.to.integration(integration.id));
} else if (integration.onClientInstall) {
- await integration.onClientInstall?.();
+ try {
+ await integration.onClientInstall();
+ } catch (error) {
+ logger.error("Client install failed", {
+ integration: integration.id,
+ error
+ });
+ toast.error(`Couldn't start the ${integration.name} connection`);
+ }
} else {
const formData = new FormData();
fetcher.submit(formData, {
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index b2d8c2cf8f..59c659325d 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -59,7 +59,9 @@ import {
Scripts,
ScrollRestoration,
UNSAFE_FrameworkContext,
- useLoaderData
+ useLoaderData,
+ useLocation,
+ useMatches
} from "react-router";
import SonnerStyle from "sonner/dist/styles.css?url";
import { preloadCatalog, useCatalog } from "~/services/lingui";
@@ -67,6 +69,7 @@ import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
import NProgress from "~/styles/nprogress.css?url";
import Tailwind from "~/styles/tailwind.css?url";
+import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import "@carbon/lib/shims";
import { MotionConfig } from "motion/react";
@@ -129,6 +132,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
MES_URL,
NODE_ENV,
ONSHAPE_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_ID,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
QUICKBOOKS_CLIENT_ID,
@@ -162,6 +166,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
MES_URL,
NODE_ENV,
ONSHAPE_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_ID,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
QUICKBOOKS_CLIENT_ID,
@@ -325,7 +330,12 @@ export default function App() {
const prefs = loaderData?.preferences;
const appLanguage = resolveLanguage(prefs.locale);
const catalog = useCatalog(appLanguage);
- const mode = useMode();
+ const userMode = useMode();
+ const { search } = useLocation();
+ const hostMode = useMatches()
+ .map((match) => (match.handle as Handle | undefined)?.hostMode)
+ .find((value) => value !== undefined);
+ const mode = hostMode ? hostMode(new URLSearchParams(search)) : userMode;
// One client for both consumers: the imperative `window.clientCache`
// read-through convention (clientLoader/cachedApiQuery) and hook-based
diff --git a/apps/erp/app/routes/api+/integrations.onshape-v2.install.ts b/apps/erp/app/routes/api+/integrations.onshape-v2.install.ts
new file mode 100644
index 0000000000..ebc5360209
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape-v2.install.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape";
+import { beginOnshapeAuthorization } from "@carbon/ee/onshape.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { path } from "~/utils/path";
+
+async function authorize(request: Request) {
+ const { userId, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+ return beginOnshapeAuthorization(request, {
+ integrationId: ONSHAPE_V2_INTEGRATION_ID,
+ userId,
+ companyId
+ });
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const started = await authorize(request);
+
+ if (!started.ok) {
+ return data(
+ { error: started.reason },
+ { status: started.reason === "not-configured" ? 500 : 409 }
+ );
+ }
+
+ return data(
+ { url: started.url },
+ { headers: { "Set-Cookie": started.cookie } }
+ );
+}
+
+/** The drawer's Reconnect action, as in `integrations.onshape.install.ts`. */
+export async function action({ request }: ActionFunctionArgs) {
+ const started = await authorize(request);
+ if (!started.ok) {
+ return data({
+ redirectUrl: `${path.to.integrations}?integration=${ONSHAPE_V2_INTEGRATION_ID}&error=${started.reason}`
+ });
+ }
+ return data(
+ { redirectUrl: started.url },
+ { headers: { "Set-Cookie": started.cookie } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape-v2.oauth.ts b/apps/erp/app/routes/api+/integrations.onshape-v2.oauth.ts
new file mode 100644
index 0000000000..cd979235cf
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape-v2.oauth.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape";
+import type { LoaderFunctionArgs } from "react-router";
+import { completeOnshapeAuthorization } from "~/modules/settings/onshape-oauth.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+/**
+ * OAuth callback for the panel's own grant, kept apart from the sync
+ * connection's so either can be uninstalled alone. Register it on the same
+ * Onshape app.
+ */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { userId, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ return completeOnshapeAuthorization({
+ request,
+ integrationId: ONSHAPE_V2_INTEGRATION_ID,
+ userId,
+ companyId
+ });
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.detach.ts b/apps/erp/app/routes/api+/integrations.onshape.detach.ts
new file mode 100644
index 0000000000..de8b1ad53b
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.detach.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape";
+import { getLogger } from "@carbon/logger";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const logger = getLogger("erp", "integrations-onshape-detach");
+
+/**
+ * Remove an item's `onshape-v2` link; the item keeps its model, documents and
+ * fields. A sync connection's `onshape` row is BOM-import bookkeeping the BoM
+ * Explorer reads, so it is never removed here.
+ */
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const formData = await request.formData();
+ const itemId = String(formData.get("itemId") ?? "");
+ if (!itemId) {
+ return data(
+ { success: false, message: "itemId is required" },
+ { status: 400 }
+ );
+ }
+
+ const removed = await getCarbonServiceRole()
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .eq("entityId", itemId)
+ .select("id");
+
+ if (removed.error) {
+ logger.error("Failed to detach an item from Onshape", {
+ companyId,
+ itemId,
+ error: removed.error
+ });
+ return data(
+ { success: false, message: "Failed to detach from Onshape" },
+ { status: 500 }
+ );
+ }
+ if (removed.data.length === 0) {
+ return data(
+ { success: false, message: "This item is not linked to Onshape" },
+ { status: 404 }
+ );
+ }
+
+ return data({ success: true, message: "Detached from Onshape" });
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.install.ts b/apps/erp/app/routes/api+/integrations.onshape.install.ts
index dfc5290753..9712cd2955 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.install.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.install.ts
@@ -5,19 +5,23 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { Onshape } from "@carbon/ee";
import { beginOnshapeAuthorization } from "@carbon/ee/onshape.server";
-import type { LoaderFunctionArgs } from "react-router";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
+import { path } from "~/utils/path";
-export async function loader({ request }: LoaderFunctionArgs) {
+async function authorize(request: Request) {
const { userId, companyId } = await requirePermissions(request, {
update: "settings"
});
-
- const started = await beginOnshapeAuthorization(request, {
+ return beginOnshapeAuthorization(request, {
integrationId: Onshape.id,
userId,
companyId
});
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const started = await authorize(request);
// `error` is an integration-errors code; the client sends it to the
// integrations page, which renders the copy.
@@ -33,3 +37,21 @@ export async function loader({ request }: LoaderFunctionArgs) {
{ headers: { "Set-Cookie": started.cookie } }
);
}
+
+/**
+ * The drawer's Reconnect action: the same authorization, answered as a
+ * `redirectUrl`. With no popup opener the callback returns to the integrations
+ * page, where a failure shows as the install-failure toast.
+ */
+export async function action({ request }: ActionFunctionArgs) {
+ const started = await authorize(request);
+ if (!started.ok) {
+ return data({
+ redirectUrl: `${path.to.integrations}?integration=${Onshape.id}&error=${started.reason}`
+ });
+ }
+ return data(
+ { redirectUrl: started.url },
+ { headers: { "Set-Cookie": started.cookie } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.fields.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.fields.ts
new file mode 100644
index 0000000000..0aa1202321
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.fields.ts
@@ -0,0 +1,486 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { Json } from "@carbon/database";
+import type {
+ DescriptionModes,
+ OnshapePropertyValue,
+ OnshapePushDefaults,
+ PlanCustomFieldDefinition,
+ PropertyMapEntry
+} from "@carbon/ee";
+import {
+ CUSTOM_FIELD_TYPE_LABELS,
+ ITEM_METHOD_TYPES,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_TRACKING_TYPES,
+ MAPPABLE_VALUE_TYPES,
+ MAPPING_MODES,
+ parseDescriptionModes,
+ parsePropertyMap,
+ reconcilePushDefaults,
+ STANDARD_FIELD_IDS,
+ standardField,
+ targetKey,
+ translationErrors
+} from "@carbon/ee";
+import type { OnshapeDocument } from "@carbon/ee/onshape";
+import {
+ getOnshapeClient,
+ loadPartCustomFieldDefinitions,
+ loadPlanOptions,
+ ONSHAPE_V2_INTEGRATION_ID,
+ OnshapeWVMType,
+ onshapeFailure
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import {
+ readAssemblyProperties,
+ readPartProperties
+} from "@carbon/ee/onshape.server";
+import { getLogger } from "@carbon/logger";
+import { sql } from "kysely";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import { getDatabaseClient } from "~/services/database.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const logger = getLogger("erp", "onshape", "panel-fields");
+
+const querySchema = z.object({
+ documentId: z.string().min(1),
+ wv: z.enum(["w", "v", "m"]),
+ wvId: z.string().min(1),
+ elementId: z.string().min(1)
+});
+
+/** Fields page data for the element the panel is open on. */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ { update: "settings" }
+ );
+
+ const url = new URL(request.url);
+ const parsed = querySchema.safeParse({
+ documentId: url.searchParams.get("documentId"),
+ wv: url.searchParams.get("wv"),
+ wvId: url.searchParams.get("wvId"),
+ elementId: url.searchParams.get("elementId")
+ });
+ if (!parsed.success) {
+ return data({ error: "Missing Onshape context" }, { status: 400 });
+ }
+ const { documentId, wv, wvId, elementId } = parsed.data;
+
+ const onshape = await getOnshapeClient(
+ client,
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ const document: OnshapeDocument = {
+ documentId,
+ wvm:
+ wv === "w"
+ ? OnshapeWVMType.WORKSPACE
+ : wv === "v"
+ ? OnshapeWVMType.VERSION
+ : OnshapeWVMType.MICROVERSION,
+ wvmId: wvId
+ };
+
+ // A part studio's properties live on its parts: take the union across them.
+ let properties: OnshapePropertyValue[];
+ try {
+ const elements = await onshape.client.getElementsIn(document);
+ const element = elements.find((e) => e.id === elementId);
+ if (element?.elementType === "PARTSTUDIO") {
+ // Hidden parts count: a property only on a hidden part is still mappable.
+ const parts = await onshape.client.getPartsInElement(document, elementId);
+ const byPartId = await readPartProperties(
+ onshape.client,
+ document,
+ elementId,
+ parts.map((part) => part.partId)
+ );
+ const seen = new Map<string, OnshapePropertyValue>();
+ for (const partProperties of byPartId.values()) {
+ for (const property of partProperties) {
+ if (!seen.has(property.propertyId)) {
+ seen.set(property.propertyId, property);
+ }
+ }
+ }
+ properties = [...seen.values()];
+ } else {
+ properties = await readAssemblyProperties(
+ onshape.client,
+ document,
+ elementId
+ );
+ }
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+
+ const reads = await Promise.all([
+ client
+ .from("companyIntegration")
+ .select("metadata")
+ .eq("id", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ loadPartCustomFieldDefinitions(client, companyId),
+ loadPlanOptions(client, companyId)
+ ]).catch((error) => {
+ logger.error("Failed to read custom fields", { companyId, error });
+ return null;
+ });
+ if (!reads) {
+ return data({ error: "Failed to read custom fields" }, { status: 500 });
+ }
+ const [integration, definitions, options] = reads;
+ if (integration.error) {
+ logger.error("Failed to read the property map", {
+ companyId,
+ error: integration.error
+ });
+ return data({ error: "Failed to read the property map" }, { status: 500 });
+ }
+
+ return data(
+ {
+ properties: properties.map((property) => ({
+ propertyId: property.propertyId,
+ name: property.name,
+ valueType: property.valueType,
+ // Own keys only: `in` calls a property named "constructor" mappable.
+ mappable: Object.hasOwn(MAPPABLE_VALUE_TYPES, property.valueType),
+ ...(property.options ? { options: property.options } : {})
+ })),
+ map: parsePropertyMap(integration.data?.metadata),
+ descriptionModes: parseDescriptionModes(integration.data?.metadata),
+ pushDefaults: options.defaults,
+ definitions,
+ units: options.unitsOfMeasure
+ },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
+
+const modeSchema = z.enum(MAPPING_MODES);
+
+const entrySchema = z.object({
+ onshapePropertyId: z.string().min(1),
+ onshapeName: z.string(),
+ valueType: z.string().min(1),
+ target: z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("customField"), fieldId: z.string().min(1) }),
+ z.object({ kind: z.literal("item"), field: z.enum(STANDARD_FIELD_IDS) })
+ ]),
+ mode: modeSchema,
+ translations: z
+ .array(
+ z.object({
+ onshape: z.string().max(255),
+ carbon: z.string().nullable()
+ })
+ )
+ .max(100)
+ .optional()
+});
+
+const payloadSchema = z.object({
+ entries: z
+ .array(entrySchema)
+ .max(100)
+ // A duplicate propertyId would make one entry silently win.
+ .refine(
+ (entries) =>
+ new Set(entries.map((e) => e.onshapePropertyId)).size === entries.length
+ ),
+ descriptionModes: z.object({ name: modeSchema, description: modeSchema }),
+ pushDefaults: z.object({
+ replenishmentSystem: z.enum(ITEM_REPLENISHMENT_SYSTEMS),
+ methodTypeForMake: z.enum(ITEM_METHOD_TYPES),
+ methodTypeForBuy: z.enum(ITEM_METHOD_TYPES),
+ itemTrackingType: z.enum(ITEM_TRACKING_TYPES),
+ unitOfMeasureCode: z.string().min(1).nullable()
+ })
+});
+
+// The metadata keys `parsePushDefaults` reads. No unit key when the unit is
+// left to the company's list.
+function pushDefaultsMetadata(defaults: OnshapePushDefaults) {
+ return {
+ defaultReplenishmentSystem: defaults.replenishmentSystem,
+ defaultMethodTypeForMake: defaults.methodTypeForMake,
+ defaultMethodTypeForBuy: defaults.methodTypeForBuy,
+ defaultItemTrackingType: defaults.itemTrackingType,
+ ...(defaults.unitOfMeasureCode
+ ? { defaultUnitOfMeasureCode: defaults.unitOfMeasureCode }
+ : {})
+ };
+}
+
+type FieldError = { key: string; errors: string[] };
+
+/** "A, B or C". */
+function orList(values: readonly string[]): string {
+ return values.length > 1
+ ? `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`
+ : (values[0] ?? "");
+}
+
+/** Replace the property map, the description modes and the push defaults. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requireOnshapePanelPermissions(request, {
+ update: "settings"
+ });
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid property map payload" }, { status: 400 });
+ }
+ const { entries } = parsed.data;
+ const descriptionModes: DescriptionModes = parsed.data.descriptionModes;
+ const pushDefaults: OnshapePushDefaults = parsed.data.pushDefaults;
+
+ // The same pairs the Part form allows; refused here so the saved value is
+ // the value pushes use, not one the plan quietly corrects.
+ const reconciled = reconcilePushDefaults(pushDefaults);
+ if (reconciled.methodTypeForMake !== pushDefaults.methodTypeForMake) {
+ return data(
+ {
+ error: `${pushDefaults.methodTypeForMake} isn't allowed with ${pushDefaults.replenishmentSystem}`
+ },
+ { status: 422 }
+ );
+ }
+ if (reconciled.methodTypeForBuy !== pushDefaults.methodTypeForBuy) {
+ return data(
+ {
+ error: `${pushDefaults.methodTypeForBuy} isn't allowed for Buy items`
+ },
+ { status: 422 }
+ );
+ }
+
+ const fieldErrors: FieldError[] = [];
+
+ // The editor hides unmappable rows; this guards a hand-made payload.
+ for (const entry of entries) {
+ if (!Object.hasOwn(MAPPABLE_VALUE_TYPES, entry.valueType)) {
+ fieldErrors.push({
+ key: entry.onshapePropertyId,
+ errors: [`${entry.valueType} properties cannot be mapped`]
+ });
+ }
+ }
+
+ // A target takes one property; each clashing entry names the others.
+ const namesByTarget = new Map<string, string[]>();
+ for (const entry of entries) {
+ const key = targetKey(entry.target);
+ namesByTarget.set(key, [
+ ...(namesByTarget.get(key) ?? []),
+ entry.onshapeName || entry.onshapePropertyId
+ ]);
+ }
+ for (const entry of entries) {
+ const own = entry.onshapeName || entry.onshapePropertyId;
+ const others = (namesByTarget.get(targetKey(entry.target)) ?? []).filter(
+ (name) => name !== own
+ );
+ if (others.length > 0) {
+ fieldErrors.push({
+ key: entry.onshapePropertyId,
+ errors: [
+ `${others.join(", ")} already maps to this Carbon field. A Carbon field takes one property.`
+ ]
+ });
+ }
+ }
+
+ const itemEntries = entries.filter((entry) => entry.target.kind === "item");
+ let units: Awaited<ReturnType<typeof loadPlanOptions>>["unitsOfMeasure"] = [];
+ if (itemEntries.length > 0 || pushDefaults.unitOfMeasureCode) {
+ units = (await loadPlanOptions(client, companyId)).unitsOfMeasure;
+ }
+ if (
+ pushDefaults.unitOfMeasureCode &&
+ !units.some((unit) => unit.code === pushDefaults.unitOfMeasureCode)
+ ) {
+ return data(
+ {
+ error: `${pushDefaults.unitOfMeasureCode} is not a unit of measure in Carbon`
+ },
+ { status: 422 }
+ );
+ }
+ for (const entry of itemEntries) {
+ if (entry.target.kind !== "item") continue;
+ const field = standardField(entry.target.field);
+ if (!field) continue;
+ const errors: string[] = [];
+ if (!field.valueTypes.includes(entry.valueType)) {
+ errors.push(
+ `An Onshape ${entry.valueType} property can't set ${field.label}. It takes ${orList(field.valueTypes)} properties.`
+ );
+ }
+ errors.push(...translationErrors(field, entry.translations ?? [], units));
+ if (errors.length > 0) {
+ fieldErrors.push({ key: entry.onshapePropertyId, errors });
+ }
+ }
+
+ const customFieldIds = entries.flatMap((entry) =>
+ entry.target.kind === "customField" ? [entry.target.fieldId] : []
+ );
+ const existingIds = [...new Set(customFieldIds)];
+ if (existingIds.length > 0) {
+ const existing = await client
+ .from("customField")
+ .select("id, name, dataTypeId")
+ .eq("companyId", companyId)
+ .eq("table", "part")
+ .in("id", existingIds);
+ if (existing.error) {
+ logger.error("Failed to read custom fields", {
+ companyId,
+ error: existing.error
+ });
+ return data({ error: "Failed to read custom fields" }, { status: 500 });
+ }
+ const fields = new Map((existing.data ?? []).map((row) => [row.id, row]));
+ for (const entry of entries) {
+ if (entry.target.kind !== "customField") continue;
+ const field = fields.get(entry.target.fieldId);
+ const dataTypeId = field?.dataTypeId;
+ if (field === undefined || dataTypeId === undefined) {
+ fieldErrors.push({
+ key: entry.onshapePropertyId,
+ errors: ["The mapped Carbon field no longer exists"]
+ });
+ } else if (
+ Object.hasOwn(MAPPABLE_VALUE_TYPES, entry.valueType) &&
+ !MAPPABLE_VALUE_TYPES[entry.valueType]?.includes(dataTypeId)
+ ) {
+ const needed = orList(
+ (MAPPABLE_VALUE_TYPES[entry.valueType] ?? []).map(
+ (id) => CUSTOM_FIELD_TYPE_LABELS[id] ?? String(id)
+ )
+ );
+ fieldErrors.push({
+ key: entry.onshapePropertyId,
+ errors: [
+ `${field.name} is a ${CUSTOM_FIELD_TYPE_LABELS[dataTypeId] ?? "different"} field. An Onshape ${entry.valueType} property needs a ${needed} field.`
+ ]
+ });
+ }
+ }
+ }
+ if (fieldErrors.length > 0) {
+ return data(
+ { error: "Some field mappings are not valid", fieldErrors },
+ { status: 422 }
+ );
+ }
+
+ // Translations are kept for list item fields only.
+ const mapEntries: PropertyMapEntry[] = entries.map((entry) => {
+ const field =
+ entry.target.kind === "item" ? standardField(entry.target.field) : null;
+ return {
+ onshapePropertyId: entry.onshapePropertyId,
+ onshapeName: entry.onshapeName,
+ valueType: entry.valueType,
+ target: entry.target,
+ mode: entry.mode,
+ ...(field?.kind === "list"
+ ? {
+ translations: (entry.translations ?? []).map((row) => ({
+ onshape: row.onshape.trim(),
+ carbon: row.carbon
+ }))
+ }
+ : {})
+ };
+ });
+
+ // Writes only this page's keys (map, modes, push defaults); other writers own
+ // the sibling keys. The column is json, hence the casts.
+ const db = getDatabaseClient();
+ let updatedRows: bigint;
+ try {
+ const updated = await db
+ .updateTable("companyIntegration")
+ .set({
+ metadata: sql<Json>`((jsonb_set(jsonb_set(metadata::jsonb, '{propertyMap}', ${JSON.stringify(
+ mapEntries
+ )}::jsonb, true), '{descriptionModes}', ${JSON.stringify(
+ descriptionModes
+ )}::jsonb, true) || ${JSON.stringify(
+ pushDefaultsMetadata(pushDefaults)
+ )}::jsonb)${
+ pushDefaults.unitOfMeasureCode
+ ? sql``
+ : sql` - 'defaultUnitOfMeasureCode'`
+ })::json`
+ })
+ .where("id", "=", ONSHAPE_V2_INTEGRATION_ID)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ updatedRows = updated.numUpdatedRows;
+ } catch (error) {
+ logger.error("Failed to save the property map", { companyId, error });
+ return data({ error: "Failed to save the property map" }, { status: 500 });
+ }
+ if (Number(updatedRows) === 0) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ // The map is saved; a failed re-read is a warning, not a failed save.
+ let definitions: PlanCustomFieldDefinition[] | null = null;
+ let warning: string | undefined;
+ try {
+ definitions = await loadPartCustomFieldDefinitions(client, companyId);
+ } catch (error) {
+ logger.error("Failed to re-read custom fields after saving the map", {
+ companyId,
+ error
+ });
+ warning =
+ "Saved. The custom field list couldn't be refreshed — press Refresh to see the latest fields.";
+ }
+
+ return data(
+ {
+ map: mapEntries,
+ descriptionModes,
+ pushDefaults,
+ definitions,
+ ...(warning ? { warning } : {})
+ },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.me.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.me.ts
new file mode 100644
index 0000000000..de35bab57d
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.me.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { hasPermission } from "@carbon/auth";
+import { getUserClaims } from "@carbon/auth/users.server";
+import type { OnshapePanelMe } from "@carbon/ee";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+/** The panel user and company, and whether they may edit the Fields page. */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId, sessionUserId, email } =
+ await requireOnshapePanelPermissions(request, {});
+
+ // `requireOnshapePanelPermissions` throws on a denial, so the Fields
+ // permission is read from the claims directly.
+ const [company, claims] = await Promise.all([
+ client.from("company").select("id, name").eq("id", companyId).maybeSingle(),
+ getUserClaims(sessionUserId, companyId)
+ ]);
+
+ const me: OnshapePanelMe = {
+ userId,
+ email,
+ company: company.data
+ ? { id: company.data.id, name: company.data.name }
+ : null,
+ canEditFields: hasPermission(
+ claims?.permissions,
+ "settings",
+ "update",
+ companyId
+ )
+ };
+
+ return data(me, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts
new file mode 100644
index 0000000000..409d136aef
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts
@@ -0,0 +1,402 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { PlanItemRow, PlanMappingContext } from "@carbon/ee";
+import {
+ buildAssemblyPlan,
+ externalIdForAssembly,
+ externalIdForBomLine,
+ flattenNodes,
+ metadataProperty,
+ missingBomColumnsMessage,
+ normalizeConfiguration,
+ parseBomTree,
+ parseProperties,
+ withoutProperties
+} from "@carbon/ee";
+import type { OnshapeDocument, StoredAssemblyPlan } from "@carbon/ee/onshape";
+import {
+ createPanelPlan,
+ getOnshapeClient,
+ loadActiveMakeMethods,
+ loadMethodLineOwnership,
+ loadPlanMapping,
+ loadPlanOptions,
+ loadReleasedRevisions,
+ loadReusableDrafts,
+ ONSHAPE_V2_INTEGRATION_ID,
+ OnshapeWVMType,
+ onshapeFailure,
+ selectInBatches,
+ withRefusedMethods
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import { loadMethodWriteRefusals } from "~/modules/settings/onshape-draft-method.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const payloadSchema = z.object({
+ documentId: z.string().min(1),
+ wv: z.enum(["w", "v"]),
+ wvId: z.string().min(1),
+ elementId: z.string().min(1),
+ depth: z.enum(["all", "top"]).default("all"),
+ configuration: z.string().nullish()
+});
+
+// Most distinct part numbers an `all` push plans: a push is one request with no
+// rollback, and a gateway can cut a large one off mid-BOM.
+const MAX_PLAN_PARTS = 1500;
+
+/** Plan an assembly push without writing; the apply reuses the stored plan. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts",
+ // Re-pushing replaces the BOM lines an earlier push wrote.
+ delete: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid plan payload" }, { status: 400 });
+ }
+ const { documentId, wv, wvId, elementId, depth } = parsed.data;
+ const configuration = normalizeConfiguration(parsed.data.configuration);
+
+ const serviceRole = getCarbonServiceRole();
+ const onshape = await getOnshapeClient(
+ serviceRole,
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ const document: OnshapeDocument = {
+ documentId,
+ wvm: wv === "w" ? OnshapeWVMType.WORKSPACE : OnshapeWVMType.VERSION,
+ wvmId: wvId
+ };
+
+ let bom: unknown;
+ try {
+ bom = await onshape.client.getBillOfMaterialsIn(
+ document,
+ elementId,
+ configuration
+ );
+ } catch (error) {
+ const failure = onshapeFailure(error, "bom");
+ return data(failure.body, { status: failure.status });
+ }
+
+ // Element metadata names the assembly; the BOM's top row is the fallback.
+ const { root: bomRoot, lines, missingColumns } = parseBomTree(bom);
+ // An empty plan from an unreadable tree would drop every Onshape line.
+ if (missingColumns.length > 0) {
+ return data(
+ { error: missingBomColumnsMessage(missingColumns) },
+ { status: 422 }
+ );
+ }
+ let rootPartNumber = bomRoot?.partNumber ?? null;
+ let rootName = bomRoot?.name ?? null;
+ let rootDescription = bomRoot?.description ?? null;
+ const rootRevision = bomRoot?.revision ?? null;
+ let elementMetadata: unknown = null;
+ let metadataError: unknown = null;
+ try {
+ elementMetadata = await onshape.client.getElementMetadata(
+ document,
+ elementId,
+ configuration
+ );
+ rootPartNumber =
+ metadataProperty(elementMetadata, "Part number") ?? rootPartNumber;
+ rootName = metadataProperty(elementMetadata, "Name") ?? rootName;
+ rootDescription =
+ metadataProperty(elementMetadata, "Description") ?? rootDescription;
+ } catch (error) {
+ metadataError = error;
+ }
+ if (!rootPartNumber) {
+ if (metadataError !== null) {
+ const failure = onshapeFailure(metadataError);
+ return data(failure.body, { status: failure.status });
+ }
+ return data(
+ { error: "Set a part number on the assembly in Onshape first" },
+ { status: 422 }
+ );
+ }
+
+ const allNodes = depth === "top" ? lines : flattenNodes(lines);
+ const partNumbers = [
+ ...new Set(
+ [rootPartNumber, ...allNodes.map((node) => node.partNumber)].filter(
+ (n): n is string => !!n
+ )
+ )
+ ];
+ if (depth === "all" && partNumbers.length > MAX_PLAN_PARTS) {
+ const subAssemblies = lines.filter(
+ (node) => node.children.length > 0
+ ).length;
+ // Counts the whole tree, so pushing sub-assemblies first does not help;
+ // `code` lets the panel offer `top`.
+ return data(
+ {
+ code: "too-large" as const,
+ error:
+ `It has ${partNumbers.length.toLocaleString("en-US")} distinct part numbers; one push handles ${MAX_PLAN_PARTS.toLocaleString("en-US")}. ` +
+ (subAssemblies > 0
+ ? `Push this level on its own — its ${subAssemblies} sub-assemblies become single lines, and each can then be pushed from its own tab in Onshape.`
+ : "Split it into sub-assemblies in Onshape, then push this level on its own.")
+ },
+ { status: 422 }
+ );
+ }
+
+ const existing = await selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select(
+ "id, readableId, revision, revisionStatus, active, name, description, type, replenishmentSystem, defaultMethodType, itemTrackingType, unitOfMeasureCode, sourcingType, mpn"
+ )
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ );
+ if (existing.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const items: PlanItemRow[] = existing.data.map((row) => ({
+ ...row,
+ revision: row.revision ?? "0"
+ }));
+ const revisionStatusByItemId = new Map(
+ existing.data.map((row) => [row.id, row.revisionStatus])
+ );
+
+ // Every revision row of a parent is included so the ownership read covers
+ // whichever row the builder pins.
+ const parentPartNumbers = new Set<string>([rootPartNumber]);
+ for (const node of allNodes) {
+ if (node.partNumber && node.children.length > 0) {
+ parentPartNumbers.add(node.partNumber);
+ }
+ }
+ const parentItemIds = items
+ .filter((item) => parentPartNumbers.has(item.readableId))
+ .map((item) => item.id);
+
+ const linkExternalIds = [
+ ...new Set(
+ [
+ externalIdForAssembly(documentId, elementId, configuration),
+ ...flattenNodes(lines).map((node) =>
+ externalIdForBomLine(node.itemSource ?? null)
+ )
+ ].filter((id): id is string => !!id)
+ )
+ ];
+
+ const [options, methods, links, itemLinks] = await Promise.all([
+ loadPlanOptions(serviceRole, companyId),
+ loadActiveMakeMethods(client, companyId, parentItemIds).then(
+ (byItemId) => ({ byItemId, error: null }),
+ (error: unknown) => ({ byItemId: null, error })
+ ),
+ selectInBatches(linkExternalIds, (batch) =>
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("externalId", batch)
+ ),
+ // An item linked elsewhere keeps its link and takes no mapped values.
+ selectInBatches(
+ items.map((item) => item.id),
+ (batch) =>
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("entityId", batch)
+ )
+ ]);
+ if (!methods.byItemId) {
+ return data(
+ {
+ error:
+ methods.error instanceof Error
+ ? methods.error.message
+ : "Failed to read the make methods"
+ },
+ { status: 500 }
+ );
+ }
+ const methodByItemId = methods.byItemId;
+ // A failed read would mark every reuse a conflict; say so instead.
+ if (links.error || itemLinks.error) {
+ return data(
+ { error: "Carbon couldn't read its Onshape links. Try again." },
+ { status: 500 }
+ );
+ }
+ const linkedItemIds = new Set(
+ (itemLinks.data ?? []).map((link) => link.entityId)
+ );
+ const linkedItemIdByExternalId = new Map<string, string>();
+ for (const link of links.data ?? []) {
+ if (link.externalId) {
+ linkedItemIdByExternalId.set(link.externalId, link.entityId);
+ }
+ }
+ let reusableDraftByItemId: Awaited<ReturnType<typeof loadReusableDrafts>>;
+ let ownership: Awaited<ReturnType<typeof loadMethodLineOwnership>>;
+ try {
+ reusableDraftByItemId = await loadReusableDrafts(
+ client,
+ serviceRole,
+ companyId,
+ new Map(
+ [...methodByItemId.entries()]
+ .filter(([, method]) => method.status === "Active")
+ .map(([itemId, method]) => [itemId, method.id])
+ )
+ );
+ ownership = await loadMethodLineOwnership(client, serviceRole, companyId, [
+ ...[...methodByItemId.values()].map((method) => method.id),
+ ...[...reusableDraftByItemId.values()].map((draft) => draft.id)
+ ]);
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the existing BOM lines"
+ },
+ { status: 500 }
+ );
+ }
+
+ let mapping: PlanMappingContext;
+ try {
+ mapping = await loadPlanMapping(
+ serviceRole,
+ companyId,
+ items.map((item) => item.readableId)
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the Onshape property map"
+ },
+ { status: 500 }
+ );
+ }
+ // The root's mapped values come from its element metadata.
+ if (mapping.map.length > 0 && elementMetadata === null && metadataError) {
+ const failure = onshapeFailure(metadataError);
+ return data(failure.body, { status: failure.status });
+ }
+
+ let released: Awaited<ReturnType<typeof loadReleasedRevisions>>;
+ try {
+ released = await loadReleasedRevisions(client, companyId, items);
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error ? error.message : "Failed to read Carbon items"
+ },
+ { status: 500 }
+ );
+ }
+
+ // The review lists a BOM the push will not write: a change notice's Draft, or
+ // a locked released revision. Apply checks again.
+ const refusals = await loadMethodWriteRefusals(
+ client,
+ companyId,
+ [...methodByItemId.entries()].map(([itemId, method]) => ({
+ itemId,
+ method,
+ revisionStatus: revisionStatusByItemId.get(itemId)
+ }))
+ );
+
+ const built = buildAssemblyPlan({
+ documentId,
+ wv,
+ wvId,
+ elementId,
+ root: {
+ partNumber: rootPartNumber,
+ name: rootName,
+ description: rootDescription,
+ revision: rootRevision
+ },
+ nodes: lines,
+ items,
+ methodByItemId,
+ mappedLinesByMethodId: ownership.mapped,
+ manualLinesByMethodId: ownership.manual,
+ options,
+ depth,
+ linkedItemIdByExternalId,
+ linkedItemIds,
+ configuration,
+ reusableDraftByItemId,
+ mapping,
+ rootProperties:
+ elementMetadata !== null ? parseProperties(elementMetadata) : null,
+ released
+ });
+ const plan = withRefusedMethods(built, refusals);
+
+ // The apply walks the stored BOM structure; the property cells are dropped.
+ const stored: StoredAssemblyPlan = {
+ ...plan,
+ nodes: withoutProperties(lines)
+ };
+ const created = await createPanelPlan({ companyId, userId, plan: stored });
+ if (!created) {
+ return data(
+ { error: "Carbon couldn't save this review. Try again." },
+ { status: 503 }
+ );
+ }
+
+ return data(
+ { planId: created.planId, expiresAt: created.expiresAt, plan },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-part.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-part.ts
new file mode 100644
index 0000000000..01e55d7227
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-part.ts
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type {
+ OnshapePropertyValue,
+ PartPlan,
+ PlanItemRow,
+ PlanMappingContext,
+ PlanMappingRow
+} from "@carbon/ee";
+import { buildPartPlan, normalizeConfiguration } from "@carbon/ee";
+import type { OnshapeDocument } from "@carbon/ee/onshape";
+import {
+ createPanelPlan,
+ getOnshapeClient,
+ loadPlanMapping,
+ loadPlanOptions,
+ loadReleasedRevisions,
+ ONSHAPE_V2_INTEGRATION_ID,
+ OnshapeWVMType,
+ onshapeFailure,
+ selectInBatches
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { readPartProperties } from "@carbon/ee/onshape.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const payloadSchema = z.object({
+ documentId: z.string().min(1),
+ // Exports need a workspace or a version, not a microversion.
+ wv: z.enum(["w", "v"]),
+ wvId: z.string().min(1),
+ elementId: z.string().min(1),
+ configuration: z.string().nullish(),
+ partIds: z.array(z.string().min(1)).min(1).max(50)
+});
+
+const ITEM_COLUMNS =
+ "id, readableId, revision, active, name, description, type, replenishmentSystem, defaultMethodType, itemTrackingType, sourcingType, unitOfMeasureCode, mpn";
+
+/** Plan a part push without writing; the apply makes no Onshape call. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid plan payload" }, { status: 400 });
+ }
+ const { documentId, wv, wvId, elementId } = parsed.data;
+ const configuration = normalizeConfiguration(parsed.data.configuration);
+ const partIds = [...new Set(parsed.data.partIds)];
+
+ const serviceRole = getCarbonServiceRole();
+ const onshape = await getOnshapeClient(
+ serviceRole,
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ const document: OnshapeDocument = {
+ documentId,
+ wvm: wv === "w" ? OnshapeWVMType.WORKSPACE : OnshapeWVMType.VERSION,
+ wvmId: wvId
+ };
+
+ let parts: Awaited<ReturnType<typeof onshape.client.getPartsInElement>>;
+ try {
+ parts = await onshape.client.getPartsInElement(
+ document,
+ elementId,
+ configuration
+ );
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+ // Hidden parts are not shown in the panel, so they cannot be pushed.
+ parts = parts.filter((part) => !part.isHidden);
+
+ const requested = parts.filter((part) => partIds.includes(part.partId));
+ const partNumbers = [
+ ...new Set(
+ requested
+ .map((part) => part.partNumber)
+ .filter((number): number is string => !!number)
+ )
+ ];
+
+ const [mappings, matches, options] = await Promise.all([
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId, lastSyncedAt, metadata")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .like("externalId", `${documentId}:${elementId}:%`),
+ selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select(ITEM_COLUMNS)
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ ),
+ loadPlanOptions(serviceRole, companyId)
+ ]);
+
+ if (mappings.error) {
+ return data({ error: "Failed to read Onshape mappings" }, { status: 500 });
+ }
+ if (matches.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+
+ const mappingRows: PlanMappingRow[] = (mappings.data ?? []).map((row) => ({
+ entityId: row.entityId,
+ externalId: row.externalId,
+ lastSyncedAt: row.lastSyncedAt,
+ metadata: (row.metadata ?? null) as Record<string, unknown> | null
+ }));
+ const matchedItems = (matches.data ?? []) as PlanItemRow[];
+
+ // A linked item renumbered since is not in `matches`; reading it by id tells
+ // a live link from a stale mapping row.
+ const mappedItemIds = [
+ ...new Set(
+ mappingRows
+ .map((row) => row.entityId)
+ .filter((id) => !matchedItems.some((item) => item.id === id))
+ )
+ ];
+ const mappedResult = await selectInBatches(mappedItemIds, (batch) =>
+ client
+ .from("item")
+ .select(ITEM_COLUMNS)
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (mappedResult.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const mappedItems = mappedResult.data as PlanItemRow[];
+
+ const candidates = [...matchedItems, ...mappedItems];
+ let released: Awaited<ReturnType<typeof loadReleasedRevisions>>;
+ try {
+ released = await loadReleasedRevisions(client, companyId, matchedItems);
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error ? error.message : "Failed to read Carbon items"
+ },
+ { status: 500 }
+ );
+ }
+
+ let mapping: PlanMappingContext;
+ try {
+ mapping = await loadPlanMapping(
+ serviceRole,
+ companyId,
+ candidates.map((item) => item.readableId)
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the Onshape property map"
+ },
+ { status: 500 }
+ );
+ }
+
+ // No map means no extra Onshape read. Unchanged parts are read too: a
+ // property mapped after the last push must reach Carbon.
+ let propertiesByPartId: Map<string, OnshapePropertyValue[]> | undefined;
+ if (mapping.map.length > 0 && requested.length > 0) {
+ try {
+ propertiesByPartId = await readPartProperties(
+ onshape.client,
+ document,
+ elementId,
+ partIds,
+ configuration
+ );
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+ }
+
+ const rows = buildPartPlan({
+ documentId,
+ elementId,
+ configuration,
+ parts,
+ requestedPartIds: partIds,
+ mappings: mappingRows,
+ items: candidates,
+ options,
+ mapping,
+ propertiesByPartId,
+ released
+ });
+ if (rows.length === 0) {
+ return data(
+ { error: "None of the selected parts are in this element" },
+ { status: 422 }
+ );
+ }
+
+ const plan: PartPlan = {
+ kind: "part",
+ documentId,
+ wv,
+ wvId,
+ elementId,
+ configuration,
+ rows,
+ options
+ };
+ const stored = await createPanelPlan({ companyId, userId, plan });
+ if (!stored) {
+ return data(
+ { error: "Carbon couldn't save this review. Try again." },
+ { status: 503 }
+ );
+ }
+
+ return data(
+ { planId: stored.planId, expiresAt: stored.expiresAt, plan },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts
new file mode 100644
index 0000000000..563e6882e4
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts
@@ -0,0 +1,405 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type {
+ OnshapeBomNode,
+ OnshapePropertyValue,
+ PlanItemRow,
+ PlanMappingContext
+} from "@carbon/ee";
+import {
+ buildReleasePlan,
+ drawingModels,
+ groupRevisionsIntoReleases,
+ isModelReleaseItem,
+ missingBomColumnsMessage,
+ parseBomTree,
+ parseProperties,
+ releaseBomKey,
+ withoutProperties
+} from "@carbon/ee";
+import type { StoredReleasePlan } from "@carbon/ee/onshape";
+import {
+ createPanelPlan,
+ getOnshapeClient,
+ loadActiveMakeMethods,
+ loadPlanMapping,
+ loadPlanOptions,
+ ONSHAPE_V2_INTEGRATION_ID,
+ OnshapeWVMType,
+ onshapeFailure,
+ selectInBatches
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { readPartProperties } from "@carbon/ee/onshape.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import { findOpenReleaseNotice } from "~/modules/settings/onshape-push.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const payloadSchema = z.object({
+ documentId: z.string().min(1),
+ releaseId: z.string().min(1)
+});
+
+/** Plan a release push without writing; the apply makes no Onshape call. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts",
+ // Re-pushing replaces the BOM lines an earlier push wrote.
+ delete: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid plan payload" }, { status: 400 });
+ }
+ const { documentId, releaseId } = parsed.data;
+
+ const serviceRole = getCarbonServiceRole();
+ const onshape = await getOnshapeClient(
+ serviceRole,
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ let revisions: Awaited<
+ ReturnType<typeof onshape.client.getDocumentRevisions>
+ >;
+ try {
+ revisions = await onshape.client.getDocumentRevisions(documentId);
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+
+ const release = groupRevisionsIntoReleases(revisions.items ?? []).find(
+ (candidate) => candidate.releaseId === releaseId
+ );
+ if (!release) {
+ return data(
+ { error: "Release not found in this document" },
+ { status: 404 }
+ );
+ }
+
+ const modelItems = release.items.filter(isModelReleaseItem);
+ const drawingItems = release.items.filter(
+ (item) => !isModelReleaseItem(item)
+ );
+ if (modelItems.length === 0 && drawingItems.length === 0) {
+ return data(
+ { error: "The release contains no parts, assemblies or drawings" },
+ { status: 422 }
+ );
+ }
+ const releasePartNumbers = [
+ ...new Set(modelItems.map((item) => item.partNumber))
+ ];
+
+ // A drawing numbered apart from its model is tied to it by the release
+ // package, which lists the model under the drawing. Read only when needed.
+ const warnings: string[] = [];
+ let drawingModelByElementId: ReturnType<typeof drawingModels> = new Map();
+ if (
+ drawingItems.some((item) => !releasePartNumbers.includes(item.partNumber))
+ ) {
+ try {
+ drawingModelByElementId = drawingModels(
+ await onshape.client.getReleasePackageItems(releaseId)
+ );
+ } catch (error) {
+ warnings.push(
+ `The release package couldn't be read, so a drawing numbered apart from its model is not attached (${onshapeFailure(error).body.error})`
+ );
+ }
+ }
+ const drawingModelPartNumbers = [...drawingModelByElementId.values()]
+ .map((model) => model.partNumber)
+ .filter((partNumber) => !releasePartNumbers.includes(partNumber));
+
+ // Read before any BOM: an assembly whose Carbon method is already released
+ // refuses its BOM at apply, so reading that BOM wastes quota.
+ const lookupPartNumbers = [
+ ...new Set([...releasePartNumbers, ...drawingModelPartNumbers])
+ ];
+ const releaseRows = await selectInBatches(lookupPartNumbers, (batch) =>
+ client
+ .from("item")
+ .select(
+ "id, readableId, revision, active, name, description, type, replenishmentSystem, defaultMethodType, itemTrackingType, unitOfMeasureCode, sourcingType, mpn"
+ )
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ );
+ if (releaseRows.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const toPlanRow = <T extends { revision: string | null }>(row: T) => ({
+ ...row,
+ revision: row.revision ?? "0"
+ });
+ const items: PlanItemRow[] = releaseRows.data.map(toPlanRow);
+
+ const letterAssemblyItemIds = modelItems
+ .filter((item) => item.elementType === 1)
+ .flatMap((item) =>
+ items
+ .filter(
+ (row) =>
+ row.readableId === item.partNumber && row.revision === item.revision
+ )
+ .map((row) => row.id)
+ );
+ const [methods, options] = await Promise.all([
+ loadActiveMakeMethods(client, companyId, letterAssemblyItemIds).then(
+ (byItemId) => ({ byItemId, error: null }),
+ (error: unknown) => ({ byItemId: null, error })
+ ),
+ loadPlanOptions(serviceRole, companyId)
+ ]);
+ if (!methods.byItemId) {
+ return data(
+ {
+ error:
+ methods.error instanceof Error
+ ? methods.error.message
+ : "Failed to read the make methods"
+ },
+ { status: 500 }
+ );
+ }
+ const methodByItemId = methods.byItemId;
+ const refusedBomKeys = new Set(
+ modelItems
+ .filter((item) => item.elementType === 1)
+ .filter((item) =>
+ items.some(
+ (row) =>
+ row.readableId === item.partNumber &&
+ row.revision === item.revision &&
+ methodByItemId.get(row.id)?.status === "Active"
+ )
+ )
+ .map(releaseBomKey)
+ );
+
+ // BOMs are read sequentially: parallel bursts hit Onshape rate limits. Null
+ // lines (a failed read) tell the apply to leave the method alone; an empty
+ // array is an empty BOM. Keyed by `releaseBomKey`: two configurations of one
+ // element have two BOMs.
+ const bomLinesByElementId: Record<string, OnshapeBomNode[] | null> = {};
+ for (const item of modelItems) {
+ if (item.elementType !== 1) continue;
+ const bomKey = releaseBomKey(item);
+ if (refusedBomKeys.has(bomKey)) {
+ bomLinesByElementId[bomKey] = null;
+ continue;
+ }
+ try {
+ const bom = await onshape.client.getBillOfMaterialsIn(
+ {
+ documentId,
+ wvm: OnshapeWVMType.VERSION,
+ wvmId: item.versionId
+ },
+ item.elementId,
+ item.configuration ?? null
+ );
+ const { lines, missingColumns } = parseBomTree(bom);
+ if (missingColumns.length > 0) {
+ bomLinesByElementId[bomKey] = null;
+ warnings.push(
+ `${item.partNumber} Rev ${item.revision}: ${missingBomColumnsMessage(
+ missingColumns
+ )}`
+ );
+ continue;
+ }
+ bomLinesByElementId[bomKey] = lines;
+ } catch (error) {
+ bomLinesByElementId[bomKey] = null;
+ warnings.push(
+ `${item.partNumber} Rev ${item.revision}: ${
+ onshapeFailure(error, "bom").body.error
+ }`
+ );
+ }
+ }
+
+ // Look up BOM children so bought parts already in Carbon are reused.
+ const childPartNumbers = [
+ ...new Set(
+ Object.values(bomLinesByElementId)
+ .flatMap((lines) => (lines ?? []).map((line) => line.partNumber))
+ .filter(
+ (partNumber): partNumber is string =>
+ !!partNumber && !lookupPartNumbers.includes(partNumber)
+ )
+ )
+ ];
+ const childRows = await selectInBatches(childPartNumbers, (batch) =>
+ client
+ .from("item")
+ .select(
+ "id, readableId, revision, active, name, description, type, replenishmentSystem, defaultMethodType, itemTrackingType, unitOfMeasureCode, sourcingType, mpn"
+ )
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ );
+ if (childRows.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ items.push(...childRows.data.map(toPlanRow));
+
+ let mapping: PlanMappingContext;
+ try {
+ mapping = await loadPlanMapping(
+ serviceRole,
+ companyId,
+ items.map((item) => item.readableId)
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the Onshape property map"
+ },
+ { status: 500 }
+ );
+ }
+
+ // Released items' properties at the released version, read sequentially:
+ // one read per assembly, one per Part Studio version. BOM children carry
+ // theirs on the BOM row.
+ const propertiesByPartNumber = new Map<string, OnshapePropertyValue[]>();
+ const needsProperties =
+ mapping.map.length > 0 ||
+ mapping.descriptionModes.name === "everyPush" ||
+ mapping.descriptionModes.description === "everyPush";
+ if (needsProperties) {
+ const studios = new Map<string, typeof modelItems>();
+ for (const item of modelItems) {
+ if (item.elementType === 1) {
+ try {
+ const metadata = await onshape.client.getElementMetadata(
+ {
+ documentId,
+ wvm: OnshapeWVMType.VERSION,
+ wvmId: item.versionId
+ },
+ item.elementId,
+ item.configuration ?? null
+ );
+ propertiesByPartNumber.set(
+ item.partNumber,
+ parseProperties(metadata)
+ );
+ } catch (error) {
+ warnings.push(
+ `${item.partNumber} Rev ${item.revision}: its Onshape properties couldn't be read, so no mapped value is written (${onshapeFailure(error).body.error})`
+ );
+ }
+ continue;
+ }
+ if (!item.partId) continue;
+ const key = `${item.elementId}:${item.versionId}:${item.configuration ?? ""}`;
+ studios.set(key, [...(studios.get(key) ?? []), item]);
+ }
+ for (const studioItems of studios.values()) {
+ const [first] = studioItems;
+ if (!first) continue;
+ try {
+ const byPartId = await readPartProperties(
+ onshape.client,
+ { documentId, wvm: OnshapeWVMType.VERSION, wvmId: first.versionId },
+ first.elementId,
+ studioItems.flatMap((item) => (item.partId ? [item.partId] : [])),
+ first.configuration ?? null
+ );
+ for (const item of studioItems) {
+ const properties = item.partId ? byPartId.get(item.partId) : null;
+ if (properties)
+ propertiesByPartNumber.set(item.partNumber, properties);
+ }
+ } catch (error) {
+ warnings.push(
+ `${studioItems.map((item) => item.partNumber).join(", ")}: their Onshape properties couldn't be read, so no mapped value is written (${onshapeFailure(error).body.error})`
+ );
+ }
+ }
+ }
+
+ const built = buildReleasePlan({
+ documentId,
+ release,
+ items,
+ bomLinesByElementId,
+ methodByItemId,
+ options,
+ mapping,
+ propertiesByPartNumber,
+ drawingModelByElementId
+ });
+ // A release pushed from a second document adds to the first push's notice.
+ const openNotice = built.changeNotice
+ ? await findOpenReleaseNotice(client, companyId, built.releaseId)
+ : { data: null, error: null };
+ if (openNotice.error !== null) {
+ return data(
+ {
+ error: `${openNotice.error}, so it can't tell which change notice to use. Try again.`
+ },
+ { status: 500 }
+ );
+ }
+ const plan = openNotice.data
+ ? { ...built, existingChangeNotice: openNotice.data.changeNoticeId }
+ : built;
+
+ // Only the stored copy carries the BOM lines the apply walks, minus cells.
+ const stored: StoredReleasePlan = {
+ ...plan,
+ bomLinesByElementId: Object.fromEntries(
+ Object.entries(bomLinesByElementId).map(([bomKey, lines]) => [
+ bomKey,
+ lines ? withoutProperties(lines) : null
+ ])
+ )
+ };
+ const saved = await createPanelPlan({ companyId, userId, plan: stored });
+ if (!saved) {
+ return data(
+ { error: "Carbon couldn't save this review. Try again." },
+ { status: 503 }
+ );
+ }
+
+ return data(
+ { planId: saved.planId, expiresAt: saved.expiresAt, plan, warnings },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.push-assembly.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.push-assembly.ts
new file mode 100644
index 0000000000..12eccb5dbe
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.push-assembly.ts
@@ -0,0 +1,1180 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database, Json } from "@carbon/database";
+import type {
+ ItemEdit,
+ ItemFieldSnapshot,
+ MappedRowPlan,
+ OnshapeBomNode,
+ OwnedFieldChange,
+ ProposedItem
+} from "@carbon/ee";
+import {
+ bomLineItemType,
+ createdItemExtras,
+ defaultUnitOfMeasureCode,
+ externalIdForAssembly,
+ externalIdForBomLine,
+ flattenNodes,
+ mappedFieldValues,
+ mergeCustomFieldValues,
+ mergeEditsForCreates,
+ normalizeConfiguration,
+ pickReuseRow,
+ proposeItem
+} from "@carbon/ee";
+import type { ManualLineRow, MappedLineRow } from "@carbon/ee/onshape";
+import {
+ chunkFilterValues,
+ loadActiveMakeMethods,
+ loadMethodLineOwnership,
+ loadReusableDrafts,
+ ONSHAPE_V2_INTEGRATION_ID,
+ peekPanelPlan,
+ selectInBatches,
+ takePanelPlan
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { trigger } from "@carbon/jobs";
+import { datetime } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import { upsertPart } from "~/modules/items";
+import {
+ ensureDraftMakeMethod,
+ loadMethodWriteRefusals
+} from "~/modules/settings/onshape-draft-method.server";
+import {
+ applyExistingItemFields,
+ applyItemFieldWrites,
+ claimManualMethodLine,
+ insertOwnedMethodLines,
+ type OwnedMethodLine,
+ swapItemMapping
+} from "~/modules/settings/onshape-push.server";
+import { getDatabaseClient } from "~/services/database.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+// Shape only: `mergeItemEdits` validates values, so a bad one is a 422 naming the row.
+const itemEditSchema = z.object({
+ name: z.string().optional(),
+ description: z.string().nullable().optional(),
+ replenishmentSystem: z.string().optional(),
+ defaultMethodType: z.string().optional(),
+ itemTrackingType: z.string().optional(),
+ unitOfMeasureCode: z.string().optional()
+});
+
+const payloadSchema = z.object({
+ planId: z.string().min(1),
+ edits: z.record(z.string(), itemEditSchema).default({}),
+ excluded: z.array(z.string().min(1)).default([])
+});
+
+type PushSummary = {
+ assemblyItemId: string | null;
+ itemsCreated: number;
+ itemsReused: number;
+ linesWritten: number;
+ linesUnchanged: number;
+ /** Manual lines now following Onshape; also counted in `linesWritten`. */
+ linesTakenOver: number;
+ descriptionsUpdated: number;
+ /** Reused items whose mapped fields this push wrote. */
+ fieldsUpdated: number;
+ methodsTouched: number;
+ /** Parent part numbers whose BOM went into a new Draft. */
+ draftVersionsCreated: string[];
+ skipped: string[];
+ errors: string[];
+};
+
+type ItemRow = {
+ id: string;
+ readableId: string;
+ revision: string | null;
+ /** Absent on an item this push created (Design). */
+ revisionStatus?: Database["public"]["Enums"]["itemRevisionStatus"] | null;
+ active?: boolean | null;
+ type: string | null;
+ defaultMethodType: string | null;
+ sourcingType: string | null;
+ unitOfMeasureCode: string | null;
+};
+
+/** Apply a reviewed assembly plan: items, BOM lines per method, links, model export. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts",
+ // Re-pushing replaces the BOM lines an earlier push wrote.
+ delete: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid push payload" }, { status: 400 });
+ }
+ const { planId } = parsed.data;
+ const edits = parsed.data.edits as Record<string, ItemEdit>;
+ const excluded = new Set(parsed.data.excluded);
+
+ // Peek, not take: a 422 on the edits leaves the plan for a retry.
+ const stored = await peekPanelPlan(planId, { companyId, userId });
+ if (!stored) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+ if (stored.plan.kind !== "assembly") {
+ return data(
+ { error: "This review is not an assembly push" },
+ { status: 400 }
+ );
+ }
+ const plan = stored.plan;
+ const { documentId, wv, wvId, elementId, root, options } = plan;
+ const configuration = plan.configuration ?? null;
+
+ if (excluded.has(root.partNumber)) {
+ return data(
+ { error: "The assembly itself cannot be excluded" },
+ { status: 400 }
+ );
+ }
+
+ const creates: Array<{ key: string; proposed: ProposedItem }> = [];
+ if (root.action === "create" && root.proposed) {
+ creates.push({ key: root.partNumber, proposed: root.proposed });
+ }
+ for (const item of plan.items) {
+ if (
+ item.action === "create" &&
+ item.proposed &&
+ !excluded.has(item.partNumber)
+ ) {
+ creates.push({ key: item.partNumber, proposed: item.proposed });
+ }
+ }
+ const merged = mergeEditsForCreates(creates, edits, options);
+ if (merged.errors.length > 0) {
+ return data(
+ { error: "Some edits are not valid", fieldErrors: merged.errors },
+ { status: 422 }
+ );
+ }
+
+ if (!(await takePanelPlan(planId, { companyId, userId }))) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+
+ const summary: PushSummary = {
+ assemblyItemId: null,
+ itemsCreated: 0,
+ itemsReused: 0,
+ linesWritten: 0,
+ linesUnchanged: 0,
+ linesTakenOver: 0,
+ descriptionsUpdated: 0,
+ fieldsUpdated: 0,
+ methodsTouched: 0,
+ draftVersionsCreated: [],
+ skipped: [...plan.skipped],
+ errors: []
+ };
+ for (const item of plan.items) {
+ if (excluded.has(item.partNumber)) {
+ summary.skipped.push(`${item.partNumber}: excluded`);
+ }
+ }
+
+ const includedItems = plan.items.filter(
+ (item) => !excluded.has(item.partNumber)
+ );
+ const partNumbers = [
+ ...new Set([root.partNumber, ...includedItems.map((i) => i.partNumber)])
+ ];
+ const existing = await selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select(
+ "id, readableId, revision, revisionStatus, active, type, defaultMethodType, sourcingType, unitOfMeasureCode"
+ )
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ );
+ if (existing.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const rowsByReadableId = new Map<string, ItemRow[]>();
+ for (const row of (existing.data ?? []) as ItemRow[]) {
+ const list = rowsByReadableId.get(row.readableId) ?? [];
+ list.push(row);
+ rowsByReadableId.set(row.readableId, list);
+ }
+
+ // A reuse whose row vanished becomes a create, described from the BOM row.
+ const allNodes = flattenNodes(plan.nodes);
+ const nodeByPartNumber = new Map<string, OnshapeBomNode>();
+ for (const node of allNodes) {
+ if (node.partNumber && !nodeByPartNumber.has(node.partNumber)) {
+ nodeByPartNumber.set(node.partNumber, node);
+ }
+ }
+
+ const itemByReadableId = new Map<string, ItemRow>();
+ const fallbackUnit = defaultUnitOfMeasureCode(options);
+
+ const serviceRole = getCarbonServiceRole();
+ const db = getDatabaseClient();
+
+ type PlannedItem = MappedRowPlan & {
+ itemId: string | null;
+ current?: ItemFieldSnapshot | null;
+ changes?: OwnedFieldChange[];
+ };
+
+ const customFieldReadIds = [root, ...includedItems]
+ .filter(
+ (row) =>
+ row.action === "reuse" &&
+ mappedFieldValues(row.customFields ?? [], false).fieldIds.size > 0
+ )
+ .map((row) => row.partNumber);
+ const heldParts = await selectInBatches(customFieldReadIds, (batch) =>
+ client
+ .from("part")
+ .select("id, customFields")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (heldParts.error) {
+ return data({ error: "Failed to read Carbon parts" }, { status: 500 });
+ }
+ const heldCustomFields = new Map<string, unknown>(
+ (heldParts.data ?? []).map((part) => [part.id, part.customFields])
+ );
+
+ const ensureItem = async (
+ partNumber: string,
+ planned: PlannedItem,
+ propose: () => ProposedItem
+ ): Promise<ItemRow | null> => {
+ const rows = rowsByReadableId.get(partNumber) ?? [];
+ const found =
+ rows.find((row) => row.id === planned.itemId) ??
+ pickReuseRow(rows) ??
+ null;
+ if (found) {
+ summary.itemsReused += 1;
+ if (planned.itemId === null) {
+ summary.skipped.push(
+ `${partNumber}: added to Carbon since the review; reused as is`
+ );
+ }
+ // Only the row the review was about takes its values and edits.
+ if (planned.itemId !== found.id) {
+ itemByReadableId.set(partNumber, found);
+ return found;
+ }
+ const applied = await applyExistingItemFields(client, db, {
+ itemId: found.id,
+ companyId,
+ userId,
+ current: planned.current,
+ target: planned.target,
+ edit: edits[partNumber],
+ descriptions: planned.changes
+ });
+ let fieldsWritten = false;
+ if (applied.error) {
+ summary.errors.push(`${partNumber}: ${applied.error}`);
+ } else {
+ if (planned.changes?.length) summary.descriptionsUpdated += 1;
+ fieldsWritten = (planned.itemFieldChanges?.length ?? 0) > 0;
+ }
+ const values = mappedFieldValues(planned.customFields ?? [], false);
+ if (values.fieldIds.size > 0) {
+ const updatedPart = await client
+ .from("part")
+ .update({
+ customFields: mergeCustomFieldValues(
+ heldCustomFields.get(partNumber),
+ values.values,
+ values.fieldIds
+ ) as Json,
+ updatedAt: datetime.timestamp(),
+ updatedBy: userId
+ })
+ .eq("id", partNumber)
+ .eq("companyId", companyId);
+ if (updatedPart.error) {
+ summary.errors.push(
+ `${partNumber}: failed to write custom fields (${updatedPart.error.message})`
+ );
+ } else {
+ fieldsWritten = true;
+ }
+ }
+ if (fieldsWritten) summary.fieldsUpdated += 1;
+ const row: ItemRow = applied.values
+ ? {
+ ...found,
+ defaultMethodType: applied.values.defaultMethodType,
+ sourcingType: applied.values.sourcingType ?? found.sourcingType,
+ unitOfMeasureCode:
+ applied.values.unitOfMeasureCode ?? found.unitOfMeasureCode
+ }
+ : found;
+ itemByReadableId.set(partNumber, row);
+ return row;
+ }
+
+ const item = merged.items.get(partNumber) ?? propose();
+ const customFields = mappedFieldValues(
+ planned.customFields ?? [],
+ true
+ ).values;
+ const created = await upsertPart(client, {
+ id: item.readableId,
+ name: item.name,
+ description: item.description ?? undefined,
+ revision: item.revision,
+ replenishmentSystem: item.replenishmentSystem,
+ defaultMethodType: item.defaultMethodType,
+ itemTrackingType: item.itemTrackingType,
+ unitOfMeasureCode: item.unitOfMeasureCode,
+ ...(Object.keys(customFields).length > 0
+ ? { customFields: customFields as Json }
+ : {}),
+ companyId,
+ createdBy: userId
+ } as any);
+ if (created.error || !created.data) {
+ summary.errors.push(
+ `${partNumber}: ${created.error?.message ?? "failed to create"}`
+ );
+ return null;
+ }
+ const row: ItemRow = {
+ id: created.data.id as string,
+ readableId: partNumber,
+ revision: item.revision,
+ type: "Part",
+ defaultMethodType: item.defaultMethodType,
+ sourcingType: item.sourcingType ?? null,
+ unitOfMeasureCode: item.unitOfMeasureCode
+ };
+ const extras = createdItemExtras(item);
+ if (Object.keys(extras).length > 0) {
+ const error = await applyItemFieldWrites(client, db, {
+ itemId: row.id,
+ companyId,
+ userId,
+ changed: extras
+ });
+ if (error) {
+ summary.errors.push(
+ `${partNumber}: created, but its mapped fields were not written (${error})`
+ );
+ }
+ }
+ itemByReadableId.set(partNumber, row);
+ summary.itemsCreated += 1;
+ return row;
+ };
+
+ const rootItem = await ensureItem(root.partNumber, root, () =>
+ proposeItem(
+ {
+ partNumber: root.partNumber,
+ name: root.name,
+ description: root.description,
+ revision: root.revision
+ },
+ options
+ )
+ );
+ if (!rootItem) {
+ return data(
+ { error: summary.errors.join("; ") || "Failed to create the assembly" },
+ { status: 500 }
+ );
+ }
+ summary.assemblyItemId = rootItem.id;
+
+ for (const item of includedItems) {
+ await ensureItem(item.partNumber, item, () =>
+ proposeItem(
+ {
+ partNumber: item.partNumber,
+ name: item.name,
+ description: nodeByPartNumber.get(item.partNumber)?.description,
+ revision: item.revision,
+ hasChildren: item.isAssembly
+ },
+ options
+ )
+ );
+ }
+
+ const isAssemblyByPartNumber = new Map(
+ plan.items.map((item) => [item.partNumber, item.isAssembly])
+ );
+
+ // Every sub-assembly, even one this push writes no lines into: its parent's line
+ // points at its method, and a null pointer flattens a `top` push's tree.
+ const parentItemIds = [
+ ...new Set(
+ [
+ ...plan.methods.map(
+ (method) => itemByReadableId.get(method.parentPartNumber)?.id
+ ),
+ ...plan.items
+ .filter((item) => item.isAssembly)
+ .map((item) => itemByReadableId.get(item.partNumber)?.id)
+ ].filter((id): id is string => !!id)
+ )
+ ];
+ // A failed read must stop the writes, or a `top` push writes null child pointers.
+ let methodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;
+ try {
+ methodByItemId = await loadActiveMakeMethods(
+ client,
+ companyId,
+ parentItemIds
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the make methods"
+ },
+ { status: 500 }
+ );
+ }
+ // A Make to Order line points at its component's make method, as the BOM
+ // editor does; this reads it for made parts that are not sub-assemblies.
+ const madePartIds = [
+ ...new Set(
+ plan.items
+ .filter((item) => !item.isAssembly && !excluded.has(item.partNumber))
+ .map((item) => itemByReadableId.get(item.partNumber))
+ .filter(
+ (row): row is ItemRow =>
+ !!row &&
+ row.defaultMethodType === "Make to Order" &&
+ !methodByItemId.has(row.id)
+ )
+ .map((row) => row.id)
+ )
+ ];
+ let madePartMethodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;
+ try {
+ madePartMethodByItemId = await loadActiveMakeMethods(
+ client,
+ companyId,
+ madePartIds
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the make methods"
+ },
+ { status: 500 }
+ );
+ }
+ const childMethodFor = (childItem: ItemRow, childMade: boolean) =>
+ childMade
+ ? methodByItemId.get(childItem.id)
+ : childItem.defaultMethodType === "Make to Order"
+ ? (madePartMethodByItemId.get(childItem.id) ??
+ methodByItemId.get(childItem.id))
+ : null;
+
+ // Not written: a change notice's Draft, or a released revision under
+ // `enforce`. Rechecked here; the plan only listed them.
+ const refusalByItemId = await loadMethodWriteRefusals(
+ client,
+ companyId,
+ plan.methods.flatMap((planned) => {
+ const parentItem = itemByReadableId.get(planned.parentPartNumber);
+ const method = parentItem ? methodByItemId.get(parentItem.id) : undefined;
+ return parentItem && method
+ ? [
+ {
+ itemId: parentItem.id,
+ method,
+ revisionStatus: parentItem.revisionStatus
+ }
+ ]
+ : [];
+ })
+ );
+
+ // An Active method is written through a Draft, made before ownership is read:
+ // ownership is keyed by method id, so a later Draft's lines would read as manual.
+ const targetMethodByItemId = new Map<string, string>();
+ const methodErrorByItemId = new Map<string, string>();
+ const activeMethodIdByItemId = new Map<string, string>();
+ for (const planned of plan.methods) {
+ const parentItem = itemByReadableId.get(planned.parentPartNumber);
+ const method = parentItem ? methodByItemId.get(parentItem.id) : undefined;
+ if (parentItem && method?.status === "Active") {
+ activeMethodIdByItemId.set(parentItem.id, method.id);
+ }
+ }
+ let reusableDraftByItemId: Awaited<ReturnType<typeof loadReusableDrafts>>;
+ try {
+ reusableDraftByItemId = await loadReusableDrafts(
+ client,
+ serviceRole,
+ companyId,
+ activeMethodIdByItemId
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error ? error.message : "Failed to read the Drafts"
+ },
+ { status: 500 }
+ );
+ }
+ // An Active method whose Onshape lines already match gets no Draft. The
+ // check pairs lines as the write loop does.
+ let activeOwnership: Awaited<ReturnType<typeof loadMethodLineOwnership>>;
+ try {
+ activeOwnership = await loadMethodLineOwnership(
+ client,
+ serviceRole,
+ companyId,
+ [...activeMethodIdByItemId.entries()]
+ .filter(([itemId]) => !reusableDraftByItemId.has(itemId))
+ .map(([, methodId]) => methodId)
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the existing BOM lines"
+ },
+ { status: 500 }
+ );
+ }
+ const linesWouldChange = (
+ planned: (typeof plan.methods)[number],
+ methodId: string
+ ) => {
+ const reusable = new Map<string, MappedLineRow[]>();
+ for (const row of activeOwnership.mappedRows.get(methodId) ?? []) {
+ const queue = reusable.get(row.itemId) ?? [];
+ queue.push(row);
+ reusable.set(row.itemId, queue);
+ }
+ let order = 0;
+ for (const write of planned.writes) {
+ if (excluded.has(write.partNumber)) continue;
+ const childItem = itemByReadableId.get(write.partNumber);
+ if (!childItem || !bomLineItemType(childItem)) continue;
+ const childMethod = childMethodFor(
+ childItem,
+ isAssemblyByPartNumber.get(write.partNumber) === true
+ );
+ const reuse = reusable.get(childItem.id)?.shift();
+ if (!reuse) return true;
+ if (
+ reuse.quantity !== write.quantity ||
+ reuse.order !== order ||
+ reuse.materialMakeMethodId !== (childMethod?.id ?? null)
+ ) {
+ return true;
+ }
+ order += 1;
+ }
+ // A leftover line would be removed.
+ return [...reusable.values()].some((queue) => queue.length > 0);
+ };
+ const unchangedItemIds = new Set<string>();
+
+ for (const planned of plan.methods) {
+ const parentItem = itemByReadableId.get(planned.parentPartNumber);
+ if (!parentItem) continue;
+ if (
+ targetMethodByItemId.has(parentItem.id) ||
+ unchangedItemIds.has(parentItem.id)
+ ) {
+ continue;
+ }
+ const method = methodByItemId.get(parentItem.id);
+ if (!method) continue; // reported in the write loop
+ if (method.status !== "Active") {
+ if (!refusalByItemId.has(parentItem.id)) {
+ targetMethodByItemId.set(parentItem.id, method.id);
+ }
+ continue;
+ }
+ if (
+ !reusableDraftByItemId.has(parentItem.id) &&
+ !linesWouldChange(planned, method.id)
+ ) {
+ unchangedItemIds.add(parentItem.id);
+ continue;
+ }
+ // Checked before a Draft is made, so a refusal leaves no Draft behind.
+ if (refusalByItemId.has(parentItem.id)) continue;
+ const draft = await ensureDraftMakeMethod(client, {
+ itemId: parentItem.id,
+ activeMethodId: method.id,
+ companyId,
+ userId,
+ reusableDraft: reusableDraftByItemId.get(parentItem.id) ?? null
+ });
+ if (!draft.ok) {
+ methodErrorByItemId.set(parentItem.id, draft.error);
+ continue;
+ }
+ targetMethodByItemId.set(parentItem.id, draft.id);
+ if (draft.created) {
+ summary.draftVersionsCreated.push(
+ draft.version === null
+ ? planned.parentPartNumber
+ : `${planned.parentPartNumber} (version ${draft.version})`
+ );
+ }
+ }
+
+ // A failed read must stop the writes, or every Onshape line is duplicated.
+ let ownership: Awaited<ReturnType<typeof loadMethodLineOwnership>>;
+ try {
+ ownership = await loadMethodLineOwnership(client, serviceRole, companyId, [
+ ...new Set([
+ ...[...methodByItemId.values()].map((method) => method.id),
+ ...targetMethodByItemId.values()
+ ])
+ ]);
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the existing BOM lines"
+ },
+ { status: 500 }
+ );
+ }
+
+ for (const planned of plan.methods) {
+ const parentLabel = planned.parentPartNumber;
+ const parentItem = itemByReadableId.get(planned.parentPartNumber);
+ if (!parentItem) continue;
+
+ const method = methodByItemId.get(parentItem.id);
+ if (!method) {
+ summary.errors.push(`${parentLabel}: no make method found`);
+ continue;
+ }
+ if (unchangedItemIds.has(parentItem.id)) {
+ summary.linesUnchanged += planned.writes.filter(
+ (write) => !excluded.has(write.partNumber)
+ ).length;
+ continue;
+ }
+ const refusal = refusalByItemId.get(parentItem.id);
+ if (refusal) {
+ summary.skipped.push(`${parentLabel}: ${refusal}`);
+ continue;
+ }
+ const methodId = targetMethodByItemId.get(parentItem.id);
+ if (!methodId) {
+ summary.errors.push(
+ `${parentLabel}: ${methodErrorByItemId.get(parentItem.id) ?? "no make method to write to"}`
+ );
+ continue;
+ }
+
+ // Owned lines are updated in place so Carbon's columns (operation, scrap,
+ // tags, kit, customFields) survive; FIFO per item keeps a repeated component's lines.
+ const reusableByItemId = new Map<string, MappedLineRow[]>();
+ for (const row of ownership.mappedRows.get(methodId) ?? []) {
+ const queue = reusableByItemId.get(row.itemId) ?? [];
+ queue.push(row);
+ reusableByItemId.set(row.itemId, queue);
+ }
+ // Manual lines pair by part number in line order, as `pairManualLines` does at plan.
+ const manualByReadableId = new Map<string, ManualLineRow[]>();
+ for (const row of ownership.manualRows.get(methodId) ?? []) {
+ const queue = manualByReadableId.get(row.readableId) ?? [];
+ queue.push(row);
+ manualByReadableId.set(row.readableId, queue);
+ }
+ // Mapping rows this method still owns; any other is cleared as an orphan.
+ const liveMappingIds: string[] = [];
+ const pendingInserts: Array<{
+ row: OwnedMethodLine["row"];
+ metadata: Record<string, unknown>;
+ }> = [];
+
+ summary.methodsTouched += 1;
+
+ let order = 0;
+ for (const write of planned.writes) {
+ if (excluded.has(write.partNumber)) continue;
+ const childItem = itemByReadableId.get(write.partNumber);
+ if (!childItem) continue;
+
+ const itemType = bomLineItemType(childItem);
+ if (!itemType) {
+ summary.errors.push(
+ `${parentLabel} → ${write.partNumber}: a ${childItem.type ?? "Part"} cannot be a BOM line`
+ );
+ continue;
+ }
+
+ const childMade = isAssemblyByPartNumber.get(write.partNumber) === true;
+ const childMethod = childMethodFor(childItem, childMade);
+ const lineSyncedAt = datetime.timestamp();
+ const lineMetadata = {
+ makeMethodId: methodId,
+ documentId,
+ elementId,
+ partNumber: write.partNumber,
+ index: write.index
+ };
+
+ // Onshape owns quantity, order and the child-method pointer; method type,
+ // sourcing and unit come from the item, at insert only.
+ const reuse = reusableByItemId.get(childItem.id)?.shift();
+ if (reuse) {
+ // Unchanged lines are not written, so the audit log shows no edit.
+ const unchanged =
+ reuse.quantity === write.quantity &&
+ reuse.order === order &&
+ reuse.materialMakeMethodId === (childMethod?.id ?? null);
+ if (unchanged) {
+ liveMappingIds.push(reuse.mappingId);
+ order += 1;
+ summary.linesUnchanged += 1;
+ continue;
+ }
+ const updated = await client
+ .from("methodMaterial")
+ .update({
+ quantity: write.quantity,
+ materialMakeMethodId: childMethod?.id ?? null,
+ order,
+ updatedBy: userId,
+ updatedAt: lineSyncedAt
+ })
+ .eq("id", reuse.lineId)
+ .eq("companyId", companyId);
+ if (updated.error) {
+ summary.errors.push(
+ `${parentLabel} → ${write.partNumber}: ${updated.error.message}`
+ );
+ // Keep its ownership row, or the next push reads it as manual.
+ liveMappingIds.push(reuse.mappingId);
+ order += 1;
+ continue;
+ }
+ const remapped = await serviceRole
+ .from("externalIntegrationMapping")
+ .update({
+ metadata: lineMetadata,
+ lastSyncedAt: lineSyncedAt,
+ updatedBy: userId,
+ updatedAt: lineSyncedAt
+ })
+ .eq("id", reuse.mappingId)
+ .eq("companyId", companyId);
+ if (remapped.error) {
+ summary.errors.push(
+ `${parentLabel} → ${write.partNumber}: line updated but its Onshape link was not refreshed (${remapped.error.message})`
+ );
+ }
+ liveMappingIds.push(reuse.mappingId);
+ order += 1;
+ summary.linesWritten += 1;
+ continue;
+ }
+
+ // Same item type only: a Material sharing a Part's number is a different item.
+ const queue = manualByReadableId.get(write.partNumber);
+ const claimIndex =
+ queue?.findIndex((row) => !row.itemType || row.itemType === itemType) ??
+ -1;
+ const claim =
+ queue && claimIndex >= 0 ? queue.splice(claimIndex, 1)[0] : undefined;
+ if (claim) {
+ const claimed = await claimManualMethodLine(db, {
+ companyId,
+ userId,
+ lineId: claim.lineId,
+ update: {
+ itemId: childItem.id,
+ quantity: write.quantity,
+ order,
+ materialMakeMethodId: childMethod?.id ?? null
+ },
+ metadata: lineMetadata
+ });
+ if (claimed.error !== null) {
+ summary.errors.push(
+ `${parentLabel} → ${write.partNumber}: the line added by hand was not taken over (${claimed.error})`
+ );
+ continue;
+ }
+ liveMappingIds.push(claimed.mappingId);
+ order += 1;
+ summary.linesWritten += 1;
+ summary.linesTakenOver += 1;
+ continue;
+ }
+
+ pendingInserts.push({
+ row: {
+ itemId: childItem.id,
+ quantity: write.quantity,
+ makeMethodId: methodId,
+ materialMakeMethodId: childMethod?.id ?? null,
+ methodType:
+ (childItem.defaultMethodType as OwnedMethodLine["row"]["methodType"]) ??
+ (childMade ? "Make to Order" : "Pull from Inventory"),
+ sourcingType:
+ (childItem.sourcingType as OwnedMethodLine["row"]["sourcingType"]) ??
+ "Specified",
+ order,
+ itemType,
+ unitOfMeasureCode: childItem.unitOfMeasureCode ?? fallbackUnit
+ },
+ metadata: lineMetadata
+ });
+ order += 1;
+ }
+
+ if (pendingInserts.length > 0) {
+ const written = await insertOwnedMethodLines(db, {
+ companyId,
+ userId,
+ lines: pendingInserts.map((pending) => ({
+ row: pending.row,
+ metadata: pending.metadata
+ }))
+ });
+ if (written.error !== null) {
+ summary.errors.push(
+ `${parentLabel}: ${pendingInserts.length} new lines were not written (${written.error})`
+ );
+ } else {
+ summary.linesWritten += pendingInserts.length;
+ liveMappingIds.push(...written.mappingIds);
+ }
+ }
+
+ // Anything still queued is a component the Onshape BOM no longer has.
+ const removed = [...reusableByItemId.values()].flat();
+ if (removed.length > 0) {
+ for (const batch of chunkFilterValues(removed.map((row) => row.lineId))) {
+ const removedLines = await client
+ .from("methodMaterial")
+ .delete()
+ .eq("companyId", companyId)
+ .in("id", batch);
+ if (removedLines.error) {
+ summary.errors.push(
+ `${parentLabel}: could not remove the lines Onshape no longer lists (${removedLines.error.message})`
+ );
+ const failed = new Set(batch);
+ for (const row of removed) {
+ if (failed.has(row.lineId)) liveMappingIds.push(row.mappingId);
+ }
+ }
+ }
+ }
+
+ // Orphans are filtered here: a `not in` filter puts every live id in the URL.
+ const methodMappings = await serviceRole
+ .from("externalIntegrationMapping")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .eq("metadata->>makeMethodId", methodId);
+ if (methodMappings.error) {
+ summary.errors.push(
+ `${parentLabel}: could not read the existing line ownership records (${methodMappings.error.message})`
+ );
+ } else {
+ const live = new Set(liveMappingIds);
+ const orphaned = (methodMappings.data ?? [])
+ .map((row) => row.id)
+ .filter((id) => !live.has(id));
+ for (const batch of chunkFilterValues(orphaned)) {
+ const clearedMappings = await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("companyId", companyId)
+ .in("id", batch);
+ if (clearedMappings.error) {
+ summary.errors.push(
+ `${parentLabel}: could not clear orphaned line ownership records (${clearedMappings.error.message})`
+ );
+ }
+ }
+ }
+ }
+
+ // A root released in Carbon keeps the link and model its release gave it.
+ if (root.released) {
+ summary.skipped.push(
+ `${root.partNumber}: released in Carbon as Rev ${root.released.revision}; its fields, link and model stay as its release left them`
+ );
+ const childLinkProblems = await linkChildParts(client, serviceRole, {
+ companyId,
+ userId,
+ nodes: allNodes,
+ itemByReadableId
+ });
+ summary.errors.push(...childLinkProblems);
+ return data({ summary }, { headers: { "Cache-Control": "no-store" } });
+ }
+ const pushedAt = datetime.timestamp();
+ const assemblyExternalId = externalIdForAssembly(
+ documentId,
+ elementId,
+ configuration
+ );
+ const assemblyMapping = await swapItemMapping(db, {
+ companyId,
+ userId,
+ itemId: rootItem.id,
+ externalId: assemblyExternalId,
+ metadata: {
+ documentId,
+ elementId,
+ configuration,
+ wv,
+ wvId,
+ kind: "assembly",
+ partNumber: root.partNumber,
+ name: root.name,
+ pushedBy: userId,
+ pushedAt,
+ planId
+ }
+ });
+ if (assemblyMapping.error !== null) {
+ summary.errors.push(
+ `${root.partNumber}: pushed, but not linked to Onshape (${assemblyMapping.error}); the next push will not recognise it`
+ );
+ }
+
+ const childLinkProblems = await linkChildParts(client, serviceRole, {
+ companyId,
+ userId,
+ nodes: allNodes,
+ itemByReadableId
+ });
+ summary.errors.push(...childLinkProblems);
+
+ try {
+ await trigger(
+ "onshape-panel-sync",
+ {
+ companyId,
+ userId,
+ itemId: rootItem.id,
+ documentId,
+ wvm: wv,
+ wvmId: wvId,
+ elementId,
+ elementKind: "assembly",
+ ...(configuration ? { configuration } : {}),
+ assetBaseName: root.partNumber
+ },
+ { id: `${planId}:${rootItem.id}:${elementId}` }
+ );
+ } catch {
+ summary.errors.push(
+ `${root.partNumber}: pushed, but the model export couldn't be queued. Push again to retry the export.`
+ );
+ }
+
+ return data({ summary }, { headers: { "Cache-Control": "no-store" } });
+}
+
+async function linkChildParts(
+ client: SupabaseClient<Database>,
+ serviceRole: SupabaseClient<Database>,
+ input: {
+ companyId: string;
+ userId: string;
+ nodes: OnshapeBomNode[];
+ itemByReadableId: Map<string, { id: string; readableId: string }>;
+ }
+) {
+ // Links only where neither the item nor the source is linked: a part push owns that link.
+ const candidates: Array<{
+ itemId: string;
+ externalId: string;
+ partNumber: string;
+ source: NonNullable<OnshapeBomNode["itemSource"]>;
+ }> = [];
+ const seen = new Set<string>();
+ for (const node of input.nodes) {
+ const source = node.itemSource;
+ if (!node.partNumber) continue;
+ const externalId = externalIdForBomLine(source);
+ if (!source || !externalId) continue;
+ const item = input.itemByReadableId.get(node.partNumber);
+ if (!item || seen.has(item.id)) continue;
+ seen.add(item.id);
+ candidates.push({
+ itemId: item.id,
+ externalId,
+ partNumber: node.partNumber,
+ source
+ });
+ }
+ if (candidates.length === 0) return [];
+
+ // One Onshape source claimed by two items is reported, not guessed at.
+ const itemsByExternalId = new Map<string, Set<string>>();
+ for (const candidate of candidates) {
+ const items = itemsByExternalId.get(candidate.externalId) ?? new Set();
+ items.add(candidate.itemId);
+ itemsByExternalId.set(candidate.externalId, items);
+ }
+ const problems: string[] = [];
+ const ambiguous = new Set(
+ [...itemsByExternalId.entries()]
+ .filter(([, items]) => items.size > 1)
+ .map(([externalId]) => externalId)
+ );
+ for (const externalId of ambiguous) {
+ const numbers = candidates
+ .filter((candidate) => candidate.externalId === externalId)
+ .map((candidate) => candidate.partNumber);
+ problems.push(
+ `${numbers.join(" and ")} come from the same Onshape part, so neither was linked to it`
+ );
+ }
+ const unambiguous = candidates.filter(
+ (candidate) => !ambiguous.has(candidate.externalId)
+ );
+ if (unambiguous.length === 0) return problems;
+
+ const [byEntity, byExternal] = await Promise.all([
+ selectInBatches(
+ unambiguous.map((candidate) => candidate.itemId),
+ (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("companyId", input.companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("entityId", batch)
+ ),
+ selectInBatches(
+ unambiguous.map((candidate) => candidate.externalId),
+ (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("externalId")
+ .eq("companyId", input.companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("externalId", batch)
+ )
+ ]);
+ // A failed read is not "no links": that would claim links a part push owns.
+ if (byEntity.error || byExternal.error) {
+ return [
+ ...problems,
+ `child parts were not linked to Onshape: ${
+ (byEntity.error ?? byExternal.error)?.message ?? "lookup failed"
+ }`
+ ];
+ }
+ const linkedItemIds = new Set(
+ (byEntity.data ?? []).map((row) => row.entityId)
+ );
+ const usedExternalIds = new Set(
+ (byExternal.data ?? []).map((row) => row.externalId)
+ );
+
+ const linkedAt = datetime.timestamp();
+ const rows = unambiguous
+ .filter(
+ (candidate) =>
+ !linkedItemIds.has(candidate.itemId) &&
+ !usedExternalIds.has(candidate.externalId)
+ )
+ .map((candidate) => ({
+ entityType: "item" as const,
+ entityId: candidate.itemId,
+ integration: ONSHAPE_V2_INTEGRATION_ID,
+ externalId: candidate.externalId,
+ metadata: {
+ documentId: candidate.source.documentId,
+ elementId: candidate.source.elementId,
+ partId: candidate.source.partId ?? null,
+ configuration: normalizeConfiguration(candidate.source.configuration),
+ kind: candidate.source.partId ? "part" : "assembly",
+ partNumber: candidate.partNumber,
+ viaAssemblyPush: true,
+ pushedBy: input.userId,
+ pushedAt: linkedAt
+ },
+ lastSyncedAt: linkedAt,
+ companyId: input.companyId,
+ createdBy: input.userId
+ }));
+ if (rows.length === 0) return problems;
+
+ // The bulk insert is all-or-nothing; on refusal retry row by row, so one
+ // conflicting row (a concurrent push's link) does not block the rest.
+ const linked = await client.from("externalIntegrationMapping").insert(rows);
+ if (!linked.error) return problems;
+
+ const failed: string[] = [];
+ for (const row of rows) {
+ const single = await client.from("externalIntegrationMapping").insert(row);
+ if (single.error) failed.push(row.metadata.partNumber);
+ }
+ if (failed.length > 0) {
+ problems.push(
+ `${failed.length} part${failed.length === 1 ? "" : "s"} could not be linked to Onshape (${failed
+ .slice(0, 5)
+ .join(", ")}${failed.length > 5 ? ", …" : ""}); push again to retry`
+ );
+ }
+ return problems;
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.push-part.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.push-part.ts
new file mode 100644
index 0000000000..ebd36dd25f
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.push-part.ts
@@ -0,0 +1,535 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Json } from "@carbon/database";
+import type {
+ ItemEdit,
+ PartPlan,
+ PartPlanRow,
+ PlanItemRow,
+ ProposedItem
+} from "@carbon/ee";
+import {
+ createdItemExtras,
+ externalIdForPart,
+ mappedFieldValues,
+ mergeCustomFieldValues,
+ mergeEditsForCreates,
+ pickAdoptTarget,
+ proposeItem
+} from "@carbon/ee";
+import {
+ peekPanelPlan,
+ selectInBatches,
+ takePanelPlan
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { trigger } from "@carbon/jobs";
+import { datetime } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import { upsertPart } from "~/modules/items";
+import {
+ applyExistingItemFields,
+ applyItemFieldWrites,
+ swapItemMapping
+} from "~/modules/settings/onshape-push.server";
+import { getDatabaseClient } from "~/services/database.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const itemEditSchema = z.object({
+ name: z.string().optional(),
+ description: z.string().nullable().optional(),
+ replenishmentSystem: z.string().optional(),
+ defaultMethodType: z.string().optional(),
+ itemTrackingType: z.string().optional(),
+ unitOfMeasureCode: z.string().optional()
+});
+
+const payloadSchema = z.object({
+ planId: z.string().min(1),
+ selected: z.array(z.string().min(1)).min(1).max(50),
+ edits: z.record(z.string(), itemEditSchema).default({})
+});
+
+type ApplyResult = {
+ partId: string;
+ action: "created" | "adopted" | "updated" | "unchanged" | "skipped" | "error";
+ itemId?: string;
+ readableId?: string;
+ message?: string;
+};
+
+/** Apply a reviewed part plan: create or adopt items, link them, queue model exports. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid push payload" }, { status: 400 });
+ }
+ const { planId } = parsed.data;
+ const selected = [...new Set(parsed.data.selected)];
+ const edits = parsed.data.edits as Record<string, ItemEdit>;
+
+ const stored = await peekPanelPlan(planId, { companyId, userId });
+ if (!stored) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+ if (stored.plan.kind !== "part") {
+ return data({ error: "This review is not a part push" }, { status: 400 });
+ }
+ const plan: PartPlan = stored.plan;
+ const { documentId, wv, wvId, elementId, options } = plan;
+ const configuration = plan.configuration ?? null;
+
+ const rowByPartId = new Map(plan.rows.map((row) => [row.partId, row]));
+ const selectedRows = selected
+ .map((partId) => rowByPartId.get(partId))
+ .filter((row): row is PartPlanRow => !!row);
+
+ const merged = mergeEditsForCreates(
+ selectedRows
+ .filter((row) => row.action === "create" && row.partNumber)
+ .map((row) => ({ key: row.partId, proposed: proposedFor(row, plan) })),
+ edits,
+ options
+ );
+ const fieldErrors = merged.errors;
+ if (fieldErrors.length > 0) {
+ return data(
+ { error: "Some edits are not valid", fieldErrors },
+ { status: 422 }
+ );
+ }
+
+ if (!(await takePanelPlan(planId, { companyId, userId }))) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+
+ // A create whose number now exists adopts it: `upsertPart` reads its new id
+ // back by readableId and could get another revision.
+ const partNumbers = [
+ ...new Set(
+ selectedRows
+ .map((row) => row.partNumber)
+ .filter((number): number is string => !!number)
+ )
+ ];
+ const targetItemIds = [
+ ...new Set(
+ selectedRows
+ .filter((row) => row.action === "adopt" || row.action === "update")
+ .map((row) => row.itemId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+ const [byNumber, byId] = await Promise.all([
+ selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, active, name, type")
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ ),
+ selectInBatches(targetItemIds, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, active, name, type")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ )
+ ]);
+ if (byNumber.error || byId.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const rowsByReadableId = new Map<string, PlanItemRow[]>();
+ for (const item of (byNumber.data ?? []) as PlanItemRow[]) {
+ const list = rowsByReadableId.get(item.readableId) ?? [];
+ list.push(item);
+ rowsByReadableId.set(item.readableId, list);
+ }
+ const itemById = new Map(
+ ((byId.data ?? []) as PlanItemRow[]).map((item) => [item.id, item])
+ );
+
+ const serviceRole = getCarbonServiceRole();
+ const db = getDatabaseClient();
+
+ const resolveTarget = (row: PartPlanRow): PlanItemRow | undefined => {
+ let target: PlanItemRow | undefined;
+ if (row.action === "adopt" || row.action === "update") {
+ target = row.itemId ? itemById.get(row.itemId) : undefined;
+ }
+ if (!target && row.partNumber) {
+ target = pickAdoptTarget(
+ rowsByReadableId.get(row.partNumber) ?? [],
+ row.revision
+ );
+ }
+ return target;
+ };
+
+ // `part.id` is the readableId, shared across revisions. Kept current as the
+ // loop writes, so a later row cannot clobber a create.
+ const partCustomFieldsByReadableId = new Map<string, unknown>();
+ const ownedReadableIds = [
+ ...new Set(
+ selectedRows.flatMap((row) => {
+ if (existingCustomFieldValues(row) === null) return [];
+ const ids: string[] = [];
+ if (row.partNumber) ids.push(row.partNumber);
+ const target = row.itemId ? itemById.get(row.itemId) : undefined;
+ if (target) ids.push(target.readableId);
+ return ids;
+ })
+ )
+ ];
+ const partRows = await selectInBatches(ownedReadableIds, (batch) =>
+ client
+ .from("part")
+ .select("id, customFields")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (partRows.error) {
+ return data({ error: "Failed to read Carbon parts" }, { status: 500 });
+ }
+ for (const partRow of partRows.data) {
+ partCustomFieldsByReadableId.set(partRow.id, partRow.customFields);
+ }
+
+ const results: ApplyResult[] = [];
+
+ for (const partId of selected) {
+ const row = rowByPartId.get(partId);
+ if (!row) {
+ results.push({
+ partId,
+ action: "error",
+ message: "Part is not in this review"
+ });
+ continue;
+ }
+
+ if (row.action === "skip-no-part-number") {
+ results.push({
+ partId,
+ action: "skipped",
+ message: "Set a part number in Onshape first"
+ });
+ continue;
+ }
+
+ if (row.action === "released") {
+ results.push({
+ partId,
+ action: "skipped",
+ message: `Released in Onshape as Rev ${row.item?.revision ?? "?"}: changes come through a release`
+ });
+ continue;
+ }
+
+ if (row.action === "unchanged") {
+ // A reviewer edit is still written; no link re-stamp, no export.
+ if (row.itemId && edits[partId]) {
+ const applied = await applyExistingItemFields(client, db, {
+ itemId: row.itemId,
+ companyId,
+ userId,
+ current: row.current,
+ edit: edits[partId]
+ });
+ if (applied.error) {
+ results.push({ partId, action: "error", message: applied.error });
+ continue;
+ }
+ results.push({
+ partId,
+ action: "updated",
+ itemId: row.itemId,
+ readableId: row.item?.readableId
+ });
+ continue;
+ }
+ results.push({
+ partId,
+ action: "unchanged",
+ itemId: row.itemId ?? undefined,
+ readableId: row.item?.readableId
+ });
+ continue;
+ }
+
+ const target = resolveTarget(row);
+ const resolved: "create" | "adopt" | "update" = target
+ ? row.action === "update" && target.id === row.itemId
+ ? "update"
+ : "adopt"
+ : "create";
+
+ let itemId: string;
+ let readableId: string;
+ if (resolved === "create") {
+ const item = merged.items.get(row.partId) ?? proposedFor(row, plan);
+ const fieldValues = planCustomFieldValues(row);
+ const created = await upsertPart(client, {
+ id: item.readableId,
+ name: item.name,
+ description: item.description ?? undefined,
+ revision: item.revision,
+ replenishmentSystem: item.replenishmentSystem,
+ defaultMethodType: item.defaultMethodType,
+ itemTrackingType: item.itemTrackingType,
+ unitOfMeasureCode: item.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ ...(Object.keys(fieldValues).length > 0 && {
+ customFields: fieldValues
+ })
+ // partValidator carries many optional form-only fields the panel never sets
+ } as any);
+ if (created.error || !created.data) {
+ results.push({
+ partId,
+ action: "error",
+ message: created.error?.message ?? "Failed to create the item"
+ });
+ continue;
+ }
+ itemId = created.data.id as string;
+ readableId = item.readableId;
+ const extras = createdItemExtras(item);
+ if (Object.keys(extras).length > 0) {
+ const error = await applyItemFieldWrites(client, db, {
+ itemId,
+ companyId,
+ userId,
+ changed: extras
+ });
+ if (error) {
+ results.push({
+ partId,
+ action: "error",
+ itemId,
+ readableId,
+ message: `Item created, but its mapped fields were not written (${error})`
+ });
+ continue;
+ }
+ }
+ // A later row with the same number adopts this item, not a second create.
+ rowsByReadableId.set(readableId, [
+ ...(rowsByReadableId.get(readableId) ?? []),
+ {
+ id: itemId,
+ readableId,
+ revision: item.revision,
+ name: item.name,
+ type: "Part"
+ }
+ ]);
+ if (Object.keys(fieldValues).length > 0) {
+ partCustomFieldsByReadableId.set(readableId, fieldValues);
+ }
+ } else {
+ itemId = (target as PlanItemRow).id;
+ readableId = (target as PlanItemRow).readableId;
+ const applied = await applyExistingItemFields(client, db, {
+ itemId,
+ companyId,
+ userId,
+ current: row.current,
+ target: row.target,
+ edit: edits[partId],
+ descriptions: row.changes
+ });
+ if (applied.error) {
+ results.push({ partId, action: "error", message: applied.error });
+ continue;
+ }
+ const owned = existingCustomFieldValues(row);
+ if (owned) {
+ const mergedFields = mergeCustomFieldValues(
+ partCustomFieldsByReadableId.get(readableId),
+ owned.values,
+ owned.fieldIds
+ );
+ const partUpdate = await client
+ .from("part")
+ .update({
+ customFields: mergedFields as Json,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", readableId)
+ .eq("companyId", companyId);
+ if (partUpdate.error) {
+ results.push({
+ partId,
+ action: "error",
+ message: partUpdate.error.message
+ });
+ continue;
+ }
+ partCustomFieldsByReadableId.set(readableId, mergedFields);
+ }
+ }
+
+ const externalId = externalIdForPart(
+ documentId,
+ elementId,
+ partId,
+ configuration
+ );
+ const now = datetime.timestamp();
+ const linked = await swapItemMapping(db, {
+ companyId,
+ userId,
+ itemId,
+ externalId,
+ metadata: {
+ documentId,
+ elementId,
+ partId,
+ configuration,
+ wv,
+ wvId,
+ // A later plan's only "unchanged" signal.
+ microversionId: row.microversionId,
+ partNumber: row.partNumber,
+ name: row.name,
+ revision: row.revision,
+ pushedBy: userId,
+ pushedAt: now,
+ planId
+ }
+ });
+ if (linked.error !== null) {
+ results.push({
+ partId,
+ action: "error",
+ message: "Item saved but the Onshape link failed; push again"
+ });
+ continue;
+ }
+
+ if (row.cadUnchanged && resolved === "update") {
+ results.push({ partId, action: "updated", itemId, readableId });
+ continue;
+ }
+
+ try {
+ await trigger(
+ "onshape-panel-sync",
+ {
+ companyId,
+ userId,
+ itemId,
+ documentId,
+ wvm: wv,
+ wvmId: wvId,
+ elementId,
+ elementKind: "partstudio",
+ partId,
+ ...(configuration ? { configuration } : {}),
+ ...(wv === "w" && row.microversionId
+ ? { microversionId: row.microversionId }
+ : {}),
+ assetBaseName: row.partNumber ?? row.name
+ },
+ { id: `${planId}:${itemId}:${elementId}` }
+ );
+ } catch (error) {
+ // Unlink so the next plan does not read "unchanged" and skip the export.
+ // By id, not externalId: a concurrent push may have replaced the row.
+ const rolledBack = await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("companyId", companyId)
+ .eq("id", linked.id);
+ results.push({
+ partId,
+ action: "error",
+ itemId,
+ readableId,
+ message: rolledBack.error
+ ? `Item saved but the model export could not be queued, and the Onshape link could not be rolled back (${rolledBack.error.message}); detach this item before pushing again`
+ : `Item saved but the model export could not be queued; push again (${
+ error instanceof Error ? error.message : "event send failed"
+ })`
+ });
+ continue;
+ }
+
+ results.push({
+ partId,
+ action:
+ resolved === "create"
+ ? "created"
+ : resolved === "adopt"
+ ? "adopted"
+ : "updated",
+ itemId,
+ readableId
+ });
+ }
+
+ return data(
+ { results },
+ {
+ headers: { "Cache-Control": "no-store" }
+ }
+ );
+}
+
+/** The plan's proposal, or one built from the row when the target vanished. */
+function proposedFor(row: PartPlanRow, plan: PartPlan): ProposedItem {
+ if (row.proposed) return row.proposed;
+ return proposeItem(
+ {
+ partNumber: row.partNumber as string,
+ name: row.name,
+ description: row.description,
+ revision: row.revision
+ },
+ plan.options
+ );
+}
+
+function planCustomFieldValues(
+ row: PartPlanRow
+): Record<string, string | number | boolean | null> {
+ return mappedFieldValues(row.customFields ?? [], true).values;
+}
+
+/** The "everyPush" values an adopt or update writes; a null value deletes the key. */
+function existingCustomFieldValues(row: PartPlanRow): {
+ values: Record<string, string | number | boolean | null>;
+ fieldIds: Set<string>;
+} | null {
+ if (row.action === "create") return null;
+ const mapped = mappedFieldValues(row.customFields ?? [], false);
+ return mapped.fieldIds.size > 0 ? mapped : null;
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.push-release.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.push-release.ts
new file mode 100644
index 0000000000..52dc645416
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.push-release.ts
@@ -0,0 +1,1376 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Json } from "@carbon/database";
+import type {
+ ItemEdit,
+ ItemFieldSnapshot,
+ MappedRowPlan,
+ OnshapeBomNode,
+ OwnedFieldChange,
+ PlanCustomField,
+ ProposedItem,
+ ReleasePlanItem
+} from "@carbon/ee";
+import {
+ bomLineItemType,
+ changeNoticeDescriptionJson,
+ createdItemExtras,
+ isModelReleaseItem,
+ mappedFieldValues,
+ mergeChangeNoticeEdit,
+ mergeCustomFieldValues,
+ mergeEditsForCreates,
+ pickBomChildRow,
+ pickRevisionBase,
+ proposeItem,
+ releaseBomKey
+} from "@carbon/ee";
+import type {
+ ReleaseExportSelection,
+ StoredReleasePlan
+} from "@carbon/ee/onshape";
+import {
+ chunkFilterValues,
+ loadActiveMakeMethods,
+ ONSHAPE_V2_INTEGRATION_ID,
+ peekPanelPlan,
+ releaseExportSelection,
+ selectInBatches,
+ takePanelPlan
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { trigger } from "@carbon/jobs";
+import { datetime } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+import {
+ createRevision,
+ deleteChangeNotice,
+ deleteItem,
+ type getItem,
+ insertChangeNotice,
+ updateDefaultRevision,
+ upsertPart
+} from "~/modules/items";
+import { requireChangeNoticeEditable } from "~/modules/items/items.server";
+import {
+ applyExistingItemFields,
+ applyItemFieldWrites,
+ findOpenReleaseNotice,
+ insertOwnedMethodLines,
+ type OwnedMethodLine,
+ stageChangeNoticeItem,
+ swapItemMapping
+} from "~/modules/settings/onshape-push.server";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import { getDatabaseClient } from "~/services/database.server";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const itemEditSchema = z.object({
+ name: z.string().optional(),
+ description: z.string().nullable().optional(),
+ replenishmentSystem: z.string().optional(),
+ defaultMethodType: z.string().optional(),
+ itemTrackingType: z.string().optional(),
+ unitOfMeasureCode: z.string().optional()
+});
+
+const payloadSchema = z.object({
+ planId: z.string().min(1),
+ edits: z.record(z.string(), itemEditSchema).default({}),
+ changeNotice: z
+ .object({
+ name: z.string().optional(),
+ description: z.string().nullable().optional()
+ })
+ .nullable()
+ .optional(),
+ makeDefault: z.boolean().optional(),
+ createChangeNotice: z.boolean().optional()
+});
+
+type PushSummary = {
+ releaseName: string | null;
+ revisionsCreated: number;
+ itemsCreated: number;
+ /** BOM children the push created; not on the change notice. */
+ childrenCreated: number;
+ drawingsQueued: number;
+ drawingsOnly: boolean;
+ reused: number;
+ linesWritten: number;
+ methodsTouched: number;
+ defaultsUpdated: number;
+ changeNotice: string | null;
+ alreadyPushed: boolean;
+ skipped: string[];
+ errors: string[];
+};
+
+type ItemRow = {
+ id: string;
+ readableId: string;
+ revision: string;
+ active?: boolean | null;
+ name: string;
+ type: string | null;
+ defaultMethodType: string | null;
+ sourcingType: string | null;
+ unitOfMeasureCode: string | null;
+};
+
+type CreatedEntry = {
+ partNumber: string;
+ revision: string;
+ itemId: string;
+ baseItemId: string | null;
+};
+
+function partInsert(
+ proposed: ProposedItem,
+ companyId: string,
+ userId: string,
+ customFields: PlanCustomField[] | undefined
+) {
+ const values = mappedFieldValues(customFields ?? [], true).values;
+ return {
+ id: proposed.readableId,
+ name: proposed.name,
+ description: proposed.description ?? undefined,
+ revision: proposed.revision,
+ replenishmentSystem: proposed.replenishmentSystem,
+ defaultMethodType: proposed.defaultMethodType,
+ itemTrackingType: proposed.itemTrackingType,
+ unitOfMeasureCode: proposed.unitOfMeasureCode,
+ ...(Object.keys(values).length > 0 ? { customFields: values as Json } : {}),
+ companyId,
+ createdBy: userId
+ } as any;
+}
+
+/** Apply a reviewed release plan; Carbon's state at apply time outranks the plan. */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ create: "parts",
+ update: "parts",
+ delete: "parts"
+ }
+ );
+
+ const parsed = payloadSchema.safeParse(
+ await request.json().catch(() => null)
+ );
+ if (!parsed.success) {
+ return data({ error: "Invalid push payload" }, { status: 400 });
+ }
+ const { planId, changeNotice: changeNoticeEdit } = parsed.data;
+ const edits = parsed.data.edits as Record<string, ItemEdit>;
+
+ const stored = await peekPanelPlan(planId, { companyId, userId });
+ if (!stored) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+ if (stored.plan.kind !== "release") {
+ return data(
+ { error: "This review is not a release push" },
+ { status: 400 }
+ );
+ }
+ const plan = stored.plan as StoredReleasePlan;
+ const makeDefault = parsed.data.makeDefault ?? plan.makeDefault;
+ // Unset: a notice whenever this push creates something.
+ const createChangeNoticeChoice = parsed.data.createChangeNotice;
+
+ const merged = mergeEditsForCreates(
+ [
+ ...plan.items
+ .filter((item) => item.action === "create" && item.proposed)
+ .map((item) => ({
+ key: item.partNumber,
+ proposed: item.proposed as ProposedItem
+ })),
+ ...plan.children
+ .filter((child) => child.action === "create" && child.proposed)
+ .map((child) => ({
+ key: child.partNumber,
+ proposed: child.proposed as ProposedItem
+ }))
+ ],
+ edits,
+ plan.options
+ );
+ // A row that vanished since review becomes a create, so even a re-push needs notice values.
+ const changeNoticeMerge = mergeChangeNoticeEdit(
+ plan.changeNotice ?? {
+ name: plan.releaseName ?? `Onshape release ${plan.releaseId}`,
+ description: null
+ },
+ changeNoticeEdit
+ );
+ if (!changeNoticeMerge.ok) {
+ return data(
+ {
+ error: "Some edits are not valid",
+ fieldErrors: [
+ ...merged.errors,
+ { key: "changeNotice", errors: changeNoticeMerge.errors }
+ ]
+ },
+ { status: 422 }
+ );
+ }
+ if (merged.errors.length > 0) {
+ return data(
+ { error: "Some edits are not valid", fieldErrors: merged.errors },
+ { status: 422 }
+ );
+ }
+ const changeNoticeValues = changeNoticeMerge.changeNotice;
+
+ const modelItems = plan.items.filter(isModelReleaseItem);
+ const drawingItems = plan.items.filter((item) => !isModelReleaseItem(item));
+
+ const summary: PushSummary = {
+ releaseName: plan.releaseName,
+ revisionsCreated: 0,
+ itemsCreated: 0,
+ childrenCreated: 0,
+ drawingsQueued: 0,
+ drawingsOnly: modelItems.length === 0,
+ reused: 0,
+ linesWritten: 0,
+ methodsTouched: 0,
+ defaultsUpdated: 0,
+ changeNotice: null,
+ alreadyPushed: false,
+ skipped: [],
+ errors: []
+ };
+
+ // A part number that is both a release item and a BOM child uses the release item's plan.
+ type PlannedRow = MappedRowPlan & {
+ current?: ItemFieldSnapshot | null;
+ changes?: OwnedFieldChange[];
+ };
+ const plannedByPartNumber = new Map<string, PlannedRow>();
+ for (const child of plan.children) {
+ if (child.current) plannedByPartNumber.set(child.partNumber, child);
+ }
+ for (const item of plan.items) {
+ if (item.current) plannedByPartNumber.set(item.partNumber, item);
+ }
+ // Written at insert. A revision shares its base's `part` row: no create-time values.
+ const createdFieldsByPartNumber = new Map<string, PlanCustomField[]>();
+ for (const row of [...plan.children, ...plan.items]) {
+ if (row.action === "create" && row.customFields) {
+ createdFieldsByPartNumber.set(row.partNumber, row.customFields);
+ }
+ }
+ const fieldEditsApplied = new Set<string>();
+ /** Writes the plan's values to an item the push did not create; updates `row` in place. */
+ const applyItemFieldEdit = async (partNumber: string, row: ItemRow) => {
+ if (fieldEditsApplied.has(partNumber)) return;
+ const planned = plannedByPartNumber.get(partNumber);
+ if (!planned?.current) return;
+ fieldEditsApplied.add(partNumber);
+ const applied = await applyExistingItemFields(client, db, {
+ itemId: row.id,
+ companyId,
+ userId,
+ current: planned.current,
+ target: planned.target,
+ edit: edits[partNumber],
+ descriptions: planned.changes
+ });
+ if (applied.error) {
+ summary.errors.push(`${partNumber}: ${applied.error}`);
+ return;
+ }
+ if (applied.values) {
+ row.defaultMethodType = applied.values.defaultMethodType;
+ row.sourcingType = applied.values.sourcingType ?? row.sourcingType;
+ row.unitOfMeasureCode =
+ applied.values.unitOfMeasureCode ?? row.unitOfMeasureCode;
+ }
+ const values = mappedFieldValues(planned.customFields ?? [], false);
+ if (values.fieldIds.size === 0) return;
+ const held = await client
+ .from("part")
+ .select("customFields")
+ .eq("id", partNumber)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (held.error) {
+ summary.errors.push(
+ `${partNumber}: failed to read custom fields (${held.error.message})`
+ );
+ return;
+ }
+ const updated = await client
+ .from("part")
+ .update({
+ customFields: mergeCustomFieldValues(
+ held.data?.customFields,
+ values.values,
+ values.fieldIds
+ ) as Json,
+ updatedAt: datetime.timestamp(),
+ updatedBy: userId
+ })
+ .eq("id", partNumber)
+ .eq("companyId", companyId);
+ if (updated.error) {
+ summary.errors.push(
+ `${partNumber}: failed to write custom fields (${updated.error.message})`
+ );
+ }
+ };
+ /** The values `upsertPart` does not take: MPN and Sourcing. */
+ const writeCreatedExtras = async (
+ label: string,
+ itemId: string,
+ proposed: ProposedItem
+ ) => {
+ const extras = createdItemExtras(proposed);
+ if (Object.keys(extras).length === 0) return;
+ const error = await applyItemFieldWrites(client, db, {
+ itemId,
+ companyId,
+ userId,
+ changed: extras
+ });
+ if (error) {
+ summary.errors.push(
+ `${label}: created, but its mapped fields were not written (${error})`
+ );
+ }
+ };
+
+ // Every revision of every part number, re-read: the plan may be minutes old.
+ const partNumbers = [
+ ...new Set([
+ ...modelItems.map((item) => item.partNumber),
+ ...Object.values(plan.bomLinesByElementId)
+ .flatMap((lines) => (lines ?? []).map((line) => line.partNumber))
+ .filter((partNumber): partNumber is string => !!partNumber)
+ ])
+ ];
+ const existing = await selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select(
+ "id, readableId, revision, active, name, type, defaultMethodType, sourcingType, unitOfMeasureCode"
+ )
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ .order("revision")
+ );
+ if (existing.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const byReadable = new Map<string, ItemRow[]>();
+ const rememberRow = (row: ItemRow) => {
+ const list = byReadable.get(row.readableId) ?? [];
+ list.push(row);
+ byReadable.set(row.readableId, list);
+ };
+ for (const row of (existing.data ?? []) as ItemRow[]) rememberRow(row);
+ const letterRowFor = (partNumber: string, revision: string) =>
+ (byReadable.get(partNumber) ?? []).find((row) => row.revision === revision);
+
+ const created: CreatedEntry[] = [];
+ const revisionItemByPartNumber = new Map<string, ItemRow>();
+
+ // The base the plan pinned is honoured while its row exists.
+ type Decision =
+ | { item: ReleasePlanItem; kind: "reuse"; row: ItemRow }
+ | { item: ReleasePlanItem; kind: "revision"; base: ItemRow }
+ | { item: ReleasePlanItem; kind: "create"; proposed: ProposedItem };
+ const decisions: Decision[] = modelItems.map((item): Decision => {
+ const existingLetter = letterRowFor(item.partNumber, item.revision);
+ if (existingLetter) return { item, kind: "reuse", row: existingLetter };
+ const bases = byReadable.get(item.partNumber) ?? [];
+ const base =
+ bases.find((row) => row.id === item.baseItemId) ??
+ pickRevisionBase(bases, item.revision);
+ if (base) return { item, kind: "revision", base };
+ return {
+ item,
+ kind: "create",
+ proposed:
+ merged.items.get(item.partNumber) ??
+ proposeItem(
+ { partNumber: item.partNumber, name: null, revision: item.revision },
+ plan.options
+ )
+ };
+ });
+
+ // An assembly whose BOM was not read at review is not minted: a revision would
+ // carry the base's Onshape lines unmapped, and a new item would have no BOM.
+ for (const decision of decisions) {
+ if (
+ decision.kind !== "reuse" &&
+ decision.item.elementType === 1 &&
+ plan.bomLinesByElementId[releaseBomKey(decision.item)] === null
+ ) {
+ summary.errors.push(
+ `${decision.item.partNumber} Rev ${decision.item.revision}: the BOM was not read at review — review and push again`
+ );
+ }
+ }
+ const applicable = decisions.filter(
+ (decision) =>
+ decision.kind === "reuse" ||
+ decision.item.elementType !== 1 ||
+ plan.bomLinesByElementId[releaseBomKey(decision.item)] !== null
+ );
+ decisions.length = 0;
+ decisions.push(...applicable);
+
+ const baseIds = [
+ ...new Set(
+ decisions.flatMap((decision) =>
+ decision.kind === "revision" ? [decision.base.id] : []
+ )
+ )
+ ];
+ type FullItem = NonNullable<Awaited<ReturnType<typeof getItem>>["data"]>;
+ const fullBaseById = new Map<string, FullItem>();
+ const bases = await selectInBatches(baseIds, (batch) =>
+ client.from("item").select("*").eq("companyId", companyId).in("id", batch)
+ );
+ // A failed read would look like "no base" and skip revisions: a partial push.
+ if (bases.error) {
+ return data(
+ { error: "Failed to read the base revisions" },
+ { status: 500 }
+ );
+ }
+ for (const row of bases.data as FullItem[]) {
+ fullBaseById.set(row.id, row);
+ }
+
+ // `createRevision` copies the base's lines without mapping rows. Key the base's
+ // Onshape lines now: after the revision exists, a failed read leaves manual-looking copies.
+ const assemblyBaseIds = [
+ ...new Set(
+ decisions.flatMap((decision) =>
+ decision.kind === "revision" && decision.item.elementType === 1
+ ? [decision.base.id]
+ : []
+ )
+ )
+ ];
+ const lineKey = (line: { itemId: string; order: number; quantity: number }) =>
+ `${line.itemId}:${line.order}:${line.quantity}`;
+ let baseMethodByItemId: Awaited<ReturnType<typeof loadActiveMakeMethods>>;
+ try {
+ baseMethodByItemId = await loadActiveMakeMethods(
+ client,
+ companyId,
+ assemblyBaseIds
+ );
+ } catch (error) {
+ return data(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to read the base revisions' make methods"
+ },
+ { status: 500 }
+ );
+ }
+ const serviceRole = getCarbonServiceRole();
+ const db = getDatabaseClient();
+ const copiedKeysByBaseMethodId = new Map<string, Set<string>>();
+ const baseMethodIds = [
+ ...new Set([...baseMethodByItemId.values()].map((method) => method.id))
+ ];
+ if (baseMethodIds.length > 0) {
+ const baseMapped = await selectInBatches(baseMethodIds, (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .in("metadata->>makeMethodId", batch)
+ );
+ const baseLines = baseMapped.error
+ ? null
+ : await selectInBatches(
+ baseMapped.data.map((mapping) => mapping.entityId),
+ (batch) =>
+ client
+ .from("methodMaterial")
+ .select("makeMethodId, itemId, order, quantity")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ const baseReadError = baseMapped.error ?? baseLines?.error;
+ if (baseReadError || !baseLines) {
+ return data(
+ {
+ error: `Couldn't identify the Onshape lines on the base revisions (${
+ baseReadError?.message ?? "read failed"
+ }); nothing was written. Try again.`
+ },
+ { status: 500 }
+ );
+ }
+ for (const line of baseLines.data) {
+ const keys =
+ copiedKeysByBaseMethodId.get(line.makeMethodId) ?? new Set<string>();
+ keys.add(lineKey(line));
+ copiedKeysByBaseMethodId.set(line.makeMethodId, keys);
+ }
+ }
+
+ // A reused revision held by a change notice whose engineering content is
+ // locked (Implementation onward, or awaiting approval) takes no writes: not
+ // its fields, not its BOM. A method's changeOrderId is cleared at release, so
+ // a set one means a notice holds the item now.
+ const lockedByItemId = new Map<string, string>();
+ const reusedItemIds = decisions.flatMap((decision) =>
+ decision.kind === "reuse" ? [decision.row.id] : []
+ );
+ if (reusedItemIds.length > 0) {
+ const held = await selectInBatches(reusedItemIds, (batch) =>
+ client
+ .from("makeMethod")
+ .select("itemId, changeOrderId, changeOrder(changeOrderId)")
+ .eq("companyId", companyId)
+ .in("itemId", batch)
+ .not("changeOrderId", "is", null)
+ );
+ if (held.error) {
+ return data(
+ {
+ error: `Couldn't check the change notices that hold the existing revisions (${held.error.message}); nothing was written. Try again.`
+ },
+ { status: 500 }
+ );
+ }
+ const noticeIds = [
+ ...new Set(
+ held.data.flatMap((method) =>
+ method.changeOrderId ? [method.changeOrderId] : []
+ )
+ )
+ ];
+ // One check per notice; a release's revisions share one or two.
+ const lockByNoticeId = new Map(
+ await Promise.all(
+ noticeIds.map(
+ async (changeNoticeId) =>
+ [
+ changeNoticeId,
+ (
+ await requireChangeNoticeEditable(client, {
+ changeNoticeId,
+ companyId,
+ scope: "engineering"
+ })
+ )?.error.message ?? null
+ ] as const
+ )
+ )
+ );
+ for (const method of held.data) {
+ const lock = method.changeOrderId
+ ? lockByNoticeId.get(method.changeOrderId)
+ : null;
+ if (!lock || lockedByItemId.has(method.itemId)) continue;
+ const notice = method.changeOrder?.changeOrderId;
+ lockedByItemId.set(
+ method.itemId,
+ notice ? `change notice ${notice}: ${lock}` : lock
+ );
+ }
+ }
+
+ // The notice exists before the first item write, so each item is staged as it
+ // is written. A second document of the same release reuses the open notice.
+ // Read before the take: a failed read must not open a second notice.
+ const needsNotice =
+ (createChangeNoticeChoice ?? true) &&
+ decisions.some((decision) => decision.kind !== "reuse");
+ const openNotice = needsNotice
+ ? await findOpenReleaseNotice(client, companyId, plan.releaseId)
+ : { data: null, error: null };
+ if (openNotice.error !== null) {
+ return data(
+ {
+ error: `${openNotice.error}, so it can't tell which change notice to add to; nothing was written. Try again.`
+ },
+ { status: 500 }
+ );
+ }
+
+ // Taken after the reads the writes depend on, so a failed read keeps the review;
+ // one-shot, so a concurrent apply of the same review finds nothing.
+ if (!(await takePanelPlan(planId, { companyId, userId }))) {
+ return data(
+ { error: "This review has expired — review again" },
+ { status: 410 }
+ );
+ }
+
+ let changeNotice: { id: string; changeNoticeId: string } | null = null;
+ let noticeReused = false;
+ let noticeSortOrder = 0;
+ if (openNotice.data) {
+ changeNotice = {
+ id: openNotice.data.id,
+ changeNoticeId: openNotice.data.changeNoticeId
+ };
+ noticeReused = true;
+ noticeSortOrder = openNotice.data.affectedCount;
+ summary.changeNotice = openNotice.data.changeNoticeId;
+ } else if (needsNotice) {
+ const description = changeNoticeDescriptionJson(
+ changeNoticeValues.description
+ );
+ const inserted = await insertChangeNotice(client, {
+ companyId,
+ createdBy: userId,
+ name: changeNoticeValues.name,
+ // Tiptap JSON; omitted, not nulled, when empty.
+ ...(description ? { description: description as Json } : {}),
+ openDate: datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString()
+ });
+ if (inserted.error || !inserted.data) {
+ return data(
+ {
+ error: `Couldn't create the change notice (${
+ inserted.error?.message ?? "no row returned"
+ }); nothing was written. Review and push again.`
+ },
+ { status: 500 }
+ );
+ }
+ changeNotice = inserted.data;
+ summary.changeNotice = inserted.data.changeNoticeId;
+ }
+ // An item the notice could not take is removed: left in place it is outside
+ // change control, and a re-push would reuse it instead of staging it. The
+ // service role removes it because the pusher may lack parts_delete.
+ const stageInNotice = async (
+ label: string,
+ itemId: string,
+ baseItemId: string | null
+ ): Promise<boolean> => {
+ if (!changeNotice) return true;
+ const staged = await stageChangeNoticeItem(db, {
+ changeOrderId: changeNotice.id,
+ companyId,
+ userId,
+ itemId,
+ baseItemId,
+ sortOrder: noticeSortOrder
+ });
+ if (!staged.error) {
+ noticeSortOrder += 1;
+ return true;
+ }
+ const notice = changeNotice.changeNoticeId;
+ const removed = await deleteItem(serviceRole, db, itemId, companyId);
+ summary.errors.push(
+ removed.error
+ ? `${label}: created but not added to change notice ${notice} (${staged.error}), and could not be removed (${removed.error.message}). Delete it in Carbon, then push again.`
+ : `${label}: not created, because it could not be added to change notice ${notice} (${staged.error}). Push again.`
+ );
+ return false;
+ };
+
+ for (const decision of decisions) {
+ const { item } = decision;
+ if (decision.kind === "reuse") {
+ summary.reused += 1;
+ revisionItemByPartNumber.set(item.partNumber, decision.row);
+ const lock = lockedByItemId.get(decision.row.id);
+ if (lock) {
+ // Also keeps the BOM-child pass from writing its fields.
+ fieldEditsApplied.add(item.partNumber);
+ summary.skipped.push(
+ `${item.partNumber} Rev ${item.revision}: ${lock} Its fields and BOM were left as they are.`
+ );
+ continue;
+ }
+ await applyItemFieldEdit(item.partNumber, decision.row);
+ continue;
+ }
+
+ let row: ItemRow | null = null;
+ if (decision.kind === "revision") {
+ const full = fullBaseById.get(decision.base.id);
+ if (!full) {
+ summary.errors.push(`${item.partNumber}: failed to read the base item`);
+ continue;
+ }
+ const inserted = await createRevision(client, db, {
+ item: full,
+ revision: item.revision,
+ createdBy: userId,
+ active: !changeNotice
+ });
+ if (inserted.error || !inserted.data) {
+ summary.errors.push(
+ `${item.partNumber}: ${
+ inserted.error?.message ?? "failed to create the revision"
+ }`
+ );
+ continue;
+ }
+ if (
+ !(await stageInNotice(
+ `${item.partNumber} Rev ${item.revision}`,
+ inserted.data.id,
+ decision.base.id
+ ))
+ ) {
+ continue;
+ }
+ row = {
+ id: inserted.data.id,
+ readableId: item.partNumber,
+ revision: item.revision,
+ name: full.name,
+ type: full.type,
+ defaultMethodType: full.defaultMethodType ?? "Make to Order",
+ sourcingType: full.sourcingType ?? null,
+ unitOfMeasureCode: full.unitOfMeasureCode ?? "EA"
+ };
+ created.push({
+ partNumber: item.partNumber,
+ revision: item.revision,
+ itemId: row.id,
+ baseItemId: decision.base.id
+ });
+ summary.revisionsCreated += 1;
+ } else {
+ // Safe with `upsertPart`'s readback by readableId: no other revision exists.
+ const { proposed } = decision;
+ const insertedItem = await upsertPart(
+ client,
+ partInsert(
+ proposed,
+ companyId,
+ userId,
+ createdFieldsByPartNumber.get(item.partNumber)
+ )
+ );
+ if (insertedItem.error || !insertedItem.data) {
+ summary.errors.push(
+ `${item.partNumber}: ${
+ insertedItem.error?.message ?? "failed to create the item"
+ }`
+ );
+ continue;
+ }
+ row = {
+ id: insertedItem.data.id as string,
+ readableId: item.partNumber,
+ revision: item.revision,
+ name: proposed.name,
+ type: "Part",
+ defaultMethodType: proposed.defaultMethodType,
+ sourcingType: proposed.sourcingType ?? null,
+ unitOfMeasureCode: proposed.unitOfMeasureCode
+ };
+ await writeCreatedExtras(item.partNumber, row.id, proposed);
+ if (
+ !(await stageInNotice(
+ `${item.partNumber} Rev ${item.revision}`,
+ row.id,
+ null
+ ))
+ ) {
+ continue;
+ }
+ created.push({
+ partNumber: item.partNumber,
+ revision: item.revision,
+ itemId: row.id,
+ baseItemId: null
+ });
+ summary.itemsCreated += 1;
+ }
+
+ revisionItemByPartNumber.set(item.partNumber, row);
+ rememberRow(row);
+ await applyItemFieldEdit(item.partNumber, row);
+ }
+
+ summary.alreadyPushed = created.length === 0;
+ if (changeNotice && !noticeReused && created.length === 0) {
+ const dropped = await deleteChangeNotice(
+ client,
+ db,
+ changeNotice.id,
+ companyId
+ );
+ if (dropped.error) {
+ summary.errors.push(
+ `Change notice ${changeNotice.changeNoticeId} is empty and could not be removed (${dropped.error.message})`
+ );
+ } else {
+ summary.changeNotice = null;
+ }
+ changeNotice = null;
+ }
+
+ // Any BOM read failure skips every BOM write: writing on a partial read
+ // duplicates or orphans lines.
+ let bomReadFailure: string | null = null;
+
+ const methodByItemId = new Map(baseMethodByItemId);
+ try {
+ for (const [itemId, method] of await loadActiveMakeMethods(
+ client,
+ companyId,
+ [
+ ...[...revisionItemByPartNumber.values()].map((row) => row.id),
+ ...created.flatMap((entry) =>
+ entry.baseItemId ? [entry.baseItemId] : []
+ )
+ ]
+ )) {
+ methodByItemId.set(itemId, method);
+ }
+ } catch (error) {
+ bomReadFailure =
+ error instanceof Error ? error.message : "failed to read make methods";
+ }
+
+ type BomTarget = {
+ item: ReleasePlanItem;
+ label: string;
+ methodId: string;
+ lines: OnshapeBomNode[];
+ /** The base method whose Onshape-origin lines the revision copy carries. */
+ baseMethodId: string | null;
+ };
+ const bomTargets: BomTarget[] = [];
+ for (const item of bomReadFailure
+ ? []
+ : modelItems.filter((candidate) => candidate.elementType === 1)) {
+ const target = revisionItemByPartNumber.get(item.partNumber);
+ if (!target) continue; // creation failed above; error already recorded
+ const label = `${item.partNumber} Rev ${item.revision}`;
+
+ const method = methodByItemId.get(target.id);
+ if (!method) {
+ summary.errors.push(`${label}: no make method found`);
+ continue;
+ }
+ if (method.status === "Active") {
+ summary.skipped.push(
+ `${label}: make method is released in Carbon, so its BOM was left as it is`
+ );
+ continue;
+ }
+ // Reported with its fields above.
+ if (lockedByItemId.has(target.id)) continue;
+
+ // null: the review could not read the BOM, so the method is left alone. An
+ // empty BOM is [] and is applied.
+ const lines = plan.bomLinesByElementId[releaseBomKey(item)];
+ if (!lines) {
+ summary.skipped.push(
+ `${label}: the BOM was not read at review — review and push again`
+ );
+ continue;
+ }
+
+ const createdEntry = created.find(
+ (candidate) =>
+ candidate.partNumber === item.partNumber &&
+ candidate.revision === item.revision
+ );
+ bomTargets.push({
+ item,
+ label,
+ methodId: method.id,
+ lines,
+ baseMethodId: createdEntry?.baseItemId
+ ? (methodByItemId.get(createdEntry.baseItemId)?.id ?? null)
+ : null
+ });
+ }
+
+ const childItemByPartNumber = new Map<string, ItemRow>();
+ const childFailed = new Set<string>();
+ const releaseItemByPartNumber = new Map(
+ modelItems.map((item) => [item.partNumber, item])
+ );
+ for (const target of bomTargets) {
+ for (const child of target.lines) {
+ if (!child.partNumber) continue;
+ if (
+ childItemByPartNumber.has(child.partNumber) ||
+ childFailed.has(child.partNumber)
+ ) {
+ continue;
+ }
+ // A release item that was held back or failed (its error is reported
+ // above) is neither created off the notice nor swapped for another revision.
+ const releaseItem = releaseItemByPartNumber.get(child.partNumber);
+ if (releaseItem && !revisionItemByPartNumber.has(child.partNumber)) {
+ summary.errors.push(
+ `${target.label} → ${child.partNumber}: line not written, because ${child.partNumber} Rev ${releaseItem.revision} was not pushed`
+ );
+ childFailed.add(child.partNumber);
+ continue;
+ }
+ const existingChild =
+ revisionItemByPartNumber.get(child.partNumber) ??
+ pickBomChildRow(byReadable.get(child.partNumber) ?? [], child.revision)
+ .row;
+ if (existingChild) {
+ childItemByPartNumber.set(child.partNumber, existingChild);
+ await applyItemFieldEdit(child.partNumber, existingChild);
+ continue;
+ }
+ const proposed =
+ merged.items.get(child.partNumber) ??
+ proposeItem(
+ {
+ partNumber: child.partNumber,
+ name: child.name,
+ description: child.description,
+ revision: child.revision,
+ hasChildren: child.children.length > 0,
+ standardContent: child.standardContent === true
+ },
+ plan.options
+ );
+ const createdChild = await upsertPart(
+ client,
+ partInsert(
+ proposed,
+ companyId,
+ userId,
+ createdFieldsByPartNumber.get(child.partNumber)
+ )
+ );
+ if (createdChild.error || !createdChild.data) {
+ summary.errors.push(
+ `${target.label} → ${child.partNumber}: ${
+ createdChild.error?.message ?? "failed to create the item"
+ }`
+ );
+ childFailed.add(child.partNumber);
+ continue;
+ }
+ const childRow: ItemRow = {
+ id: createdChild.data.id as string,
+ readableId: child.partNumber,
+ revision: proposed.revision,
+ name: proposed.name,
+ type: "Part",
+ defaultMethodType: proposed.defaultMethodType,
+ sourcingType: proposed.sourcingType ?? null,
+ unitOfMeasureCode: proposed.unitOfMeasureCode
+ };
+ await writeCreatedExtras(child.partNumber, childRow.id, proposed);
+ childItemByPartNumber.set(child.partNumber, childRow);
+ rememberRow(childRow);
+ summary.childrenCreated += 1;
+ }
+ }
+
+ const madeChildItemIds = [
+ ...new Set(
+ bomTargets.flatMap((target) =>
+ target.lines.flatMap((child) => {
+ if (!child.partNumber) return [];
+ const row = childItemByPartNumber.get(child.partNumber);
+ if (
+ child.children.length === 0 &&
+ row?.defaultMethodType !== "Make to Order"
+ ) {
+ return [];
+ }
+ return row && !methodByItemId.has(row.id) ? [row.id] : [];
+ })
+ )
+ )
+ ];
+ if (!bomReadFailure) {
+ try {
+ for (const [itemId, method] of await loadActiveMakeMethods(
+ client,
+ companyId,
+ madeChildItemIds
+ )) {
+ methodByItemId.set(itemId, method);
+ }
+ } catch (error) {
+ // Without them every sub-assembly line gets a null method and flattens the tree.
+ bomReadFailure =
+ error instanceof Error
+ ? error.message
+ : "failed to read the sub-assemblies' make methods";
+ }
+ }
+
+ // Delete the revision's copies of the base's Onshape lines (manual lines stay),
+ // then the lines a previous push of this release wrote.
+ const baseMethodIdByTargetMethodId = new Map<string, string>(
+ bomTargets.flatMap(
+ (target): Array<[string, string]> =>
+ target.baseMethodId ? [[target.methodId, target.baseMethodId]] : []
+ )
+ );
+ const copyTargetMethodIds = [...baseMethodIdByTargetMethodId.entries()]
+ .filter(([, baseMethodId]) => copiedKeysByBaseMethodId.has(baseMethodId))
+ .map(([targetMethodId]) => targetMethodId);
+ const targetMethodIds = bomTargets.map((target) => target.methodId);
+ const [copies, mapped] = bomReadFailure
+ ? [null, null]
+ : await Promise.all([
+ selectInBatches(copyTargetMethodIds, (batch) =>
+ client
+ .from("methodMaterial")
+ .select("id, makeMethodId, itemId, order, quantity")
+ .eq("companyId", companyId)
+ .in("makeMethodId", batch)
+ ),
+ selectInBatches(targetMethodIds, (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("id, entityId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .in("metadata->>makeMethodId", batch)
+ )
+ ]);
+ if (!bomReadFailure && (copies?.error || mapped?.error)) {
+ bomReadFailure =
+ (copies?.error ?? mapped?.error)?.message ?? "failed to read BOM lines";
+ }
+
+ if (bomReadFailure) {
+ const carriesCopies = created.some((entry) => {
+ const baseMethod = entry.baseItemId
+ ? baseMethodByItemId.get(entry.baseItemId)
+ : undefined;
+ return !!baseMethod && copiedKeysByBaseMethodId.has(baseMethod.id);
+ });
+ summary.errors.push(
+ `The released BOMs were not written: Carbon couldn't read what they replace (${bomReadFailure}). Push the release again.${
+ carriesCopies
+ ? " A revision this push created still carries its base revision's lines — check its bill of materials before pushing again."
+ : ""
+ }`
+ );
+ bomTargets.length = 0;
+ }
+
+ const toDelete = (copies?.data ?? [])
+ .filter((line) => {
+ const baseMethodId = baseMethodIdByTargetMethodId.get(line.makeMethodId);
+ return (
+ !!baseMethodId &&
+ copiedKeysByBaseMethodId.get(baseMethodId)?.has(lineKey(line))
+ );
+ })
+ .map((line) => line.id);
+ for (const batch of bomReadFailure ? [] : chunkFilterValues(toDelete)) {
+ const deduped = await client
+ .from("methodMaterial")
+ .delete()
+ .eq("companyId", companyId)
+ .in("id", batch);
+ if (deduped.error) {
+ summary.errors.push(
+ `Could not remove the lines copied from the base revisions (${deduped.error.message}); released BOMs may contain duplicates`
+ );
+ }
+ }
+
+ if (mapped && !bomReadFailure) {
+ const failedLineIds = new Set<string>();
+ for (const batch of chunkFilterValues(
+ mapped.data.map((mapping) => mapping.entityId)
+ )) {
+ const removedLines = await client
+ .from("methodMaterial")
+ .delete()
+ .eq("companyId", companyId)
+ .in("id", batch);
+ if (removedLines.error) {
+ for (const id of batch) failedLineIds.add(id);
+ summary.errors.push(
+ `Could not replace the lines a previous release push wrote (${removedLines.error.message}); this push may add a second copy of them`
+ );
+ }
+ }
+ for (const batch of chunkFilterValues(
+ mapped.data
+ .filter((mapping) => !failedLineIds.has(mapping.entityId))
+ .map((mapping) => mapping.id)
+ )) {
+ const removedMappings = await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("companyId", companyId)
+ .in("id", batch);
+ if (removedMappings.error) {
+ summary.errors.push(
+ `Could not clear the ownership records for the replaced released lines (${removedMappings.error.message})`
+ );
+ }
+ }
+ }
+ summary.methodsTouched += bomTargets.length;
+
+ // One level only: a sub-assembly gets its lines from its own release item.
+ for (const target of bomTargets) {
+ const { item, label, methodId } = target;
+ const lines: OwnedMethodLine[] = [];
+ for (const child of target.lines) {
+ if (!child.partNumber) {
+ summary.skipped.push(
+ `${label} → ${child.name ?? child.index}: no part number in Onshape`
+ );
+ continue;
+ }
+ const childItem = childItemByPartNumber.get(child.partNumber);
+ if (!childItem) continue; // creation failed above; error already recorded
+
+ // A reused Material or Consumable keeps its type; a Tool or Service cannot be a line.
+ const itemType = bomLineItemType(childItem);
+ if (!itemType) {
+ summary.errors.push(
+ `${label} → ${child.partNumber}: a ${
+ childItem.type ?? "Part"
+ } item cannot be a BOM line`
+ );
+ continue;
+ }
+
+ const childMethod =
+ child.children.length > 0 ||
+ childItem.defaultMethodType === "Make to Order"
+ ? methodByItemId.get(childItem.id)
+ : null;
+ lines.push({
+ row: {
+ itemId: childItem.id,
+ quantity: child.quantity,
+ makeMethodId: methodId,
+ materialMakeMethodId: childMethod?.id ?? null,
+ methodType:
+ (childItem.defaultMethodType as OwnedMethodLine["row"]["methodType"]) ??
+ (child.children.length > 0
+ ? "Make to Order"
+ : "Pull from Inventory"),
+ sourcingType:
+ (childItem.sourcingType as OwnedMethodLine["row"]["sourcingType"]) ??
+ "Specified",
+ order: lines.length,
+ itemType,
+ unitOfMeasureCode: childItem.unitOfMeasureCode ?? "EA"
+ },
+ metadata: {
+ makeMethodId: methodId,
+ documentId: plan.documentId,
+ elementId: item.elementId,
+ partNumber: child.partNumber,
+ index: child.index,
+ releaseId: plan.releaseId
+ }
+ });
+ }
+ const written = await insertOwnedMethodLines(db, {
+ companyId,
+ userId,
+ lines
+ });
+ if (written.error !== null) {
+ summary.errors.push(
+ `${label}: the released BOM lines were not written (${written.error}); push the release again`
+ );
+ } else {
+ summary.linesWritten += lines.length;
+ }
+ }
+
+ // An item holds one Onshape link: a reused revision linked to its part or
+ // assembly keeps that link, which status and change detection read.
+ const reusedIds = decisions
+ .filter((decision) => decision.kind === "reuse")
+ .map((decision) => decision.row.id);
+ const keepsLink = new Set<string>();
+ if (reusedIds.length > 0) {
+ const links = await selectInBatches(reusedIds, (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("entityId", batch)
+ );
+ if (links.error) {
+ for (const id of reusedIds) keepsLink.add(id);
+ summary.errors.push(
+ `Could not read the Onshape links of existing revisions (${links.error.message}); they keep their current links`
+ );
+ } else {
+ for (const link of links.data) {
+ if (!link.externalId?.startsWith("release:")) {
+ keepsLink.add(link.entityId);
+ }
+ }
+ }
+ }
+ for (const item of modelItems) {
+ const row = revisionItemByPartNumber.get(item.partNumber);
+ if (!row || keepsLink.has(row.id)) continue;
+ const externalId = `release:${plan.releaseId}:${item.partNumber}`;
+ const pushedAt = datetime.timestamp();
+ const releaseMapping = await swapItemMapping(db, {
+ companyId,
+ userId,
+ itemId: row.id,
+ externalId,
+ metadata: {
+ kind: "release",
+ releaseId: plan.releaseId,
+ releaseName: plan.releaseName,
+ documentId: plan.documentId,
+ elementId: item.elementId,
+ wv: "v",
+ wvId: item.versionId,
+ partNumber: item.partNumber,
+ revision: item.revision,
+ pushedBy: userId,
+ pushedAt,
+ planId
+ }
+ });
+ if (releaseMapping.error !== null) {
+ summary.errors.push(
+ `${item.partNumber} Rev ${item.revision}: revision written but not linked to Onshape (${releaseMapping.error}); it is invisible to change detection and to Detach`
+ );
+ }
+ }
+
+ // Make Default repoints every BOM line using a sibling revision to the new one.
+ // Not for a staged revision: releasing its notice supersedes the old one instead.
+ if (makeDefault && !changeNotice) {
+ for (const entry of created) {
+ if (!entry.baseItemId) continue; // brand-new item: it is the only revision
+ const updated = await updateDefaultRevision(client, {
+ id: entry.itemId,
+ updatedBy: userId
+ });
+ if (updated.error) {
+ summary.errors.push(
+ `${entry.partNumber}: failed to make Rev ${entry.revision} the default`
+ );
+ } else {
+ summary.defaultsUpdated += 1;
+ }
+ }
+ }
+
+ const assetTargets: Array<{
+ item: ReleasePlanItem;
+ itemId: string;
+ kind: "partstudio" | "assembly" | "drawing";
+ }> = [];
+ for (const item of modelItems) {
+ const row = revisionItemByPartNumber.get(item.partNumber);
+ if (!row) continue;
+ assetTargets.push({
+ item,
+ itemId: row.id,
+ kind: item.elementType === 1 ? "assembly" : "partstudio"
+ });
+ }
+ for (const drawing of drawingItems) {
+ // The drawing's model: in this release, or in Carbon at the revision the plan named.
+ const model = drawing.drawingOf;
+ const targetId = model
+ ? (revisionItemByPartNumber.get(model.partNumber)?.id ??
+ model.itemId ??
+ null)
+ : null;
+ if (!targetId) {
+ summary.skipped.push(
+ model
+ ? `${drawing.partNumber}: drawing waits for ${model.partNumber}${
+ model.revision ? ` Rev ${model.revision}` : ""
+ }, which isn't in Carbon; push its release first`
+ : `${drawing.partNumber}: drawing has no matching model item in this release`
+ );
+ continue;
+ }
+ assetTargets.push({ item: drawing, itemId: targetId, kind: "drawing" });
+ }
+ for (const target of assetTargets) {
+ const selection: ReleaseExportSelection =
+ target.kind === "drawing"
+ ? { ok: true }
+ : releaseExportSelection(target.item);
+ if (!selection.ok) {
+ summary.skipped.push(
+ `${target.item.partNumber} Rev ${target.item.revision}: ${selection.reason}`
+ );
+ continue;
+ }
+ // The event id dedupes a retried apply (each run spends Onshape quota). The
+ // writes have landed, so a queue failure is reported, not thrown.
+ try {
+ await trigger(
+ "onshape-panel-sync",
+ {
+ companyId,
+ userId,
+ itemId: target.itemId,
+ documentId: plan.documentId,
+ wvm: "v",
+ wvmId: target.item.versionId,
+ elementId: target.item.elementId,
+ elementKind: target.kind,
+ ...(selection.partId ? { partId: selection.partId } : {}),
+ ...(selection.configuration
+ ? { configuration: selection.configuration }
+ : {}),
+ assetBaseName: `${target.item.partNumber}-${target.item.revision}`
+ },
+ { id: `${planId}:${target.itemId}:${target.item.elementId}` }
+ );
+ if (target.kind === "drawing") summary.drawingsQueued += 1;
+ } catch {
+ summary.errors.push(
+ `${target.item.partNumber} Rev ${target.item.revision}: pushed, but the ${
+ target.kind === "drawing" ? "drawing" : "model"
+ } export couldn't be queued. Push again to retry the export.`
+ );
+ }
+ }
+
+ return data({ summary }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.releases.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.releases.ts
new file mode 100644
index 0000000000..d6bdf4a0e8
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.releases.ts
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { ReleaseCarbonItemRow } from "@carbon/ee";
+import {
+ groupRevisionsIntoReleases,
+ isModelReleaseItem,
+ releaseDrawingFileName,
+ resolveReleaseStates
+} from "@carbon/ee";
+import {
+ getOnshapeClient,
+ ONSHAPE_V2_INTEGRATION_ID,
+ onshapeFailure,
+ selectInBatches
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import { getLogger } from "@carbon/logger";
+import type { LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const logger = getLogger("erp", "integrations-onshape-panel-releases");
+
+const MAX_RELEASES = 20;
+
+/**
+ * The document's releases (revisions grouped by releaseId), each with what
+ * Carbon already holds by part number and revision letter.
+ */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ view: "parts"
+ }
+ );
+
+ const url = new URL(request.url);
+ const documentId = url.searchParams.get("documentId");
+ if (!documentId) {
+ return data({ error: "Missing Onshape context" }, { status: 400 });
+ }
+
+ const onshape = await getOnshapeClient(
+ getCarbonServiceRole(),
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ let revisions: Awaited<
+ ReturnType<typeof onshape.client.getDocumentRevisions>
+ >;
+ try {
+ revisions = await onshape.client.getDocumentRevisions(documentId);
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+
+ const releases = groupRevisionsIntoReleases(revisions.items ?? []).slice(
+ 0,
+ MAX_RELEASES
+ );
+
+ // Release management is an Onshape company feature: on an empty list, one
+ // call tells "none yet" from "not available to the connected account".
+ let releaseManagementAvailable = true;
+ if (releases.length === 0) {
+ try {
+ releaseManagementAvailable =
+ (await onshape.client.getCompanies()).length > 0;
+ } catch (error) {
+ // The generic empty state is still correct; don't fail the read.
+ logger.warn("Onshape companies read failed", { companyId, error });
+ }
+ }
+
+ const partNumbers = [
+ ...new Set(
+ releases.flatMap((release) =>
+ release.items.filter(isModelReleaseItem).map((item) => item.partNumber)
+ )
+ )
+ ];
+
+ const rows = await selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision")
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ );
+ if (rows.error) {
+ return data({ error: "Failed to read Carbon items" }, { status: 500 });
+ }
+ const carbonRows = rows.data as ReleaseCarbonItemRow[];
+
+ // A pushed drawing is only the PDF attached to its model item. Read with the
+ // service role, company-scoped: release state ignores document permissions.
+ const drawingNames = [
+ ...new Set(
+ releases.flatMap((release) =>
+ release.items
+ .filter((item) => !isModelReleaseItem(item))
+ .map(releaseDrawingFileName)
+ )
+ )
+ ];
+ const attachedDrawings = new Set<string>();
+ if (drawingNames.length > 0) {
+ const documents = await selectInBatches(drawingNames, (batch) =>
+ getCarbonServiceRole()
+ .from("document")
+ .select("name")
+ .eq("companyId", companyId)
+ .eq("sourceDocument", "Part")
+ .eq("active", true)
+ .in("name", batch)
+ );
+ if (documents.error) {
+ return data(
+ { error: "Failed to read Carbon documents" },
+ { status: 500 }
+ );
+ }
+ for (const document of documents.data) attachedDrawings.add(document.name);
+ }
+
+ return data(
+ {
+ releases: resolveReleaseStates(releases, carbonRows, attachedDrawings),
+ releaseManagementAvailable
+ },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.session.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.session.ts
new file mode 100644
index 0000000000..06428fb513
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.session.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ deletePanelSession,
+ panelSessionTokenFromRequest
+} from "@carbon/ee/onshape/panel-session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ if (request.method !== "DELETE") {
+ return data({ error: "Method not allowed" }, { status: 405 });
+ }
+
+ const token = panelSessionTokenFromRequest(request);
+ if (token) {
+ await deletePanelSession(token);
+ }
+
+ return data({ ok: true });
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts
new file mode 100644
index 0000000000..663a7006d2
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts
@@ -0,0 +1,398 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { PanelAssemblyLineInput, PanelItemRow } from "@carbon/ee";
+import {
+ buildAssemblyLineStatuses,
+ buildPartStatuses,
+ externalIdForAssembly,
+ externalIdForBomLine,
+ metadataProperty,
+ missingBomColumnsMessage,
+ normalizeConfiguration,
+ parseBomTree
+} from "@carbon/ee";
+import type { OnshapeDocument } from "@carbon/ee/onshape";
+import {
+ getOnshapeClient,
+ loadReleasedRevisions,
+ ONSHAPE_V2_INTEGRATION_ID,
+ OnshapeWVMType,
+ onshapeFailure,
+ selectInBatches
+} from "@carbon/ee/onshape";
+import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+/** Carbon status for the current Onshape element: its parts or its BOM. */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requireOnshapePanelPermissions(
+ request,
+ {
+ view: "parts"
+ }
+ );
+
+ const url = new URL(request.url);
+ const documentId = url.searchParams.get("documentId");
+ const wv = url.searchParams.get("wv");
+ const wvId = url.searchParams.get("wvId");
+ const elementId = url.searchParams.get("elementId");
+ // Part of every identity key: a configured part's part number depends on it.
+ const configuration = normalizeConfiguration(
+ url.searchParams.get("configuration")
+ );
+
+ if (
+ !documentId ||
+ !wvId ||
+ !elementId ||
+ (wv !== "w" && wv !== "v" && wv !== "m")
+ ) {
+ return data({ error: "Missing Onshape context" }, { status: 400 });
+ }
+
+ const onshape = await getOnshapeClient(
+ getCarbonServiceRole(),
+ companyId,
+ userId,
+ ONSHAPE_V2_INTEGRATION_ID
+ );
+ if (onshape.error || !onshape.client) {
+ return data(
+ { error: "Onshape is not connected for this company" },
+ { status: 422 }
+ );
+ }
+
+ const wvm =
+ wv === "w"
+ ? OnshapeWVMType.WORKSPACE
+ : wv === "v"
+ ? OnshapeWVMType.VERSION
+ : OnshapeWVMType.MICROVERSION;
+ const document: OnshapeDocument = { documentId, wvm, wvmId: wvId };
+
+ let kind: "partstudio" | "assembly" | "other";
+ try {
+ const elements = await onshape.client.getElementsIn(document);
+ const element = elements.find((e) => e.id === elementId);
+ kind =
+ element?.elementType === "ASSEMBLY"
+ ? "assembly"
+ : element?.elementType === "PARTSTUDIO"
+ ? "partstudio"
+ : "other";
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+
+ if (kind === "other") {
+ return data({ kind }, { headers: { "Cache-Control": "no-store" } });
+ }
+
+ if (kind === "assembly") {
+ let bom: unknown;
+ try {
+ bom = await onshape.client.getBillOfMaterialsIn(
+ document,
+ elementId,
+ configuration
+ );
+ } catch (error) {
+ const failure = onshapeFailure(error, "bom");
+ return data(failure.body, { status: failure.status });
+ }
+
+ const { root: bomRoot, lines, missingColumns } = parseBomTree(bom);
+ // Without its required columns every line would read "Not in Carbon".
+ if (missingColumns.length > 0) {
+ return data(
+ { error: missingBomColumnsMessage(missingColumns) },
+ { status: 422 }
+ );
+ }
+ let rootPartNumber = bomRoot?.partNumber ?? null;
+ let rootName = bomRoot?.name ?? null;
+ // Non-fatal: the BOM itself read fine.
+ let rootIdentityUnavailable = false;
+ try {
+ const metadata = await onshape.client.getElementMetadata(
+ document,
+ elementId,
+ configuration
+ );
+ rootPartNumber =
+ metadataProperty(metadata, "Part number") ?? rootPartNumber;
+ rootName = metadataProperty(metadata, "Name") ?? rootName;
+ } catch {
+ rootIdentityUnavailable = true;
+ }
+ const flat: PanelAssemblyLineInput[] = [];
+ const walk = (nodes: ReturnType<typeof parseBomTree>["lines"]) => {
+ for (const node of nodes) {
+ flat.push({
+ index: node.index,
+ level: node.level,
+ partNumber: node.partNumber,
+ name: node.name,
+ quantity: node.quantity,
+ itemSource: node.itemSource
+ });
+ walk(node.children);
+ }
+ };
+ walk(lines);
+
+ const partNumbers = [
+ ...new Set(
+ [rootPartNumber, ...flat.map((l) => l.partNumber)].filter(
+ (n): n is string => !!n
+ )
+ )
+ ];
+ // A child's mapping is keyed by the part studio it came from, not by this
+ // assembly element, so the lookup is over the lines' own source keys.
+ const lineExternalIds = [
+ ...new Set(
+ flat
+ .map((line) => externalIdForBomLine(line.itemSource))
+ .filter((id): id is string => !!id)
+ )
+ ];
+
+ const [rootMapping, lineMappings, items] = await Promise.all([
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId, lastSyncedAt")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .eq(
+ "externalId",
+ externalIdForAssembly(documentId, elementId, configuration)
+ )
+ .maybeSingle(),
+ selectInBatches(lineExternalIds, (batch) =>
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId, lastSyncedAt")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .in("externalId", batch)
+ ),
+ selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, name")
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ )
+ ]);
+
+ if (lineMappings.error || rootMapping.error || items.error) {
+ return data(
+ {
+ error: "Carbon couldn't read its items for this assembly. Try again."
+ },
+ { status: 500 }
+ );
+ }
+
+ // entityId has no foreign key, so a mapping can outlive its item. Load the
+ // mapped items to tell a live link from a stale row.
+ const assemblyItems = (items.data ?? []) as PanelItemRow[];
+ const mappedItemIds = [
+ ...new Set(
+ [
+ ...(lineMappings.data ?? []),
+ ...(rootMapping.data ? [rootMapping.data] : [])
+ ]
+ .map((m) => m.entityId)
+ .filter((id) => !assemblyItems.some((i) => i.id === id))
+ )
+ ];
+ const mappedResult = await selectInBatches(mappedItemIds, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, name")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (mappedResult.error) {
+ return data(
+ {
+ error: "Carbon couldn't read its items for this assembly. Try again."
+ },
+ { status: 500 }
+ );
+ }
+ const mappedItems = mappedResult.data as PanelItemRow[];
+ const allItems = [...assemblyItems, ...mappedItems];
+ let released: Awaited<ReturnType<typeof loadReleasedRevisions>>;
+ try {
+ released = await loadReleasedRevisions(client, companyId, assemblyItems);
+ } catch {
+ return data(
+ {
+ error: "Carbon couldn't read its items for this assembly. Try again."
+ },
+ { status: 500 }
+ );
+ }
+
+ const itemByReadableId = new Map(
+ assemblyItems.map((i) => [i.readableId, i])
+ );
+ const rootItem = rootPartNumber
+ ? itemByReadableId.get(rootPartNumber)
+ : undefined;
+ const rootLinkedItem = rootMapping.data
+ ? allItems.find((i) => i.id === rootMapping.data?.entityId)
+ : undefined;
+ const rootReleased = rootPartNumber
+ ? released.get(rootPartNumber)
+ : undefined;
+
+ return data(
+ {
+ kind,
+ assembly: {
+ root: {
+ partNumber: rootPartNumber,
+ name: rootName,
+ identityUnavailable: rootIdentityUnavailable,
+ state: rootReleased
+ ? ("released" as const)
+ : rootLinkedItem
+ ? ("linked" as const)
+ : rootItem
+ ? ("matched" as const)
+ : ("missing" as const),
+ itemId:
+ rootReleased?.itemId ??
+ rootLinkedItem?.id ??
+ rootItem?.id ??
+ null,
+ ...(rootReleased
+ ? { releasedRevision: rootReleased.revision }
+ : {}),
+ lastSyncedAt:
+ rootLinkedItem && !rootReleased
+ ? (rootMapping.data?.lastSyncedAt ?? null)
+ : null
+ },
+ lines: buildAssemblyLineStatuses({
+ lines: flat,
+ mappings: lineMappings.data ?? [],
+ items: allItems,
+ released
+ })
+ }
+ },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+ }
+
+ let parts: Awaited<ReturnType<typeof onshape.client.getPartsInElement>>;
+ try {
+ parts = await onshape.client.getPartsInElement(
+ document,
+ elementId,
+ configuration
+ );
+ } catch (error) {
+ const failure = onshapeFailure(error);
+ return data(failure.body, { status: failure.status });
+ }
+
+ const [mappings, matches] = await Promise.all([
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, externalId, lastSyncedAt")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .like("externalId", `${documentId}:${elementId}:%`),
+ (async () => {
+ const partNumbers = parts
+ .map((p) => p.partNumber)
+ .filter((n): n is string => !!n);
+ return selectInBatches(partNumbers, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, name")
+ .eq("companyId", companyId)
+ .in("readableId", batch)
+ );
+ })()
+ ]);
+
+ if (mappings.error || matches.error) {
+ return data(
+ {
+ error: "Carbon couldn't read its items for these parts. Try again."
+ },
+ { status: 500 }
+ );
+ }
+
+ const mappedItemIds = (mappings.data ?? [])
+ .map((m) => m.entityId)
+ .filter((id) => !(matches.data ?? []).some((i) => i.id === id));
+ const mappedResult = await selectInBatches(mappedItemIds, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId, revision, name")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (mappedResult.error) {
+ return data(
+ {
+ error: "Carbon couldn't read its items for these parts. Try again."
+ },
+ { status: 500 }
+ );
+ }
+ const mappedItems = mappedResult.data as PanelItemRow[];
+ let released: Awaited<ReturnType<typeof loadReleasedRevisions>>;
+ try {
+ released = await loadReleasedRevisions(
+ client,
+ companyId,
+ (matches.data ?? []) as PanelItemRow[]
+ );
+ } catch {
+ return data(
+ {
+ error: "Carbon couldn't read its items for these parts. Try again."
+ },
+ { status: 500 }
+ );
+ }
+
+ const statuses = buildPartStatuses({
+ documentId,
+ elementId,
+ configuration,
+ parts,
+ mappings: mappings.data ?? [],
+ items: [...((matches.data ?? []) as PanelItemRow[]), ...mappedItems],
+ released
+ });
+
+ return data(
+ { kind, parts: statuses },
+ { headers: { "Cache-Control": "no-store" } }
+ );
+}
diff --git a/apps/erp/app/routes/onshape+/_layout.tsx b/apps/erp/app/routes/onshape+/_layout.tsx
new file mode 100644
index 0000000000..6fc8ca6a76
--- /dev/null
+++ b/apps/erp/app/routes/onshape+/_layout.tsx
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { TooltipProvider } from "@carbon/react";
+import { Outlet } from "react-router";
+import type { Handle } from "~/utils/handle";
+
+/** Onshape's `theme` parameter sets the mode; light when it is missing. */
+export const handle: Handle = {
+ hostMode: (searchParams) =>
+ searchParams.get("theme")?.toLowerCase() === "dark" ? "dark" : "light"
+};
+
+/** Bare shell for pages Onshape frames: no app chrome or navigation. */
+export default function OnshapeLayout() {
+ return (
+ <TooltipProvider>
+ {/*
+ * Owns the scroll; never `min-h-dvh`. The app shell makes the root element
+ * a fixed-height scroller, and opening a Radix Select there snaps it to
+ * the top and closes the popup.
+ */}
+ <div className="isolate flex h-dvh flex-col overflow-hidden bg-card text-foreground antialiased">
+ <Outlet />
+ </div>
+ </TooltipProvider>
+ );
+}
diff --git a/apps/erp/app/routes/onshape+/auth.tsx b/apps/erp/app/routes/onshape+/auth.tsx
new file mode 100644
index 0000000000..99502e748d
--- /dev/null
+++ b/apps/erp/app/routes/onshape+/auth.tsx
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";
+import { getUserScopedClient } from "@carbon/auth/client.server";
+import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
+import { requireAuthSession } from "@carbon/auth/session.server";
+import { getUserClaims } from "@carbon/auth/users.server";
+import { PANEL_SESSION_MESSAGE } from "@carbon/ee";
+import { createPanelSession } from "@carbon/ee/onshape/panel-session.server";
+import { getLogger } from "@carbon/logger";
+import { requiresItarEntityCertification } from "@carbon/utils";
+import type { LoaderFunctionArgs } from "react-router";
+import { getCompanySettings } from "~/modules/settings";
+import { getItarCertificationStatus } from "~/modules/users";
+import { path } from "~/utils/path";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+const logger = getLogger("erp", "onshape", "panel-auth");
+
+/** Panel sign-in popup; applies the app shell's MFA and ITAR gates itself. */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const authSession = await requireAuthSession(request);
+ const { companyId, userId } = authSession;
+
+ // Also refuses customer and supplier portal accounts.
+ const claims = await getUserClaims(userId, companyId);
+ if (claims.role !== "employee") {
+ return page("The Onshape panel is available to employees only.", 403);
+ }
+
+ // A console session is a shared device; writes would be stamped with it.
+ if (authSession.console) {
+ return page(
+ "The Onshape panel can't be used from a console session. Sign in to Carbon with your own account.",
+ 403
+ );
+ }
+
+ const client = await getUserScopedClient(userId);
+ const [companySettings, itar] = await Promise.all([
+ getCompanySettings(client, companyId),
+ CONTROLLED_ENVIRONMENT
+ ? getItarCertificationStatus(client, companyId, userId)
+ : Promise.resolve({ entityCertified: true, userCertified: true })
+ ]);
+
+ const itarBlocked =
+ CONTROLLED_ENVIRONMENT &&
+ ((requiresItarEntityCertification(authSession.email) &&
+ !itar.entityCertified) ||
+ !itar.userCertified);
+ const mfaRequired =
+ (CONTROLLED_ENVIRONMENT || companySettings.data?.requireMfa === true) &&
+ !authSession.ssoProviderId;
+ if (
+ itarBlocked ||
+ (mfaRequired && !(await userHasVerifiedTotpFactor(userId)))
+ ) {
+ return page(
+ "Finish setting up your Carbon account, then sign in to the panel again.",
+ 403,
+ { href: path.to.authenticatedRoot, label: "Open Carbon" }
+ );
+ }
+
+ const token = await createPanelSession(authSession);
+ if (!token) {
+ logger.error("Could not store an Onshape panel session", {
+ companyId,
+ userId
+ });
+ return page("Carbon couldn't sign you in. Try again in a moment.", 503);
+ }
+
+ // Safe inside a <script>: no "</" and no JS line terminators.
+ const message = JSON.stringify({ type: PANEL_SESSION_MESSAGE, token })
+ .replace(/</g, "\\u003c")
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+
+ const html = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="robots" content="noindex">
+<title>Carbon</title>
+</head>
+<body style="font-family: system-ui, sans-serif; padding: 2rem; color: #333;">
+<p id="status">Signing you in to the Onshape panel…</p>
+<script>
+(function () {
+ var message = ${message};
+ var opener = window.opener;
+ var delivered = false;
+ try {
+ if (opener && !opener.closed) {
+ opener.postMessage(message, window.location.origin);
+ delivered = true;
+ }
+ } catch (_) {}
+ var status = document.getElementById("status");
+ if (delivered) {
+ status.textContent = "Signed in. You can close this window.";
+ window.close();
+ } else {
+ status.textContent = "Open this page from the Carbon panel in Onshape.";
+ }
+})();
+</script>
+</body>
+</html>
+`;
+
+ return new Response(html, {
+ status: 200,
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Cache-Control": "no-store"
+ }
+ });
+}
+
+function escapeHtml(value: string) {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;");
+}
+
+/** A refusal the user reads in the popup. Nothing is posted to the panel. */
+function page(
+ message: string,
+ status: number,
+ link?: { href: string; label: string }
+) {
+ const action = link
+ ? `<p><a href="${escapeHtml(link.href)}">${escapeHtml(link.label)}</a></p>`
+ : "";
+ return new Response(
+ `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="robots" content="noindex">
+<title>Carbon</title>
+</head>
+<body style="font-family: system-ui, sans-serif; padding: 2rem; color: #333;">
+<p>${escapeHtml(message)}</p>
+${action}
+</body>
+</html>
+`,
+ {
+ status,
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Cache-Control": "no-store"
+ }
+ }
+ );
+}
diff --git a/apps/erp/app/routes/onshape+/panel.tsx b/apps/erp/app/routes/onshape+/panel.tsx
new file mode 100644
index 0000000000..c8291a6fb9
--- /dev/null
+++ b/apps/erp/app/routes/onshape+/panel.tsx
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { OnshapePanel, parsePanelContext } from "@carbon/ee";
+import type {
+ HeadersFunction,
+ LoaderFunctionArgs,
+ MetaFunction
+} from "react-router";
+import { useLoaderData } from "react-router";
+import { path } from "~/utils/path";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+export const meta: MetaFunction = () => [{ title: "Carbon for Onshape" }];
+
+/**
+ * The one route Carbon allows to be framed, and only by Onshape.
+ */
+export const headers: HeadersFunction = () => ({
+ "Content-Security-Policy":
+ "frame-ancestors https://onshape.com https://*.onshape.com"
+});
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const url = new URL(request.url);
+ // No auth here: the iframe cannot carry the session cookie. The panel signs
+ // the user in through a popup and talks to the API with a bearer token.
+ return parsePanelContext(url.searchParams);
+}
+
+export default function OnshapePanelRoute() {
+ const { context, serverOrigin } = useLoaderData<typeof loader>();
+
+ return (
+ <OnshapePanel
+ context={context}
+ serverOrigin={serverOrigin}
+ paths={{
+ auth: path.to.onshapePanelAuth,
+ me: path.to.api.onShapePanelMe,
+ fields: path.to.api.onShapePanelFields,
+ session: path.to.api.onShapePanelSession,
+ status: path.to.api.onShapePanelStatus,
+ planPart: path.to.api.onShapePanelPlanPart,
+ planAssembly: path.to.api.onShapePanelPlanAssembly,
+ planRelease: path.to.api.onShapePanelPlanRelease,
+ pushPart: path.to.api.onShapePanelPushPart,
+ pushAssembly: path.to.api.onShapePanelPushAssembly,
+ pushRelease: path.to.api.onShapePanelPushRelease,
+ releases: path.to.api.onShapePanelReleases
+ }}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
index fbc2565dc5..a292c1f982 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
@@ -16,6 +16,7 @@ import { Suspense } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Await, useLoaderData, useParams } from "react-router";
import { CadModel, DeferredFiles } from "~/components";
+import { ExternalSourceCard } from "~/components/ExternalSource";
import { usePermissions, useRouteData } from "~/hooks";
import type { ItemFile, MakeMethod, PartSummary } from "~/modules/items";
import {
@@ -420,6 +421,10 @@ export default function PartDetailsRoute() {
title={t`CAD Model`}
titleExtras={lockHint}
/>
+ <ExternalSourceCard
+ itemId={itemId}
+ canDetach={permissions.can("update", "parts")}
+ />
<ItemRiskRegister itemId={itemId} />
<ItemChangeNotices
changeNotices={changeNotices ?? []}
diff --git a/apps/erp/app/utils/handle.ts b/apps/erp/app/utils/handle.ts
index ce215249f6..e49aa04bb5 100644
--- a/apps/erp/app/utils/handle.ts
+++ b/apps/erp/app/utils/handle.ts
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { RouteRealtimeTable } from "@carbon/database/realtime-tables";
+import type { Mode } from "@carbon/utils";
import type { MessageDescriptor } from "@lingui/core";
import type { ComponentType, ReactNode } from "react";
@@ -26,6 +27,9 @@ export type Handle = {
// Phones only: the app bar's subtitle under a record's ID ("Sales Order"),
// in place of the list crumb. Child routes (a line page) inherit it.
appBarSubtitle?: MessageDescriptor;
+ // A page another product frames (the Onshape panel) takes its mode from the
+ // host's URL, not from the user's own mode.
+ hostMode?: (searchParams: URLSearchParams) => Mode;
};
// A breadcrumb label may be plain text/markup or a Lingui MessageDescriptor
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 61934b05d2..9f6974c767 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -252,11 +252,23 @@ export const path = {
generatePath(
`${api}/integrations/onshape/d/${documentId}/v/${versionId}/e/${elementId}/bom`
),
+ onShapeDetach: `${api}/integrations/onshape/detach`,
onShapeDocuments: `${api}/integrations/onshape/documents`,
onShapeElements: (documentId: string, versionId: string) =>
generatePath(
`${api}/integrations/onshape/d/${documentId}/v/${versionId}/elements`
),
+ onShapePanelFields: `${api}/integrations/onshape/panel/fields`,
+ onShapePanelMe: `${api}/integrations/onshape/panel/me`,
+ onShapePanelPlanAssembly: `${api}/integrations/onshape/panel/plan-assembly`,
+ onShapePanelPlanPart: `${api}/integrations/onshape/panel/plan-part`,
+ onShapePanelPlanRelease: `${api}/integrations/onshape/panel/plan-release`,
+ onShapePanelPushAssembly: `${api}/integrations/onshape/panel/push-assembly`,
+ onShapePanelPushPart: `${api}/integrations/onshape/panel/push-part`,
+ onShapePanelPushRelease: `${api}/integrations/onshape/panel/push-release`,
+ onShapePanelReleases: `${api}/integrations/onshape/panel/releases`,
+ onShapePanelSession: `${api}/integrations/onshape/panel/session`,
+ onShapePanelStatus: `${api}/integrations/onshape/panel/status`,
onShapeSync: `${api}/integrations/onshape/sync`,
onShapeVersions: (documentId: string) =>
generatePath(`${api}/integrations/onshape/d/${documentId}/versions`),
@@ -1925,6 +1937,8 @@ export const path = {
theme: `${onboarding}/theme`,
user: `${onboarding}/user`
},
+ onshapePanel: "/onshape/panel",
+ onshapePanelAuth: "/onshape/auth",
operationBatch: (id: string) =>
generatePath(`${x}/production/batches/${id}`),
operationBatches: `${x}/production/batches`,
diff --git a/ci/src/deploy.ts b/ci/src/deploy.ts
index 76bf862403..756f08ae38 100644
--- a/ci/src/deploy.ts
+++ b/ci/src/deploy.ts
@@ -59,6 +59,9 @@ export type Workspace = {
onshape_client_id: string | null;
onshape_client_secret: string | null;
onshape_oauth_redirect_url: string | null;
+ onshape_v2_client_id: string | null;
+ onshape_v2_client_secret: string | null;
+ onshape_v2_oauth_redirect_url: string | null;
openai_api_key: string | null;
posthog_api_host: string | null;
posthog_project_public_key: string | null;
@@ -146,6 +149,9 @@ async function deploy(): Promise<void> {
onshape_client_id,
onshape_client_secret,
onshape_oauth_redirect_url,
+ onshape_v2_client_id,
+ onshape_v2_client_secret,
+ onshape_v2_oauth_redirect_url,
openai_api_key,
posthog_api_host,
posthog_project_public_key,
@@ -310,6 +316,10 @@ async function deploy(): Promise<void> {
ONSHAPE_CLIENT_ID: onshape_client_id ?? undefined,
ONSHAPE_CLIENT_SECRET: onshape_client_secret ?? undefined,
ONSHAPE_OAUTH_REDIRECT_URL: onshape_oauth_redirect_url ?? undefined,
+ ONSHAPE_V2_CLIENT_ID: onshape_v2_client_id ?? undefined,
+ ONSHAPE_V2_CLIENT_SECRET: onshape_v2_client_secret ?? undefined,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL:
+ onshape_v2_oauth_redirect_url ?? undefined,
OPENAI_API_KEY: openai_api_key,
POSTHOG_API_HOST: posthog_api_host ?? undefined,
POSTHOG_PROJECT_PUBLIC_KEY: posthog_project_public_key ?? undefined,
diff --git a/docs/content/docs/integrations/cad.mdx b/docs/content/docs/integrations/cad.mdx
index a1f3822851..07ff8894d4 100644
--- a/docs/content/docs/integrations/cad.mdx
+++ b/docs/content/docs/integrations/cad.mdx
@@ -1,39 +1,154 @@
---
title: CAD
plan: Business
-description: Sync CAD data from Onshape and Onshape Government into Carbon.
+description: Sync CAD data from Onshape and Onshape Government into Carbon, or push it from inside Onshape.
---
-## Onshape
+## Two Onshape integrations
-Connect **Onshape** through **OAuth** to import CAD data into Carbon.
+Carbon ships two Onshape integrations side by side. They share nothing: each is its
+own Onshape OAuth application, with its own connection, its own credentials and its
+own record of which Carbon items are linked. A company can connect either, both, or
+neither, and disconnecting one never affects the other.
+
+| Integration | Id | Direction | What it does |
+| --- | --- | --- | --- |
+| **Onshape** | `onshape` | Pull | Carbon lists documents and pulls models. With **Sync released assets** on, a webhook attaches released drawings and CAD models to Carbon items that already exist, matched by part number. It never creates items. |
+| **Onshape V2** | `onshape-v2` | Push | A Carbon panel inside Onshape. You push parts, assemblies and releases from the CAD document when they are ready. Carbon never pulls on its own. |
+
+**Onshape Government** is a third, pull-only variant of **Onshape** for the ITAR and
+FedRAMP edition, connected through a private OAuth app your Enterprise owns; see
+[Onshape Government](#onshape-government).
+
+**Onshape V2** is the one to use for the panel. If the Carbon icon appears in
+Onshape but the panel reports that nothing is connected, the company connected
+**Onshape** and not **Onshape V2** — connect V2 as well.
+
+<Callout type="warn">
+Each card needs its own OAuth client configured server-side: **Onshape V2** reads
+`ONSHAPE_V2_CLIENT_ID`, **Onshape** reads `ONSHAPE_CLIENT_ID`. Without it the card
+reads **Not Configured** and cannot be installed. Connect also needs that
+integration's client secret and redirect URL. See
+[Environment variables](/docs/platform/self-hosting/environment-variables) and the
+setup section below.
+</Callout>
+
+## Set up the Onshape applications
+
+Everything below is done once per Carbon deployment, by whoever operates it. It is
+the same for cloud and self-hosted Carbon. Each integration has its own OAuth
+application in the Onshape developer portal, and each reads only its own variables:
+
+| | Onshape V2 (panel) | Onshape (pull) |
+| --- | --- | --- |
+| Client id | `ONSHAPE_V2_CLIENT_ID` | `ONSHAPE_CLIENT_ID` |
+| Client secret | `ONSHAPE_V2_CLIENT_SECRET` | `ONSHAPE_CLIENT_SECRET` |
+| Redirect URL | `ONSHAPE_V2_OAUTH_REDIRECT_URL` | `ONSHAPE_OAUTH_REDIRECT_URL` |
+| Redirect URI to register | `https://<erp-host>/api/integrations/onshape-v2/oauth` | `https://<erp-host>/api/integrations/onshape/oauth` |
+| Panel extension | Yes | No |
+
+Set up **Onshape V2** to use the panel. Set up **Onshape** only if you want
+released-asset sync.
<Steps>
<Step>
- ### Authorize over OAuth
+ ### Create an OAuth application for each integration
+
+ Sign in at [dev-portal.onshape.com](https://dev-portal.onshape.com), create an
+ OAuth application, and grant it both the read scope (`OAuth2Read`) and the write
+ scope (`OAuth2Write`, labelled **Application can write to your documents**). The
+ panel writes nothing to Onshape, but Onshape refuses the authorization with
+ `invalid_scope` unless the application holds every scope Carbon asks for, and
+ Carbon asks for both.
+
+ Copy the application's client id and secret into that integration's variables
+ from the table above.
+ </Step>
+ <Step>
+ ### Register each application's redirect URI
- Start the connection and Carbon opens an Onshape popup.
+ Each integration completes OAuth at its own callback. On each application,
+ register that integration's redirect URI from the table above, with your Carbon
+ ERP origin as the host, and put the same value in its redirect URL variable.
+
+ The value in each env var must match the registered URI character for character.
+ A mismatch fails the token exchange, which the Connect popup reports as a
+ connection error.
</Step>
<Step>
- ### Approve read access
+ ### Add an extension for the panel
+
+ On the **Onshape V2** application, add an extension with location **Element right
+ panel** and this action URL, again with your Carbon ERP origin:
+
+ ```
+ https://<erp-host>/onshape/panel?documentId={$documentId}&wv={$workspaceOrVersion}&wvId={$workspaceOrVersionId}&elementId={$elementId}&partNumber={$partNumber}&revision={$revision}&nodeId={$nodeId}&occurrencePath={$occurrencePath}&configuration={$configuration}
+ ```
- Approve read access to your Onshape documents in the popup.
+ Carbon reads the parameters by the names on the left of each `=`; the `{$…}`
+ placeholders are substituted by Onshape. Onshape appends `server`, `companyId`,
+ `userId`, `locale` and `clientId` on its own; do not add them. The panel tells
+ Onshape it is ready at the `server` origin. Without `server` it shows "Open this
+ panel from Onshape".
</Step>
<Step>
- ### Tokens stored
+ ### Subscribe the users who should see the panel
- Carbon stores the access and refresh tokens and can then read your Onshape documents.
+ An extension renders only for Onshape users who are **subscribed** to the
+ **Onshape V2** application. Publish it to your private App Store and have each
+ user open it there and choose **Get for free**. Completing OAuth in Carbon does
+ not do this — a user with a working Carbon connection and no subscription sees no
+ Carbon icon in Onshape at all.
</Step>
-</Steps>
+ <Step>
+ ### Restart Carbon with the new environment
-| Setting | What it controls |
-| --- | --- |
-| Connection | Established by OAuth — no keys to paste. Carbon stores the access and refresh tokens for you. |
+ The env vars are read at boot. On the Carbon side the `onshape-v2` integration
+ row is seeded by a database migration, so a deployment that is behind on
+ migrations shows only the **Onshape** card.
-<Callout type="warn">
-Onshape appears only when `ONSHAPE_CLIENT_ID` is configured server-side. See [Environment variables](/docs/platform/self-hosting/environment-variables).
+ A connection belongs to the application that authorized it. If you change an
+ integration's client id, every company must connect that integration again.
+ </Step>
+</Steps>
+
+<Callout type="note">
+Private Onshape applications debit the application owner's annual API quota on every
+call. A publicly listed App Store application is exempt.
</Callout>
+## Connect a company
+
+In Carbon, open **Settings → Integrations**. Both Onshape cards are in the CAD
+category.
+
+<Steps>
+ <Step>
+ ### Connect Onshape V2
+
+ Press **Connect** on **Onshape V2**. A popup opens on Onshape; approve access. The
+ popup closes on its own and the card switches to Installed. The card holds the
+ connection only; the property map and the push defaults are on the panel's
+ **Fields** page.
+ </Step>
+ <Step>
+ ### Optionally connect Onshape
+
+ Only if you want released-asset sync. **Sync released assets** and **Backfill
+ released assets** are on this card. This connection is independent of V2.
+ </Step>
+</Steps>
+
+If the popup ends in an error:
+
+| Message | Cause | Fix |
+| --- | --- | --- |
+| *Onshape isn't configured* | The integration's client id, client secret or redirect URL env var is missing. Each integration reads only its own three variables. | Set the variable for that integration and restart. |
+| *Onshape denied the connection*, mentioning write permission | Onshape returned `invalid_scope`. | Grant `OAuth2Write` on the OAuth application. |
+| *Onshape rejected the authorization* | The token exchange failed: redirect URI mismatch, wrong client secret, or the redirect URI is registered on the other integration's application. | Compare the env var to the URI registered on that integration's own application, character for character. |
+| *Couldn't save the Onshape connection* | Onshape authorized but the database write failed. | Check the server logs; retry. |
+| Nothing happens on Connect | The browser blocked the popup. | Allow popups for the Carbon origin and retry. |
+
## Onshape Government
**Onshape Government** is Onshape's ITAR and FedRAMP edition. Because it has no public App Store, your Enterprise must create a **private OAuth app** for Carbon. After connection, it supports document browsing, bill-of-materials imports, and released-asset synchronization.
@@ -75,6 +190,224 @@ leave it off if your allowance is tight.
A company can connect to only one Onshape environment. Disconnect the current integration before connecting the other.
+## The Carbon panel in Onshape
+
+Open a Part Studio, an assembly or a drawing and click the Carbon icon in the right
+panel. Press **Sign in to Carbon**: a popup on Carbon's own origin signs you in (or
+sends you through the normal login first) and closes itself. The session lasts up to
+12 hours and is held only in that browser tab.
+
+The panel works in the Carbon **company you are signed in to** in the Carbon tab the
+popup used; the top of the panel shows which. To push into a different company,
+switch company in Carbon, then press **Sign out** and **Sign in to Carbon** in the
+panel.
+
+The panel has three pages:
+
+- **Parts**, **Assembly** or **Push**, after the element you have open. A drawing
+ has nothing to push here; its PDF comes in with a release.
+- **Releases**, for the whole document.
+- **Fields**, on a Part Studio or an assembly, for users with the
+ **settings: update** permission in Carbon.
+
+Pushing works in a workspace or a version. In a microversion the panel shows status
+only.
+
+### Status
+
+Each part or BOM line shows its state before anything is pushed:
+
+| State | Meaning |
+| --- | --- |
+| **Linked** | A panel push linked this Onshape part to a Carbon item. |
+| **Conflict** | Carbon has an item with this part number that is not linked to this part. A push uses that item. |
+| **Unlinked** | Carbon has no item with this part number. A push creates one. |
+| **Released** | The part is released in Onshape. Push it from **Releases**; its Push button is off. |
+
+An assembly's bill of materials shows as a tree, collapsed to the top level, the way
+Onshape's structured BOM does.
+
+### Review before anything is written
+
+Every push is two steps. Pressing **Push** shows a review of what Carbon would do;
+nothing is written yet:
+
+- items that will be **created**, with the values they will get. Replenishment,
+ default method type and tracking type can be changed here; the item ID and
+ revision come from Onshape. Each mapped value shows the Onshape property it came
+ from (see [Fields](#fields)); anything not mapped starts from the push defaults.
+- items that will be **linked** to an existing Carbon item by part number, or
+ **updated** because Onshape changed. The review lists the values the push replaces
+ (fields set to *Update on every push*) and the Onshape values Carbon keeps (fields
+ set to *Set at creation*).
+- for an assembly, each make method with the lines it gains, the lines a previous
+ push wrote that change, the lines added by hand that the push takes over, and the
+ ones it keeps.
+- for a release, every revision it creates and the change notice it uses.
+
+**Push _n_ to Carbon** applies the review as shown; **Cancel** writes nothing. A
+review is held for 15 minutes; after that, **Review again**. A choice made in the
+review is written to Carbon only; Onshape keeps its values.
+
+### Push a part
+
+Creates or updates the Carbon item for an Onshape part: the part number becomes the
+item ID, plus name, description, revision, the 3D model and a thumbnail. Pushing again
+after a change updates the item. Pushing an unchanged part writes only mapped values
+that differ, and exports nothing. Parts need a part number in Onshape first. **Push
+all** pushes every numbered part in the Part Studio, at most 50.
+
+After the push the item is a Carbon item like any other, and every field stays
+editable. A later push replaces only the fields set to *Update on every push* on the
+[Fields](#fields) page. The item page shows an **Onshape card** with the link, the
+fields a push replaces, **Open in Onshape**, and **Detach**, which removes the link
+so pushes stop updating the item. The card shows links made by the panel only.
+
+### Push an assembly
+
+Pushes the assembly and its bill of materials: every item in the BOM is created if
+missing, and the BOM lands on the assembly's make methods, sub-assemblies included.
+A push changes only what Onshape changed: lines a previous push wrote are updated or
+removed. A line you added by hand for a part Onshape's BOM also lists is taken over;
+its quantity follows Onshape, and its operation and scrap stay. A hand-added line for
+a part Onshape doesn't list is left alone.
+
+An assembly with more than 1,500 distinct parts is refused as a whole; **Push this
+level only** pushes its top-level BOM, with each sub-assembly as one line.
+
+Items in the BOM that are not yet linked to an Onshape part are linked to theirs.
+Every item linked to its BOM row takes the values set to *Update on every push*. Only
+values Onshape has are written, so an empty Name or Description cell never blanks
+Carbon's text. An item already linked to a different Onshape part keeps that link,
+and the push writes nothing to it.
+
+**Buy or Make.** For a new item, the first of these that gives a value wins:
+
+1. your choice in the review,
+2. the Onshape property mapped to Replenishment (see [Fields](#fields)),
+3. a BOM row with components is Make,
+4. a part from Onshape's Standard content library is Buy,
+5. the push default.
+
+A sub-assembly whose **Subassembly BOM behavior** is *Show assembly only* is listed
+without components, so the push writes no BOM for it. It says nothing about Buy or
+Make. The review warns when an item's Buy or Make and Onshape's BOM disagree: a Buy
+item that would get a BOM, or a Make item Onshape shows as one unit.
+
+**A released make method is never edited.** When an assembly's method is Active and
+Onshape's BOM differs from it, the push takes a new **Draft** version and writes
+there, the same way a Version change works in Carbon. Nothing live moves until
+someone releases the Draft. Pushing again writes into the same Draft. The push result
+lists each new Draft as *not yet live*.
+
+### Push a release
+
+The **Releases** page lists the document's 20 newest Onshape releases, each marked
+**In Carbon**, **Partial** or **Not in Carbon**. Pushing one:
+
+- creates a Carbon **revision** of every released part and assembly at the released
+ revision letter, copied from the revision below it when Carbon has one,
+- writes each released assembly's BOM, as of the released version, to the new
+ revision's method,
+- takes each released item's mapped values at its released version,
+- attaches models and thumbnails at the released version, and each released drawing
+ as a PDF named `<part number>-<revision>.pdf` on its part.
+
+The new revisions go on one draft **change notice**, named after the release. They
+stay inactive until you release that notice in Carbon, which activates them and
+supersedes each previous revision. Pushing the release again adds to the same notice
+while it is open and not waiting for approval, and creates nothing twice; otherwise
+the push starts a new notice. BOM components the push has to create are not on the
+notice.
+
+A release with only a drawing reads **In Carbon** once its PDF is attached. Release
+management needs an Onshape company account; without one the page says so.
+
+### Fields
+
+The **Fields** page maps Onshape properties (Vendor, Project, Material, your
+company's custom properties) onto Carbon. A property can set an **item field** or a
+**custom field** on the part. The page lists the properties of the element you have
+open, but the mappings belong to the company and apply to every push. It lives in
+the panel because Onshape lists properties only from inside a document.
+
+The page starts with fixed rows: Part number and Revision always come from Onshape,
+and Name and Description each have a mode (below). Then come the item fields with
+their **push defaults**, the values a new item gets when no property sets them:
+
+| Item field | Values | Push default |
+| --- | --- | --- |
+| Replenishment | Buy, Make, Buy and Make | Make |
+| Default Method Type | Make to Order, Pull from Inventory, Purchase to Order | Make to Order (Make), Pull from Inventory (Buy) |
+| Tracking Type | Inventory, Non-Inventory, Serial, Batch | Inventory |
+| Unit of Measure | your company's units | EA, or your company's first unit |
+| Manufacturer Part Number | the property's text | none |
+| Sourcing | Specified, Drop Ship, Ship from Inventory (Buy and Make items only) | none |
+
+- A list field has a **translation**: each row turns an Onshape value into a Carbon
+ value. The rows start with Carbon's own values, so an Onshape list with the same
+ options needs no setup. Set a row to *No value* to leave the field to the next
+ rule. An Onshape value with no row is called out in the review and not written.
+- A Unit of Measure value that matches a unit's code or name needs no row.
+- Item fields are written the way the item page writes them. Changing Replenishment
+ also sets the method that goes with it. A change of Replenishment, method or
+ sourcing also updates the item's lines on Draft BOMs; a change of tracking type
+ also updates open jobs, receipts, shipments and transfers.
+
+**Custom fields:** create the field in Carbon first, then select it here. Text, list
+and object properties map to Text fields, booleans to Yes/No, numbers to Numeric,
+dates to Date. Onshape's computed, user, file and category properties can't be
+mapped; the page names them under the list. A property with no Carbon field of its
+type says which part custom field type to add.
+
+Each Carbon field takes one property. A field another property already sets stays in
+the list, greyed out, with that property's name.
+
+**When Onshape writes a field.** Each mapping, and the item's Name and Description,
+has one of two modes:
+
+- **Set at creation** (the default): Onshape fills the field when a push creates the
+ item. After that, Carbon owns the field and later pushes don't change it.
+- **Update on every push**: every push replaces Carbon's value with Onshape's,
+ including edits made in Carbon. An empty custom field property clears the Carbon
+ field; an empty item field or description is never written.
+
+**Set up Buy or Make.** Onshape has no Buy/Make property. Create a list property in
+Onshape, for example *Make or buy*, with the options Buy, Make, and Buy and Make. Map
+it to Replenishment here and set the value on the parts your company buys. Parts from
+Onshape's Standard content library (fasteners and other hardware) come in as Buy when
+no property gives a value.
+
+- Carbon matches a list value by its display name in Onshape, or by its value when it
+ has no display name.
+- An Onshape default is a value: every part with no value of its own sends the
+ default. With **Update on every push**, a default replaces Carbon's value on every
+ linked item nobody set in Onshape. Leave the Onshape default empty to let the push
+ defaults decide for new items.
+- A property that applies only to parts has no value on assembly rows. Carbon writes
+ nothing there.
+
+**Refresh** re-reads the properties and the field list. **Save** saves the map and
+the push defaults together.
+
+## Troubleshooting the panel
+
+| Symptom | Cause | Fix |
+| --- | --- | --- |
+| No Carbon icon in the Onshape right panel | The Onshape user is not subscribed to the **Onshape V2** application, or the extension is missing from it. | Subscribe via the private App Store; check the extension exists with location Element right panel. |
+| *Open this panel from Onshape* | The page was opened outside Onshape, so no Onshape `server` origin arrived with it. | Open the panel from the Onshape right panel; check the extension's action URL points at the ERP host. |
+| Panel is blank inside Onshape | The route is framed from an origin other than `*.onshape.com`, or the ERP host is unreachable from the browser. | Carbon only allows Onshape to frame it; check the ERP origin in the action URL. |
+| Sign-in popup shows *Open this page from the Carbon panel in Onshape* | The popup was opened directly, not from the panel. | Use the **Sign in to Carbon** button. |
+| The panel returns to **Sign in to Carbon** | The panel session ended: 12 hours, the controlled-environment session limit, or Sign out. | Sign in again. |
+| *Carbon is not reachable* | The panel's first request to Carbon failed: the ERP host is unreachable or answered with an error, shown under the title. | **Retry**, or **Sign in again**; check the ERP host and the server logs. |
+| *The yearly API limit for Carbon's Onshape app is used up* | Onshape answers every call with HTTP 402 once the yearly API limit of the account that owns the OAuth application is spent. | Raise the limit with Onshape. The owner sees its usage under **Company settings → Developer**. A publicly listed App Store application is exempt. |
+| *Onshape is not connected for this company* | Only **Onshape** (sync) is connected, or no Onshape integration is. | Connect **Onshape V2**. |
+| The review fails to open with a 503 | Carbon could not store the review in Redis. | Check `REDIS_URL`. |
+| *Review again* after **Push to Carbon** | The 15-minute review expired, or it was already applied. | Press **Review again**. |
+| A part shows **Conflict** | Carbon already has an item with that part number, made by hand, by an import or by the sync integration. | Push it: the panel links and updates that item instead of creating a duplicate. |
+| The push result says *New Draft version, not yet live* | The assembly's make method was released, so the push wrote to a Draft version. | Release the Draft in Carbon when ready. |
+| `invalid_scope` on Connect | The OAuth application lacks `OAuth2Write`. | Grant it in the developer portal. |
+
## Related
<Cards>
@@ -84,4 +417,10 @@ A company can connect to only one Onshape environment. Disconnect the current in
<Card title="Methods & sourcing" href="/docs/reference/methods">
How a part's bill of materials is built up.
</Card>
+ <Card title="Revisions" href="/docs/reference/items#revisions">
+ Why each revision of a part is its own item record.
+ </Card>
+ <Card title="Environment variables" href="/docs/platform/self-hosting/environment-variables">
+ The Onshape variables a deployment needs.
+ </Card>
</Cards>
diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdx
index 35992c0fd0..23fd7e5011 100644
--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx
+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx
@@ -112,12 +112,20 @@ OAuth credentials for each connector, all optional, set only the ones you use.
<EnvVar name="JIRA_CLIENT_SECRET" type="string">Jira OAuth client secret.</EnvVar>
<EnvVar name="SLACK_CLIENT_ID" type="string">Slack OAuth client id.</EnvVar>
<EnvVar name="SLACK_CLIENT_SECRET" type="string">Slack OAuth client secret.</EnvVar>
-<EnvVar name="ONSHAPE_CLIENT_ID" type="string">Onshape OAuth client id.</EnvVar>
-<EnvVar name="ONSHAPE_CLIENT_SECRET" type="string">Onshape OAuth client secret.</EnvVar>
+<EnvVar name="ONSHAPE_CLIENT_ID" type="string">Client id of the Onshape OAuth application for the pull integration (`onshape`). Without it the Onshape card reads Not Configured.</EnvVar>
+<EnvVar name="ONSHAPE_CLIENT_SECRET" type="string">Client secret of the pull integration's Onshape OAuth application.</EnvVar>
+<EnvVar name="ONSHAPE_OAUTH_REDIRECT_URL" type="url">Callback for the pull integration: `https://<erp-host>/api/integrations/onshape/oauth`. Must be registered on the pull integration's Onshape application.</EnvVar>
+<EnvVar name="ONSHAPE_V2_CLIENT_ID" type="string">Client id of the Onshape OAuth application for the panel integration (`onshape-v2`), a separate application from the pull integration's. Without it the Onshape V2 card reads Not Configured.</EnvVar>
+<EnvVar name="ONSHAPE_V2_CLIENT_SECRET" type="string">Client secret of the panel integration's Onshape OAuth application.</EnvVar>
+<EnvVar name="ONSHAPE_V2_OAUTH_REDIRECT_URL" type="url">Callback for the panel integration: `https://<erp-host>/api/integrations/onshape-v2/oauth`. Must be registered on the panel integration's Onshape application. Without it the Onshape V2 Connect button fails with "Onshape isn't configured".</EnvVar>
<EnvVar name="EXCHANGE_RATES_API_KEY" type="string">Currency exchange-rate feed.</EnvVar>
<EnvVar name="GOOGLE_PLACES_API_KEY" type="string">Address autocomplete.</EnvVar>
</EnvVars>
+The Onshape panel also needs an extension registered on the Onshape application and the
+panel's users subscribed to it — see [CAD](/docs/integrations/cad). Panel sessions and push
+reviews are held in Redis, so `REDIS_URL` is required for the panel to work.
+
## Infrastructure — SST
Read by `sst.config.ts` at deploy time, not by the app.
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 0c2d40e908..914baba0ee 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -54,6 +54,12 @@ pnpm --filter @carbon/auth test
SAML SSO lives in `@carbon/ee/sso.server` (Enterprise-gated), NOT here — auth
only carries `AuthSession.ssoProviderId` and its preservation across refresh.
+The Onshape panel's bearer credential (the `cps_` iframe session) lives in
+`@carbon/ee/onshape/panel-session.server`, not here, with its own gate
+`requireOnshapePanelPermissions`. `requirePermissions` stays cookie and API key
+only. ee imports `getUserClaims`, `userHasVerifiedTotpFactor`,
+`getUserScopedClient` and `hasPermission` from auth, never the reverse.
+
## Cross-References
- `.claude/rules/authentication-system.md` — full auth architecture, login flows, claims caching
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index 2b350ab4a2..9462b45e2a 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -537,6 +537,7 @@
"no-raw-rounding::packages/ee/src/accounting/providers/rillet/entities/journal-entry.ts::amount: roundCurrency(Math.abs(signedAmount)).toFixed(2),",
"no-raw-rounding::packages/ee/src/accounting/providers/xero/provider.ts::Number.isNaN(sinceMs) ? Date.now() : Math.floor(sinceMs / 1000) * 1000",
"no-raw-rounding::packages/ee/src/onshape/lib/client.ts::`Onshape external data ${foreignId} exceeds the ${Math.round(",
+ "no-raw-rounding::packages/ee/src/onshape/panel/session-policy.ts::Math.min(PANEL_SESSION_TTL_SECONDS, Math.floor(remainingMs / 1000))",
"no-raw-rounding::packages/ee/src/slack/lib/client.ts::const currentTime = Math.floor(Date.now() / 1000);",
"no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `on <!date^${Math.floor(",
"no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `• Completed <!date^${Math.floor(",
diff --git a/packages/database/supabase/migrations/20261016051650_onshape-v2-integration.sql b/packages/database/supabase/migrations/20261016051650_onshape-v2-integration.sql
new file mode 100644
index 0000000000..8e1e6d72e0
--- /dev/null
+++ b/packages/database/supabase/migrations/20261016051650_onshape-v2-integration.sql
@@ -0,0 +1,31 @@
+-- `onshape-v2`: the push-only panel integration, with its own OAuth grant,
+-- companyIntegration row and mapping namespace beside `onshape`.
+-- `baseUrl` is optional: the client defaults it to cad.onshape.com.
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES
+ (
+ 'onshape-v2',
+ '{
+ "type": "object",
+ "properties": {
+ "baseUrl": {"type": "string"},
+ "credentials": {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string"},
+ "expiresAt": {"type": "string"}
+ },
+ "required": ["type"]
+ },
+ "scope": {"type": "string"},
+ "propertyMap": {"type": "array"},
+ "defaultUnitOfMeasureCode": {"type": "string"},
+ "defaultReplenishmentSystem": {"type": "string"},
+ "defaultMethodTypeForMake": {"type": "string"},
+ "defaultMethodTypeForBuy": {"type": "string"},
+ "defaultItemTrackingType": {"type": "string"}
+ },
+ "required": ["credentials"]
+ }'::json
+ )
+ON CONFLICT ("id") DO NOTHING;
diff --git a/packages/database/supabase/migrations/20261016051651_onshape-v2-vault-secrets.sql b/packages/database/supabase/migrations/20261016051651_onshape-v2-vault-secrets.sql
new file mode 100644
index 0000000000..26911c591e
--- /dev/null
+++ b/packages/database/supabase/migrations/20261016051651_onshape-v2-vault-secrets.sql
@@ -0,0 +1,37 @@
+-- NIST 800-171 3.13.16: moves `onshape-v2` OAuth tokens from
+-- companyIntegration.metadata into Supabase Vault and strips them in the same
+-- pass. Idempotent: a stripped row has nothing to vault.
+DO $$
+DECLARE
+ r RECORD;
+ v_meta jsonb;
+ v_bag jsonb;
+ v_path text;
+ v_val jsonb;
+ v_paths text[] := ARRAY['credentials.accessToken', 'credentials.refreshToken'];
+BEGIN
+ FOR r IN
+ SELECT "companyId", metadata FROM "companyIntegration" WHERE id = 'onshape-v2'
+ LOOP
+ v_meta := r.metadata::jsonb;
+ IF v_meta IS NULL THEN CONTINUE; END IF;
+
+ v_bag := '{}'::jsonb;
+ FOREACH v_path IN ARRAY v_paths LOOP
+ v_val := v_meta #> string_to_array(v_path, '.');
+ IF v_val IS NOT NULL AND v_val <> '""'::jsonb AND v_val <> 'null'::jsonb THEN
+ v_bag := v_bag || jsonb_build_object(v_path, v_val);
+ END IF;
+ END LOOP;
+
+ IF v_bag <> '{}'::jsonb THEN
+ PERFORM upsert_integration_secret(r."companyId", 'onshape-v2', v_bag);
+ END IF;
+
+ FOREACH v_path IN ARRAY v_paths LOOP
+ v_meta := v_meta #- string_to_array(v_path, '.');
+ END LOOP;
+ UPDATE "companyIntegration" SET metadata = v_meta::json
+ WHERE "companyId" = r."companyId" AND id = 'onshape-v2';
+ END LOOP;
+END $$;
diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.md
index 76e078cbf0..eafeed1861 100644
--- a/packages/dev/AGENTS.md
+++ b/packages/dev/AGENTS.md
@@ -54,7 +54,7 @@ pnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, u
- **Dev servers** — they hold more than the containers (roughly 1 GB each). After `CRBN_APPS_IDLE_MINUTES` (default 120) `crbn up` aborts them (`spawnApps`' `signal`) and listens on their ports itself (`startWaker`). A request there cannot be handed over — the dev server needs that port — so a browser gets a page that polls and reloads, anything else a 503 with `x-crbn-waking`. Inngest polls and WebSocket upgrades (an open tab's Vite client probing for its server) do not wake it. That wake is about 40 s: the dev servers boot from cold.
- Off for `--no-apps`, `--run`, `--borrow` (the owning `crbn up` does it) and `--no-hibernate`. Traffic that never reaches ERP/MES (`psql`, scripts on the API) does not count; `crbn migrate` and `crbn restore` wake a sleeping stack themselves (`wakeIfAsleep`). `crbn list` and `crbn status` show a hibernated stack.
- **`crbn prune` also clears stale portless routes** (`findStaleAliases`): static aliases crbn registered whose port no live slot owns. `portless prune` only reaps routes that have a process.
-- **Env**: `env.ts` — `renderEnv()`, `writeEnv()`, `syncAppPortlessConfigs()`
+- **Env**: `env.ts` — `renderEnv()`, `writeEnv()`, `syncAppPortlessConfigs()`. URLs derived from the stack's ERP host (`ERP_URL`, `VERCEL_URL`, `INNGEST_SERVE_HOST`, `ONSHAPE_V2_OAUTH_REDIRECT_URL`) come from one `erpUrl`; a key a developer must keep fixed (a tunnel, a registered redirect URI) is pinned in `.env` with `#force`
- **`--run` flag**: scopes stack lifetime to a command (for headless/CI builds); `--volumes` cleans up Docker volumes on teardown
## Cross-References
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
index 8004bcfe38..f483efce0b 100644
--- a/packages/dev/src/env.test.ts
+++ b/packages/dev/src/env.test.ts
@@ -37,6 +37,9 @@ describe("renderEnv (portless disabled)", () => {
expect(out).toContain("ERP_URL=http://localhost:54005");
expect(out).toContain("MES_URL=http://localhost:54006");
expect(out).toContain("SUPABASE_URL=http://localhost:54001");
+ expect(out).toContain(
+ "ONSHAPE_V2_OAUTH_REDIRECT_URL=http://localhost:54005/api/integrations/onshape-v2/oauth"
+ );
expect(out).not.toContain("PORTLESS_TLD");
});
@@ -110,6 +113,23 @@ describe("renderEnv (portless disabled)", () => {
});
});
+describe("ONSHAPE_V2_OAUTH_REDIRECT_URL #force", () => {
+ it("leaves a redirect URL pinned in .env to .env", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ portless: false
+ });
+ const dotEnv =
+ 'ONSHAPE_V2_OAUTH_REDIRECT_URL="https://tunnel.example/api/integrations/onshape-v2/oauth" #force';
+ expect(omitForcedKeys(out, dotEnv)).not.toContain(
+ "ONSHAPE_V2_OAUTH_REDIRECT_URL=http://localhost"
+ );
+ });
+});
+
describe("renderEnv (portless enabled)", () => {
it("emits portless hostnames for app and supabase", () => {
const out = renderEnv({
@@ -124,6 +144,9 @@ describe("renderEnv (portless enabled)", () => {
expect(out).toContain("ERP_URL=https://erp.feat-x.dev");
expect(out).toContain("MES_URL=https://mes.feat-x.dev");
expect(out).toContain("SUPABASE_URL=https://api.feat-x.dev");
+ expect(out).toContain(
+ "ONSHAPE_V2_OAUTH_REDIRECT_URL=https://erp.feat-x.dev/api/integrations/onshape-v2/oauth"
+ );
expect(out).toContain("PORTLESS_TLD=dev");
});
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index 2b40263e67..0b47129240 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -38,6 +38,7 @@ export function renderEnv(opts: {
const host = (sub: string) => `${sub}.${branchPrefix}.dev`;
const local = (port: number) => `http://localhost:${port}`;
+ const erpUrl = portless ? `https://${host("erp")}` : local(ports.PORT_ERP);
const lines: string[] = [];
lines.push("# Generated by crbn. Do not edit by hand.");
@@ -63,15 +64,11 @@ export function renderEnv(opts: {
: "# App-facing URLs (localhost)"
);
lines.push(`DOMAIN=${portless ? `${branchPrefix}.dev` : "localhost"}`);
- lines.push(
- `ERP_URL=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
- );
+ lines.push(`ERP_URL=${erpUrl}`);
lines.push(
`MES_URL=${portless ? `https://${host("mes")}` : local(ports.PORT_MES)}`
);
- lines.push(
- `VERCEL_URL=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
- );
+ lines.push(`VERCEL_URL=${erpUrl}`);
if (portless) lines.push(`GTM_URL=https://${host("erp")}`);
lines.push("");
lines.push(
@@ -100,6 +97,16 @@ export function renderEnv(opts: {
`SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI=${oauthBase}/auth/v1/callback`
);
lines.push("");
+ lines.push(
+ "# Integration OAuth callbacks on this stack's ERP host. Register the"
+ );
+ lines.push(
+ "# URL on the provider's app, or pin your own in .env with #force."
+ );
+ lines.push(
+ `ONSHAPE_V2_OAUTH_REDIRECT_URL=${erpUrl}/api/integrations/onshape-v2/oauth`
+ );
+ lines.push("");
lines.push("# Aux services");
lines.push(`REDIS_URL=redis://localhost:${SHARED_REDIS_PORT}/${redisDb}`);
lines.push("INNGEST_DEV=1");
@@ -107,9 +114,7 @@ export function renderEnv(opts: {
// SDK advertises this as its serve URL during self-register. Must be
// reachable from inside the inngest container (handled via extra_hosts +
// portless CA mount in docker-compose.dev.yml).
- lines.push(
- `INNGEST_SERVE_HOST=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
- );
+ lines.push(`INNGEST_SERVE_HOST=${erpUrl}`);
// Hostname (no scheme) that docker-compose maps to host-gateway inside the
// inngest container, so the SDK URL above resolves to the dev server on the
// host. extra_hosts only accepts fully-qualified names — no wildcards —
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 53cba796f1..1f7e81598d 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -52,7 +52,7 @@ pnpm --filter @carbon/ee typecheck
| `./mcp`, `./mcp.server` | The MCP protocol engine (moved from `apps/erp/.../api+/mcp+/lib`). `./mcp` = pure logic (catalog search, the agent's doc search `createDocSearch`, formatters, instructions, types) with no auth/entitlement chain — safe for tests; `./mcp.server` = `server.ts` (`createMcpServer`, embeds `requireEntitlement("MCP")`). The dispatch + generated tool metadata stay in the app and are injected as `deps`. `server.ts` is `@ts-nocheck` |
| `./workflows.server` | Workflows runtime lock: `workflowsEnabledForCompany(companyId)` (runtime DEGRADE — a non-entitled run settles Skipped, embedded in `@carbon/jobs` `engine/execute.ts`) and `requireWorkflowsEntitlement(client, companyId)` (authoring throw, embedded in the ERP's `publishWorkflowVersion`) |
| `./jira`, `./jira.server`, `./linear`, `./linear.server`, `./onshape`, `./paperless-parts` | Integration client/server seams |
-| `./onshape`, `./onshape.server` | Onshape runtime shared by BOTH Onshape integrations — `onshape` (the public App Store app, client from `ONSHAPE_CLIENT_*`) and `onshape-government` (a customer-owned private OAuth app on their own tenant URL; tenant URL and client id/secret entered in settings; the tenant URL also serves OAuth, secret vaulted; always offered). Runtime code resolves the company's connection with `getOnshapeIntegration` rather than naming an id; `getOnshapeOAuthConfig` picks the client per variant; `./onshape.server` has `beginOnshapeAuthorization` / `loadOnshapeOAuthConfig`. `externalIntegrationMapping` rows stay under `"onshape"` for both. A company holds one active Onshape connection at a time (`getConflictingOnshapeIntegration`, app-level) |
+| `./onshape`, `./onshape.server` | Onshape runtime shared by BOTH Onshape integrations — `onshape` (the public App Store app, client from `ONSHAPE_CLIENT_*`) and `onshape-government` (a customer-owned private OAuth app on their own tenant URL; tenant URL and client id/secret entered in settings; the tenant URL also serves OAuth, secret vaulted; always offered). Runtime code resolves the company's connection with `getOnshapeIntegration` rather than naming an id; `getOnshapeOAuthConfig` picks the client per variant; `./onshape.server` (`lib/index.server.ts`) has `beginOnshapeAuthorization` / `loadOnshapeOAuthConfig`, the metadata patch helpers of `lib/state.ts` (`patchOnshapeOAuthGrant`, `patchOnshapeSettings`, …) and the panel's server-side property reads (`lib/panel-properties.server.ts`). `externalIntegrationMapping` rows stay under `"onshape"` for both. A company holds one active Onshape connection at a time (`getConflictingOnshapeIntegration`, app-level). The Onshape panel (`onshape-v2`, id from `./onshape/integration-id`) is a third grant outside that rule, on its own Onshape app (client from `ONSHAPE_V2_CLIENT_*`, never `ONSHAPE_CLIENT_*`): panel code passes its id explicitly and keeps its own mapping namespace (`.claude/rules/onshape-panel.md`) |
| `./slack.server`, `./stripe-connect.server`, `./xero/hooks.server`, `./quickbooks/hooks.server`, `./rillet/hooks.server` | Integration-specific server seams |
## Key Patterns
@@ -77,7 +77,8 @@ pnpm --filter @carbon/ee typecheck
- **Ledger delegation**: when a spend provider's mode declares `ownsLedgerFamilies`, `applyLedgerDelegation` sets that family to `"none"` AND disables its backing entities — derived from `POSTING_POLICY`, never a hard-coded `"bill"`. Each half alone is wrong (families-only leaves the document pushing; entity-only parks a `DOC_SYNC_DISABLED` Warning forever). `getJournalPostingPolicyDecision` accepts only `EffectivePostingSyncSettings`, so the compiler refuses a posting decision made from raw settings
- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions
- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`
-- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, `./oee`, `./oee.server`, `./sense/hooks.server`, etc.
+- **Onshape panel auth** (`./onshape/panel-session.server`, `src/onshape/panel/session.server.ts`): the `cps_` bearer credential for the Onshape iframe, which the `SameSite=Lax` `carbon` cookie cannot reach. Mints, stores (Redis `panel-session:<token>`, 12 h) and revokes sessions, and exports `requireOnshapePanelPermissions`, the panel routes' gate: the same claims check as `requirePermissions`, answering 401/403 with no redirect. Imports `getUserClaims`, `userHasVerifiedTotpFactor`, `getUserScopedClient` and `hasPermission` from `@carbon/auth`; auth never imports it back. See `.claude/rules/onshape-panel.md`
+- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./onshape/integration-id`, `./onshape/panel-session.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, `./oee`, `./oee.server`, `./sense/hooks.server`, etc.
## Cross-References
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 9a6f9eff43..ffc4a13c6c 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -33,7 +33,9 @@
"./mount/hooks.server": "./src/mount/hooks.server.ts",
"./notifications": "./src/notifications/index.ts",
"./onshape": "./src/onshape/lib/index.ts",
- "./onshape.server": "./src/onshape/oauth.server.ts",
+ "./onshape.server": "./src/onshape/lib/index.server.ts",
+ "./onshape/integration-id": "./src/onshape/lib/integration-id.ts",
+ "./onshape/panel-session.server": "./src/onshape/panel/session.server.ts",
"./paperless-parts": "./src/paperless-parts/lib/index.ts",
"./permissions.server": "./src/permissions.server.ts",
"./plan": "./src/plan.ts",
diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.ts
index 9bde0ef71b..39f00a1235 100644
--- a/packages/ee/src/hooks.server.ts
+++ b/packages/ee/src/hooks.server.ts
@@ -6,7 +6,12 @@ import { emailHealthcheck } from "./email/hooks.server";
import { jiraHealthcheck } from "./jira/hooks.server";
import { linearHealthcheck } from "./linear/hooks.server";
import { mountHealthcheck } from "./mount/hooks.server";
-import { onshapeOnUninstall } from "./onshape/hooks.server";
+import { onshapeHealthcheck, onshapeOnUninstall } from "./onshape/hooks.server";
+import {
+ ONSHAPE_GOVERNMENT_INTEGRATION_ID,
+ ONSHAPE_INTEGRATION_ID
+} from "./onshape/lib/connection";
+import { ONSHAPE_V2_INTEGRATION_ID } from "./onshape/lib/integration-id";
import {
quickbooksOnInstall,
quickbooksOnUninstall
@@ -66,10 +71,15 @@ const serverHooks: Record<string, IntegrationServerHooks> = {
onHealthcheck: mountHealthcheck
},
onshape: {
- onUninstall: onshapeOnUninstall
+ onUninstall: onshapeOnUninstall,
+ onHealthcheck: onshapeHealthcheck(ONSHAPE_INTEGRATION_ID)
},
"onshape-government": {
- onUninstall: onshapeOnUninstall
+ onUninstall: onshapeOnUninstall,
+ onHealthcheck: onshapeHealthcheck(ONSHAPE_GOVERNMENT_INTEGRATION_ID)
+ },
+ "onshape-v2": {
+ onHealthcheck: onshapeHealthcheck(ONSHAPE_V2_INTEGRATION_ID)
},
// The accounting providers' onUpdate re-runs the same subscription
// convergence as onInstall: a settings save on an existing install
diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.ts
index 429aedf0a3..1b075be195 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -7,6 +7,7 @@ import { Jira } from "./jira/config";
import { Linear } from "./linear/config";
import { Mount } from "./mount/config";
import { Onshape, OnshapeGovernment } from "./onshape/config";
+import { OnshapeV2 } from "./onshape/config-v2";
import { PaperlessParts } from "./paperless-parts/config";
import { QuickBooks } from "./quickbooks/config";
// import { Radan } from "./radan/config";
@@ -62,6 +63,7 @@ export const integrations = [
Mount,
Onshape,
OnshapeGovernment,
+ OnshapeV2,
PaperlessParts,
QuickBooks,
Ramp,
@@ -77,11 +79,14 @@ export type IntegrationID = (typeof integrations)[number]["id"];
export { Jira } from "./jira/config";
export { Mount } from "./mount/config";
+export { beginOAuthPopup } from "./oauth-popup";
export {
Logo as OnshapeLogo,
Onshape,
OnshapeGovernment
} from "./onshape/config";
+export { OnshapeV2 } from "./onshape/config-v2";
+export type { OnshapeDocument } from "./onshape/lib";
// Client-safe (no client or env imports): lets UI ask "is Onshape connected?"
// without naming either integration id.
export {
@@ -89,6 +94,190 @@ export {
isOnshapeIntegrationId,
ONSHAPE_INTEGRATION_IDS
} from "./onshape/lib/connection";
+export type { OnshapeBomNode } from "./onshape/panel/bom";
+export {
+ flattenBomTree,
+ metadataProperty,
+ missingBomColumnsMessage,
+ parseBomTree,
+ withoutProperties
+} from "./onshape/panel/bom";
+export type { OnshapePanelContext } from "./onshape/panel/messages";
+export {
+ PANEL_SESSION_MESSAGE,
+ parsePanelContext
+} from "./onshape/panel/messages";
+export { correlateCopiedLines } from "./onshape/panel/method-version";
+export type { OnshapePanelMe, OnshapePanelPaths } from "./onshape/panel/Panel";
+export { OnshapePanel } from "./onshape/panel/Panel";
+export type {
+ AssemblyPlan,
+ AssemblyPlanItem,
+ AssemblyPlanMethod,
+ AssemblyPlanMethodStatus,
+ AssemblyPlanRoot,
+ ChangeNoticeEdit,
+ ItemEdit,
+ ItemFieldChange,
+ ItemFieldSnapshot,
+ ItemMethodType,
+ ItemReplenishmentSystem,
+ ItemSourcingType,
+ ItemTrackingType,
+ KeptDifference,
+ MappedItemValues,
+ MappedRowPlan,
+ MergeResult,
+ OwnedFieldChange,
+ PartPlan,
+ PartPlanAction,
+ PartPlanRow,
+ PlanItemRow,
+ PlanLine,
+ PlanMappingContext,
+ PlanMappingRow,
+ PlanMethodRow,
+ PlanOptions,
+ PlanUnitOfMeasure,
+ ProposalInput,
+ ProposedItem,
+ ReleasePlan,
+ ReleasePlanChild,
+ ReleasePlanItem,
+ ReleasePlanItemAction
+} from "./onshape/panel/plan";
+export {
+ BOM_LINE_ITEM_TYPES,
+ bomLineItemType,
+ buildAssemblyPlan,
+ buildPartPlan,
+ buildReleasePlan,
+ CHANGE_NOTICE_DESCRIPTION_MAX_LENGTH,
+ CHANGE_NOTICE_NAME_MAX_LENGTH,
+ changedItemFields,
+ changeNoticeDescriptionJson,
+ createdItemExtras,
+ currentItemFields,
+ defaultUnitOfMeasureCode,
+ EDITABLE_ITEM_FIELDS,
+ flattenNodes,
+ ITEM_DESCRIPTION_MAX_LENGTH,
+ ITEM_METHOD_TYPES,
+ ITEM_NAME_MAX_LENGTH,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_SOURCING_TYPES,
+ ITEM_TRACKING_TYPES,
+ interlockItemFields,
+ mappedItemValues,
+ mergeChangeNoticeEdit,
+ mergeEditsForCreates,
+ mergeExistingItemEdits,
+ mergeItemEdits,
+ methodForReplenishment,
+ pickAdoptTarget,
+ pickBomChildRow,
+ pickLatestRow,
+ pickReuseRow,
+ pickRevisionBase,
+ planCreatedItem,
+ planExistingItem,
+ proposeItem,
+ proposeMappedItem,
+ reconcileMethodForReplenishment,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./onshape/panel/plan";
+export type { OnshapePushDefaults } from "./onshape/panel/preferences";
+export {
+ DEFAULT_PUSH_DEFAULTS,
+ parsePushDefaults,
+ reconcilePushDefaults
+} from "./onshape/panel/preferences";
+export type {
+ DescriptionModes,
+ MappingMode,
+ OnshapePropertyValue,
+ PlanCustomField,
+ PlanCustomFieldDefinition,
+ PlanItemField,
+ PropertyMapEntry,
+ PropertyMapTarget,
+ UnmappedProperty
+} from "./onshape/panel/properties";
+export {
+ CUSTOM_FIELD_DATA_TYPES,
+ CUSTOM_FIELD_TYPE_LABELS,
+ coerceOnshapeValue,
+ customFieldDisplayValue,
+ customFieldKeptDifferences,
+ customFieldWrites,
+ DEFAULT_DESCRIPTION_MODES,
+ everyPushTargets,
+ MAPPABLE_VALUE_TYPES,
+ MAPPING_MODES,
+ mappedFieldValues,
+ mergeCustomFieldValues,
+ parseDescriptionModes,
+ parseProperties,
+ parsePropertyMap,
+ partPropertiesFromElementMetadata,
+ propertyDisplayValue,
+ resolveMappedFields,
+ targetKey
+} from "./onshape/panel/properties";
+export type {
+ PanelRelease,
+ PanelReleaseItem,
+ ReleaseCarbonItemRow,
+ ReleasePackageItemLike,
+ ReleaseRevisionLike
+} from "./onshape/panel/releases";
+export {
+ drawingModels,
+ groupRevisionsIntoReleases,
+ isModelReleaseItem,
+ releaseBomKey,
+ releaseDrawingFileName,
+ releaseKeyFor,
+ resolveReleaseStates
+} from "./onshape/panel/releases";
+export type {
+ StandardField,
+ StandardFieldId,
+ StandardFieldWriter,
+ TranslatedValue,
+ ValueTranslation
+} from "./onshape/panel/standard-fields";
+export {
+ defaultTranslations,
+ isStandardFieldId,
+ matchingUnit,
+ onshapeValueOptions,
+ repeatedTranslationRows,
+ STANDARD_FIELD_IDS,
+ STANDARD_FIELDS,
+ standardField,
+ standardFieldValues,
+ translateValue,
+ translationErrors,
+ untranslatedOptions
+} from "./onshape/panel/standard-fields";
+export type {
+ PanelAssemblyLineInput,
+ PanelAssemblyLineStatus,
+ PanelItemRow,
+ PanelMappingRow,
+ PanelPartStatus,
+ ReleasedRevision
+} from "./onshape/panel/status";
+export {
+ buildAssemblyLineStatuses,
+ buildPartStatuses,
+ externalIdForAssembly,
+ externalIdForBomLine,
+ externalIdForPart,
+ normalizeConfiguration,
+ releasedRevisionsByPartNumber
+} from "./onshape/panel/status";
// TODO: export as @carbon/ee/paperless
export { PaperlessPartsClient } from "./paperless-parts/lib/client";
export { QuickBooks } from "./quickbooks/config";
diff --git a/packages/ee/src/integrations/secrets.ts b/packages/ee/src/integrations/secrets.ts
index 1e398baf59..31729cafeb 100644
--- a/packages/ee/src/integrations/secrets.ts
+++ b/packages/ee/src/integrations/secrets.ts
@@ -42,6 +42,7 @@ export const SECRET_KEYS: Record<string, string[]> = {
"credentials.accessToken",
"credentials.refreshToken"
],
+ "onshape-v2": ["credentials.accessToken", "credentials.refreshToken"],
xero: ["credentials.accessToken", "credentials.refreshToken"],
quickbooks: ["credentials.accessToken", "credentials.refreshToken"],
ramp: [
diff --git a/packages/ee/src/oauth-popup.ts b/packages/ee/src/oauth-popup.ts
new file mode 100644
index 0000000000..1c08140d7c
--- /dev/null
+++ b/packages/ee/src/oauth-popup.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * Browser only. Opens the popup synchronously inside the click and navigates it
+ * once the authorize URL arrives: `window.open` after an awaited fetch can
+ * outlive transient user activation, and Chrome then blocks it silently.
+ */
+export type OAuthPopupHandle = {
+ /** Falls back to the current window when the popup was blocked. */
+ navigate: (url: string) => void;
+ close: () => void;
+};
+
+export function beginOAuthPopup(): OAuthPopupHandle {
+ const width = 600;
+ const height = 800;
+ const left = window.screenX + (window.outerWidth - width) / 2;
+ const top = window.screenY + (window.outerHeight - height) / 2.5;
+
+ const popup = window.open(
+ "",
+ "",
+ `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${top}, left=${left}`
+ );
+
+ return {
+ navigate(url: string) {
+ if (popup && !popup.closed) {
+ popup.location.href = url;
+ popup.focus();
+ } else {
+ // With no opener, the callback redirects to the integrations page.
+ window.location.href = url;
+ }
+ },
+ close() {
+ if (popup && !popup.closed) popup.close();
+ }
+ };
+}
diff --git a/packages/ee/src/onshape/config-v2.tsx b/packages/ee/src/onshape/config-v2.tsx
new file mode 100644
index 0000000000..7001a2a248
--- /dev/null
+++ b/packages/ee/src/onshape/config-v2.tsx
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { ONSHAPE_V2_CLIENT_ID } from "@carbon/auth";
+import { z } from "zod";
+import { defineIntegration } from "../fns";
+import { beginOAuthPopup } from "../oauth-popup";
+import { Logo, onshapeReconnectAction } from "./config";
+import { ONSHAPE_V2_INTEGRATION_ID } from "./lib/integration-id";
+
+export const OnshapeV2 = defineIntegration({
+ name: "Onshape V2",
+ id: ONSHAPE_V2_INTEGRATION_ID,
+ active: !!ONSHAPE_V2_CLIENT_ID,
+ category: "CAD",
+ logo: Logo,
+ description:
+ "Onshape is a browser-based CAD/PLM software for modern engineering teams. This integration adds a panel inside Onshape for pushing parts, assemblies and releases into Carbon.",
+ shortDescription: "Push CAD data to Carbon from inside Onshape.",
+ images: [],
+ // Push defaults live on the panel's Fields page beside the property map.
+ settings: [],
+ schema: z.object({}),
+ actions: [onshapeReconnectAction("/api/integrations/onshape-v2/install")],
+ onClientInstall: async () => {
+ const popup = beginOAuthPopup();
+ let error = "unexpected";
+ try {
+ const response = await fetch("/api/integrations/onshape-v2/install");
+ const body = (await response.json()) as { url?: string; error?: string };
+ if (body?.url) {
+ popup.navigate(body.url);
+ return;
+ }
+ error = body?.error ?? error;
+ } catch {
+ // Falls through to the error redirect.
+ }
+ popup.close();
+ window.location.href = `/x/settings/integrations?integration=${ONSHAPE_V2_INTEGRATION_ID}&error=${error}`;
+ }
+});
diff --git a/packages/ee/src/onshape/config.tsx b/packages/ee/src/onshape/config.tsx
index 65952cbe17..f42a5ba7b0 100644
--- a/packages/ee/src/onshape/config.tsx
+++ b/packages/ee/src/onshape/config.tsx
@@ -6,6 +6,7 @@ import { ONSHAPE_CLIENT_ID } from "@carbon/auth";
import { type SVGProps, useEffect, useState } from "react";
import { z } from "zod";
import { defineIntegration } from "../fns";
+import { beginOAuthPopup } from "../oauth-popup";
import {
normalizeOnshapeUrl,
ONSHAPE_GOVERNMENT_INTEGRATION_ID,
@@ -47,6 +48,17 @@ const backfillAction = {
enabledWhenSetting: "assetSyncEnabled"
};
+// A revoked grant or dead refresh token can only be re-authorized.
+export function onshapeReconnectAction(installEndpoint: string) {
+ return {
+ id: "reconnect",
+ label: "Reconnect Onshape",
+ description:
+ "Sign in to Onshape again to renew Carbon's access. Use this when the connection shows Unhealthy; settings and linked items are kept.",
+ endpoint: installEndpoint
+ };
+}
+
export const Onshape = defineIntegration({
name: "Onshape",
id: ONSHAPE_INTEGRATION_ID,
@@ -61,45 +73,26 @@ export const Onshape = defineIntegration({
schema: z.object({
assetSyncEnabled: assetSyncEnabledSchema
}),
- actions: [backfillAction],
+ actions: [
+ onshapeReconnectAction("/api/integrations/onshape/install"),
+ backfillAction
+ ],
onClientInstall: async () => {
- const response = await fetch("/api/integrations/onshape/install").then(
- (res) => res.json()
- );
-
- const { url, error } = response as { url?: string; error?: string };
- if (!url) {
- // The integrations page turns `?integration=&error=` into a toast — the
- // same place a failed callback lands (see integration-errors.ts).
- window.location.href = `/x/settings/integrations?integration=${ONSHAPE_INTEGRATION_ID}&error=${error ?? "unexpected"}`;
- return;
- }
-
- const width = 600;
- const height = 800;
- const left = window.screenX + (window.outerWidth - width) / 2;
- const top = window.screenY + (window.outerHeight - height) / 2.5;
-
- const popup = window.open(
- url,
- "",
- `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${top}, left=${left}`
- );
-
- if (!popup) {
- window.location.href = url;
- return;
- }
-
- const listener = (e: MessageEvent) => {
- if (e.data === "app_oauth_completed") {
- window.location.reload();
- window.removeEventListener("message", listener);
- popup.close();
+ const popup = beginOAuthPopup();
+ let error = "unexpected";
+ try {
+ const response = await fetch("/api/integrations/onshape/install");
+ const body = (await response.json()) as { url?: string; error?: string };
+ if (body?.url) {
+ popup.navigate(body.url);
+ return;
}
- };
-
- window.addEventListener("message", listener);
+ error = body?.error ?? error;
+ } catch {
+ // Falls through to the error redirect.
+ }
+ popup.close();
+ window.location.href = `/x/settings/integrations?integration=${ONSHAPE_INTEGRATION_ID}&error=${error}`;
}
});
diff --git a/packages/ee/src/onshape/hooks.server.ts b/packages/ee/src/onshape/hooks.server.ts
index b88a6235c0..f3cca74880 100644
--- a/packages/ee/src/onshape/hooks.server.ts
+++ b/packages/ee/src/onshape/hooks.server.ts
@@ -4,8 +4,16 @@
import { getAppUrl } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
import { getOnshapeClient } from "./lib/client";
-import { getOnshapeIntegration } from "./lib/connection";
+import {
+ getOnshapeIntegration,
+ type OnshapeIntegrationId
+} from "./lib/connection";
+import type { OnshapeOAuthIntegrationId } from "./lib/integration-id";
+import { patchOnshapeCompanyId } from "./lib/state";
+
+const logger = getLogger("ee", "onshape");
// The release webhook's callback path for a company. We match/deregister by this
// PATH (not the full URL) so a host change — localhost, a tunnel, or the prod
@@ -48,17 +56,19 @@ async function resolveAndStoreOnshapeCompanyId(
const resolved = companies[0]?.id;
if (!resolved) return null;
- const update = await carbon
- .from("companyIntegration")
- .update({ metadata: { ...metadata, onshapeCompanyId: resolved } })
- .eq("id", integrationId)
- .eq("companyId", companyId);
- if (update.error) {
+ try {
+ await patchOnshapeCompanyId(
+ carbon,
+ companyId,
+ integrationId as OnshapeIntegrationId,
+ resolved
+ );
+ } catch (error) {
// Non-fatal: we can still register with the resolved id; the jobs just fall
// back to their own getCompanies() resolve if the store didn't stick.
console.error(
"onshape: failed to persist resolved Onshape company id",
- update.error
+ error
);
}
return resolved;
@@ -190,3 +200,38 @@ export async function ensureOnshapeReleaseWebhook(
export async function onshapeOnUninstall(companyId: string): Promise<void> {
await deregisterOnshapeWebhooks(companyId);
}
+
+/**
+ * Building the client refreshes an expired token and one read proves it is
+ * accepted, so a revoked grant reads unhealthy. `getIntegrationHealth` caches a
+ * healthy answer for five hours, which bounds the quota this spends.
+ */
+export function onshapeHealthcheck(integrationId: OnshapeOAuthIntegrationId) {
+ return async (companyId: string): Promise<boolean> => {
+ try {
+ const onshape = await getOnshapeClient(
+ getCarbonServiceRole(),
+ companyId,
+ "system",
+ integrationId
+ );
+ if (!onshape.client) {
+ logger.warn("Onshape healthcheck: no client", {
+ companyId,
+ integrationId,
+ error: onshape.error
+ });
+ return false;
+ }
+ await onshape.client.getCompanies();
+ return true;
+ } catch (error) {
+ logger.warn("Onshape healthcheck: request failed", {
+ companyId,
+ integrationId,
+ error
+ });
+ return false;
+ }
+ };
+}
diff --git a/packages/ee/src/onshape/lib/batched-filter.test.ts b/packages/ee/src/onshape/lib/batched-filter.test.ts
new file mode 100644
index 0000000000..b16ca97c96
--- /dev/null
+++ b/packages/ee/src/onshape/lib/batched-filter.test.ts
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { chunkFilterValues, selectInBatches } from "./batched-filter";
+
+// Measured gateway limit: a 3,821-byte request line succeeds, 4,001 fails.
+
+/** What supabase-js puts on the wire for `.in(column, values)`. */
+function encodedFilterLength(column: string, values: string[]): number {
+ const params = new URLSearchParams();
+ params.append(
+ column,
+ `in.(${values.map((v) => (/[,()]/.test(v) ? `"${v}"` : v)).join(",")})`
+ );
+ return params.toString().length;
+}
+
+const partNumber = (i: number) => `PN-${String(i).padStart(6, "0")}`;
+const externalId = (i: number) =>
+ `d8247ee963c19d092f559c08:70719a8d835c474854aba1a1:J${String(i).padStart(2, "0")}D`;
+
+describe("chunkFilterValues", () => {
+ it("keeps every batch under the 4KB request line, for short values", () => {
+ const values = Array.from({ length: 334 }, (_, i) => partNumber(i));
+ const batches = chunkFilterValues(values);
+ expect(batches.length).toBeGreaterThan(1);
+ for (const batch of batches) {
+ expect(encodedFilterLength("readableId", batch)).toBeLessThan(3800);
+ }
+ expect(batches.flat()).toEqual(values);
+ });
+
+ it("keeps every batch under the limit for long values too", () => {
+ const values = Array.from({ length: 334 }, (_, i) => externalId(i));
+ const batches = chunkFilterValues(values);
+ for (const batch of batches) {
+ expect(encodedFilterLength("externalId", batch)).toBeLessThan(3800);
+ }
+ expect(batches.flat()).toEqual(values);
+ });
+
+ it("batches long values more aggressively than short ones", () => {
+ const count = 334;
+ const short = chunkFilterValues(
+ Array.from({ length: count }, (_, i) => partNumber(i))
+ );
+ const long = chunkFilterValues(
+ Array.from({ length: count }, (_, i) => externalId(i))
+ );
+ expect(long.length).toBeGreaterThan(short.length);
+ });
+
+ it("accounts for the quotes supabase-js adds around , ( and )", () => {
+ const values = Array.from({ length: 200 }, (_, i) => `PART,(${i})`);
+ for (const batch of chunkFilterValues(values)) {
+ expect(encodedFilterLength("readableId", batch)).toBeLessThan(3800);
+ }
+ });
+
+ it("dedupes, and returns nothing for no values", () => {
+ expect(chunkFilterValues(["a", "b", "a", "b"])).toEqual([["a", "b"]]);
+ expect(chunkFilterValues([])).toEqual([]);
+ });
+
+ it("gives a value larger than the whole budget its own batch", () => {
+ const huge = "x".repeat(5000);
+ expect(chunkFilterValues(["a", huge, "b"])).toEqual([["a"], [huge], ["b"]]);
+ });
+
+ it("fits a small list in one request", () => {
+ const values = Array.from({ length: 12 }, (_, i) => partNumber(i));
+ expect(chunkFilterValues(values)).toEqual([values]);
+ });
+});
+
+/**
+ * A fake supabase-js builder over `rows`: `.in()` is the batch, `.order()` and
+ * `.range()` behave as PostgREST's do, and a page never exceeds `maxRows`.
+ */
+function fakeTable<Row extends { id: string; key: string }>(
+ rows: Row[],
+ log: { pages: Array<{ batch: string[]; from: number; to: number }> },
+ maxRows = 1000
+) {
+ return (batch: string[]) => {
+ const orders: string[] = [];
+ const query = {
+ order(column: string) {
+ orders.push(column);
+ return query;
+ },
+ range(from: number, to: number) {
+ log.pages.push({ batch, from, to });
+ const matched = rows
+ .filter((row) => batch.includes(row.key))
+ .sort((a, b) => {
+ for (const column of orders) {
+ const left = String(a[column as keyof Row]);
+ const right = String(b[column as keyof Row]);
+ if (left !== right) return left < right ? -1 : 1;
+ }
+ return 0;
+ });
+ const end = Math.min(to + 1, from + maxRows);
+ return Promise.resolve({
+ data: matched.slice(from, end),
+ error: null as { message: string } | null
+ });
+ }
+ };
+ return query;
+ };
+}
+
+describe("selectInBatches", () => {
+ it("concatenates the rows from every batch", async () => {
+ const values = Array.from({ length: 334 }, (_, i) => externalId(i));
+ const log = {
+ pages: [] as Array<{ batch: string[]; from: number; to: number }>
+ };
+ const rows = values.map((key) => ({ id: key, key }));
+ const result = await selectInBatches(values, fakeTable(rows, log));
+ expect(log.pages.length).toBeGreaterThan(1);
+ expect(result.error).toBeNull();
+ // Batches arrive in batch order; each batch in id order.
+ expect(result.data.map((row) => row.key).sort()).toEqual(
+ [...values].sort()
+ );
+ });
+
+ it("pages a batch that matches more than 1,000 rows", async () => {
+ // One method id with 2,500 BOM lines: a single read stops at 1,000.
+ const rows = Array.from({ length: 2500 }, (_, i) => ({
+ id: `line-${String(i).padStart(5, "0")}`,
+ key: "method-1"
+ }));
+ const log = {
+ pages: [] as Array<{ batch: string[]; from: number; to: number }>
+ };
+ const result = await selectInBatches(["method-1"], fakeTable(rows, log));
+ expect(result.error).toBeNull();
+ expect(result.data).toHaveLength(2500);
+ expect(new Set(result.data.map((row) => row.id)).size).toBe(2500);
+ expect(log.pages.map((page) => [page.from, page.to])).toEqual([
+ [0, 999],
+ [1000, 1999],
+ [2000, 2999]
+ ]);
+ });
+
+ it("asks for one more page when the last one is exactly full", async () => {
+ const rows = Array.from({ length: 1000 }, (_, i) => ({
+ id: `line-${String(i).padStart(5, "0")}`,
+ key: "method-1"
+ }));
+ const log = {
+ pages: [] as Array<{ batch: string[]; from: number; to: number }>
+ };
+ const result = await selectInBatches(["method-1"], fakeTable(rows, log));
+ expect(result.data).toHaveLength(1000);
+ expect(log.pages).toHaveLength(2);
+ });
+
+ it("orders every page by id after the query's own order", async () => {
+ const orders: string[][] = [];
+ await selectInBatches(["a"], () => {
+ const seen: string[] = [];
+ orders.push(seen);
+ const query = {
+ order(column: string) {
+ seen.push(column);
+ return query;
+ },
+ range: () => Promise.resolve({ data: [], error: null })
+ };
+ return query.order("revision");
+ });
+ expect(orders).toEqual([["revision", "id"]]);
+ });
+
+ it("returns no rows alongside an error, and stops asking", async () => {
+ const values = Array.from({ length: 334 }, (_, i) => externalId(i));
+ let calls = 0;
+ const result = await selectInBatches(values, () => {
+ const query = {
+ order: () => query,
+ range: () => {
+ calls += 1;
+ return Promise.resolve({ data: null, error: { message: "boom" } });
+ }
+ };
+ return query;
+ });
+ expect(calls).toBe(1);
+ expect(result.error).toEqual({ message: "boom" });
+ expect(result.data).toEqual([]);
+ });
+
+ it("does not run a query at all for no values", async () => {
+ let calls = 0;
+ const result = await selectInBatches([], () => {
+ calls += 1;
+ const query = {
+ order: () => query,
+ range: () => Promise.resolve({ data: [], error: null })
+ };
+ return query;
+ });
+ expect(calls).toBe(0);
+ expect(result.data).toEqual([]);
+ });
+});
diff --git a/packages/ee/src/onshape/lib/batched-filter.ts b/packages/ee/src/onshape/lib/batched-filter.ts
new file mode 100644
index 0000000000..bbbab5c368
--- /dev/null
+++ b/packages/ee/src/onshape/lib/batched-filter.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// PostgREST filters travel in the URL, so an `.in()` list is bounded by the
+// gateway's 4 KB request line (Kong answers 414 or 502 above it), measured in
+// bytes rather than values.
+const FILTER_BYTE_BUDGET = 3000;
+
+const SEPARATOR_BYTES = 3;
+
+// supabase-js quotes a value containing , ( or ).
+const QUOTE_BYTES = 6;
+
+function filterValueBytes(value: string): number {
+ // - 2 drops the "v=" of the serialization.
+ const encoded = new URLSearchParams({ v: value }).toString().length - 2;
+ return encoded + (/[,()]/.test(value) ? QUOTE_BYTES : 0);
+}
+
+/**
+ * Dedupes values and splits them, in order, into `.in()` batches under the byte
+ * budget. A value over the budget gets its own batch rather than being dropped.
+ */
+export function chunkFilterValues(
+ values: string[],
+ options: { budgetBytes?: number } = {}
+): string[][] {
+ const budget = options.budgetBytes ?? FILTER_BYTE_BUDGET;
+ const batches: string[][] = [];
+ let current: string[] = [];
+ let used = 0;
+
+ for (const value of new Set(values)) {
+ const cost = filterValueBytes(value) + SEPARATOR_BYTES;
+ if (current.length > 0 && used + cost > budget) {
+ batches.push(current);
+ current = [];
+ used = 0;
+ }
+ current.push(value);
+ used += cost;
+ }
+ if (current.length > 0) batches.push(current);
+ return batches;
+}
+
+// PostgREST's `max_rows` cap. A page shorter than this is the last one.
+const PAGE_SIZE = 1000;
+// Backstop only: a server that ignored `Range` would otherwise loop forever.
+const MAX_PAGES = 1000;
+
+/**
+ * What paging needs from a batch query. Structural, as `fetchAllRecords`
+ * (`@carbon/database`) types it: naming the supabase-js builder makes the
+ * compiler walk the whole schema per call.
+ */
+export type BatchQuery<Row, Err> = {
+ order(
+ column: string,
+ options?: { ascending?: boolean }
+ ): BatchQuery<Row, Err>;
+ range(
+ from: number,
+ to: number
+ ): PromiseLike<{ data: Row[] | null; error: Err | null }>;
+};
+
+/**
+ * Runs the query once per batch and concatenates the rows. Each batch is paged
+ * past PostgREST's 1,000-row cap: a batch of values can match more rows than
+ * that (lines of many methods), and a cut read loses rows silently. Pages are
+ * ordered by `orderBy` (default `id`), appended after any order the query
+ * sets, so offsets are stable. `buildBatch` is called once per page:
+ * supabase-js builders are mutable. The first error returns no rows: a partial
+ * result read as whole makes a sync delete rows.
+ */
+export async function selectInBatches<Row, Err>(
+ values: string[],
+ buildBatch: (batch: string[]) => BatchQuery<Row, Err>,
+ options: { budgetBytes?: number; orderBy?: string } = {}
+): Promise<{ data: Row[]; error: Err | null }> {
+ const batches = chunkFilterValues(values, options);
+ const orderBy = options.orderBy ?? "id";
+ const rows: Row[] = [];
+ for (const batch of batches) {
+ for (let page = 0; ; page += 1) {
+ if (page === MAX_PAGES) {
+ throw new Error(
+ `selectInBatches exceeded ${MAX_PAGES} pages; refusing a partial read`
+ );
+ }
+ const from = page * PAGE_SIZE;
+ const result = await buildBatch(batch)
+ .order(orderBy)
+ .range(from, from + PAGE_SIZE - 1);
+ if (result.error) return { data: [], error: result.error };
+ const pageRows = result.data ?? [];
+ rows.push(...pageRows);
+ if (pageRows.length < PAGE_SIZE) break;
+ }
+ }
+ return { data: rows, error: null };
+}
diff --git a/packages/ee/src/onshape/lib/client.ts b/packages/ee/src/onshape/lib/client.ts
index 50d2576d2d..f88b449858 100644
--- a/packages/ee/src/onshape/lib/client.ts
+++ b/packages/ee/src/onshape/lib/client.ts
@@ -7,27 +7,57 @@
// test runners — that imports this client).
import type { Database } from "@carbon/database";
+import { acquireLease, redis, withLease } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import axios from "axios";
import {
- persistIntegrationSecrets,
+ IntegrationSecretUnavailableError,
resolveIntegrationSecrets
} from "../../integrations/secrets";
+import { normalizeConfiguration } from "../panel/status";
import {
getOnshapeIntegration,
- ONSHAPE_DEFAULT_BASE_URL,
- type OnshapeIntegrationId
+ isOnshapeIntegrationId,
+ ONSHAPE_DEFAULT_BASE_URL
} from "./connection";
import type { OnshapeDocument } from "./document.type";
import type { OnshapeElementType } from "./element.type";
+import type { OnshapeOAuthIntegrationId } from "./integration-id";
import { getOnshapeOAuthConfig, refreshOnshapeAccessToken } from "./oauth";
+import { patchOnshapeRefreshedTokens } from "./state";
+import {
+ isFresh,
+ resolveOnshapeRefresh,
+ type StoredOnshapeCredentials
+} from "./token-refresh";
const logger = getLogger("ee", "onshape");
interface OnshapeClientConfig {
baseUrl: string;
accessToken: string;
+ /**
+ * Called after a 401 for a new token, or null. A stored expiry cannot see a
+ * revocation, clock skew or a token that dies mid-call.
+ */
+ onUnauthorized?: () => Promise<string | null>;
+}
+
+/**
+ * `microversionId` changes with the part's definition: the cheap "changed since
+ * the last push" check.
+ */
+export interface OnshapeElementPart {
+ partId: string;
+ name: string;
+ partNumber: string | null;
+ revision: string | null;
+ description?: string | null;
+ state?: string;
+ microversionId?: string;
+ isHidden?: boolean;
+ [key: string]: unknown;
}
export interface OnshapePart {
@@ -39,6 +69,42 @@ export interface OnshapePart {
metadata: Record<string, string>;
}
+const DEV_CACHE_TTL_SECONDS = 10 * 60;
+const DOCUMENT_REVISION_MAX_PAGES = 20;
+
+export interface OnshapeElementRow {
+ id: string;
+ name: string;
+ elementType: string; // "PARTSTUDIO" | "ASSEMBLY" | "DRAWING" | ...
+ [key: string]: unknown;
+}
+
+// Stable content reads only: caching a polled endpoint (/translations) would
+// break the poll loop.
+const DEV_CACHEABLE_PATHS = [
+ /^\/api\/v\d+\/parts\//,
+ /^\/api\/v\d+\/partstudios\/.*\/massproperties/,
+ /^\/api\/v\d+\/documents\//,
+ /^\/api\/v\d+\/assemblies\/.*\/bom/,
+ /^\/api\/v\d+\/metadata\//,
+ // A new release shows after the TTL; flush onshape-dev-cache:* for sooner.
+ /^\/api\/v\d+\/revisions\/d\//
+];
+
+export interface OnshapeMassProperties {
+ bodies: Record<
+ string,
+ {
+ mass: number[];
+ volume: number[];
+ centroid: number[];
+ hasMass: boolean;
+ [key: string]: unknown;
+ }
+ >;
+ [key: string]: unknown;
+}
+
export interface OnshapeCompany {
id: string;
name?: string;
@@ -87,10 +153,27 @@ export interface OnshapeRevision {
name?: string;
releaseId?: string;
releaseName?: string;
+ releaseCreatedDate?: string;
isObsolete?: boolean;
[key: string]: unknown;
}
+/** `parentId`: the item it sits under; a drawing's children are its models. */
+export interface OnshapeReleasePackageItem {
+ id: string;
+ parentId: string | null;
+ elementType: number;
+ elementId: string | null;
+ partNumber: string | null;
+ revision: string | null;
+}
+
+/** Empty for the default configuration, so its URL and cache key stay put. */
+function configurationQuery(configuration?: string | null): string {
+ const normalized = normalizeConfiguration(configuration);
+ return normalized ? `&configuration=${encodeURIComponent(normalized)}` : "";
+}
+
// Typed API error so callers can detect rate limiting (status 429) and honor
// Retry-After instead of hammering the quota.
export class OnshapeApiError extends Error {
@@ -120,10 +203,14 @@ export class OnshapeClient {
private baseUrl: string;
private accessToken: string;
private axiosInstance: ReturnType<typeof axios.create>;
+ private onUnauthorized?: () => Promise<string | null>;
+ /** One recovery per client: a second 401 is a real authorization failure. */
+ private retriedUnauthorized = false;
constructor(config: OnshapeClientConfig) {
this.baseUrl = config.baseUrl;
this.accessToken = config.accessToken;
+ this.onUnauthorized = config.onUnauthorized;
this.axiosInstance = axios.create({
baseURL: this.baseUrl,
@@ -147,18 +234,78 @@ export class OnshapeClient {
path: string,
body?: Record<string, unknown>
): Promise<T> {
+ // Dev-only cache to spare the annual API quota.
+ const cacheable =
+ method === "GET" && DEV_CACHEABLE_PATHS.some((re) => re.test(path));
+ const cacheKey =
+ process.env.ONSHAPE_DEV_CACHE === "1" && cacheable
+ ? `onshape-dev-cache:${path}`
+ : null;
+
+ if (cacheKey) {
+ try {
+ const cached = await redis.get(cacheKey);
+ if (cached) return JSON.parse(cached) as T;
+ } catch {
+ // Cache is best-effort.
+ }
+ }
+
try {
const response = await this.axiosInstance.request<T>({
method,
url: path,
data: body
});
+ void this.countLiveCall(path);
+ if (cacheKey) {
+ try {
+ await redis.set(
+ cacheKey,
+ JSON.stringify(response.data),
+ "EX",
+ DEV_CACHE_TTL_SECONDS
+ );
+ } catch {
+ // best-effort
+ }
+ }
return response.data;
} catch (error) {
+ void this.countLiveCall(path);
+
+ if (
+ axios.isAxiosError(error) &&
+ error.response?.status === 401 &&
+ this.onUnauthorized &&
+ !this.retriedUnauthorized
+ ) {
+ this.retriedUnauthorized = true;
+ const token = await this.onUnauthorized();
+ if (token) {
+ this.accessToken = token;
+ this.axiosInstance.defaults.headers = {
+ ...this.axiosInstance.defaults.headers,
+ ...this.getAuthHeaders()
+ } as typeof this.axiosInstance.defaults.headers;
+ return this.request<T>(method, path, body);
+ }
+ }
+
throw this.toApiError(error);
}
}
+ /** Counts in Redis `onshape:api-calls:<year>`; never awaited. */
+ private async countLiveCall(path: string) {
+ try {
+ const year = new Date().getUTCFullYear();
+ await redis.incr(`onshape:api-calls:${year}`);
+ } catch {
+ // Never let accounting break a real request.
+ }
+ }
+
private toApiError(error: unknown): Error {
if (axios.isAxiosError(error)) {
const status = error.response?.status;
@@ -335,6 +482,74 @@ export class OnshapeClient {
>("GET", nextUrl);
}
+ // Onshape has no packages-by-document endpoint; grouping these revisions by
+ // releaseId rebuilds the packages. Follows `next` up to the page limit.
+ async getDocumentRevisions(
+ documentId: string
+ ): Promise<{ items: OnshapeRevision[]; next: string | null }> {
+ type Page = { items?: OnshapeRevision[]; next?: string | null };
+ const items: OnshapeRevision[] = [];
+ let page = await this.request<Page>(
+ "GET",
+ `/api/v10/revisions/d/${documentId}`
+ );
+ items.push(...(page.items ?? []));
+ for (
+ let pages = 1;
+ page.next && pages < DOCUMENT_REVISION_MAX_PAGES;
+ pages++
+ ) {
+ page = await this.request<Page>("GET", page.next);
+ items.push(...(page.items ?? []));
+ }
+ return { items, next: page.next ?? null };
+ }
+
+ /**
+ * Flattened. Onshape nests a package's items while it is being set up and
+ * lists them flat with `parentId` once released; both shapes are read.
+ */
+ async getReleasePackageItems(
+ releaseId: string
+ ): Promise<OnshapeReleasePackageItem[]> {
+ type RawItem = {
+ id?: string;
+ parentId?: string | null;
+ elementType?: number;
+ elementId?: string | null;
+ properties?: Array<{ name?: string; value?: unknown }>;
+ children?: RawItem[];
+ };
+ const pkg = await this.request<{ items?: RawItem[] }>(
+ "GET",
+ `/api/v10/releasepackages/${releaseId}?detailed=true`
+ );
+ const text = (item: RawItem, name: string) => {
+ const value = item.properties?.find((p) => p.name === name)?.value;
+ return typeof value === "string" && value.trim() !== ""
+ ? value.trim()
+ : null;
+ };
+ const out: OnshapeReleasePackageItem[] = [];
+ const walk = (items: RawItem[], parentId: string | null) => {
+ for (const item of items) {
+ if (!item.id) continue;
+ out.push({
+ id: item.id,
+ parentId: item.parentId ?? parentId,
+ elementType:
+ typeof item.elementType === "number" ? item.elementType : -1,
+ elementId: item.elementId ?? null,
+ partNumber: text(item, "Part number"),
+ revision: text(item, "Revision")
+ });
+ walk(item.children ?? [], item.id);
+ }
+ };
+ walk(pkg.items ?? [], null);
+ return out;
+ }
+
// --- Release-asset export ---------------------------------------------------
// Onshape's api/v10 translation API. Version-scoped (/v/) to match
// getBillOfMaterials — released assets live at a version. The async flow:
@@ -368,6 +583,97 @@ export class OnshapeClient {
);
}
+ /** SI units; triples are [value, min, max]; no material: hasMass=false. */
+ async getPartStudioMassProperties(
+ document: OnshapeDocument,
+ elementId: string
+ ): Promise<OnshapeMassProperties> {
+ return this.request<OnshapeMassProperties>(
+ "GET",
+ `/api/v10/partstudios/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}/massproperties?massAsGroup=false&useMassPropertyOverrides=true`
+ );
+ }
+
+ async getElementsIn(
+ document: OnshapeDocument,
+ elementType?: OnshapeElementType
+ ): Promise<OnshapeElementRow[]> {
+ return this.request<OnshapeElementRow[]>(
+ "GET",
+ `/api/v10/documents/d/${document.documentId}/${document.wvm}/${document.wvmId}/elements${elementType ? "?elementType=" + elementType : ""}`
+ );
+ }
+
+ async getBillOfMaterialsIn(
+ document: OnshapeDocument,
+ elementId: string,
+ configuration?: string | null
+ ): Promise<Record<string, unknown>> {
+ return this.request<Record<string, unknown>>(
+ "GET",
+ `/api/v10/assemblies/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}/bom?indented=true&multiLevel=true&generateIfAbsent=true&onlyVisibleColumns=false&includeItemMicroversions=true&includeTopLevelAssemblyRow=true&thumbnail=false${configurationQuery(configuration)}`
+ );
+ }
+
+ /** Without mates. Far cheaper than the BOM when only the parts are needed. */
+ async getAssemblyDefinitionIn(
+ document: OnshapeDocument,
+ elementId: string,
+ configuration?: string | null
+ ): Promise<Record<string, unknown>> {
+ return this.request<Record<string, unknown>>(
+ "GET",
+ `/api/v10/assemblies/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}?includeMateFeatures=false&includeNonSolids=false&includeMateConnectors=false${configurationQuery(configuration)}`
+ );
+ }
+
+ /** An assembly's own identity comes from here: the BOM omits it. */
+ async getElementMetadata(
+ document: OnshapeDocument,
+ elementId: string,
+ configuration?: string | null
+ ): Promise<Record<string, unknown>> {
+ return this.request<Record<string, unknown>>(
+ "GET",
+ `/api/v10/metadata/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}?inferMetadataOwner=false&depth=1${configurationQuery(configuration)}`
+ );
+ }
+
+ /** `depth=2` nests a Part Studio's `parts.items[].properties`: one read. */
+ async getElementMetadataWithParts(
+ document: OnshapeDocument,
+ elementId: string,
+ configuration?: string | null
+ ): Promise<Record<string, unknown>> {
+ return this.request<Record<string, unknown>>(
+ "GET",
+ `/api/v10/metadata/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}?inferMetadataOwner=false&depth=2${configurationQuery(configuration)}`
+ );
+ }
+
+ async getPartMetadata(
+ document: OnshapeDocument,
+ elementId: string,
+ partId: string,
+ configuration?: string | null
+ ): Promise<Record<string, unknown>> {
+ return this.request<Record<string, unknown>>(
+ "GET",
+ `/api/v10/metadata/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}/p/${encodeURIComponent(partId)}?inferMetadataOwner=false${configurationQuery(configuration)}`
+ );
+ }
+
+ async getPartsInElement(
+ document: OnshapeDocument,
+ elementId: string,
+ configuration?: string | null
+ ): Promise<OnshapeElementPart[]> {
+ return this.request<OnshapeElementPart[]>(
+ "GET",
+ `/api/v10/parts/d/${document.documentId}/${document.wvm}/${document.wvmId}/e/${elementId}?includePropertyDefaults=true${configurationQuery(configuration)}`
+ );
+ }
+
async createPartStudioTranslation(
documentId: string,
versionId: string,
@@ -380,11 +686,12 @@ export class OnshapeClient {
// FLAGGED: single-part export support unverified. Omit to export the whole
// Part Studio; the reliable documented path is a whole-Part-Studio translation.
partIds?: string;
+ wvm?: "w" | "v";
} = {}
): Promise<OnshapeTranslation> {
return this.request<OnshapeTranslation>(
"POST",
- `/api/v10/partstudios/d/${documentId}/v/${versionId}/e/${elementId}/translations`,
+ `/api/v10/partstudios/d/${documentId}/${options.wvm ?? "v"}/${versionId}/e/${elementId}/translations`,
{
formatName: options.formatName ?? "GLTF",
storeInDocument: options.storeInDocument ?? false,
@@ -409,11 +716,12 @@ export class OnshapeClient {
storeInDocument?: boolean;
configuration?: string;
resolution?: OnshapeMeshResolution;
+ wvm?: "w" | "v";
} = {}
): Promise<OnshapeTranslation> {
return this.request<OnshapeTranslation>(
"POST",
- `/api/v10/assemblies/d/${documentId}/v/${versionId}/e/${elementId}/translations`,
+ `/api/v10/assemblies/d/${documentId}/${options.wvm ?? "v"}/${versionId}/e/${elementId}/translations`,
{
formatName: options.formatName ?? "GLTF",
storeInDocument: options.storeInDocument ?? false,
@@ -433,11 +741,12 @@ export class OnshapeClient {
options: {
formatName?: OnshapeDrawingTranslationFormat;
storeInDocument?: boolean;
+ wvm?: "w" | "v";
} = {}
): Promise<OnshapeTranslation> {
return this.request<OnshapeTranslation>(
"POST",
- `/api/v10/drawings/d/${documentId}/v/${versionId}/e/${elementId}/translations`,
+ `/api/v10/drawings/d/${documentId}/${options.wvm ?? "v"}/${versionId}/e/${elementId}/translations`,
{
formatName: options.formatName ?? "PDF",
storeInDocument: options.storeInDocument ?? false
@@ -495,12 +804,13 @@ export class OnshapeClient {
documentId: string,
versionId: string,
elementId: string,
- size: string = "300x300"
+ size: string = "300x300",
+ wvm: "w" | "v" = "v"
): Promise<ArrayBuffer> {
try {
const response = await this.axiosInstance.request<ArrayBuffer>({
method: "GET",
- url: `/api/v10/thumbnails/d/${documentId}/v/${versionId}/e/${elementId}/s/${size}`,
+ url: `/api/v10/thumbnails/d/${documentId}/${wvm}/${versionId}/e/${elementId}/s/${size}`,
responseType: "arraybuffer",
headers: { Accept: "image/png" }
});
@@ -573,34 +883,62 @@ export class OnshapeClient {
}
}
+const REFRESH_LEASE_MS = 5_000;
+const REFRESH_LEASE_RENEW_MS = 2_000;
+const REFRESH_WAIT_DEADLINE_MS = 20_000;
+const REFRESH_WAIT_MS = 250;
+
export async function getOnshapeClient(
+ /** The panel passes the service role: the row needs settings view. */
client: SupabaseClient<Database>,
companyId: string,
- userId: string
+ userId: string,
+ /** Omitted or a sync id: the company's active sync connection. */
+ requestedIntegrationId?: OnshapeOAuthIntegrationId
): Promise<
{ client: OnshapeClient; error: null } | { client: null; error: string }
> {
- // Either Onshape connection — the public app or a Government private app.
+ // Either sync connection — the public app or a Government private app.
// Past authorization they are the same API, just on a different host.
- const integration = await getOnshapeIntegration(client, companyId);
+ // The panel's connection must be active: uninstalling only sets
+ // `active = false` and leaves the tokens, so without the filter an
+ // uninstalled panel kept reading Onshape.
+ const integration =
+ requestedIntegrationId && !isOnshapeIntegrationId(requestedIntegrationId)
+ ? await client
+ .from("companyIntegration")
+ .select("*")
+ .eq("id", requestedIntegrationId)
+ .eq("companyId", companyId)
+ .eq("active", true)
+ .maybeSingle()
+ : await getOnshapeIntegration(client, companyId);
if (integration.error || !integration.data) {
return { client: null, error: "Onshape integration not found" };
}
-
// Secret material (accessToken/refreshToken) lives in Supabase Vault; merge it
// back so we read `metadata.credentials` the same as before. Vault RPCs require
// the service-role client (the passed `client` may be RLS-scoped).
const { getCarbonServiceRole } = await import("@carbon/auth/client.server");
const serviceRole = getCarbonServiceRole();
- const integrationId: OnshapeIntegrationId = integration.data.id;
- const metadata = (await resolveIntegrationSecrets(
- serviceRole,
- companyId,
- integrationId,
- integration.data.metadata,
- integration.data.secretRef
- )) as Record<string, any>;
+ const integrationId = integration.data.id as OnshapeOAuthIntegrationId;
+ // No vaulted secret means never connected, not a server error.
+ let metadata: Record<string, any>;
+ try {
+ metadata = (await resolveIntegrationSecrets(
+ serviceRole,
+ companyId,
+ integrationId,
+ integration.data.metadata,
+ integration.data.secretRef
+ )) as Record<string, any>;
+ } catch (error) {
+ if (error instanceof IntegrationSecretUnavailableError) {
+ return { client: null, error: "Onshape credentials not found" };
+ }
+ throw error;
+ }
const credentials = metadata?.credentials;
if (!credentials?.accessToken) {
@@ -610,41 +948,154 @@ export async function getOnshapeClient(
let accessToken = credentials.accessToken;
const baseUrl = metadata?.baseUrl ?? ONSHAPE_DEFAULT_BASE_URL;
- // Refresh token if expired
- if (
- credentials.expiresAt &&
- credentials.refreshToken &&
- new Date(credentials.expiresAt) <= new Date()
- ) {
+ /** Onshape rotates refresh tokens: a later refresh must spend the new one. */
+ const adoptCredentials = (next: Record<string, any> | undefined) => {
+ if (!next?.accessToken) return;
+ credentials.accessToken = next.accessToken;
+ if (next.refreshToken) credentials.refreshToken = next.refreshToken;
+ if (next.expiresAt) credentials.expiresAt = next.expiresAt;
+ accessToken = next.accessToken;
+ };
+
+ /** The credentials as stored now, not as loaded when this request started. */
+ const readStoredCredentials = async (): Promise<Record<
+ string,
+ any
+ > | null> => {
+ const row = await serviceRole
+ .from("companyIntegration")
+ .select("metadata, secretRef")
+ .eq("id", integrationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (row.error || !row.data) return null;
+ const current = (await resolveIntegrationSecrets(
+ serviceRole,
+ companyId,
+ integrationId,
+ row.data.metadata,
+ row.data.secretRef
+ ).catch(() => null)) as Record<string, any> | null;
+ return current?.credentials ?? null;
+ };
+
+ const refreshFromStored = async (): Promise<string | null> => {
+ const next = resolveOnshapeRefresh(
+ await readStoredCredentials(),
+ credentials,
+ accessToken,
+ Date.now()
+ );
+ if (next.action === "exchange") return exchange(next.credentials);
+ adoptCredentials(next.credentials);
+ return accessToken;
+ };
+
+ const exchange = async (
+ from: StoredOnshapeCredentials
+ ): Promise<string | null> => {
+ if (!from.refreshToken) return null;
+ let next: { accessToken: string; refreshToken?: string; expiresAt: string };
try {
const oauth = getOnshapeOAuthConfig(integrationId, metadata);
if (!oauth) throw new Error("Onshape OAuth not configured");
const refreshed = await refreshOnshapeAccessToken(
oauth,
- credentials.refreshToken
+ from.refreshToken
);
-
- accessToken = refreshed.access_token;
-
- // Persist the new tokens. Secret material is split out to Supabase Vault;
- // only the non-secret config is written to the metadata column.
- await persistIntegrationSecrets(serviceRole, companyId, integrationId, {
- ...metadata,
- credentials: {
- ...credentials,
- accessToken: refreshed.access_token,
- refreshToken: refreshed.refresh_token,
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString()
- }
+ const lifetimeSeconds = refreshed.expires_in ?? 3600;
+ next = {
+ accessToken: refreshed.access_token,
+ refreshToken: refreshed.refresh_token,
+ expiresAt: new Date(Date.now() + lifetimeSeconds * 1000).toISOString()
+ };
+ } catch (error) {
+ logger.error("Failed to refresh Onshape token", {
+ companyId,
+ integrationId,
+ error
});
+ return null;
+ }
+ // The old refresh token is spent: keep the new pair even if saving fails.
+ adoptCredentials(next);
+ try {
+ await patchOnshapeRefreshedTokens(
+ serviceRole,
+ companyId,
+ integrationId,
+ next
+ );
} catch (error) {
- logger.error("Failed to refresh Onshape token", { error });
+ logger.error("Failed to save the refreshed Onshape token", {
+ companyId,
+ integrationId,
+ error
+ });
+ }
+ return next.accessToken;
+ };
+
+ /**
+ * One refresh across concurrent callers, under a Redis lease: with rotating
+ * refresh tokens the losing caller would store a dead pair over the live one.
+ * Waiters adopt the holder's result. With Redis down it runs unlocked.
+ */
+ const refreshNow = async (): Promise<string | null> => {
+ // Per integration: each holds its own refresh token.
+ const leaseKey = `onshape-token-refresh:${companyId}:${integrationId}`;
+ const deadline = Date.now() + REFRESH_WAIT_DEADLINE_MS;
+
+ while (true) {
+ const lease = await acquireLease(leaseKey, REFRESH_LEASE_MS);
+
+ if (lease.status === "unavailable") {
+ logger.warn("Refreshing the Onshape token without a lock", {
+ companyId,
+ integrationId
+ });
+ return refreshFromStored();
+ }
+
+ if (lease.status === "acquired") {
+ return withLease(
+ leaseKey,
+ lease.owner,
+ { leaseMs: REFRESH_LEASE_MS, renewMs: REFRESH_LEASE_RENEW_MS },
+ refreshFromStored
+ );
+ }
+
+ if (Date.now() >= deadline) return null;
+ await new Promise((resolve) => setTimeout(resolve, REFRESH_WAIT_MS));
+ const next = resolveOnshapeRefresh(
+ await readStoredCredentials(),
+ credentials,
+ accessToken,
+ Date.now()
+ );
+ if (next.action === "adopt") {
+ adoptCredentials(next.credentials);
+ return accessToken;
+ }
+ }
+ };
+
+ // No `expiresAt` guard: a connection without a stored expiry must refresh.
+ if (credentials.refreshToken && !isFresh(credentials, Date.now())) {
+ const refreshedToken = await refreshNow();
+ if (!refreshedToken) {
return { client: null, error: "Failed to refresh Onshape token" };
}
+ accessToken = refreshedToken;
}
return {
- client: new OnshapeClient({ baseUrl, accessToken }),
+ client: new OnshapeClient({
+ baseUrl,
+ accessToken,
+ onUnauthorized: refreshNow
+ }),
error: null
};
}
diff --git a/packages/ee/src/onshape/lib/index.server.ts b/packages/ee/src/onshape/lib/index.server.ts
new file mode 100644
index 0000000000..b51a96d72f
--- /dev/null
+++ b/packages/ee/src/onshape/lib/index.server.ts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// Server-only exports, kept out of `@carbon/ee/onshape` so client modules
+// cannot reach a `.server` file.
+export * from "../oauth.server";
+export * from "./panel-properties.server";
+export * from "./state";
diff --git a/packages/ee/src/onshape/lib/index.ts b/packages/ee/src/onshape/lib/index.ts
index d302f38289..04acfc5e3c 100644
--- a/packages/ee/src/onshape/lib/index.ts
+++ b/packages/ee/src/onshape/lib/index.ts
@@ -2,9 +2,23 @@
// Carbon Enterprise file, licensed only under the Carbon Commercial License
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+export type { DraftCandidate } from "../panel/method-version";
+export {
+ DRAFT_MARKER_ENTITY_TYPE,
+ pairOwnedCopiedLines,
+ pickReusableDraft
+} from "../panel/method-version";
+export type { ReleaseExportSelection } from "../panel/releases";
+export { releaseExportSelection } from "../panel/releases";
+export { compareRevisions } from "../panel/revision";
+export * from "./batched-filter";
export * from "./client";
export * from "./connection";
export * from "./data";
export * from "./document.type";
export * from "./element.type";
+export * from "./integration-id";
export * from "./oauth";
+export * from "./onshape-failure";
+export * from "./panel-plan-data";
+export * from "./panel-plan-store";
diff --git a/packages/ee/src/onshape/lib/integration-id.ts b/packages/ee/src/onshape/lib/integration-id.ts
new file mode 100644
index 0000000000..35f0b194bc
--- /dev/null
+++ b/packages/ee/src/onshape/lib/integration-id.ts
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { OnshapeIntegrationId } from "./connection";
+
+// The panel's own grant, credential row and mapping namespace. Sync rows
+// (`onshape`, `onshape-government`) are BOM-import bookkeeping: the item lock,
+// card and Detach read `onshape-v2` only, never an `"onshape"` literal.
+export const ONSHAPE_V2_INTEGRATION_ID = "onshape-v2";
+
+export type OnshapeV2IntegrationId = typeof ONSHAPE_V2_INTEGRATION_ID;
+
+/** Every Onshape integration with its own OAuth grant: sync and panel. */
+export type OnshapeOAuthIntegrationId =
+ | OnshapeIntegrationId
+ | OnshapeV2IntegrationId;
diff --git a/packages/ee/src/onshape/lib/oauth.test.ts b/packages/ee/src/onshape/lib/oauth.test.ts
index c0c2737de9..661d20cc31 100644
--- a/packages/ee/src/onshape/lib/oauth.test.ts
+++ b/packages/ee/src/onshape/lib/oauth.test.ts
@@ -2,14 +2,46 @@
// Carbon Enterprise file, licensed only under the Carbon Commercial License
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// The sync app and the panel app, each set or unset per test.
+const env = vi.hoisted(() => {
+ const configured = {
+ ONSHAPE_CLIENT_ID: "public-client",
+ ONSHAPE_CLIENT_SECRET: "public-secret",
+ ONSHAPE_OAUTH_REDIRECT_URL:
+ "https://app.carbon.ms/api/integrations/onshape/oauth",
+ ONSHAPE_V2_CLIENT_ID: "panel-client",
+ ONSHAPE_V2_CLIENT_SECRET: "panel-secret",
+ ONSHAPE_V2_OAUTH_REDIRECT_URL:
+ "https://app.carbon.ms/api/integrations/onshape-v2/oauth"
+ };
+ return {
+ configured,
+ current: { ...configured } as Partial<typeof configured>
+ };
+});
vi.mock("@carbon/env", () => ({
getAppUrl: () => "https://itar.carbon.ms",
- ONSHAPE_CLIENT_ID: "public-client",
- ONSHAPE_CLIENT_SECRET: "public-secret",
- ONSHAPE_OAUTH_REDIRECT_URL:
- "https://app.carbon.ms/api/integrations/onshape/oauth"
+ get ONSHAPE_CLIENT_ID() {
+ return env.current.ONSHAPE_CLIENT_ID;
+ },
+ get ONSHAPE_CLIENT_SECRET() {
+ return env.current.ONSHAPE_CLIENT_SECRET;
+ },
+ get ONSHAPE_OAUTH_REDIRECT_URL() {
+ return env.current.ONSHAPE_OAUTH_REDIRECT_URL;
+ },
+ get ONSHAPE_V2_CLIENT_ID() {
+ return env.current.ONSHAPE_V2_CLIENT_ID;
+ },
+ get ONSHAPE_V2_CLIENT_SECRET() {
+ return env.current.ONSHAPE_V2_CLIENT_SECRET;
+ },
+ get ONSHAPE_V2_OAUTH_REDIRECT_URL() {
+ return env.current.ONSHAPE_V2_OAUTH_REDIRECT_URL;
+ }
}));
import {
@@ -43,6 +75,10 @@ describe("normalizeOnshapeUrl", () => {
});
describe("getOnshapeOAuthConfig", () => {
+ afterEach(() => {
+ env.current = { ...env.configured };
+ });
+
it("uses this instance's public app for the standard integration", () => {
expect(getOnshapeOAuthConfig("onshape", {})).toEqual({
clientId: "public-client",
@@ -54,6 +90,45 @@ describe("getOnshapeOAuthConfig", () => {
});
});
+ it("uses the panel's own app for Onshape V2", () => {
+ expect(getOnshapeOAuthConfig("onshape-v2", {})).toEqual({
+ clientId: "panel-client",
+ clientSecret: "panel-secret",
+ redirectUri: "https://app.carbon.ms/api/integrations/onshape-v2/oauth",
+ baseUrl: "https://cad.onshape.com",
+ authorizeUrl: "https://oauth.onshape.com/oauth/authorize",
+ tokenUrl: "https://oauth.onshape.com/oauth/token"
+ });
+ });
+
+ it("never lends the sync app's client to the panel", () => {
+ env.current = {
+ ONSHAPE_CLIENT_ID: env.configured.ONSHAPE_CLIENT_ID,
+ ONSHAPE_CLIENT_SECRET: env.configured.ONSHAPE_CLIENT_SECRET,
+ ONSHAPE_OAUTH_REDIRECT_URL: env.configured.ONSHAPE_OAUTH_REDIRECT_URL,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL:
+ env.configured.ONSHAPE_V2_OAUTH_REDIRECT_URL
+ };
+ expect(getOnshapeOAuthConfig("onshape-v2", {})).toBeNull();
+ expect(getOnshapeOAuthConfig("onshape", {})?.clientId).toBe(
+ "public-client"
+ );
+ });
+
+ it("never lends the panel's client to the sync integration", () => {
+ env.current = {
+ ONSHAPE_OAUTH_REDIRECT_URL: env.configured.ONSHAPE_OAUTH_REDIRECT_URL,
+ ONSHAPE_V2_CLIENT_ID: env.configured.ONSHAPE_V2_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_SECRET: env.configured.ONSHAPE_V2_CLIENT_SECRET,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL:
+ env.configured.ONSHAPE_V2_OAUTH_REDIRECT_URL
+ };
+ expect(getOnshapeOAuthConfig("onshape", {})).toBeNull();
+ expect(getOnshapeOAuthConfig("onshape-v2", {})?.clientId).toBe(
+ "panel-client"
+ );
+ });
+
it("uses the customer's private app and tenant for Government", () => {
expect(getOnshapeOAuthConfig("onshape-government", government)).toEqual({
clientId: "gov-client",
diff --git a/packages/ee/src/onshape/lib/oauth.ts b/packages/ee/src/onshape/lib/oauth.ts
index d36bca4f07..f845d1f6f7 100644
--- a/packages/ee/src/onshape/lib/oauth.ts
+++ b/packages/ee/src/onshape/lib/oauth.ts
@@ -6,24 +6,32 @@ import {
getAppUrl,
ONSHAPE_CLIENT_ID,
ONSHAPE_CLIENT_SECRET,
- ONSHAPE_OAUTH_REDIRECT_URL
+ ONSHAPE_OAUTH_REDIRECT_URL,
+ ONSHAPE_V2_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_SECRET,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL
} from "@carbon/env";
import {
normalizeOnshapeUrl,
ONSHAPE_DEFAULT_BASE_URL,
ONSHAPE_DEFAULT_OAUTH_URL,
ONSHAPE_GOVERNMENT_INTEGRATION_ID,
- ONSHAPE_GOVERNMENT_OAUTH_CALLBACK_PATH,
- type OnshapeIntegrationId
+ ONSHAPE_GOVERNMENT_OAUTH_CALLBACK_PATH
} from "./connection";
+import {
+ ONSHAPE_V2_INTEGRATION_ID,
+ type OnshapeOAuthIntegrationId
+} from "./integration-id";
/**
* Where to authorize, which client to authorize as, and which API host the
* resulting token is good for.
*
- * The public app's client lives in this Carbon instance's environment. A
- * Government customer's private app lives in THEIR Enterprise, so its client id,
- * secret and hosts come from the integration's own (vaulted) settings instead.
+ * The sync integration and the panel are two Onshape apps, each with its own
+ * client in this Carbon instance's environment (`ONSHAPE_*` and
+ * `ONSHAPE_V2_*`). A Government customer's private app lives in THEIR
+ * Enterprise, so its client id, secret and hosts come from the integration's
+ * own (vaulted) settings instead.
*/
export type OnshapeOAuthConfig = {
clientId: string;
@@ -59,7 +67,7 @@ function oauthEndpoints(oauthUrl: string) {
* (`resolveIntegrationSecrets`) — the Government client secret is one of them.
*/
export function getOnshapeOAuthConfig(
- integrationId: OnshapeIntegrationId,
+ integrationId: OnshapeOAuthIntegrationId,
metadata: Record<string, unknown> | null | undefined
): OnshapeOAuthConfig | null {
if (integrationId === ONSHAPE_GOVERNMENT_INTEGRATION_ID) {
@@ -85,17 +93,26 @@ export function getOnshapeOAuthConfig(
};
}
- if (
- !ONSHAPE_CLIENT_ID ||
- !ONSHAPE_CLIENT_SECRET ||
- !ONSHAPE_OAUTH_REDIRECT_URL
- ) {
+ // The panel is its own Onshape app: it never falls back to the sync app's client.
+ const { clientId, clientSecret, redirectUri } =
+ integrationId === ONSHAPE_V2_INTEGRATION_ID
+ ? {
+ clientId: ONSHAPE_V2_CLIENT_ID,
+ clientSecret: ONSHAPE_V2_CLIENT_SECRET,
+ redirectUri: ONSHAPE_V2_OAUTH_REDIRECT_URL
+ }
+ : {
+ clientId: ONSHAPE_CLIENT_ID,
+ clientSecret: ONSHAPE_CLIENT_SECRET,
+ redirectUri: ONSHAPE_OAUTH_REDIRECT_URL
+ };
+ if (!clientId || !clientSecret || !redirectUri) {
return null;
}
return {
- clientId: ONSHAPE_CLIENT_ID,
- clientSecret: ONSHAPE_CLIENT_SECRET,
- redirectUri: ONSHAPE_OAUTH_REDIRECT_URL,
+ clientId,
+ clientSecret,
+ redirectUri,
baseUrl: ONSHAPE_DEFAULT_BASE_URL,
...oauthEndpoints(ONSHAPE_DEFAULT_OAUTH_URL)
};
@@ -138,6 +155,10 @@ export class OnshapeTokenError extends Error {
}
}
+// A hung token exchange would hold the refresh lease and stall every request
+// for the connection.
+const TOKEN_REQUEST_TIMEOUT_MS = 15_000;
+
async function requestToken(
config: OnshapeOAuthConfig,
body: Record<string, string>
@@ -149,7 +170,8 @@ async function requestToken(
...body,
client_id: config.clientId,
client_secret: config.clientSecret
- })
+ }),
+ signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS)
});
if (!response.ok) {
diff --git a/packages/ee/src/onshape/lib/onshape-failure.test.ts b/packages/ee/src/onshape/lib/onshape-failure.test.ts
new file mode 100644
index 0000000000..7327567fb1
--- /dev/null
+++ b/packages/ee/src/onshape/lib/onshape-failure.test.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { onshapeFailure } from "./onshape-failure";
+
+/** The shape the client throws, without loading the client and its env. */
+class OnshapeApiError extends Error {
+ constructor(
+ message: string,
+ public status?: number,
+ public retryAfterSeconds?: number
+ ) {
+ super(message);
+ }
+}
+
+const timeout = new OnshapeApiError(
+ "Onshape request failed: timeout of 60000ms exceeded"
+);
+
+describe("onshapeFailure", () => {
+ it("never passes axios's own text through", () => {
+ for (const read of ["bom", "other"] as const) {
+ expect(onshapeFailure(timeout, read).body.error).not.toMatch(/60000ms/);
+ }
+ });
+
+ it("tells a cold BOM read to press Refresh, since Onshape is still building it", () => {
+ const failure = onshapeFailure(timeout, "bom");
+ expect(failure.status).toBe(504);
+ expect(failure.body.error).toMatch(/still building this BOM/);
+ expect(failure.body.error).toMatch(/try again/i);
+ });
+
+ it("gives other timeouts the generic wording", () => {
+ expect(onshapeFailure(timeout).body.error).toMatch(/didn't answer in time/);
+ });
+
+ it("separates a dead network from a timeout", () => {
+ const refused = new OnshapeApiError(
+ "Onshape request failed: connect ECONNREFUSED"
+ );
+ const failure = onshapeFailure(refused);
+ expect(failure.status).toBe(502);
+ expect(failure.body.error).toMatch(/couldn't reach Onshape/);
+ });
+
+ it("carries Retry-After into a rate-limit message", () => {
+ const failure = onshapeFailure(new OnshapeApiError("x", 429, 30));
+ expect(failure.status).toBe(429);
+ expect(failure.body).toMatchObject({ retryAfterSeconds: 30 });
+ expect(failure.body.error).toMatch(/30 seconds/);
+ });
+
+ it("falls back to a minute when Onshape gives no Retry-After", () => {
+ const failure = onshapeFailure(new OnshapeApiError("x", 429));
+ expect(failure.body.error).toMatch(/60 seconds/);
+ expect(failure.body).not.toHaveProperty("retryAfterSeconds");
+ });
+
+ it("never answers Onshape's 401 or 403 as a 401", () => {
+ for (const status of [401, 403]) {
+ const failure = onshapeFailure(new OnshapeApiError("x", status));
+ expect(failure.status).toBe(422);
+ expect(failure.body.error).toMatch(/Reconnect Onshape/);
+ }
+ });
+
+ it("names a missing document as missing", () => {
+ expect(onshapeFailure(new OnshapeApiError("x", 404)).status).toBe(404);
+ });
+
+ it("names a used-up API limit instead of asking for a retry", () => {
+ const failure = onshapeFailure(new OnshapeApiError("x", 402));
+ expect(failure.body.error).toMatch(/yearly API limit/);
+ expect(failure.body.error).not.toMatch(/Try again/);
+ });
+
+ it("reports any other Onshape status without echoing its body", () => {
+ const failure = onshapeFailure(
+ new OnshapeApiError('Onshape API error (500): {"stack":"secret"}', 500)
+ );
+ expect(failure.status).toBe(502);
+ expect(failure.body.error).toMatch(/HTTP 500/);
+ expect(failure.body.error).not.toMatch(/stack|secret/);
+ });
+
+ it("handles a non-Onshape throw", () => {
+ expect(onshapeFailure(new Error("boom")).status).toBe(502);
+ expect(onshapeFailure("not an error").status).toBe(502);
+ });
+});
diff --git a/packages/ee/src/onshape/lib/onshape-failure.ts b/packages/ee/src/onshape/lib/onshape-failure.ts
new file mode 100644
index 0000000000..3424751825
--- /dev/null
+++ b/packages/ee/src/onshape/lib/onshape-failure.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { getLogger } from "@carbon/logger";
+import type { OnshapeApiError } from "./client";
+
+const logger = getLogger("ee", "onshape", "panel");
+
+/**
+ * The status and user-facing message a panel route returns for a failed Onshape
+ * call. Onshape's 401/403 maps to 422: the panel reads a 401 as an expired
+ * Carbon session and signs the user out.
+ */
+export type OnshapeFailure = {
+ status: 404 | 422 | 429 | 502 | 504;
+ body: { error: string; retryAfterSeconds?: number };
+};
+
+/** A BOM read gets its own timeout wording: Onshape builds BOMs on demand. */
+export type OnshapeRead = "bom" | "other";
+
+export function onshapeFailure(
+ error: unknown,
+ read: OnshapeRead = "other"
+): OnshapeFailure {
+ // Structural read: `instanceof` would import the client, which loads the env.
+ const apiError = error as Partial<OnshapeApiError> | null;
+ const status =
+ typeof apiError?.status === "number" ? apiError.status : undefined;
+ const message = error instanceof Error ? error.message : String(error);
+ logger.warn("Onshape call failed", { read, status, message });
+
+ if (status === undefined) {
+ // No response: axios says "timeout of Nms exceeded"; else the network.
+ if (/timeout/i.test(message)) {
+ return {
+ status: 504,
+ body: {
+ error:
+ read === "bom"
+ ? "Onshape is still building this BOM. It can take a minute the first time — try again shortly."
+ : "Onshape didn't answer in time. Try again."
+ }
+ };
+ }
+ return {
+ status: 502,
+ body: {
+ error: "Carbon couldn't reach Onshape. Try again."
+ }
+ };
+ }
+
+ if (status === 429) {
+ const retryAfterSeconds =
+ typeof apiError?.retryAfterSeconds === "number"
+ ? apiError.retryAfterSeconds
+ : undefined;
+ return {
+ status: 429,
+ body: {
+ error: `Onshape is rate-limiting this connection. Try again in ${
+ retryAfterSeconds ?? 60
+ } seconds.`,
+ ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds })
+ }
+ };
+ }
+
+ if (status === 401 || status === 403) {
+ return {
+ status: 422,
+ body: {
+ error:
+ "Onshape rejected Carbon's connection. Reconnect Onshape in Carbon's integration settings."
+ }
+ };
+ }
+
+ if (status === 404) {
+ return {
+ status: 404,
+ body: {
+ error: "That Onshape document, version or element no longer exists."
+ }
+ };
+ }
+
+ // Onshape answers 402 once the OAuth app owner's yearly API limit is used up;
+ // a retry cannot help.
+ if (status === 402) {
+ return {
+ status: 502,
+ body: {
+ error:
+ "Onshape refused the request: the yearly API limit for Carbon's Onshape app is used up. Ask your Carbon administrator to raise it with Onshape."
+ }
+ };
+ }
+
+ return {
+ status: 502,
+ body: {
+ error: `Onshape returned an error (HTTP ${status}). Try again; if it keeps happening, contact support.`
+ }
+ };
+}
diff --git a/packages/ee/src/onshape/lib/panel-plan-data.ts b/packages/ee/src/onshape/lib/panel-plan-data.ts
new file mode 100644
index 0000000000..b468e316c5
--- /dev/null
+++ b/packages/ee/src/onshape/lib/panel-plan-data.ts
@@ -0,0 +1,451 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ DRAFT_MARKER_ENTITY_TYPE,
+ type DraftCandidate,
+ pickReusableDraft
+} from "../panel/method-version";
+import type {
+ PlanLine,
+ PlanMappingContext,
+ PlanMethodRow,
+ PlanOptions
+} from "../panel/plan";
+import { parsePushDefaults } from "../panel/preferences";
+import { parseDescriptionModes, parsePropertyMap } from "../panel/properties";
+import {
+ type ReleasedRevision,
+ releasedRevisionsByPartNumber
+} from "../panel/status";
+import { selectInBatches } from "./batched-filter";
+import { ONSHAPE_V2_INTEGRATION_ID } from "./integration-id";
+
+// The plan and apply routes reach the panel's pure helpers through this barrel.
+export { withRefusedMethods } from "../panel/plan";
+
+// Carbon reads shared by the panel's plan and apply routes.
+
+type Client = SupabaseClient<Database>;
+
+/**
+ * Fail-soft so a plan always builds. Takes the service role: the
+ * `companyIntegration` SELECT needs settings view, so through a user's client
+ * the row reads as absent and every push takes the built-in defaults.
+ */
+export async function loadPlanOptions(
+ client: Client,
+ companyId: string
+): Promise<PlanOptions> {
+ const [units, integration] = await Promise.all([
+ client
+ .from("unitOfMeasure")
+ .select("code, name")
+ .eq("companyId", companyId)
+ .order("name"),
+ client
+ .from("companyIntegration")
+ .select("metadata")
+ .eq("id", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+ return {
+ unitsOfMeasure: (units.data ?? []).map((unit) => ({
+ code: unit.code,
+ name: unit.name
+ })),
+ defaults: parsePushDefaults(integration.data?.metadata)
+ };
+}
+
+/**
+ * Throws on a failed read: an empty map reads as "no method" everywhere. With
+ * no Active method the view returns the newest Draft, which can be a change
+ * notice's; `changeOrderId` says so (the view does not carry it).
+ */
+export async function loadActiveMakeMethods(
+ client: Client,
+ companyId: string,
+ itemIds: string[]
+): Promise<Map<string, PlanMethodRow>> {
+ const ids = [...new Set(itemIds)];
+ if (ids.length === 0) return new Map();
+ const rows = await selectInBatches(ids, (batch) =>
+ client
+ .from("activeMakeMethods")
+ .select("id, itemId, status")
+ .eq("companyId", companyId)
+ .in("itemId", batch)
+ );
+ if (rows.error) {
+ throw new Error(`Failed to read make methods: ${rows.error.message}`);
+ }
+ const draftIds = (rows.data ?? [])
+ .filter((row) => row.id && row.status !== "Active")
+ .map((row) => row.id as string);
+ const owners = await selectInBatches(draftIds, (batch) =>
+ client
+ .from("makeMethod")
+ .select("id, changeOrderId")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (owners.error) {
+ throw new Error(`Failed to read make methods: ${owners.error.message}`);
+ }
+ const changeOrderIdByMethodId = new Map(
+ owners.data.map((row) => [row.id, row.changeOrderId])
+ );
+ const byItemId = new Map<string, PlanMethodRow>();
+ for (const row of rows.data ?? []) {
+ if (row.id && row.itemId) {
+ byItemId.set(row.itemId, {
+ id: row.id,
+ status: row.status ?? "Draft",
+ changeOrderId: changeOrderIdByMethodId.get(row.id) ?? null
+ });
+ }
+ }
+ return byItemId;
+}
+
+/**
+ * Per part number, the newest revision with a `release:` link. Throws on a
+ * failed read, so a workspace push never writes into a released part.
+ */
+export async function loadReleasedRevisions(
+ client: Client,
+ companyId: string,
+ items: Array<{ id: string; readableId: string; revision: string | null }>
+): Promise<Map<string, ReleasedRevision>> {
+ const ids = [...new Set(items.map((item) => item.id))];
+ if (ids.length === 0) return new Map();
+ const rows = await selectInBatches(ids, (batch) =>
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "item")
+ .like("externalId", "release:%")
+ .in("entityId", batch)
+ );
+ if (rows.error) {
+ throw new Error(`Failed to read the release links: ${rows.error.message}`);
+ }
+ return releasedRevisionsByPartNumber(
+ items,
+ new Set((rows.data ?? []).map((row) => row.entityId))
+ );
+}
+
+/**
+ * Per item with an Active method, the Draft a push would reuse. Throws on a
+ * failed read, which would otherwise make every push mint another version.
+ */
+export async function loadReusableDrafts(
+ client: Client,
+ serviceRole: Client,
+ companyId: string,
+ activeMethodIdByItemId: Map<string, string>
+): Promise<Map<string, DraftCandidate>> {
+ const itemIds = [...activeMethodIdByItemId.keys()];
+ const result = new Map<string, DraftCandidate>();
+ if (itemIds.length === 0) return result;
+
+ const drafts = await selectInBatches(itemIds, (batch) =>
+ client
+ .from("makeMethod")
+ .select("id, itemId, version, changeOrderId")
+ .eq("companyId", companyId)
+ .eq("status", "Draft")
+ .in("itemId", batch)
+ );
+ if (drafts.error) {
+ throw new Error(
+ `Failed to read Draft make methods: ${drafts.error.message}`
+ );
+ }
+ const draftIds = (drafts.data ?? []).map((draft) => draft.id);
+ const markers = await selectInBatches(draftIds, (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("entityId, metadata")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", DRAFT_MARKER_ENTITY_TYPE)
+ .in("entityId", batch)
+ );
+ if (markers.error) {
+ throw new Error(
+ `Failed to read the Onshape Draft markers: ${markers.error.message}`
+ );
+ }
+ const markerRows = (markers.data ?? []).map((row) => ({
+ draftId: row.entityId,
+ sourceMethodId:
+ ((row.metadata as Record<string, unknown> | null)?.sourceMethodId as
+ | string
+ | undefined) ?? null
+ }));
+
+ const draftsByItemId = new Map<string, DraftCandidate[]>();
+ for (const draft of drafts.data ?? []) {
+ if (!draft.itemId) continue;
+ const list = draftsByItemId.get(draft.itemId) ?? [];
+ list.push({
+ id: draft.id,
+ version: draft.version ?? null,
+ changeOrderId: draft.changeOrderId ?? null
+ });
+ draftsByItemId.set(draft.itemId, list);
+ }
+ for (const [itemId, activeMethodId] of activeMethodIdByItemId) {
+ const chosen = pickReusableDraft(
+ draftsByItemId.get(itemId) ?? [],
+ markerRows,
+ activeMethodId
+ );
+ if (chosen) result.set(itemId, chosen);
+ }
+ return result;
+}
+
+/** Carries the push-owned columns so apply can skip an unchanged line. */
+export type MappedLineRow = {
+ mappingId: string;
+ lineId: string;
+ itemId: string;
+ quantity: number | null;
+ order: number | null;
+ materialMakeMethodId: string | null;
+};
+
+/** A push takes a manual line over when Onshape lists the same part number. */
+export type ManualLineRow = {
+ lineId: string;
+ itemId: string;
+ readableId: string;
+ /** Only a line of the same item type is taken over. */
+ itemType: string | null;
+ quantity: number | null;
+ order: number | null;
+ materialMakeMethodId: string | null;
+};
+
+export type MethodLineOwnership = {
+ /** Lines a previous push wrote, per method id. */
+ mapped: Map<string, PlanLine[]>;
+ manual: Map<string, PlanLine[]>;
+ /**
+ * `itemId` pairs a line with its write so it is updated in place; a reinsert
+ * would drop its operation, scrap and custom fields.
+ */
+ mappedRows: Map<string, MappedLineRow[]>;
+ /** In line order. */
+ manualRows: Map<string, ManualLineRow[]>;
+};
+
+/**
+ * Line provenance lives only in `externalIntegrationMapping` (`methodMaterial`
+ * rows keyed by `metadata.makeMethodId`), read with the service role.
+ */
+export async function loadMethodLineOwnership(
+ client: Client,
+ serviceRole: Client,
+ companyId: string,
+ methodIds: string[]
+): Promise<MethodLineOwnership> {
+ const ids = [...new Set(methodIds)];
+ const result: MethodLineOwnership = {
+ mapped: new Map(),
+ manual: new Map(),
+ mappedRows: new Map(),
+ manualRows: new Map()
+ };
+ if (ids.length === 0) return result;
+
+ const [lines, mappings] = await Promise.all([
+ selectInBatches(ids, (batch) =>
+ client
+ .from("methodMaterial")
+ .select(
+ "id, makeMethodId, itemId, itemType, quantity, order, materialMakeMethodId"
+ )
+ .eq("companyId", companyId)
+ .in("makeMethodId", batch)
+ ),
+ selectInBatches(ids, (batch) =>
+ serviceRole
+ .from("externalIntegrationMapping")
+ .select("id, entityId, metadata")
+ .eq("companyId", companyId)
+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("entityType", "methodMaterial")
+ .in("metadata->>makeMethodId", batch)
+ )
+ ]);
+
+ // Read as empty, a failure would make apply rewrite a method without deleting
+ // its lines.
+ if (lines.error || mappings.error) {
+ throw new Error(
+ `Failed to read the existing BOM lines: ${
+ lines.error?.message ?? mappings.error?.message ?? "unknown error"
+ }`
+ );
+ }
+ const mappingByLineId = new Map(
+ (mappings.data ?? []).map((mapping) => [mapping.entityId, mapping.id])
+ );
+
+ const itemIds = [
+ ...new Set((lines.data ?? []).map((line) => line.itemId).filter(Boolean))
+ ];
+ const items = await selectInBatches(itemIds, (batch) =>
+ client
+ .from("item")
+ .select("id, readableId")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ );
+ if (items.error) {
+ throw new Error(
+ `Failed to read the existing BOM lines: ${items.error.message}`
+ );
+ }
+ const readableIdByItemId = new Map(
+ (items.data ?? []).map((item) => [item.id, item.readableId])
+ );
+
+ const append = <T>(map: Map<string, T[]>, key: string, value: T) => {
+ const list = map.get(key);
+ if (list) {
+ list.push(value);
+ } else {
+ map.set(key, [value]);
+ }
+ };
+
+ // Batches arrive in batch order; plan and apply must pair lines the same way.
+ const ordered = [...(lines.data ?? [])].sort(
+ (a, b) =>
+ (a.order ?? 0) - (b.order ?? 0) ||
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
+ );
+ for (const line of ordered) {
+ const methodId = line.makeMethodId;
+ if (!methodId) continue;
+ const planLine: PlanLine = {
+ readableId: readableIdByItemId.get(line.itemId) ?? line.itemId,
+ quantity: line.quantity
+ };
+ const mappingId = mappingByLineId.get(line.id);
+ if (mappingId) {
+ append(result.mapped, methodId, planLine);
+ append(result.mappedRows, methodId, {
+ mappingId,
+ lineId: line.id,
+ itemId: line.itemId,
+ quantity: line.quantity,
+ order: line.order,
+ materialMakeMethodId: line.materialMakeMethodId
+ });
+ } else {
+ append(result.manual, methodId, { ...planLine, itemType: line.itemType });
+ append(result.manualRows, methodId, {
+ lineId: line.id,
+ itemId: line.itemId,
+ readableId: planLine.readableId,
+ itemType: line.itemType,
+ quantity: line.quantity,
+ order: line.order,
+ materialMakeMethodId: line.materialMakeMethodId
+ });
+ }
+ }
+ return result;
+}
+
+export async function loadPartCustomFieldDefinitions(
+ client: Client,
+ companyId: string
+): Promise<
+ Array<{
+ id: string;
+ name: string;
+ dataTypeId: number;
+ listOptions: string[] | null;
+ }>
+> {
+ const rows = await client
+ .from("customField")
+ .select("id, name, dataTypeId, listOptions, active")
+ .eq("companyId", companyId)
+ .eq("table", "part")
+ .order("sortOrder");
+ // Read as empty, a failure would mark every mapped custom field deleted.
+ if (rows.error) {
+ throw new Error(
+ `Failed to read custom field definitions: ${rows.error.message}`
+ );
+ }
+ return (rows.data ?? [])
+ .filter((row) => row.active !== false)
+ .map((row) => ({
+ id: row.id,
+ name: row.name,
+ dataTypeId: row.dataTypeId,
+ listOptions: row.listOptions
+ }));
+}
+
+/**
+ * Reads custom field definitions and held values only when the map targets a
+ * custom field. Takes the service role for the reason `loadPlanOptions` gives.
+ */
+export async function loadPlanMapping(
+ client: Client,
+ companyId: string,
+ readableIds: string[]
+): Promise<PlanMappingContext> {
+ const integration = await client
+ .from("companyIntegration")
+ .select("metadata")
+ .eq("id", ONSHAPE_V2_INTEGRATION_ID)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (integration.error) {
+ throw new Error(
+ `Failed to read the Onshape property map: ${integration.error.message}`
+ );
+ }
+ const metadata = integration.data?.metadata;
+ const map = parsePropertyMap(metadata);
+ const descriptionModes = parseDescriptionModes(metadata);
+ const heldCustomFields = new Map<string, unknown>();
+ if (!map.some((entry) => entry.target.kind === "customField")) {
+ return { map, definitions: [], descriptionModes, heldCustomFields };
+ }
+ const [definitions, held] = await Promise.all([
+ loadPartCustomFieldDefinitions(client, companyId),
+ selectInBatches([...new Set(readableIds)], (batch) =>
+ client
+ .from("part")
+ .select("id, customFields")
+ .eq("companyId", companyId)
+ .in("id", batch)
+ )
+ ]);
+ if (held.error) {
+ throw new Error(`Failed to read Carbon parts: ${held.error.message}`);
+ }
+ for (const part of held.data ?? []) {
+ heldCustomFields.set(part.id, part.customFields);
+ }
+ return { map, definitions, descriptionModes, heldCustomFields };
+}
diff --git a/packages/ee/src/onshape/lib/panel-plan-store.ts b/packages/ee/src/onshape/lib/panel-plan-store.ts
new file mode 100644
index 0000000000..11f606f9ff
--- /dev/null
+++ b/packages/ee/src/onshape/lib/panel-plan-store.ts
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { randomBytes } from "node:crypto";
+import { redis } from "@carbon/kv";
+import { datetime } from "@carbon/utils";
+import { parseAbsolute } from "@internationalized/date";
+import type { OnshapeBomNode } from "../panel/bom";
+import type { AssemblyPlan, PartPlan, ReleasePlan } from "../panel/plan";
+
+// Reviewed push plans in Redis. A plan holds every Onshape read the push needs,
+// so apply makes no Onshape call; GETDEL makes it one-shot, so a double-click
+// cannot write twice.
+
+export const PANEL_PLAN_TTL_SECONDS = 15 * 60;
+
+const PLAN_PREFIX = "cpp_";
+const PLAN_PATTERN = /^cpp_[A-Za-z0-9_-]{32}$/;
+
+export type StoredAssemblyPlan = AssemblyPlan & {
+ /** parseBomTree().lines at plan time. */
+ nodes: OnshapeBomNode[];
+};
+
+export type StoredReleasePlan = ReleasePlan & {
+ /** Per released assembly element; null (unread) leaves that method alone. */
+ bomLinesByElementId: Record<string, OnshapeBomNode[] | null>;
+};
+
+export type StoredPanelPlan = {
+ companyId: string;
+ userId: string;
+ createdAt: string;
+ plan: PartPlan | StoredAssemblyPlan | StoredReleasePlan;
+};
+
+function keyFor(planId: string) {
+ return `panel-plan:${planId}`;
+}
+
+export function isPanelPlanId(value: unknown): value is string {
+ return typeof value === "string" && PLAN_PATTERN.test(value);
+}
+
+/**
+ * Null when Redis did not take the write: `@carbon/kv` resolves null during an
+ * outage, and an unstored plan must fail the PLAN request, not the later apply.
+ */
+export async function createPanelPlan(
+ stored: Omit<StoredPanelPlan, "createdAt">
+): Promise<{ planId: string; expiresAt: string } | null> {
+ const planId = `${PLAN_PREFIX}${randomBytes(24).toString("base64url")}`;
+ const createdAt = datetime.timestamp();
+ const written = await redis.set(
+ keyFor(planId),
+ JSON.stringify({ ...stored, createdAt }),
+ "EX",
+ PANEL_PLAN_TTL_SECONDS
+ );
+ if (written !== "OK") return null;
+ return {
+ planId,
+ expiresAt: parseAbsolute(createdAt, "UTC")
+ .add({ seconds: PANEL_PLAN_TTL_SECONDS })
+ .toAbsoluteString()
+ };
+}
+
+/** Reads without consuming: a 422 on the user's edits keeps the plan. */
+export async function peekPanelPlan(
+ planId: string,
+ owner: { companyId: string; userId: string }
+): Promise<StoredPanelPlan | null> {
+ if (!isPanelPlanId(planId)) return null;
+ const raw = await redis.get(keyFor(planId));
+ if (!raw) return null;
+ let stored: StoredPanelPlan;
+ try {
+ stored = JSON.parse(raw) as StoredPanelPlan;
+ } catch {
+ await redis.del(keyFor(planId));
+ return null;
+ }
+ if (stored.companyId !== owner.companyId || stored.userId !== owner.userId) {
+ return null;
+ }
+ return stored;
+}
+
+/**
+ * Removes the plan atomically. Expired, taken, malformed and foreign plans all
+ * return null, indistinguishably.
+ */
+export async function takePanelPlan(
+ planId: string,
+ owner: { companyId: string; userId: string }
+): Promise<StoredPanelPlan | null> {
+ if (!isPanelPlanId(planId)) return null;
+ const raw = await redis.getdel(keyFor(planId));
+ if (!raw) return null;
+ let stored: StoredPanelPlan;
+ try {
+ stored = JSON.parse(raw) as StoredPanelPlan;
+ } catch {
+ return null;
+ }
+ if (stored.companyId !== owner.companyId || stored.userId !== owner.userId) {
+ return null;
+ }
+ return stored;
+}
diff --git a/packages/ee/src/onshape/lib/panel-properties.server.ts b/packages/ee/src/onshape/lib/panel-properties.server.ts
new file mode 100644
index 0000000000..f051c185ad
--- /dev/null
+++ b/packages/ee/src/onshape/lib/panel-properties.server.ts
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { getLogger } from "@carbon/logger";
+import { firstOwnAssemblyPart } from "../panel/bom";
+import type { OnshapePropertyValue } from "../panel/properties";
+import {
+ parseProperties,
+ partPropertiesFromElementMetadata
+} from "../panel/properties";
+import { OnshapeApiError, type OnshapeClient } from "./client";
+import type { OnshapeDocument, OnshapeWVMType } from "./document.type";
+
+const logger = getLogger("ee", "onshape", "part-properties");
+
+/**
+ * One element metadata read at `depth=2`, plus one read per requested part that
+ * payload lacks. Onshape's depth semantics are loosely documented, so the
+ * nested shape is probed rather than assumed.
+ */
+export async function readPartProperties(
+ client: OnshapeClient,
+ document: OnshapeDocument,
+ elementId: string,
+ partIds: string[],
+ configuration?: string | null
+): Promise<Map<string, OnshapePropertyValue[]>> {
+ const byPartId =
+ partPropertiesFromElementMetadata(
+ await client.getElementMetadataWithParts(
+ document,
+ elementId,
+ configuration
+ )
+ ) ?? new Map<string, OnshapePropertyValue[]>();
+
+ for (const partId of [...new Set(partIds)]) {
+ if (byPartId.has(partId)) continue;
+ try {
+ byPartId.set(
+ partId,
+ parseProperties(
+ await client.getPartMetadata(
+ document,
+ elementId,
+ partId,
+ configuration
+ )
+ )
+ );
+ } catch (error) {
+ // Only a 404 means "no values"; any other failure fails the plan rather
+ // than push stale mapped fields as current.
+ if (error instanceof OnshapeApiError && error.status === 404) {
+ logger.warn("Onshape part has no metadata; no mapped values", {
+ documentId: document.documentId,
+ elementId,
+ partId
+ });
+ continue;
+ }
+ logger.error("Failed to read Onshape part properties", {
+ documentId: document.documentId,
+ elementId,
+ partId,
+ error
+ });
+ throw error;
+ }
+ }
+ return byPartId;
+}
+
+/**
+ * The assembly's own properties plus one of its parts', since part-scoped
+ * properties never show on the assembly element. The part comes from the
+ * assembly definition (cheaper than the BOM); a failed read keeps the own list.
+ */
+export async function readAssemblyProperties(
+ client: OnshapeClient,
+ document: OnshapeDocument,
+ elementId: string
+): Promise<OnshapePropertyValue[]> {
+ const own = parseProperties(
+ await client.getElementMetadata(document, elementId)
+ );
+ try {
+ const part = firstOwnAssemblyPart(
+ await client.getAssemblyDefinitionIn(document, elementId)
+ );
+ if (!part) return own;
+ const partDocument: OnshapeDocument | null =
+ part.wvm && part.wvmId
+ ? {
+ documentId: part.documentId,
+ wvm: part.wvm as OnshapeWVMType,
+ wvmId: part.wvmId
+ }
+ : part.documentId === document.documentId
+ ? document
+ : null;
+ if (!partDocument) return own;
+ const partProperties = parseProperties(
+ await client.getPartMetadata(partDocument, part.elementId, part.partId)
+ );
+ const seen = new Set(own.map((property) => property.propertyId));
+ return [
+ ...own,
+ ...partProperties.filter((property) => !seen.has(property.propertyId))
+ ];
+ } catch (error) {
+ logger.warn("Failed to read an assembly part's properties", {
+ documentId: document.documentId,
+ elementId,
+ error
+ });
+ return own;
+ }
+}
diff --git a/packages/ee/src/onshape/lib/state.test.ts b/packages/ee/src/onshape/lib/state.test.ts
new file mode 100644
index 0000000000..d1c7d64dde
--- /dev/null
+++ b/packages/ee/src/onshape/lib/state.test.ts
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ onshapeGrantPatch,
+ onshapeSettingsPatch,
+ onshapeTokenPatch
+} from "./state";
+
+function touchedPaths(patch: {
+ metadata?: object;
+ secrets?: object;
+ removeMetadata?: string[];
+ removeSecrets?: string[];
+}) {
+ return [
+ ...Object.keys(patch.metadata ?? {}),
+ ...Object.keys(patch.secrets ?? {}),
+ ...(patch.removeMetadata ?? []),
+ ...(patch.removeSecrets ?? [])
+ ];
+}
+
+describe("onshapeSettingsPatch", () => {
+ it("writes only the keys the form owns, never credentials or the property map", () => {
+ const patch = onshapeSettingsPatch("onshape-government", {
+ baseUrl: "https://acme.onshape.com",
+ credentials: { accessToken: "stale" },
+ propertyMap: []
+ });
+ expect(touchedPaths(patch)).toEqual(["baseUrl"]);
+ });
+
+ it("writes nothing for the panel integration, whose push defaults the Fields page owns", () => {
+ const patch = onshapeSettingsPatch("onshape-v2", {
+ defaultReplenishmentSystem: "Make",
+ credentials: { accessToken: "stale" },
+ propertyMap: []
+ });
+ expect(touchedPaths(patch)).toEqual([]);
+ });
+
+ it("clears a field saved empty", () => {
+ expect(
+ onshapeSettingsPatch("onshape-government", { baseUrl: "" }).removeMetadata
+ ).toEqual(["baseUrl"]);
+ });
+
+ it("vaults a new Government client secret and keeps the old one when left empty", () => {
+ expect(
+ onshapeSettingsPatch("onshape-government", { clientSecret: "new" })
+ .secrets
+ ).toEqual({ clientSecret: "new" });
+ expect(
+ touchedPaths(
+ onshapeSettingsPatch("onshape-government", { clientSecret: "" })
+ )
+ ).toEqual([]);
+ });
+
+ it("leaves a sync connection's grant alone when asset sync is saved", () => {
+ expect(
+ touchedPaths(
+ onshapeSettingsPatch("onshape", {
+ assetSyncEnabled: true,
+ scope: "OAuth2Read",
+ onshapeCompanyId: "c1"
+ })
+ )
+ ).toEqual(["assetSyncEnabled"]);
+ });
+});
+
+describe("onshapeTokenPatch", () => {
+ it("touches only credential paths", () => {
+ const patch = onshapeTokenPatch({
+ accessToken: "a",
+ refreshToken: "r",
+ expiresAt: "2026-10-01T00:00:00.000Z"
+ });
+ expect(
+ touchedPaths(patch).every((path) => path.startsWith("credentials."))
+ ).toBe(true);
+ });
+
+ it("keeps the stored refresh token when the response carries none", () => {
+ expect(
+ onshapeTokenPatch({ accessToken: "a", expiresAt: "2026-10-01" }).secrets
+ ).toEqual({ "credentials.accessToken": "a" });
+ });
+});
+
+describe("onshapeGrantPatch", () => {
+ const grant = {
+ accessToken: "a",
+ expiresAt: "2026-10-01T00:00:00.000Z",
+ scope: "OAuth2Read",
+ baseUrl: "https://cad.onshape.com",
+ updatedBy: "u"
+ };
+
+ it("turns asset sync off for a read-only grant and drops the old refresh token", () => {
+ const patch = onshapeGrantPatch({ ...grant, canWrite: false });
+ expect(patch.metadata.assetSyncEnabled).toBe(false);
+ expect(patch.removeSecrets).toEqual(["credentials.refreshToken"]);
+ expect(patch.removeMetadata).toEqual(["onshapeCompanyId"]);
+ });
+
+ it("leaves asset sync and the property map untouched for a write grant", () => {
+ const patch = onshapeGrantPatch({
+ ...grant,
+ canWrite: true,
+ refreshToken: "r"
+ });
+ expect(touchedPaths(patch)).not.toContain("assetSyncEnabled");
+ expect(touchedPaths(patch)).not.toContain("propertyMap");
+ expect(patch.removeSecrets).toEqual([]);
+ });
+});
diff --git a/packages/ee/src/onshape/lib/state.ts b/packages/ee/src/onshape/lib/state.ts
new file mode 100644
index 0000000000..1887df2fcf
--- /dev/null
+++ b/packages/ee/src/onshape/lib/state.ts
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { Database, Json } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { patchIntegrationState } from "../../integrations/secrets";
+import {
+ ONSHAPE_GOVERNMENT_INTEGRATION_ID,
+ ONSHAPE_INTEGRATION_ID
+} from "./connection";
+import {
+ ONSHAPE_V2_INTEGRATION_ID,
+ type OnshapeOAuthIntegrationId
+} from "./integration-id";
+
+// Token refresh, OAuth callback, settings save, the webhook's company id and
+// the panel's Fields save share the metadata column, so each patch names only
+// its own keys and goes through `patchIntegrationState` (a row lock).
+
+const SETTINGS_PATHS: Record<OnshapeOAuthIntegrationId, readonly string[]> = {
+ [ONSHAPE_INTEGRATION_ID]: ["assetSyncEnabled"],
+ [ONSHAPE_GOVERNMENT_INTEGRATION_ID]: [
+ "baseUrl",
+ "clientId",
+ "assetSyncEnabled"
+ ],
+ // The panel's Fields save owns its keys.
+ [ONSHAPE_V2_INTEGRATION_ID]: []
+};
+
+const SETTINGS_SECRET_PATHS: Partial<
+ Record<OnshapeOAuthIntegrationId, readonly string[]>
+> = {
+ [ONSHAPE_GOVERNMENT_INTEGRATION_ID]: ["clientSecret"]
+};
+
+export function isOnshapeOAuthIntegrationId(
+ value: unknown
+): value is OnshapeOAuthIntegrationId {
+ return typeof value === "string" && Object.hasOwn(SETTINGS_PATHS, value);
+}
+
+export function onshapeSettingsPatch(
+ integrationId: OnshapeOAuthIntegrationId,
+ metadata: Record<string, unknown>
+) {
+ const patch: Record<string, Json> = {};
+ const removeMetadata: string[] = [];
+ for (const path of SETTINGS_PATHS[integrationId]) {
+ if (!Object.hasOwn(metadata, path)) continue;
+ const value = metadata[path];
+ if (value === undefined || value === null || value === "") {
+ removeMetadata.push(path);
+ } else {
+ patch[path] = value as Json;
+ }
+ }
+
+ // An empty secret field means "keep the vaulted value".
+ const secrets: Record<string, Json> = {};
+ for (const path of SETTINGS_SECRET_PATHS[integrationId] ?? []) {
+ const value = metadata[path];
+ if (typeof value === "string" && value.trim().length > 0) {
+ secrets[path] = value;
+ }
+ }
+
+ return { metadata: patch, removeMetadata, secrets };
+}
+
+export async function patchOnshapeSettings(
+ serviceRole: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: OnshapeOAuthIntegrationId,
+ args: {
+ metadata: Record<string, unknown>;
+ active?: boolean;
+ updatedBy?: string;
+ }
+) {
+ return patchIntegrationState(serviceRole, companyId, integrationId, {
+ ...onshapeSettingsPatch(integrationId, args.metadata),
+ active: args.active,
+ updatedBy: args.updatedBy
+ });
+}
+
+export type OnshapeTokenSet = {
+ accessToken: string;
+ refreshToken?: string | null;
+ expiresAt: string;
+};
+
+export function onshapeTokenPatch(tokens: OnshapeTokenSet) {
+ const secrets: Record<string, Json> = {
+ "credentials.accessToken": tokens.accessToken
+ };
+ // A response without a refresh token keeps the stored one.
+ if (tokens.refreshToken) {
+ secrets["credentials.refreshToken"] = tokens.refreshToken;
+ }
+ return {
+ metadata: {
+ "credentials.type": "oauth2",
+ "credentials.expiresAt": tokens.expiresAt
+ } as Record<string, Json>,
+ secrets
+ };
+}
+
+export async function patchOnshapeRefreshedTokens(
+ serviceRole: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: OnshapeOAuthIntegrationId,
+ tokens: OnshapeTokenSet
+) {
+ return patchIntegrationState(
+ serviceRole,
+ companyId,
+ integrationId,
+ onshapeTokenPatch(tokens)
+ );
+}
+
+export type OnshapeGrant = OnshapeTokenSet & {
+ scope: string;
+ baseUrl: string;
+ canWrite: boolean;
+ updatedBy: string;
+};
+
+/**
+ * Drops the cached Onshape company so it is re-resolved from the new token. A
+ * grant without write scope turns asset sync off: a refresh cannot widen it.
+ */
+export function onshapeGrantPatch(grant: OnshapeGrant) {
+ const tokens = onshapeTokenPatch(grant);
+ return {
+ metadata: {
+ ...tokens.metadata,
+ scope: grant.scope,
+ baseUrl: grant.baseUrl,
+ ...(grant.canWrite ? {} : { assetSyncEnabled: false })
+ } as Record<string, Json>,
+ secrets: tokens.secrets,
+ removeMetadata: ["onshapeCompanyId"],
+ // A new grant never inherits the previous grant's refresh token.
+ removeSecrets: grant.refreshToken ? [] : ["credentials.refreshToken"],
+ active: true,
+ updatedBy: grant.updatedBy
+ };
+}
+
+export async function patchOnshapeOAuthGrant(
+ serviceRole: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: OnshapeOAuthIntegrationId,
+ grant: OnshapeGrant
+) {
+ return patchIntegrationState(
+ serviceRole,
+ companyId,
+ integrationId,
+ onshapeGrantPatch(grant)
+ );
+}
+
+/** The Onshape company a sync connection's webhook and jobs target. */
+export async function patchOnshapeCompanyId(
+ serviceRole: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: OnshapeOAuthIntegrationId,
+ onshapeCompanyId: string
+) {
+ return patchIntegrationState(serviceRole, companyId, integrationId, {
+ metadata: { onshapeCompanyId }
+ });
+}
diff --git a/packages/ee/src/onshape/lib/token-refresh.test.ts b/packages/ee/src/onshape/lib/token-refresh.test.ts
new file mode 100644
index 0000000000..bbf4823591
--- /dev/null
+++ b/packages/ee/src/onshape/lib/token-refresh.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { isFresh, resolveOnshapeRefresh } from "./token-refresh";
+
+const NOW = Date.parse("2026-09-30T12:00:00.000Z");
+const inMinutes = (minutes: number) =>
+ new Date(NOW + minutes * 60_000).toISOString();
+
+describe("isFresh", () => {
+ it("treats a token inside the two-minute margin as expired", () => {
+ expect(isFresh({ expiresAt: inMinutes(1) }, NOW)).toBe(false);
+ expect(isFresh({ expiresAt: inMinutes(5) }, NOW)).toBe(true);
+ });
+
+ it("treats a missing expiry as expired, so an old install still refreshes", () => {
+ expect(isFresh({}, NOW)).toBe(false);
+ });
+});
+
+describe("resolveOnshapeRefresh", () => {
+ const requestCopy = {
+ accessToken: "loaded-access",
+ refreshToken: "loaded-refresh",
+ expiresAt: inMinutes(-10)
+ };
+
+ it("adopts a live pair another caller stored", () => {
+ const stored = {
+ accessToken: "newer-access",
+ refreshToken: "newer-refresh",
+ expiresAt: inMinutes(60)
+ };
+ expect(
+ resolveOnshapeRefresh(stored, requestCopy, "loaded-access", NOW)
+ ).toEqual({ action: "adopt", credentials: stored });
+ });
+
+ it("spends the stored refresh token, not the one this request loaded", () => {
+ const stored = {
+ accessToken: "newer-access",
+ refreshToken: "newer-refresh",
+ expiresAt: inMinutes(-1)
+ };
+ expect(
+ resolveOnshapeRefresh(stored, requestCopy, "loaded-access", NOW)
+ ).toEqual({ action: "exchange", credentials: stored });
+ });
+
+ it("refreshes after a 401 even when the rejected token looks unexpired", () => {
+ const stored = { ...requestCopy, expiresAt: inMinutes(60) };
+ expect(
+ resolveOnshapeRefresh(stored, requestCopy, "loaded-access", NOW).action
+ ).toBe("exchange");
+ });
+
+ it("falls back to this request's copy only when the row could not be read", () => {
+ expect(
+ resolveOnshapeRefresh(null, requestCopy, "loaded-access", NOW)
+ ).toEqual({ action: "exchange", credentials: requestCopy });
+ });
+});
diff --git a/packages/ee/src/onshape/lib/token-refresh.ts b/packages/ee/src/onshape/lib/token-refresh.ts
new file mode 100644
index 0000000000..b41ff59757
--- /dev/null
+++ b/packages/ee/src/onshape/lib/token-refresh.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// Refresh early to cover clock skew and a token expiring mid-call.
+const REFRESH_MARGIN_SECONDS = 120;
+
+export type StoredOnshapeCredentials = {
+ accessToken?: string;
+ refreshToken?: string;
+ expiresAt?: string;
+};
+
+export function isFresh(
+ credentials: StoredOnshapeCredentials | null | undefined,
+ now: number
+) {
+ const expiresAt = credentials?.expiresAt
+ ? new Date(credentials.expiresAt).getTime()
+ : 0;
+ return expiresAt - REFRESH_MARGIN_SECONDS * 1000 > now;
+}
+
+/**
+ * Adopts a live token another caller stored, else exchanges the stored refresh
+ * token: Onshape rotates them, so this request's copy is usually dead. The
+ * request's copy is used only when the row could not be read.
+ */
+export function resolveOnshapeRefresh(
+ stored: StoredOnshapeCredentials | null,
+ requestCopy: StoredOnshapeCredentials,
+ heldAccessToken: string,
+ now: number
+):
+ | { action: "adopt"; credentials: StoredOnshapeCredentials }
+ | { action: "exchange"; credentials: StoredOnshapeCredentials } {
+ if (
+ stored?.accessToken &&
+ stored.accessToken !== heldAccessToken &&
+ isFresh(stored, now)
+ ) {
+ return { action: "adopt", credentials: stored };
+ }
+ return { action: "exchange", credentials: stored ?? requestCopy };
+}
diff --git a/packages/ee/src/onshape/oauth.server.ts b/packages/ee/src/onshape/oauth.server.ts
index fa9f25a157..39a0524455 100644
--- a/packages/ee/src/onshape/oauth.server.ts
+++ b/packages/ee/src/onshape/oauth.server.ts
@@ -7,8 +7,9 @@ import { issueOAuthState } from "@carbon/auth/oauth-state.server";
import { resolveIntegrationSecrets } from "../integrations/secrets";
import {
getConflictingOnshapeIntegration,
- type OnshapeIntegrationId
+ isOnshapeIntegrationId
} from "./lib/connection";
+import type { OnshapeOAuthIntegrationId } from "./lib/integration-id";
import {
getOnshapeAuthorizeUrl,
getOnshapeOAuthConfig,
@@ -23,7 +24,7 @@ import {
*/
export async function loadOnshapeOAuthConfig(
companyId: string,
- integrationId: OnshapeIntegrationId
+ integrationId: OnshapeOAuthIntegrationId
): Promise<OnshapeOAuthConfig | null> {
const serviceRole = getCarbonServiceRole();
const integration = await serviceRole
@@ -58,27 +59,26 @@ export type OnshapeAuthorizationStart =
| { ok: false; reason: "not-configured" | "connection-conflict" };
/**
- * Start the OAuth round trip for an Onshape connection: resolve its client,
- * refuse while the OTHER Onshape connection is active, and issue the state the
- * callback will consume. The state is bound to this browser, user, company and
- * integration — 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.
+ * Refuses a sync connection while the other one is active; the panel's grant
+ * sits beside either. The state is bound to this browser, user, company and
+ * integration, so a callback URL carrying another account's code is refused.
*/
export async function beginOnshapeAuthorization(
request: Request,
params: {
- integrationId: OnshapeIntegrationId;
+ integrationId: OnshapeOAuthIntegrationId;
userId: string;
companyId: string;
}
): Promise<OnshapeAuthorizationStart> {
- const conflict = await getConflictingOnshapeIntegration(
- getCarbonServiceRole(),
- params.companyId,
- params.integrationId
- );
- if (conflict) return { ok: false, reason: "connection-conflict" };
+ if (isOnshapeIntegrationId(params.integrationId)) {
+ const conflict = await getConflictingOnshapeIntegration(
+ getCarbonServiceRole(),
+ params.companyId,
+ params.integrationId
+ );
+ if (conflict) return { ok: false, reason: "connection-conflict" };
+ }
const config = await loadOnshapeOAuthConfig(
params.companyId,
diff --git a/packages/ee/src/onshape/panel/ItemFieldSelects.tsx b/packages/ee/src/onshape/panel/ItemFieldSelects.tsx
new file mode 100644
index 0000000000..1456acc7f5
--- /dev/null
+++ b/packages/ee/src/onshape/panel/ItemFieldSelects.tsx
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger
+} from "@carbon/react";
+import type { ReactNode } from "react";
+import { AiOutlinePartition } from "react-icons/ai";
+import { FaCodePullRequest } from "react-icons/fa6";
+import {
+ LuBarcode,
+ LuBox,
+ LuFlaskConical,
+ LuGroup,
+ LuShoppingCart,
+ LuSquare
+} from "react-icons/lu";
+import { RxCodesandboxLogo } from "react-icons/rx";
+import { TbTargetOff } from "react-icons/tb";
+import type {
+ ItemEdit,
+ ItemFieldSnapshot,
+ ItemMethodType,
+ ItemReplenishmentSystem,
+ ItemTrackingType
+} from "./plan";
+import {
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_TRACKING_TYPES,
+ methodForReplenishment,
+ reconcileMethodForReplenishment,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./plan";
+
+// Icons mirror apps/erp/app/components/Icons.tsx; @carbon/ee cannot import app code.
+function replenishmentIcon(value: string): ReactNode {
+ switch (value) {
+ case "Buy":
+ return <LuShoppingCart className="size-3.5 text-blue-500" />;
+ case "Make":
+ return <RxCodesandboxLogo className="size-3.5 text-emerald-500" />;
+ case "Buy and Make":
+ return <LuFlaskConical className="size-3.5 text-teal-500" />;
+ default:
+ return <LuSquare className="size-3.5 text-muted-foreground" />;
+ }
+}
+
+function methodIcon(value: string): ReactNode {
+ switch (value) {
+ case "Purchase to Order":
+ return <LuShoppingCart className="size-3.5 text-blue-500" />;
+ case "Make to Order":
+ return <RxCodesandboxLogo className="size-3.5 text-emerald-500" />;
+ case "Pull from Inventory":
+ return <FaCodePullRequest className="size-3.5 text-yellow-500" />;
+ default:
+ return <AiOutlinePartition className="size-3.5 text-muted-foreground" />;
+ }
+}
+
+function trackingIcon(value: string): ReactNode {
+ switch (value) {
+ case "Serial":
+ return <LuBarcode className="size-3.5" />;
+ case "Batch":
+ return <LuGroup className="size-3.5 text-emerald-500" />;
+ case "Inventory":
+ return <LuBox className="size-3.5 text-blue-500" />;
+ case "Non-Inventory":
+ return <TbTargetOff className="size-3.5 text-red-500" />;
+ default:
+ return <LuSquare className="size-3.5 text-muted-foreground" />;
+ }
+}
+
+function FieldSelect<T extends string>({
+ label,
+ value,
+ options,
+ icon,
+ disabled,
+ onChange
+}: {
+ label: string;
+ value: T;
+ options: readonly T[];
+ icon: (value: string) => ReactNode;
+ disabled?: boolean;
+ onChange: (value: T) => void;
+}) {
+ return (
+ <Select
+ value={value}
+ onValueChange={(next) => onChange(next as T)}
+ disabled={disabled}
+ >
+ <SelectTrigger
+ size="sm"
+ hideIcon
+ aria-label={`${label}: ${value}`}
+ title={`${label}: ${value}`}
+ className="h-7 w-auto shrink-0 gap-0 px-1.5 max-md:h-7 max-md:text-xs"
+ >
+ {icon(value)}
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option} value={option}>
+ <span className="flex items-center gap-2">
+ {icon(option)}
+ <span>{option}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+/** Icon-only Replenishment, Method and Tracking selects; onChange reports only what the user changes. */
+export function ItemFieldSelects({
+ baseline,
+ existing,
+ edit,
+ disabled,
+ onChange
+}: {
+ /** The create proposal, the "everyPush" target, or the item's current values. */
+ baseline: ItemFieldSnapshot;
+ /** In Carbon: a Replenishment change sets the method as the item page does; else as the Part form does. */
+ existing?: boolean;
+ edit: ItemEdit | undefined;
+ disabled?: boolean;
+ onChange: (patch: Partial<ItemFieldSnapshot>) => void;
+}) {
+ const replenishmentSystem =
+ (edit?.replenishmentSystem as ItemReplenishmentSystem | undefined) ??
+ baseline.replenishmentSystem;
+ const defaultMethodType =
+ (edit?.defaultMethodType as ItemMethodType | undefined) ??
+ baseline.defaultMethodType;
+ const itemTrackingType =
+ (edit?.itemTrackingType as ItemTrackingType | undefined) ??
+ baseline.itemTrackingType;
+
+ return (
+ <div className="mt-1.5 flex items-center gap-1">
+ <FieldSelect
+ label="Replenishment"
+ value={replenishmentSystem}
+ options={ITEM_REPLENISHMENT_SYSTEMS}
+ icon={replenishmentIcon}
+ disabled={disabled}
+ onChange={(next) =>
+ // Send both so the apply never sees an illegal pair.
+ onChange({
+ replenishmentSystem: next,
+ defaultMethodType: existing
+ ? methodForReplenishment(next, defaultMethodType)
+ : reconcileMethodForReplenishment(next, defaultMethodType)
+ })
+ }
+ />
+ <FieldSelect
+ label="Method"
+ value={defaultMethodType}
+ options={VALID_METHOD_TYPES_BY_REPLENISHMENT[replenishmentSystem]}
+ icon={methodIcon}
+ disabled={disabled}
+ onChange={(next) => onChange({ defaultMethodType: next })}
+ />
+ <FieldSelect
+ label="Tracking"
+ value={itemTrackingType}
+ options={ITEM_TRACKING_TYPES}
+ icon={trackingIcon}
+ disabled={disabled}
+ onChange={(next) => onChange({ itemTrackingType: next })}
+ />
+ </div>
+ );
+}
diff --git a/packages/ee/src/onshape/panel/Panel.tsx b/packages/ee/src/onshape/panel/Panel.tsx
new file mode 100644
index 0000000000..debd786d2f
--- /dev/null
+++ b/packages/ee/src/onshape/panel/Panel.tsx
@@ -0,0 +1,4861 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";
+import type { ComboboxOption } from "@carbon/react";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ Combobox,
+ cn,
+ DisabledReason,
+ HStack,
+ IconButton,
+ Input,
+ Loading,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Skeleton,
+ Status,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ TruncatedTooltipText,
+ VStack
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import type { ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ LuArrowRight,
+ LuChevronRight,
+ LuCircleCheck,
+ LuCircleDashed,
+ LuInfo,
+ LuListChecks,
+ LuLock,
+ LuPlus,
+ LuRefreshCw,
+ LuTrash,
+ LuTriangleAlert,
+ LuX
+} from "react-icons/lu";
+import { bomParentIndexes, buildBomViewTree, visibleBomRows } from "./bom-view";
+import { ItemFieldSelects } from "./ItemFieldSelects";
+import type { OnshapePanelContext } from "./messages";
+import { isPanelSessionMessage, postApplicationInit } from "./messages";
+import type {
+ AssemblyPlan,
+ AssemblyPlanDepth,
+ ItemFieldSnapshot,
+ MappedRowPlan,
+ OwnedFieldChange,
+ PartPlan,
+ PartPlanRow,
+ PlanUnitOfMeasure,
+ ProposedItem,
+ ReleasePlan,
+ ReleasePlanItem
+} from "./plan";
+import {
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_TRACKING_TYPES,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./plan";
+import type { OnshapePushDefaults } from "./preferences";
+import { reconcilePushDefaults } from "./preferences";
+import type {
+ DescriptionModes,
+ MappingMode,
+ PlanCustomFieldDefinition,
+ PropertyMapEntry,
+ PropertyMapTarget
+} from "./properties";
+import {
+ CUSTOM_FIELD_TYPE_LABELS,
+ customFieldDisplayValue,
+ MAPPABLE_VALUE_TYPES,
+ MAPPING_MODES,
+ propertyMapEqual,
+ targetKey
+} from "./properties";
+import type { PanelRelease } from "./releases";
+import type {
+ ApplyFieldError,
+ AssemblyReview,
+ PartApplyResult,
+ PartReview,
+ ReleaseReview,
+ ReviewState
+} from "./review";
+import {
+ applyCount,
+ applyRequestBody,
+ CARBON_ONLY_NOTE,
+ clearFieldErrors,
+ createReview,
+ customFieldChangeText,
+ describeMethod,
+ indexFieldErrors,
+ itemFieldChangeText,
+ keptDifferenceText,
+ mappedValueText,
+ normalizeWarnings,
+ patchPartStatuses,
+ releaseResultText,
+ replenishmentMismatches
+} from "./review";
+import {
+ clearPanelSessionToken,
+ getPanelSessionToken,
+ PanelUnauthorizedError,
+ panelFetch,
+ setPanelSessionToken
+} from "./session-storage";
+import type {
+ StandardField,
+ StandardFieldId,
+ ValueTranslation
+} from "./standard-fields";
+import {
+ defaultTranslations,
+ matchingUnit,
+ onshapeValueOptions,
+ repeatedTranslationRows,
+ STANDARD_FIELDS,
+ standardField,
+ standardFieldValues,
+ untranslatedOptions
+} from "./standard-fields";
+import type { PanelPartStatus } from "./status";
+
+export type PanelAssemblyLine = {
+ index: string;
+ level: number;
+ partNumber: string | null;
+ name: string | null;
+ quantity: number;
+ state: "linked" | "matched" | "missing" | "released";
+ itemId: string | null;
+ releasedRevision?: string;
+ lastSyncedAt: string | null;
+};
+
+export type PanelAssemblyStatus = {
+ root: {
+ partNumber: string | null;
+ name: string | null;
+ /** Element metadata could not be read, so a null part number says nothing. */
+ identityUnavailable?: boolean;
+ state: "linked" | "matched" | "missing" | "released";
+ itemId: string | null;
+ releasedRevision?: string;
+ lastSyncedAt: string | null;
+ };
+ lines: PanelAssemblyLine[];
+};
+
+/** forbidden: a Retry cannot fix it, so it renders as a warning with no Retry. */
+type LoadFailure = { message: string; forbidden: boolean };
+
+// refreshing / refreshFailure: a re-read keeps the rows on screen; only a first
+// read shows a skeleton.
+type PanelStatusState =
+ | { status: "idle" }
+ | { status: "loading" }
+ | {
+ status: "ready";
+ rows: PanelPartStatus[];
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ }
+ | {
+ status: "ready-assembly";
+ assembly: PanelAssemblyStatus;
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ }
+ | {
+ status: "ready-other";
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ }
+ | { status: "error"; message: string; forbidden?: boolean };
+
+type PanelReleasesState =
+ | { status: "idle" }
+ | { status: "loading" }
+ | {
+ status: "ready";
+ releases: PanelRelease[];
+ /** False when the connected Onshape account is in no company. */
+ releaseManagementAvailable?: boolean;
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ }
+ | { status: "error"; message: string; forbidden?: boolean };
+
+/**
+ * push: the current element. releases: the whole document, so it shows on an
+ * element with nothing to push. fields: the company's property map.
+ */
+type PanelTab = "push" | "releases" | "fields";
+
+type PanelFieldsProperty = {
+ propertyId: string;
+ name: string;
+ valueType: string;
+ mappable: boolean;
+ /** An ENUM's options, when Onshape listed them. */
+ options?: string[];
+};
+
+type PanelFieldsData = {
+ properties: PanelFieldsProperty[];
+ map: PropertyMapEntry[];
+ definitions: PlanCustomFieldDefinition[];
+ units: PlanUnitOfMeasure[];
+ descriptionModes: DescriptionModes;
+ /** What a push gives a new item when nothing maps a field. */
+ pushDefaults: OnshapePushDefaults;
+};
+
+type FieldsDraftEntry = PropertyMapEntry;
+
+type PanelFieldsState =
+ | { status: "closed" }
+ | { status: "loading" }
+ | {
+ status: "ready";
+ data: PanelFieldsData;
+ /** The whole next map: the save replaces it, so other elements' entries ride along. */
+ entries: FieldsDraftEntry[];
+ descriptionModes: DescriptionModes;
+ pushDefaults: OnshapePushDefaults;
+ saving: boolean;
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ error: string | null;
+ /** The map saved but the field list could not be re-read. */
+ warning?: string;
+ /** Per-property 422 errors, keyed by onshapePropertyId. */
+ fieldErrors: Record<string, string[]>;
+ }
+ | { status: "error"; message: string; forbidden?: boolean };
+
+// Every push reads these four itself: the Fields page shows them as fixed rows, never as a mapping.
+const FIXED_PROPERTY_NAMES = new Set([
+ "Part number",
+ "Revision",
+ "Name",
+ "Description"
+]);
+
+// hasOwn: MAPPABLE_VALUE_TYPES is a plain object, so "constructor" would resolve to Object.prototype's.
+function mappableTypesFor(valueType: string): readonly number[] {
+ if (!Object.hasOwn(MAPPABLE_VALUE_TYPES, valueType)) return [];
+ return MAPPABLE_VALUE_TYPES[valueType] ?? [];
+}
+
+/** Copies, so an edit never touches the saved map. */
+function fieldsDraft(map: PropertyMapEntry[]): FieldsDraftEntry[] {
+ return map.map((entry) => ({
+ ...entry,
+ ...(entry.translations
+ ? { translations: entry.translations.map((row) => ({ ...row })) }
+ : {})
+ }));
+}
+
+function targetFromKey(key: string): PropertyMapTarget | null {
+ if (key.startsWith("customField:")) {
+ return { kind: "customField", fieldId: key.slice("customField:".length) };
+ }
+ const field = key.startsWith("item:")
+ ? standardField(key.slice("item:".length))
+ : undefined;
+ return field ? { kind: "item", field: field.id } : null;
+}
+
+/**
+ * auth: popup that mints the panel session; session: DELETE revokes it.
+ * plan*: store a plan and write nothing; push*: apply a stored plan by planId.
+ */
+export type OnshapePanelPaths = {
+ auth: string;
+ me: string;
+ fields: string;
+ session: string;
+ status: string;
+ planPart: string;
+ planAssembly: string;
+ planRelease: string;
+ pushPart: string;
+ pushAssembly: string;
+ releases: string;
+ pushRelease: string;
+};
+
+export type OnshapePanelMe = {
+ userId: string;
+ email: string;
+ company: { id: string; name: string } | null;
+ /** Settings update; the Fields page shows only with it. */
+ canEditFields: boolean;
+};
+
+type SessionState =
+ | { status: "unknown" }
+ /** popupBlocked: the browser refused the sign-in window; still signed out. */
+ | { status: "signed-out"; popupBlocked?: boolean }
+ | { status: "loading"; token: string }
+ | { status: "signed-in"; token: string; me: OnshapePanelMe }
+ | { status: "error"; token: string | null; message: string };
+
+type PlanResponse<P> = {
+ planId: string;
+ expiresAt: string;
+ plan: P;
+ /** plan-release only: assemblies whose BOM could not be read. */
+ warnings?: unknown;
+};
+
+type PanelErrorResponse = {
+ error: string;
+ fieldErrors?: ApplyFieldError[];
+ /** too-large: the panel offers a push of the top level only. */
+ code?: "too-large";
+};
+
+type AssemblyPushSummary = {
+ itemsCreated: number;
+ itemsReused: number;
+ linesWritten: number;
+ linesUnchanged?: number;
+ /** Lines added by hand that now follow Onshape. */
+ linesTakenOver?: number;
+ descriptionsUpdated?: number;
+ fieldsUpdated?: number;
+ methodsTouched: number;
+ /** Draft versions the push made of released methods. */
+ draftVersionsCreated?: string[];
+ skipped: string[];
+ errors: string[];
+};
+
+type ReleasePushSummary = {
+ releaseName: string | null;
+ revisionsCreated: number;
+ itemsCreated: number;
+ childrenCreated?: number;
+ drawingsQueued?: number;
+ drawingsOnly?: boolean;
+ reused: number;
+ linesWritten: number;
+ methodsTouched: number;
+ defaultsUpdated: number;
+ changeNotice: string | null;
+ alreadyPushed: boolean;
+ skipped: string[];
+ errors: string[];
+};
+
+type PartRowOutcome = { kind: "ok" | "skipped" | "error"; text: string };
+
+function partOutcome(result: PartApplyResult): PartRowOutcome {
+ switch (result.action) {
+ case "created":
+ return { kind: "ok", text: "Created" };
+ case "adopted":
+ return { kind: "ok", text: "Linked" };
+ case "updated":
+ return { kind: "ok", text: "Updated" };
+ case "unchanged":
+ return { kind: "ok", text: "Up to date" };
+ case "skipped":
+ return { kind: "skipped", text: "Skipped" };
+ default:
+ // The message goes in the section's alert.
+ return { kind: "error", text: "Failed" };
+ }
+}
+
+function partsOutcomeText(
+ results: PartApplyResult[],
+ rows: Array<{ partId: string; partNumber: string | null }>
+): PushOutcome {
+ const label = (r: PartApplyResult) =>
+ rows.find((row) => row.partId === r.partId)?.partNumber ??
+ r.readableId ??
+ r.partId;
+ const count = (action: PartApplyResult["action"]) =>
+ results.filter((r) => r.action === action).length;
+ const parts = [
+ [count("created"), "created"],
+ [count("adopted"), "linked"],
+ [count("updated"), "updated"],
+ [count("unchanged"), "already up to date"]
+ ]
+ .filter(([n]) => (n as number) > 0)
+ .map(([n, what]) => `${n} ${what}`);
+ return {
+ text: parts.length > 0 ? `Parts: ${parts.join(", ")}` : "",
+ skipped: results
+ .filter((r) => r.action === "skipped")
+ .map((r) => `${label(r)}: ${r.message ?? "skipped"}`),
+ errors: results
+ .filter((r) => r.action === "error")
+ .map((r) => `${label(r)}: ${r.message ?? "failed"}`)
+ };
+}
+
+/** skipped and errors stay apart from text so a partial failure never reads as a clean push. */
+type PushOutcome = {
+ text: string;
+ skipped: string[];
+ errors: string[];
+ /** Done, but worth knowing: a new Draft version, lines taken over. */
+ notes?: string[];
+};
+
+function plural(count: number, noun: string) {
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
+}
+
+function assemblyOutcomeText(s: AssemblyPushSummary): PushOutcome {
+ const unchanged = s.linesUnchanged ?? 0;
+ // "0 BOM lines" reads as a failure; say they are already up to date.
+ const lines =
+ s.linesWritten === 0 && unchanged > 0
+ ? `${plural(unchanged, "BOM line")} already up to date`
+ : plural(s.linesWritten, "BOM line") +
+ (unchanged > 0 ? ` (${unchanged} unchanged)` : "");
+ const fieldsUpdated = s.fieldsUpdated ?? 0;
+ const methods =
+ s.methodsTouched > 0 ? ` across ${plural(s.methodsTouched, "method")}` : "";
+ const text =
+ `${plural(s.itemsCreated, "item")} created, ${s.itemsReused} reused` +
+ (fieldsUpdated > 0 ? ` (${fieldsUpdated} updated)` : "") +
+ `, ${lines}${methods}`;
+ const drafts = s.draftVersionsCreated ?? [];
+ const takenOver = s.linesTakenOver ?? 0;
+ const described = s.descriptionsUpdated ?? 0;
+ return {
+ text,
+ skipped: s.skipped,
+ errors: s.errors,
+ notes: [
+ ...(drafts.length > 0
+ ? [`New Draft version, not yet live: ${drafts.join(", ")}`]
+ : []),
+ ...(described > 0
+ ? [
+ `${plural(described, "item")} now ${described === 1 ? "has" : "have"} Onshape's short and long descriptions`
+ ]
+ : []),
+ ...(takenOver > 0
+ ? [
+ `${plural(takenOver, "line")} added by hand in Carbon now ${takenOver === 1 ? "follows" : "follow"} Onshape`
+ ]
+ : [])
+ ]
+ };
+}
+
+function releaseOutcomeText(s: ReleasePushSummary): PushOutcome {
+ // Skipped items render as their own warning; text is a success alert's title.
+ return { text: releaseResultText(s), skipped: s.skipped, errors: s.errors };
+}
+
+function failedOutcome(message: string): PushOutcome {
+ return { text: "", skipped: [], errors: [message] };
+}
+
+function PushOutcomeView({ outcome }: { outcome: PushOutcome }) {
+ const failed = outcome.errors.length > 0;
+ return (
+ <>
+ {outcome.text ? (
+ failed ? (
+ <p className="text-xs text-muted-foreground w-full">{outcome.text}</p>
+ ) : (
+ <Alert variant="success">
+ <LuCircleCheck />
+ <AlertTitle>{outcome.text}</AlertTitle>
+ </Alert>
+ )
+ ) : null}
+ {(outcome.notes ?? []).length > 0 ? (
+ <Alert variant="info">
+ <LuInfo />
+ {/* No title above the notes, so they take the title's size. */}
+ <AlertDescription className="text-sm">
+ <ul className="list-disc space-y-1 pl-4">
+ {(outcome.notes ?? []).map((note) => (
+ <li key={note}>{note}</li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ {outcome.skipped.length > 0 ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ {outcome.skipped.length === 1
+ ? "1 thing was skipped"
+ : `${outcome.skipped.length} things were skipped`}
+ </AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc space-y-1 pl-4">
+ {outcome.skipped.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ {failed ? (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>
+ {outcome.errors.length === 1
+ ? "1 problem — the push was not complete"
+ : `${outcome.errors.length} problems — the push was not complete`}
+ </AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc space-y-1 pl-4">
+ {outcome.errors.map((problem) => (
+ <li key={problem}>{problem}</li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ </>
+ );
+}
+
+function PanelListSkeleton({ rows = 5 }: { rows?: number }) {
+ return (
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {Array.from({ length: rows }, (_, index) => (
+ <li
+ key={index}
+ className="flex items-center justify-between gap-2 px-3 py-2"
+ >
+ <div className="min-w-0 space-y-1.5">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-3 w-24" />
+ </div>
+ <Skeleton className="h-5 w-24 shrink-0" />
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+// fetch rejects with a TypeError worded per browser on a network failure. The
+// wording is matched too, so a TypeError that is a real bug still reports itself.
+function thrownMessage(error: unknown): string {
+ if (
+ error instanceof TypeError &&
+ /fetch|network|load failed/i.test(error.message)
+ ) {
+ return "Carbon couldn't be reached. Check your connection and try again.";
+ }
+ return error instanceof Error ? error.message : String(error);
+}
+
+// Skipped BOM components arrive one per occurrence: identical lines fold into one
+// with a count, and the title counts occurrences.
+const CAPPED_WARNING_VISIBLE = 6;
+
+function CappedWarningList({
+ title,
+ lines,
+ description,
+ variant = "warning"
+}: {
+ title: (count: number) => string;
+ lines: string[];
+ description?: string;
+ variant?: "warning" | "destructive";
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const folded = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const line of lines) counts.set(line, (counts.get(line) ?? 0) + 1);
+ return [...counts.entries()];
+ }, [lines]);
+ const visible = expanded ? folded : folded.slice(0, CAPPED_WARNING_VISIBLE);
+ const hidden = folded.length - visible.length;
+ return (
+ <Alert variant={variant}>
+ <LuTriangleAlert />
+ <AlertTitle>{title(lines.length)}</AlertTitle>
+ <AlertDescription>
+ {description ? <p className="mb-1">{description}</p> : null}
+ <ul className="list-disc space-y-1 pl-4">
+ {visible.map(([line, count]) => (
+ <li key={line}>
+ {line}
+ {count > 1 ? ` (×${count})` : null}
+ </li>
+ ))}
+ </ul>
+ {hidden > 0 || expanded ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="mt-1 h-auto p-0"
+ onClick={() => setExpanded((current) => !current)}
+ >
+ {expanded ? "Show fewer" : `Show ${hidden} more`}
+ </Button>
+ ) : null}
+ </AlertDescription>
+ </Alert>
+ );
+}
+
+/** stale: a failed Refresh over rows still on screen. */
+function PanelLoadError({
+ title,
+ failure,
+ stale,
+ retrying,
+ onRetry
+}: {
+ title: string;
+ failure: LoadFailure;
+ stale?: boolean;
+ retrying?: boolean;
+ onRetry?: () => void;
+}) {
+ if (failure.forbidden) {
+ return (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>You don't have permission for this</AlertTitle>
+ <AlertDescription>{failure.message}</AlertDescription>
+ </Alert>
+ );
+ }
+ return (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>{title}</AlertTitle>
+ <AlertDescription>
+ {failure.message}
+ {stale ? (
+ <span className="mt-1 block">Showing what was loaded before.</span>
+ ) : null}
+ </AlertDescription>
+ {onRetry ? (
+ <HStack className="mt-2">
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={onRetry}
+ isDisabled={retrying}
+ isLoading={retrying}
+ >
+ Retry
+ </Button>
+ </HStack>
+ ) : null}
+ </Alert>
+ );
+}
+
+function PanelEmpty({ children }: { children: ReactNode }) {
+ return (
+ <HStack
+ spacing={2}
+ className="w-full justify-center py-3 text-sm text-muted-foreground"
+ >
+ <LuCircleDashed className="size-4 shrink-0" />
+ <span>{children}</span>
+ </HStack>
+ );
+}
+
+export function OnshapePanel({
+ context,
+ serverOrigin,
+ paths
+}: {
+ context: OnshapePanelContext;
+ serverOrigin: string | null;
+ paths: OnshapePanelPaths;
+}) {
+ const [session, setSession] = useState<SessionState>({ status: "unknown" });
+ const [parts, setParts] = useState<PanelStatusState>({ status: "idle" });
+ const [releases, setReleases] = useState<PanelReleasesState>({
+ status: "idle"
+ });
+ const [pushingReleaseId, setPushingReleaseId] = useState<string | null>(null);
+ const [releaseOutcome, setReleaseOutcome] = useState<
+ Record<string, PushOutcome>
+ >({});
+
+ const canLoadParts =
+ !!context.documentId &&
+ !!context.wv &&
+ !!context.wvId &&
+ !!context.elementId;
+ const canPush = canLoadParts && (context.wv === "w" || context.wv === "v");
+ const [pushing, setPushing] = useState<Set<string> | null>(null);
+ const [pushOutcome, setPushOutcome] = useState<
+ Record<string, PartRowOutcome>
+ >({});
+ const [partsOutcome, setPartsOutcome] = useState<PushOutcome | null>(null);
+
+ const [tab, setTab] = useState<PanelTab>("push");
+
+ const [fields, setFields] = useState<PanelFieldsState>({ status: "closed" });
+
+ // A section renders its review in place of its list. A part or assembly
+ // review is scoped to the element, a release review to the document.
+ const [review, setReview] = useState<ReviewState | null>(null);
+ const elementScope = [
+ context.documentId,
+ context.wv,
+ context.wvId,
+ context.elementId
+ ].join(":");
+ const documentScope = context.documentId ?? "";
+
+ // A stored plan describes the element it was built for, so moving voids the review.
+ useEffect(() => {
+ setReview((current) => {
+ if (!current) return current;
+ const expected =
+ current.kind === "release" ? documentScope : elementScope;
+ return current.scope === expected ? current : null;
+ });
+ setAssemblyOutcome(null);
+ setPartsOutcome(null);
+ setPushOutcome({});
+ setAssemblyTooLarge(null);
+ setFields({ status: "closed" });
+ setTab("push");
+ }, [elementScope, documentScope]);
+
+ // Sign-out drops everything read under the session: the next one can be another
+ // user or company, and a section a 401 abandoned mid-read would stay loading.
+ useEffect(() => {
+ if (session.status === "signed-out") {
+ setReview(null);
+ setParts({ status: "idle" });
+ setReleases({ status: "idle" });
+ setFields({ status: "closed" });
+ setTab("push");
+ }
+ }, [session.status]);
+
+ const loadParts = useCallback(
+ async (token: string) => {
+ if (!canLoadParts) return;
+ setAssemblyTooLarge(null);
+ const fail = (message: string, forbidden: boolean) =>
+ setParts((current) =>
+ current.status === "ready" ||
+ current.status === "ready-assembly" ||
+ current.status === "ready-other"
+ ? {
+ ...current,
+ refreshing: false,
+ refreshFailure: { message, forbidden }
+ }
+ : { status: "error", message, forbidden }
+ );
+ setParts((current) =>
+ current.status === "ready" ||
+ current.status === "ready-assembly" ||
+ current.status === "ready-other"
+ ? { ...current, refreshing: true, refreshFailure: undefined }
+ : { status: "loading" }
+ );
+ try {
+ const query = new URLSearchParams({
+ documentId: context.documentId as string,
+ wv: context.wv as string,
+ wvId: context.wvId as string,
+ elementId: context.elementId as string
+ });
+ // A configured part's part number depends on the configuration.
+ if (context.configuration) {
+ query.set("configuration", context.configuration);
+ }
+ const response = await panelFetch(token, `${paths.status}?${query}`);
+ const body = (await response.json()) as
+ | { kind: "partstudio"; parts: PanelPartStatus[] }
+ | { kind: "assembly"; assembly: PanelAssemblyStatus }
+ | { kind: "other" }
+ | { error: string };
+ if (!response.ok || "error" in body) {
+ fail(
+ "error" in body ? body.error : `Carbon answered ${response.status}`,
+ response.status === 403
+ );
+ return;
+ }
+ if (body.kind === "assembly" && body.assembly) {
+ setParts({ status: "ready-assembly", assembly: body.assembly });
+ } else if (body.kind === "partstudio" && Array.isArray(body.parts)) {
+ setParts({ status: "ready", rows: body.parts });
+ } else {
+ setParts({ status: "ready-other" });
+ }
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ setParts({ status: "idle" });
+ return;
+ }
+ fail(thrownMessage(error), false);
+ }
+ },
+ [canLoadParts, context, paths.status]
+ );
+
+ const loadReleases = useCallback(
+ async (token: string) => {
+ if (!context.documentId) return;
+ const fail = (message: string, forbidden: boolean) =>
+ setReleases((current) =>
+ current.status === "ready"
+ ? {
+ ...current,
+ refreshing: false,
+ refreshFailure: { message, forbidden }
+ }
+ : { status: "error", message, forbidden }
+ );
+ setReleases((current) =>
+ current.status === "ready"
+ ? { ...current, refreshing: true, refreshFailure: undefined }
+ : { status: "loading" }
+ );
+ try {
+ const query = new URLSearchParams({ documentId: context.documentId });
+ const response = await panelFetch(token, `${paths.releases}?${query}`);
+ const body = (await response.json()) as
+ | { releases: PanelRelease[]; releaseManagementAvailable?: boolean }
+ | { error: string };
+ if (!response.ok || "error" in body) {
+ fail(
+ "error" in body ? body.error : `Carbon answered ${response.status}`,
+ response.status === 403
+ );
+ return;
+ }
+ setReleases({
+ status: "ready",
+ releases: body.releases,
+ releaseManagementAvailable: body.releaseManagementAvailable
+ });
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ fail(thrownMessage(error), false);
+ }
+ },
+ [context.documentId, paths.releases]
+ );
+
+ const loadMe = useCallback(
+ async (token: string) => {
+ setSession({ status: "loading", token });
+ try {
+ const response = await panelFetch(token, paths.me);
+ if (!response.ok) {
+ setSession({
+ status: "error",
+ token,
+ message: `Carbon answered ${response.status}`
+ });
+ return;
+ }
+ const me = (await response.json()) as OnshapePanelMe;
+ setSession({ status: "signed-in", token, me });
+ void loadParts(token);
+ void loadReleases(token);
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ setSession({
+ status: "error",
+ token,
+ message: thrownMessage(error)
+ });
+ }
+ },
+ [paths.me, loadParts, loadReleases]
+ );
+
+ useEffect(() => {
+ if (serverOrigin) postApplicationInit(context, serverOrigin);
+
+ const stored = getPanelSessionToken();
+ if (stored) {
+ void loadMe(stored);
+ } else {
+ setSession({ status: "signed-out" });
+ }
+
+ const onMessage = (event: MessageEvent) => {
+ // Onshape's messages are ignored so one is never read as a session token.
+ if (serverOrigin && event.origin === serverOrigin) return;
+ if (
+ event.origin === window.location.origin &&
+ isPanelSessionMessage(event.data)
+ ) {
+ setPanelSessionToken(event.data.token);
+ void loadMe(event.data.token);
+ }
+ };
+
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, [context, serverOrigin, loadMe]);
+
+ const planParts = useCallback(
+ async (token: string, partIds: string[]) => {
+ if (!canPush || partIds.length === 0) return;
+ setPushing(new Set(partIds));
+ setPartsOutcome(null);
+ try {
+ const response = await panelFetch(token, paths.planPart, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ documentId: context.documentId,
+ wv: context.wv,
+ wvId: context.wvId,
+ elementId: context.elementId,
+ configuration: context.configuration,
+ partIds
+ })
+ });
+ const body = (await response.json()) as
+ | PlanResponse<PartPlan>
+ | PanelErrorResponse;
+ if (!response.ok || "error" in body) {
+ setReview(null);
+ setPartsOutcome(
+ failedOutcome(
+ "error" in body
+ ? body.error
+ : `Carbon answered ${response.status}`
+ )
+ );
+ return;
+ }
+ setReview(
+ createReview({
+ planId: body.planId,
+ expiresAt: body.expiresAt,
+ scope: elementScope,
+ plan: body.plan
+ })
+ );
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ setReview(null);
+ setPartsOutcome(failedOutcome(thrownMessage(error)));
+ } finally {
+ setPushing(null);
+ }
+ },
+ [canPush, context, paths.planPart, elementScope]
+ );
+
+ const [assemblyOutcome, setAssemblyOutcome] = useState<PushOutcome | null>(
+ null
+ );
+ /** The plan route's too-large refusal message. */
+ const [assemblyTooLarge, setAssemblyTooLarge] = useState<string | null>(null);
+ // `top` is offered only after a too-large refusal: it counts every distinct part
+ // number in the tree, so pushing sub-assemblies first never lowers it.
+ const planAssembly = useCallback(
+ async (token: string, depth: AssemblyPlanDepth = "all") => {
+ if (!canPush) return;
+ setPushing(new Set(["__assembly__"]));
+ setAssemblyOutcome(null);
+ setAssemblyTooLarge(null);
+ try {
+ const response = await panelFetch(token, paths.planAssembly, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ documentId: context.documentId,
+ wv: context.wv,
+ wvId: context.wvId,
+ elementId: context.elementId,
+ configuration: context.configuration,
+ depth
+ })
+ });
+ const body = (await response.json()) as
+ | PlanResponse<AssemblyPlan>
+ | PanelErrorResponse;
+ if (!response.ok || "error" in body) {
+ setReview(null);
+ if ("error" in body && body.code === "too-large") {
+ setAssemblyTooLarge(body.error);
+ return;
+ }
+ setAssemblyOutcome(
+ failedOutcome(
+ "error" in body
+ ? body.error
+ : `Carbon answered ${response.status}`
+ )
+ );
+ return;
+ }
+ setReview(
+ createReview({
+ planId: body.planId,
+ expiresAt: body.expiresAt,
+ scope: elementScope,
+ plan: body.plan
+ })
+ );
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ setReview(null);
+ setAssemblyOutcome(failedOutcome(thrownMessage(error)));
+ } finally {
+ setPushing(null);
+ }
+ },
+ [canPush, context, paths.planAssembly, elementScope]
+ );
+
+ const planRelease = useCallback(
+ async (token: string, releaseId: string) => {
+ setPushingReleaseId(releaseId);
+ try {
+ const response = await panelFetch(token, paths.planRelease, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ documentId: context.documentId, releaseId })
+ });
+ const body = (await response.json()) as
+ | PlanResponse<ReleasePlan>
+ | PanelErrorResponse;
+ if (!response.ok || "error" in body) {
+ setReview(null);
+ setReleaseOutcome((prev) => ({
+ ...prev,
+ [releaseId]: failedOutcome(
+ "error" in body
+ ? body.error
+ : `Carbon answered ${response.status}`
+ )
+ }));
+ return;
+ }
+ setReview(
+ createReview({
+ planId: body.planId,
+ expiresAt: body.expiresAt,
+ scope: documentScope,
+ plan: body.plan,
+ warnings: normalizeWarnings(body.warnings)
+ })
+ );
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ setReview(null);
+ setReleaseOutcome((prev) => ({
+ ...prev,
+ [releaseId]: failedOutcome(thrownMessage(error))
+ }));
+ } finally {
+ setPushingReleaseId(null);
+ }
+ },
+ [context.documentId, paths.planRelease, documentScope]
+ );
+
+ // 422 pins errors to rows; 410: the plan expired. A part apply patches the list
+ // from its results; assembly and release applies reload.
+ const applyReview = useCallback(
+ async (token: string) => {
+ if (!review || review.applying) return;
+ const current = review;
+ setReview({ ...current, applying: true, error: null, fieldErrors: {} });
+ const path =
+ current.kind === "part"
+ ? paths.pushPart
+ : current.kind === "assembly"
+ ? paths.pushAssembly
+ : paths.pushRelease;
+ try {
+ // No timeout: the push keeps writing after the panel stops waiting, and its plan is spent.
+ const response = await panelFetch(
+ token,
+ path,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(applyRequestBody(current))
+ },
+ null
+ );
+ const body = (await response.json()) as
+ | { results: PartApplyResult[] }
+ | { summary: AssemblyPushSummary | ReleasePushSummary }
+ | PanelErrorResponse;
+ if (!response.ok || "error" in body) {
+ setReview({
+ ...current,
+ applying: false,
+ error:
+ "error" in body
+ ? body.error
+ : `Carbon answered ${response.status}`,
+ fieldErrors:
+ response.status === 422 && "fieldErrors" in body
+ ? indexFieldErrors(body.fieldErrors)
+ : {},
+ expired: response.status === 410
+ });
+ return;
+ }
+ setReview(null);
+ if (current.kind === "part") {
+ const results = "results" in body ? body.results : [];
+ setPushOutcome((prev) => ({
+ ...prev,
+ ...Object.fromEntries(
+ results.map((r) => [r.partId, partOutcome(r)])
+ )
+ }));
+ setPartsOutcome(partsOutcomeText(results, current.plan.rows));
+ setParts((prev) =>
+ prev.status === "ready"
+ ? {
+ status: "ready",
+ rows: patchPartStatuses(prev.rows, current, results)
+ }
+ : prev
+ );
+ } else if (current.kind === "assembly") {
+ const summary = (body as { summary: AssemblyPushSummary }).summary;
+ setAssemblyOutcome(assemblyOutcomeText(summary));
+ await loadParts(token);
+ } else {
+ const summary = (body as { summary: ReleasePushSummary }).summary;
+ setReleaseOutcome((prev) => ({
+ ...prev,
+ [current.plan.releaseId]: releaseOutcomeText(summary)
+ }));
+ await loadReleases(token);
+ await loadParts(token);
+ }
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ setReview({
+ ...current,
+ applying: false,
+ error: thrownMessage(error)
+ });
+ }
+ },
+ [
+ review,
+ paths.pushPart,
+ paths.pushAssembly,
+ paths.pushRelease,
+ loadParts,
+ loadReleases
+ ]
+ );
+
+ const cancelReview = () => setReview(null);
+
+ // Keyed by partId (parts) or part number. Editing a part row selects it:
+ // applyRequestBody drops the edits of unselected rows.
+ const editItem = useCallback(
+ (key: string, patch: Partial<ItemFieldSnapshot>) => {
+ setReview((current) => {
+ if (!current) return current;
+ const edits = {
+ ...current.edits,
+ [key]: { ...(current.edits[key] ?? {}), ...patch }
+ };
+ if (current.kind === "part") {
+ const selected = new Set(current.selected);
+ selected.add(key);
+ return { ...current, edits, selected };
+ }
+ return { ...current, edits };
+ });
+ },
+ []
+ );
+
+ /** After a 410: the same plan request again, which replaces the review. */
+ const replan = (token: string) => {
+ if (!review) return;
+ if (review.kind === "part") {
+ void planParts(
+ token,
+ review.plan.rows.map((row) => row.partId)
+ );
+ } else if (review.kind === "assembly") {
+ void planAssembly(token, review.plan.depth);
+ } else {
+ void planRelease(token, review.plan.releaseId);
+ }
+ };
+
+ const signIn = () => {
+ const width = 480;
+ const height = 680;
+ const left = window.screenX + Math.max(0, (window.outerWidth - width) / 2);
+ const top = window.screenY + Math.max(0, (window.outerHeight - height) / 3);
+ const popup = window.open(
+ paths.auth,
+ "carbon-onshape-auth",
+ `popup=yes,width=${width},height=${height},left=${left},top=${top}`
+ );
+ setSession(
+ popup
+ ? { status: "signed-out" }
+ : { status: "signed-out", popupBlocked: true }
+ );
+ };
+
+ const signOut = async () => {
+ const token = "token" in session ? session.token : null;
+ clearPanelSessionToken();
+ setSession({ status: "signed-out" });
+ if (token) {
+ try {
+ await panelFetch(token, paths.session, { method: "DELETE" });
+ } catch {
+ // Best effort: the token is already dropped locally.
+ }
+ }
+ };
+
+ const loadFields = useCallback(
+ async (token: string) => {
+ if (!canLoadParts) return;
+ // A landing commits only while the page still waits for this read: a move to
+ // another element leaves `closed`, which the answer must not undo.
+ const fail = (message: string, forbidden: boolean) =>
+ setFields((current) =>
+ current.status === "ready" && current.refreshing
+ ? {
+ ...current,
+ refreshing: false,
+ refreshFailure: { message, forbidden }
+ }
+ : current.status === "loading"
+ ? { status: "error", message, forbidden }
+ : current
+ );
+ setFields((current) =>
+ current.status === "ready"
+ ? { ...current, refreshing: true, refreshFailure: undefined }
+ : { status: "loading" }
+ );
+ try {
+ const query = new URLSearchParams({
+ documentId: context.documentId as string,
+ wv: context.wv as string,
+ wvId: context.wvId as string,
+ elementId: context.elementId as string
+ });
+ const response = await panelFetch(token, `${paths.fields}?${query}`);
+ const body = (await response.json()) as
+ | PanelFieldsData
+ | { error: string };
+ if (!response.ok || "error" in body) {
+ fail(
+ "error" in body ? body.error : `Carbon answered ${response.status}`,
+ response.status === 403
+ );
+ return;
+ }
+ setFields((current) =>
+ current.status === "loading" ||
+ (current.status === "ready" && !!current.refreshing)
+ ? {
+ status: "ready",
+ data: body,
+ // A re-read replaces the draft rather than merging with it.
+ entries: fieldsDraft(body.map),
+ descriptionModes: { ...body.descriptionModes },
+ pushDefaults: { ...body.pushDefaults },
+ saving: false,
+ error: null,
+ fieldErrors: {}
+ }
+ : current
+ );
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ fail(thrownMessage(error), false);
+ }
+ },
+ [canLoadParts, context, paths.fields]
+ );
+
+ const saveFields = useCallback(
+ async (token: string) => {
+ if (fields.status !== "ready" || fields.saving) return;
+ const current = fields;
+ setFields({
+ ...current,
+ saving: true,
+ error: null,
+ warning: undefined,
+ fieldErrors: {}
+ });
+ // As in loadFields: lands only on the save still in flight.
+ const land = (next: PanelFieldsState) =>
+ setFields((latest) =>
+ latest.status === "ready" && latest.saving ? next : latest
+ );
+ try {
+ const response = await panelFetch(token, paths.fields, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ entries: current.entries,
+ descriptionModes: current.descriptionModes,
+ pushDefaults: current.pushDefaults
+ })
+ });
+ const body = (await response.json()) as
+ | {
+ map: PropertyMapEntry[];
+ descriptionModes: DescriptionModes;
+ pushDefaults: OnshapePushDefaults;
+ definitions: PlanCustomFieldDefinition[] | null;
+ warning?: string;
+ }
+ | PanelErrorResponse;
+ if (!response.ok || "error" in body) {
+ land({
+ ...current,
+ saving: false,
+ error:
+ "error" in body
+ ? body.error
+ : `Carbon answered ${response.status}`,
+ fieldErrors:
+ response.status === 422 && "fieldErrors" in body
+ ? indexFieldErrors(body.fieldErrors)
+ : {}
+ });
+ return;
+ }
+ land({
+ ...current,
+ data: {
+ ...current.data,
+ map: body.map,
+ descriptionModes: body.descriptionModes,
+ pushDefaults: body.pushDefaults,
+ // Null when the re-read after the save failed: keep the ones on screen.
+ definitions: body.definitions ?? current.data.definitions
+ },
+ entries: fieldsDraft(body.map),
+ descriptionModes: { ...body.descriptionModes },
+ pushDefaults: { ...body.pushDefaults },
+ saving: false,
+ error: null,
+ warning: body.warning,
+ fieldErrors: {}
+ });
+ } catch (error) {
+ if (error instanceof PanelUnauthorizedError) {
+ setSession({ status: "signed-out" });
+ return;
+ }
+ land({ ...current, saving: false, error: thrownMessage(error) });
+ }
+ },
+ [fields, paths.fields]
+ );
+
+ const mapFieldsProperty = (
+ property: PanelFieldsProperty,
+ selection: string
+ ) =>
+ setFields((current) => {
+ if (current.status !== "ready") return current;
+ const previous = current.entries.find(
+ (entry) => entry.onshapePropertyId === property.propertyId
+ );
+ const entries = current.entries.filter(
+ (entry) => entry.onshapePropertyId !== property.propertyId
+ );
+ const target = targetFromKey(selection);
+ if (target) {
+ const field =
+ target.kind === "item" ? standardField(target.field) : undefined;
+ entries.push({
+ onshapePropertyId: property.propertyId,
+ onshapeName: property.name,
+ valueType: property.valueType,
+ target,
+ mode: previous?.mode ?? "create",
+ ...(field?.kind === "list"
+ ? {
+ translations: defaultTranslations(
+ field,
+ property.valueType,
+ property.options
+ )
+ }
+ : {})
+ });
+ }
+ return {
+ ...current,
+ entries,
+ error: null,
+ fieldErrors: clearFieldErrors(current.fieldErrors, property.propertyId)
+ };
+ });
+
+ const editFieldsEntry = (
+ propertyId: string,
+ patch: Partial<Pick<FieldsDraftEntry, "mode" | "translations">>
+ ) =>
+ setFields((current) => {
+ if (current.status !== "ready") return current;
+ return {
+ ...current,
+ entries: current.entries.map((entry) =>
+ entry.onshapePropertyId === propertyId
+ ? { ...entry, ...patch }
+ : entry
+ ),
+ error: null,
+ fieldErrors: clearFieldErrors(current.fieldErrors, propertyId)
+ };
+ });
+
+ // null: no property, which for an item field means its push default. The chosen
+ // property leaves any other field.
+ const setTargetSource = (
+ target: PropertyMapTarget,
+ property: PanelFieldsProperty | null
+ ) =>
+ setFields((current) => {
+ if (current.status !== "ready") return current;
+ const key = targetKey(target);
+ const feeds = (entry: FieldsDraftEntry) =>
+ targetKey(entry.target) === key;
+ const previous = current.entries.find(feeds);
+ const entries = current.entries.filter(
+ (entry) =>
+ !feeds(entry) && entry.onshapePropertyId !== property?.propertyId
+ );
+ const field =
+ target.kind === "item" ? standardField(target.field) : undefined;
+ if (property) {
+ entries.push({
+ onshapePropertyId: property.propertyId,
+ onshapeName: property.name,
+ valueType: property.valueType,
+ target,
+ mode: previous?.mode ?? "create",
+ ...(field?.kind === "list"
+ ? {
+ translations: defaultTranslations(
+ field,
+ property.valueType,
+ property.options
+ )
+ }
+ : {})
+ });
+ }
+ let fieldErrors = current.fieldErrors;
+ for (const id of [previous?.onshapePropertyId, property?.propertyId]) {
+ if (id) fieldErrors = clearFieldErrors(fieldErrors, id);
+ }
+ return { ...current, entries, error: null, fieldErrors };
+ });
+
+ const setPushDefaults = (patch: Partial<OnshapePushDefaults>) =>
+ setFields((current) =>
+ current.status === "ready"
+ ? {
+ ...current,
+ pushDefaults: reconcilePushDefaults({
+ ...current.pushDefaults,
+ ...patch
+ }),
+ error: null
+ }
+ : current
+ );
+
+ const setDescriptionMode = (
+ field: keyof DescriptionModes,
+ mode: MappingMode
+ ) =>
+ setFields((current) =>
+ current.status === "ready"
+ ? {
+ ...current,
+ descriptionModes: { ...current.descriptionModes, [field]: mode },
+ error: null
+ }
+ : current
+ );
+
+ // A drawing has no parts but its document has releases. Fields needs an
+ // element with properties and settings update.
+ const availableTabs = useMemo<PanelTab[]>(() => {
+ if (session.status !== "signed-in") return [];
+ const tabs: PanelTab[] = [];
+ if (canLoadParts) tabs.push("push");
+ if (context.documentId) tabs.push("releases");
+ if (
+ canLoadParts &&
+ session.me.canEditFields &&
+ (parts.status === "ready" || parts.status === "ready-assembly")
+ ) {
+ tabs.push("fields");
+ }
+ return tabs;
+ }, [session, canLoadParts, context.documentId, parts.status]);
+
+ // Opening the Fields page loads it, so a panel that never opens it spends no Onshape reads.
+ useEffect(() => {
+ if (tab !== "fields" || session.status !== "signed-in") return;
+ if (fields.status === "closed") void loadFields(session.token);
+ }, [tab, session, fields.status, loadFields]);
+
+ // Onshape moves the panel between elements: fall back to the first page that still exists.
+ useEffect(() => {
+ const first = availableTabs[0];
+ if (first && !availableTabs.includes(tab)) setTab(first);
+ }, [availableTabs, tab]);
+
+ // Tab labels wait on the status read (the element kind); until then one skeleton
+ // as wide as the expected tabs holds the bar.
+ const tabsPending =
+ session.status === "signed-in" &&
+ canLoadParts &&
+ (parts.status === "idle" || parts.status === "loading");
+ const pendingTabLabels = [
+ "Assembly",
+ ...(context.documentId ? ["Releases"] : []),
+ ...(session.status === "signed-in" && session.me.canEditFields
+ ? ["Fields"]
+ : [])
+ ];
+
+ const pushTabLabel =
+ parts.status === "ready-assembly"
+ ? "Assembly"
+ : parts.status === "ready"
+ ? "Parts"
+ : "Push";
+
+ // Every hook has run above; keep this early return after them.
+ if (session.status === "signed-out" || session.status === "unknown") {
+ return (
+ <div className="flex h-full min-h-0 flex-col items-center justify-center gap-6 p-4">
+ {!serverOrigin ? (
+ <Alert variant="warning" className="max-w-sm">
+ <LuTriangleAlert />
+ <AlertTitle>Open this panel from Onshape</AlertTitle>
+ </Alert>
+ ) : null}
+ {session.status === "signed-out" && session.popupBlocked ? (
+ <Alert variant="warning" className="max-w-sm">
+ <LuTriangleAlert />
+ <AlertTitle>Your browser blocked the sign-in window</AlertTitle>
+ <AlertDescription>
+ Allow pop-ups for this page, then press Sign in to Carbon again.
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ <PanelSignIn
+ onSignIn={signIn}
+ disabled={session.status === "unknown"}
+ />
+ </div>
+ );
+ }
+
+ return (
+ // Pinned header, one scrolling body (min-h-0 lets it shrink), a pinned action bar.
+ // Tabs is outermost: Radix needs the strip and the panes in one root.
+ // See .claude/rules/onshape-panel.md.
+ <Tabs
+ value={tab}
+ onValueChange={(value) =>
+ (value === "push" || value === "releases" || value === "fields") &&
+ setTab(value)
+ }
+ className="flex h-full min-h-0 flex-col"
+ >
+ {/* The company tells a user in several companies where a push lands. */}
+ <HStack className="w-full shrink-0 justify-between gap-2 border-b border-border px-4 py-2">
+ {tabsPending ? (
+ // Sized by invisible copies of the tabs, so it is as wide as the bar after it.
+ <Skeleton
+ aria-hidden
+ className="flex rounded-[0.5rem] border border-transparent p-0.5"
+ >
+ {pendingTabLabels.map((label) => (
+ <span
+ key={label}
+ className="invisible border border-transparent px-3 py-1 text-sm font-medium"
+ >
+ {label}
+ </span>
+ ))}
+ </Skeleton>
+ ) : availableTabs.length > 1 ? (
+ <TabsList>
+ {availableTabs.includes("push") ? (
+ <TabsTrigger value="push">{pushTabLabel}</TabsTrigger>
+ ) : null}
+ {availableTabs.includes("releases") ? (
+ <TabsTrigger value="releases">Releases</TabsTrigger>
+ ) : null}
+ {availableTabs.includes("fields") ? (
+ <TabsTrigger value="fields">Fields</TabsTrigger>
+ ) : null}
+ </TabsList>
+ ) : (
+ <span />
+ )}
+ {session.status === "signed-in" ? (
+ <HStack spacing={1} className="min-w-0">
+ <span
+ className="truncate text-xs text-muted-foreground"
+ title={session.me.email}
+ >
+ {session.me.company?.name ?? session.me.email}
+ </span>
+ <Button variant="ghost" size="sm" onClick={signOut}>
+ Sign out
+ </Button>
+ </HStack>
+ ) : null}
+ </HStack>
+
+ <VStack spacing={4} className="min-h-0 flex-1 overflow-y-auto p-4">
+ {!serverOrigin ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>Open this panel from Onshape</AlertTitle>
+ </Alert>
+ ) : null}
+
+ {session.status === "loading" ? (
+ <Loading isLoading className="py-8" />
+ ) : null}
+
+ {session.status === "error" ? (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>Carbon is not reachable</AlertTitle>
+ <AlertDescription>{session.message}</AlertDescription>
+ <HStack className="mt-2">
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => session.token && loadMe(session.token)}
+ isDisabled={!session.token}
+ >
+ Retry
+ </Button>
+ <Button size="sm" variant="ghost" onClick={signOut}>
+ Sign in again
+ </Button>
+ </HStack>
+ </Alert>
+ ) : null}
+
+ <TabsContent value="push" className="w-full">
+ <VStack spacing={4} className="w-full">
+ {session.status === "signed-in" &&
+ canLoadParts &&
+ !review &&
+ (parts.status === "loading" || parts.status === "idle") ? (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-8 w-20" />
+ </HStack>
+ <PanelListSkeleton />
+ </VStack>
+ ) : null}
+
+ {session.status === "signed-in" &&
+ canLoadParts &&
+ (parts.status === "ready-assembly" ||
+ parts.status === "ready-other") ? (
+ parts.status === "ready-assembly" ? (
+ review?.kind === "assembly" ? (
+ <AssemblyReviewSection
+ review={review}
+ onCancel={cancelReview}
+ onApply={() => applyReview(session.token)}
+ onReplan={() => replan(session.token)}
+ onEditItem={editItem}
+ replanning={!!pushing}
+ />
+ ) : (
+ <AssemblySection
+ locked={!!review}
+ assembly={parts.assembly}
+ canPush={canPush}
+ busy={!!pushing}
+ refreshing={!!parts.refreshing}
+ outcome={assemblyOutcome}
+ tooLarge={assemblyTooLarge}
+ refreshFailure={parts.refreshFailure}
+ onPush={() => planAssembly(session.token)}
+ onPushLevel={() => planAssembly(session.token, "top")}
+ onRefresh={() => loadParts(session.token)}
+ />
+ )
+ ) : (
+ <PanelEmpty>Nothing to push in this element</PanelEmpty>
+ )
+ ) : null}
+
+ {session.status === "signed-in" &&
+ canLoadParts &&
+ parts.status !== "ready-assembly" &&
+ parts.status !== "ready-other" &&
+ (!!review ||
+ (parts.status !== "loading" && parts.status !== "idle")) ? (
+ review?.kind === "part" ? (
+ <PartReviewSection
+ review={review}
+ onCancel={cancelReview}
+ onApply={() => applyReview(session.token)}
+ onReplan={() => replan(session.token)}
+ onEditItem={editItem}
+ replanning={!!pushing}
+ />
+ ) : (
+ <PartsSection
+ locked={!!review}
+ parts={parts}
+ canPush={canPush}
+ pushing={pushing}
+ pushOutcome={pushOutcome}
+ outcome={partsOutcome}
+ onRefresh={() => loadParts(session.token)}
+ onPush={(partIds) => planParts(session.token, partIds)}
+ />
+ )
+ ) : null}
+ </VStack>
+ </TabsContent>
+
+ <TabsContent value="releases" className="w-full">
+ {session.status === "signed-in" && context.documentId ? (
+ review?.kind === "release" ? (
+ <ReleaseReviewSection
+ review={review}
+ onCancel={cancelReview}
+ onApply={() => applyReview(session.token)}
+ onReplan={() => replan(session.token)}
+ onEditItem={editItem}
+ replanning={!!pushingReleaseId}
+ />
+ ) : (
+ <ReleasesSection
+ locked={!!review}
+ releases={releases}
+ pushingReleaseId={pushingReleaseId}
+ outcome={releaseOutcome}
+ onPush={(releaseId) => planRelease(session.token, releaseId)}
+ onRefresh={() => {
+ setReleaseOutcome({});
+ void loadReleases(session.token);
+ }}
+ />
+ )
+ ) : null}
+ </TabsContent>
+
+ <TabsContent value="fields" className="w-full">
+ {session.status === "signed-in" && fields.status !== "closed" ? (
+ <FieldsSection
+ state={fields}
+ onMap={mapFieldsProperty}
+ onTargetSource={setTargetSource}
+ onEdit={editFieldsEntry}
+ onDescriptionMode={setDescriptionMode}
+ onPushDefaults={setPushDefaults}
+ onRefresh={() => loadFields(session.token)}
+ onSave={() => saveFields(session.token)}
+ />
+ ) : null}
+ </TabsContent>
+ </VStack>
+ </Tabs>
+ );
+}
+
+function AssemblySection({
+ assembly,
+ canPush,
+ busy,
+ refreshing,
+ locked,
+ outcome,
+ tooLarge,
+ refreshFailure,
+ onPush,
+ onPushLevel,
+ onRefresh
+}: {
+ assembly: PanelAssemblyStatus;
+ canPush: boolean;
+ busy: boolean;
+ refreshing: boolean;
+ /** A review is open elsewhere: a second push would replace it unseen. */
+ locked: boolean;
+ outcome: PushOutcome | null;
+ tooLarge: string | null;
+ refreshFailure?: LoadFailure;
+ onPush: () => void;
+ onPushLevel: () => void;
+ onRefresh: () => void;
+}) {
+ return (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <HStack spacing={2}>
+ <span className="text-sm font-medium">
+ {assembly.root.partNumber ?? assembly.root.name ?? "Assembly"}
+ </span>
+ <PartStateBadge state={assembly.root.state} />
+ </HStack>
+ <HStack spacing={1}>
+ {canPush ? (
+ <Button
+ size="sm"
+ onClick={onPush}
+ isDisabled={busy || locked || refreshing}
+ isLoading={busy}
+ >
+ {assembly.root.state === "linked" ||
+ assembly.root.state === "released"
+ ? "Re-push assembly"
+ : "Push assembly"}
+ </Button>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onRefresh}
+ isDisabled={busy || refreshing}
+ isLoading={refreshing}
+ leftIcon={<LuRefreshCw />}
+ >
+ Refresh
+ </Button>
+ </HStack>
+ </HStack>
+
+ {!assembly.root.partNumber ? (
+ assembly.root.identityUnavailable ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>Couldn't read this assembly's part number</AlertTitle>
+ <AlertDescription>
+ Onshape didn't return it this time. Refresh to try again.
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>This assembly has no part number</AlertTitle>
+ <AlertDescription>
+ In Onshape, right-click the assembly's tab, choose Properties and
+ set Part number. Then press Refresh.
+ </AlertDescription>
+ </Alert>
+ )
+ ) : null}
+
+ {refreshFailure ? (
+ <PanelLoadError
+ title="Couldn't refresh the BOM"
+ failure={refreshFailure}
+ stale
+ retrying={refreshing}
+ onRetry={onRefresh}
+ />
+ ) : null}
+
+ {tooLarge ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>This assembly is too large for one push</AlertTitle>
+ <AlertDescription>{tooLarge}</AlertDescription>
+ <HStack className="mt-2">
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={onPushLevel}
+ isDisabled={busy || locked || refreshing}
+ isLoading={busy}
+ >
+ Push this level only
+ </Button>
+ </HStack>
+ </Alert>
+ ) : null}
+
+ {outcome ? <PushOutcomeView outcome={outcome} /> : null}
+
+ {assembly.lines.length === 0 ? (
+ <PanelEmpty>The BOM is empty</PanelEmpty>
+ ) : (
+ <AssemblyBomList lines={assembly.lines} disabled={refreshing} />
+ )}
+ </VStack>
+ );
+}
+
+// Opens at the top level, as Onshape's structured BOM does. Open indexes are
+// tracked, not collapsed ones, so a refresh keeps those that still exist.
+function AssemblyBomList({
+ lines,
+ disabled
+}: {
+ lines: PanelAssemblyLine[];
+ disabled: boolean;
+}) {
+ const [open, setOpen] = useState<Set<string>>(new Set());
+
+ const tree = useMemo(() => buildBomViewTree(lines), [lines]);
+ const structured = useMemo(() => visibleBomRows(tree, open), [tree, open]);
+ const parents = useMemo(() => bomParentIndexes(tree), [tree]);
+
+ const toggle = (index: string) =>
+ setOpen((current) => {
+ const next = new Set(current);
+ if (!next.delete(index)) next.add(index);
+ return next;
+ });
+
+ const allOpen = parents.length > 0 && parents.every((i) => open.has(i));
+
+ return (
+ <VStack spacing={2} className="w-full">
+ {parents.length > 0 ? (
+ <HStack className="w-full justify-end">
+ <Button
+ variant="link"
+ size="sm"
+ onClick={() => setOpen(allOpen ? new Set() : new Set(parents))}
+ isDisabled={disabled}
+ >
+ {allOpen ? "Collapse all" : "Expand all"}
+ </Button>
+ </HStack>
+ ) : null}
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {structured.map((row) => (
+ <li key={row.line.index} className="px-3 py-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <HStack
+ spacing={1}
+ className="min-w-0"
+ style={{ paddingLeft: `${(row.level - 1) * 14}px` }}
+ >
+ {row.hasChildren ? (
+ <button
+ type="button"
+ onClick={() => toggle(row.line.index)}
+ disabled={disabled}
+ aria-expanded={row.open}
+ aria-label={`${row.open ? "Collapse" : "Expand"} ${
+ row.line.partNumber ?? row.line.index
+ }`}
+ className="shrink-0 text-muted-foreground transition-transform hover:text-foreground active:scale-[0.96] active:duration-75"
+ >
+ <LuChevronRight
+ className={cn(
+ "size-3.5 transition-transform",
+ row.open && "rotate-90"
+ )}
+ />
+ </button>
+ ) : (
+ <span className="size-3.5 shrink-0" aria-hidden />
+ )}
+ <BomLineText
+ line={row.line}
+ quantity={row.line.quantity}
+ note={
+ row.hasChildren && !row.open
+ ? `${row.descendantCount} inside`
+ : null
+ }
+ />
+ </HStack>
+ <PartStateBadge state={row.line.state} />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </VStack>
+ );
+}
+
+function BomLineText({
+ line,
+ quantity,
+ note
+}: {
+ line: PanelAssemblyLine;
+ /** Per-parent. */
+ quantity: number;
+ note: string | null;
+}) {
+ return (
+ <div className="min-w-0">
+ <p
+ className="text-sm truncate"
+ title={line.name ?? line.partNumber ?? line.index}
+ >
+ {line.name ?? line.partNumber ?? line.index}
+ <span className="tabular-nums text-muted-foreground">
+ {" "}
+ × {quantity}
+ </span>
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {line.partNumber ?? "No part number"}
+ {line.state === "matched" ? " · number already used in Carbon" : ""}
+ {line.state === "released" && line.releasedRevision
+ ? ` · released as Rev ${line.releasedRevision}`
+ : ""}
+ {note ? ` · ${note}` : ""}
+ </p>
+ </div>
+ );
+}
+
+function PartsSection({
+ parts,
+ canPush,
+ pushing,
+ locked,
+ pushOutcome,
+ outcome,
+ onRefresh,
+ onPush
+}: {
+ parts:
+ | { status: "idle" }
+ | { status: "loading" }
+ | {
+ status: "ready";
+ rows: PanelPartStatus[];
+ refreshing?: boolean;
+ refreshFailure?: LoadFailure;
+ }
+ | { status: "error"; message: string; forbidden?: boolean };
+ canPush: boolean;
+ pushing: Set<string> | null;
+ locked: boolean;
+ pushOutcome: Record<string, PartRowOutcome>;
+ outcome: PushOutcome | null;
+ onRefresh: () => void;
+ onPush: (partIds: string[]) => void;
+}) {
+ // A stale HMR closure can deliver ready without rows.
+ const rows =
+ parts.status === "ready" && Array.isArray(parts.rows) ? parts.rows : [];
+ const pushableIds = rows.filter((r) => r.partNumber).map((r) => r.partId);
+ return (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <span className="text-sm font-medium">Parts in this element</span>
+ <HStack spacing={1}>
+ {canPush && pushableIds.length > 0 ? (
+ <Button
+ size="sm"
+ onClick={() => onPush(pushableIds)}
+ isDisabled={
+ !!pushing ||
+ locked ||
+ parts.status === "loading" ||
+ (parts.status === "ready" && !!parts.refreshing)
+ }
+ isLoading={!!pushing && pushing.size > 1}
+ >
+ Push all
+ </Button>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onRefresh}
+ isDisabled={parts.status === "loading" || !!pushing}
+ isLoading={parts.status === "ready" && !!parts.refreshing}
+ leftIcon={<LuRefreshCw />}
+ >
+ Refresh
+ </Button>
+ </HStack>
+ </HStack>
+
+ {parts.status === "loading" || parts.status === "idle" ? (
+ <PanelListSkeleton />
+ ) : null}
+
+ {parts.status === "error" ? (
+ <PanelLoadError
+ title="Couldn't load part status"
+ failure={{ message: parts.message, forbidden: !!parts.forbidden }}
+ onRetry={onRefresh}
+ />
+ ) : null}
+
+ {parts.status === "ready" && parts.refreshFailure ? (
+ <PanelLoadError
+ title="Couldn't refresh part status"
+ failure={parts.refreshFailure}
+ stale
+ retrying={!!parts.refreshing}
+ onRetry={onRefresh}
+ />
+ ) : null}
+
+ {outcome ? <PushOutcomeView outcome={outcome} /> : null}
+
+ {parts.status === "ready" && rows.length === 0 ? (
+ <PanelEmpty>This element has no parts</PanelEmpty>
+ ) : null}
+
+ {parts.status === "ready" && rows.length > 0 ? (
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {rows.map((part) => (
+ <li
+ key={part.partId}
+ className="flex items-center justify-between gap-2 px-3 py-2"
+ >
+ <div className="min-w-0">
+ <p className="text-sm truncate" title={part.name}>
+ {part.name}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {part.partNumber ?? "No part number"}
+ {part.revision ? ` · Rev ${part.revision}` : ""}
+ {part.state === "linked" && part.item
+ ? ` → ${part.item.readableId}`
+ : ""}
+ {part.state === "matched" && part.item
+ ? " · number already used in Carbon"
+ : ""}
+ {part.state === "released" && part.item
+ ? ` · released in Carbon as Rev ${part.item.revision}`
+ : ""}
+ </p>
+ </div>
+ <HStack spacing={2} className="shrink-0">
+ {pushOutcome[part.partId] ? (
+ <span
+ className={cn(
+ "text-xs",
+ pushOutcome[part.partId]?.kind === "error"
+ ? "font-medium text-destructive"
+ : pushOutcome[part.partId]?.kind === "skipped"
+ ? "text-amber-600 dark:text-amber-400"
+ : "text-muted-foreground"
+ )}
+ >
+ {pushOutcome[part.partId]?.text}
+ </span>
+ ) : null}
+ <PartStateBadge state={part.state} />
+ {canPush ? (
+ <DisabledReason
+ reason={
+ !part.partNumber
+ ? "Set a part number in Onshape first"
+ : part.state === "released"
+ ? "Released in Onshape: changes come through a release"
+ : undefined
+ }
+ >
+ <Button
+ size="sm"
+ variant={part.state === "linked" ? "ghost" : "secondary"}
+ onClick={() => onPush([part.partId])}
+ isDisabled={
+ !!pushing ||
+ locked ||
+ !part.partNumber ||
+ part.state === "released" ||
+ (parts.status === "ready" && !!parts.refreshing)
+ }
+ isLoading={!!pushing && pushing.has(part.partId)}
+ >
+ {part.state === "linked" ? "Re-push" : "Push"}
+ </Button>
+ </DisabledReason>
+ ) : null}
+ </HStack>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </VStack>
+ );
+}
+
+function ReleasesSection({
+ releases,
+ pushingReleaseId,
+ locked,
+ outcome,
+ onPush,
+ onRefresh
+}: {
+ releases: PanelReleasesState;
+ pushingReleaseId: string | null;
+ locked: boolean;
+ outcome: Record<string, PushOutcome>;
+ onPush: (releaseId: string) => void;
+ onRefresh: () => void;
+}) {
+ return (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <span className="text-sm font-medium">Releases</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onRefresh}
+ isDisabled={releases.status === "loading" || !!pushingReleaseId}
+ isLoading={releases.status === "ready" && !!releases.refreshing}
+ leftIcon={<LuRefreshCw />}
+ >
+ Refresh
+ </Button>
+ </HStack>
+
+ {releases.status === "loading" || releases.status === "idle" ? (
+ <PanelListSkeleton rows={3} />
+ ) : null}
+
+ {releases.status === "error" ? (
+ <PanelLoadError
+ title="Couldn't load releases"
+ failure={{
+ message: releases.message,
+ forbidden: !!releases.forbidden
+ }}
+ onRetry={onRefresh}
+ />
+ ) : null}
+
+ {releases.status === "ready" && releases.refreshFailure ? (
+ <PanelLoadError
+ title="Couldn't refresh releases"
+ failure={releases.refreshFailure}
+ stale
+ retrying={!!releases.refreshing}
+ onRetry={onRefresh}
+ />
+ ) : null}
+
+ {releases.status === "ready" && releases.releases.length === 0 ? (
+ <PanelEmpty>
+ {releases.releaseManagementAvailable === false
+ ? "No releases. Releases need an Onshape company account; a revision letter on a part is only a property."
+ : "No releases yet"}
+ </PanelEmpty>
+ ) : null}
+
+ {releases.status === "ready" && releases.releases.length > 0 ? (
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {releases.releases.map((release) => {
+ const models = release.items.filter(
+ (item) => item.elementType === 0 || item.elementType === 1
+ );
+ const drawings = release.items.length - models.length;
+ const releaseOutcome = outcome[release.releaseId];
+ return (
+ <li key={release.releaseId} className="px-3 py-2">
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <p
+ className="text-sm truncate"
+ title={release.releaseName ?? "Release"}
+ >
+ {release.releaseName ?? "Release"}
+ {release.createdAt
+ ? ` · ${formatDate(release.createdAt)}`
+ : ""}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {models
+ .map(
+ (item) => `${item.partNumber} Rev ${item.revision}`
+ )
+ .join(", ")}
+ {drawings > 0 ? ` · ${plural(drawings, "drawing")}` : ""}
+ </p>
+ </div>
+ <HStack spacing={2} className="shrink-0">
+ <ReleaseStateBadge state={release.state} />
+ <Button
+ size="sm"
+ variant={
+ release.state === "pushed" ? "ghost" : "secondary"
+ }
+ onClick={() => onPush(release.releaseId)}
+ isDisabled={
+ !!pushingReleaseId ||
+ locked ||
+ (releases.status === "ready" && !!releases.refreshing)
+ }
+ isLoading={pushingReleaseId === release.releaseId}
+ >
+ {release.state === "pushed"
+ ? "Re-push release"
+ : "Push release"}
+ </Button>
+ </HStack>
+ </div>
+ {releaseOutcome ? (
+ <div className="mt-1 space-y-1">
+ <PushOutcomeView outcome={releaseOutcome} />
+ </div>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ ) : null}
+ </VStack>
+ );
+}
+
+const MODE_LABEL: Record<MappingMode, string> = {
+ create: "Set at creation",
+ everyPush: "Update on every push"
+};
+
+function modeHelper(mode: MappingMode, cascades: boolean): string {
+ if (mode === "create") return "Only items a push creates get it";
+ return cascades
+ ? "Every push overwrites it, Draft BOMs and jobs too"
+ : "Every push overwrites Carbon's value";
+}
+
+/** Radix Select refuses an empty item value, so "No value" is named. */
+const TRANSLATION_NO_VALUE = "__no-value__";
+/** An Onshape option with no row: the review flags it. */
+const TRANSLATION_UNSET = "__unset__";
+
+const VALUE_TYPE_LABEL: Record<string, string> = {
+ STRING: "Text",
+ ENUM: "List",
+ BOOL: "Yes/No",
+ INT: "Number",
+ DOUBLE: "Number",
+ DATE: "Date",
+ OBJECT: "Text (display name)"
+};
+
+function sameText(a: string, b: string): boolean {
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
+}
+
+// The company's property map; it lives in the panel because Onshape lists
+// properties only inside a document.
+function FieldsSection({
+ state,
+ onMap,
+ onTargetSource,
+ onEdit,
+ onDescriptionMode,
+ onPushDefaults,
+ onRefresh,
+ onSave
+}: {
+ state: Exclude<PanelFieldsState, { status: "closed" }>;
+ onMap: (property: PanelFieldsProperty, selection: string) => void;
+ onTargetSource: (
+ target: PropertyMapTarget,
+ property: PanelFieldsProperty | null
+ ) => void;
+ onEdit: (
+ propertyId: string,
+ patch: Partial<Pick<FieldsDraftEntry, "mode" | "translations">>
+ ) => void;
+ onDescriptionMode: (field: keyof DescriptionModes, mode: MappingMode) => void;
+ onPushDefaults: (patch: Partial<OnshapePushDefaults>) => void;
+ onRefresh: () => void;
+ onSave: () => void;
+}) {
+ const [adding, setAdding] = useState(false);
+ const [confirmingRefresh, setConfirmingRefresh] = useState(false);
+ // Unsaved edits: Refresh replaces the draft with the saved map, so it asks.
+ const dirty =
+ state.status === "ready" &&
+ (!propertyMapEqual(state.entries, state.data.map) ||
+ state.descriptionModes.name !== state.data.descriptionModes.name ||
+ state.descriptionModes.description !==
+ state.data.descriptionModes.description ||
+ !pushDefaultsEqual(state.pushDefaults, state.data.pushDefaults));
+ const header = (
+ <HStack className="w-full justify-between">
+ <span className="text-sm font-medium">Fields</span>
+ {confirmingRefresh ? (
+ <Modal
+ open
+ onOpenChange={(open) =>
+ open ? undefined : setConfirmingRefresh(false)
+ }
+ >
+ <ModalContent size="small" aria-describedby={undefined}>
+ <ModalHeader>
+ <ModalTitle>Discard unsaved changes?</ModalTitle>
+ </ModalHeader>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => setConfirmingRefresh(false)}
+ >
+ Keep editing
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ setConfirmingRefresh(false);
+ onRefresh();
+ }}
+ >
+ Discard and refresh
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => (dirty ? setConfirmingRefresh(true) : onRefresh())}
+ isDisabled={
+ state.status === "loading" ||
+ (state.status === "ready" && state.saving)
+ }
+ isLoading={state.status === "ready" && !!state.refreshing}
+ leftIcon={<LuRefreshCw />}
+ >
+ Refresh
+ </Button>
+ </HStack>
+ );
+
+ if (state.status === "loading") {
+ return (
+ <VStack spacing={2} className="w-full">
+ {header}
+ <PanelListSkeleton />
+ </VStack>
+ );
+ }
+ if (state.status === "error") {
+ return (
+ <VStack spacing={2} className="w-full">
+ {header}
+ <PanelLoadError
+ title="Couldn't load properties"
+ failure={{ message: state.message, forbidden: !!state.forbidden }}
+ onRetry={onRefresh}
+ />
+ </VStack>
+ );
+ }
+
+ const { data } = state;
+ const propertyById = new Map(
+ data.properties.map((property) => [property.propertyId, property])
+ );
+ // One property per Carbon field, and one field per property.
+ const mappedFrom = new Map(
+ state.entries.map((entry) => [targetKey(entry.target), entry])
+ );
+ const mappingOf = new Map(
+ state.entries.map((entry) => [entry.onshapePropertyId, entry])
+ );
+ const offered = data.properties
+ .filter(
+ (property) =>
+ property.mappable && !FIXED_PROPERTY_NAMES.has(property.name)
+ )
+ .sort((a, b) => a.name.localeCompare(b.name));
+ // Item fields with a row of their own are set in that row.
+ const otherEntries = state.entries.filter(
+ (entry) =>
+ !(
+ entry.target.kind === "item" &&
+ ITEM_FIELD_ROW_FIELDS.has(entry.target.field)
+ )
+ );
+ // Every entry has a row, so an error naming another property is a stray.
+ const listed = new Set(state.entries.map((entry) => entry.onshapePropertyId));
+ const strayErrors = Object.entries(state.fieldErrors)
+ .filter(([propertyId]) => !listed.has(propertyId))
+ .flatMap(([propertyId, messages]) =>
+ messages.map((message) => ({ propertyId, message }))
+ );
+ const addable = offered.filter(
+ (property) => !listed.has(property.propertyId)
+ );
+ const busy = state.saving || !!state.refreshing;
+ // Includes the property a target holds even when it is not on this element.
+ const candidatesFor = (
+ target: PropertyMapTarget,
+ entry: FieldsDraftEntry | undefined
+ ): PanelFieldsProperty[] => {
+ const takes = (valueType: string) => {
+ if (target.kind === "item") {
+ return !!standardField(target.field)?.valueTypes.includes(valueType);
+ }
+ const definition = data.definitions.find(
+ (field) => field.id === target.fieldId
+ );
+ return (
+ !!definition &&
+ mappableTypesFor(valueType).includes(definition.dataTypeId)
+ );
+ };
+ const candidates = offered.filter((property) => takes(property.valueType));
+ return entry &&
+ !candidates.some((c) => c.propertyId === entry.onshapePropertyId)
+ ? [
+ ...candidates,
+ {
+ propertyId: entry.onshapePropertyId,
+ name: entry.onshapeName,
+ valueType: entry.valueType,
+ mappable: true
+ }
+ ]
+ : candidates;
+ };
+
+ return (
+ <VStack spacing={3} className="w-full">
+ {header}
+ {state.refreshFailure ? (
+ <PanelLoadError
+ title="Couldn't refresh properties"
+ failure={state.refreshFailure}
+ stale
+ retrying={!!state.refreshing}
+ onRetry={onRefresh}
+ />
+ ) : null}
+ {state.warning ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>Custom field list may be out of date</AlertTitle>
+ <AlertDescription>{state.warning}</AlertDescription>
+ </Alert>
+ ) : null}
+ {state.error ? (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>Couldn't save the map</AlertTitle>
+ <AlertDescription>{state.error}</AlertDescription>
+ </Alert>
+ ) : null}
+ {strayErrors.map(({ propertyId, message }) => (
+ <p
+ key={`${propertyId}:${message}`}
+ className="w-full text-xs text-destructive"
+ >
+ {message}
+ </p>
+ ))}
+
+ <ul className="flex w-full flex-col divide-y divide-border rounded-lg border border-border">
+ <FieldRow
+ source={<SourceText>Part number</SourceText>}
+ carbon="Part ID"
+ control={<AlwaysTag />}
+ />
+ <FieldRow
+ source={<SourceText>Revision</SourceText>}
+ carbon="Revision"
+ control={<AlwaysTag />}
+ />
+ <FieldRow
+ source={<SourceText>Name</SourceText>}
+ carbon="Short Description"
+ control={
+ <ModeSelect
+ mode={state.descriptionModes.name}
+ label="Short Description: when Onshape writes it"
+ disabled={busy}
+ onChange={(mode) => onDescriptionMode("name", mode)}
+ />
+ }
+ />
+ <FieldRow
+ source={<SourceText>Description</SourceText>}
+ carbon="Long Description"
+ control={
+ <ModeSelect
+ mode={state.descriptionModes.description}
+ label="Long Description: when Onshape writes it"
+ disabled={busy}
+ onChange={(mode) => onDescriptionMode("description", mode)}
+ />
+ }
+ />
+ {ITEM_FIELD_ROWS.map((row) => {
+ const target: PropertyMapTarget | null = row.field
+ ? { kind: "item", field: row.field }
+ : null;
+ const entry = target ? mappedFrom.get(targetKey(target)) : undefined;
+ return (
+ <ItemFieldRow
+ key={row.key}
+ row={row}
+ defaults={state.pushDefaults}
+ entry={entry}
+ property={
+ entry ? propertyById.get(entry.onshapePropertyId) : undefined
+ }
+ candidates={target ? candidatesFor(target, entry) : []}
+ mappingOf={mappingOf}
+ definitions={data.definitions}
+ units={data.units}
+ errors={
+ entry ? state.fieldErrors[entry.onshapePropertyId] : undefined
+ }
+ disabled={busy}
+ onSource={(property) =>
+ target && onTargetSource(target, property)
+ }
+ onDefault={onPushDefaults}
+ onEdit={(patch) =>
+ entry && onEdit(entry.onshapePropertyId, patch)
+ }
+ />
+ );
+ })}
+ {otherEntries.map((entry) => (
+ <MappingRow
+ key={entry.onshapePropertyId}
+ entry={entry}
+ property={propertyById.get(entry.onshapePropertyId)}
+ candidates={candidatesFor(entry.target, entry)}
+ mappingOf={mappingOf}
+ definitions={data.definitions}
+ units={data.units}
+ errors={state.fieldErrors[entry.onshapePropertyId]}
+ disabled={busy}
+ onSource={(property) => onTargetSource(entry.target, property)}
+ onEdit={(patch) => onEdit(entry.onshapePropertyId, patch)}
+ />
+ ))}
+ {adding ? (
+ <AddMappingRow
+ properties={addable}
+ mappedFrom={mappedFrom}
+ definitions={data.definitions}
+ disabled={busy}
+ onAdd={(property, selection) => {
+ onMap(property, selection);
+ setAdding(false);
+ }}
+ onCancel={() => setAdding(false)}
+ />
+ ) : null}
+ </ul>
+ {adding ? null : (
+ <Button
+ variant="secondary"
+ size="sm"
+ className="self-start"
+ leftIcon={<LuPlus />}
+ isDisabled={busy || addable.length === 0}
+ onClick={() => setAdding(true)}
+ >
+ Add mapping
+ </Button>
+ )}
+
+ <PanelActionBar>
+ <Button
+ className="w-full"
+ onClick={onSave}
+ isDisabled={!dirty || busy}
+ isLoading={state.saving}
+ >
+ {dirty ? "Save" : "No changes"}
+ </Button>
+ </PanelActionBar>
+ </VStack>
+ );
+}
+
+function pushDefaultsEqual(
+ a: OnshapePushDefaults,
+ b: OnshapePushDefaults
+): boolean {
+ return (
+ a.replenishmentSystem === b.replenishmentSystem &&
+ a.methodTypeForMake === b.methodTypeForMake &&
+ a.methodTypeForBuy === b.methodTypeForBuy &&
+ a.itemTrackingType === b.itemTrackingType &&
+ a.unitOfMeasureCode === b.unitOfMeasureCode
+ );
+}
+
+/** Radix Select refuses an empty item value, so "the company's unit" is named. */
+const DEFAULT_UNIT_AUTOMATIC = "__automatic__";
+
+const SOURCE_DEFAULT = "__default__";
+const SOURCE_NONE = "__none__";
+const SOURCE_PROPERTY = "property:";
+
+// Item fields a push always fills: a mapped property, else the push default
+// under `key`. The Buy items method is a default only.
+const ITEM_FIELD_ROWS: {
+ key: keyof OnshapePushDefaults;
+ field: StandardFieldId | null;
+ label: string;
+}[] = [
+ {
+ key: "replenishmentSystem",
+ field: "replenishmentSystem",
+ label: "Replenishment"
+ },
+ {
+ key: "methodTypeForMake",
+ field: "defaultMethodType",
+ label: "Default Method Type"
+ },
+ {
+ key: "methodTypeForBuy",
+ field: null,
+ label: "Default Method Type for Buy items"
+ },
+ {
+ key: "itemTrackingType",
+ field: "itemTrackingType",
+ label: "Tracking Type"
+ },
+ {
+ key: "unitOfMeasureCode",
+ field: "unitOfMeasureCode",
+ label: "Unit of Measure"
+ }
+];
+
+// Add mapping does not offer these.
+const ITEM_FIELD_ROW_FIELDS = new Set<string>(
+ ITEM_FIELD_ROWS.flatMap((row) => (row.field ? [row.field] : []))
+);
+
+type SelectOption = { value: string; label: string; helper?: string };
+
+function defaultValueOptions(
+ key: keyof OnshapePushDefaults,
+ defaults: OnshapePushDefaults,
+ units: PlanUnitOfMeasure[]
+): SelectOption[] {
+ const plain = (values: readonly string[]) =>
+ values.map((value) => ({ value, label: value }));
+ switch (key) {
+ case "replenishmentSystem":
+ return plain(ITEM_REPLENISHMENT_SYSTEMS);
+ case "methodTypeForMake":
+ return plain(
+ VALID_METHOD_TYPES_BY_REPLENISHMENT[defaults.replenishmentSystem]
+ );
+ case "methodTypeForBuy":
+ return plain(VALID_METHOD_TYPES_BY_REPLENISHMENT.Buy);
+ case "itemTrackingType":
+ return plain(ITEM_TRACKING_TYPES);
+ case "unitOfMeasureCode":
+ return [
+ {
+ value: DEFAULT_UNIT_AUTOMATIC,
+ label: "Automatic",
+ helper: "EA, or the company's first unit"
+ },
+ ...units.map((unit) => ({
+ value: unit.code,
+ label: `${unit.code} · ${unit.name}`
+ }))
+ ];
+ }
+}
+
+function defaultValueKey(
+ key: keyof OnshapePushDefaults,
+ defaults: OnshapePushDefaults
+): string {
+ return defaults[key] ?? DEFAULT_UNIT_AUTOMATIC;
+}
+
+function defaultPatch(
+ key: keyof OnshapePushDefaults,
+ value: string
+): Partial<OnshapePushDefaults> {
+ if (key === "unitOfMeasureCode") {
+ return {
+ unitOfMeasureCode: value === DEFAULT_UNIT_AUTOMATIC ? null : value
+ };
+ }
+ return { [key]: value } as Partial<OnshapePushDefaults>;
+}
+
+function FieldRow({
+ source,
+ carbon,
+ control,
+ action,
+ notes
+}: {
+ source: ReactNode;
+ carbon: ReactNode;
+ control?: ReactNode;
+ action?: ReactNode;
+ notes?: ReactNode;
+}) {
+ return (
+ <li className="flex w-full flex-col gap-1 px-3 py-1.5">
+ <div className={FIELD_ROW_GRID}>
+ <div className="min-w-0 text-sm">{source}</div>
+ <LuArrowRight
+ aria-hidden
+ className="size-3.5 justify-self-center text-muted-foreground"
+ />
+ <div className="min-w-0 text-sm">
+ {typeof carbon === "string" ? (
+ <FieldName>{carbon}</FieldName>
+ ) : (
+ carbon
+ )}
+ </div>
+ <div className="min-w-0">{control}</div>
+ <div className="flex size-8 items-center justify-center">{action}</div>
+ </div>
+ {notes ? <div className="px-1">{notes}</div> : null}
+ </li>
+ );
+}
+
+// The panel is narrower than `md`, where the shared selects and comboboxes
+// grow to touch size (h-11, text-base). Keep them at the rows' size.
+const PANEL_CONTROL = "h-8 text-sm max-md:h-8 max-md:text-sm";
+
+// The three text columns share the width, so a narrow panel shortens all three.
+const FIELD_ROW_GRID =
+ "grid w-full grid-cols-[minmax(0,1fr)_16px_minmax(0,1fr)_minmax(0,1fr)_32px] items-center gap-x-2";
+
+function FieldName({
+ children,
+ emphasis
+}: {
+ children: string;
+ emphasis?: boolean;
+}) {
+ return (
+ <TruncatedTooltipText
+ tooltip={children}
+ className={cn(
+ "line-clamp-2 break-words px-1 leading-snug",
+ emphasis && "font-medium"
+ )}
+ >
+ {children}
+ </TruncatedTooltipText>
+ );
+}
+
+function SourceText({ children }: { children: string }) {
+ return <FieldName emphasis>{children}</FieldName>;
+}
+
+/** Options another field holds (disabled) are left out. */
+function SourceSelect({
+ value,
+ label,
+ groups,
+ disabled,
+ placeholder,
+ onChange
+}: {
+ value: string | undefined;
+ label: string;
+ groups: {
+ label?: string;
+ options: (SelectOption & { disabled?: boolean })[];
+ }[];
+ disabled: boolean;
+ placeholder?: string;
+ onChange: (value: string) => void;
+}) {
+ const options: ComboboxOption[] = groups.flatMap((group) =>
+ group.options
+ .filter((option) => !option.disabled)
+ .map((option) => ({
+ value: option.value,
+ label: option.label,
+ helper:
+ [group.label, option.helper].filter(Boolean).join(" · ") || undefined
+ }))
+ );
+ return (
+ <div className="w-full min-w-0">
+ <Combobox
+ size="sm"
+ value={value}
+ options={options}
+ placeholder={placeholder}
+ disabled={disabled}
+ aria-label={label}
+ className={`w-full min-w-0 ${PANEL_CONTROL}`}
+ onChange={onChange}
+ />
+ </div>
+ );
+}
+
+function propertyOptions(
+ candidates: PanelFieldsProperty[],
+ own: FieldsDraftEntry | undefined,
+ mappingOf: Map<string, FieldsDraftEntry>,
+ definitions: PlanCustomFieldDefinition[]
+): (SelectOption & { disabled?: boolean })[] {
+ return candidates.map((candidate) => {
+ const elsewhere = mappingOf.get(candidate.propertyId);
+ const taken = elsewhere !== undefined && elsewhere !== own;
+ return {
+ value: `${SOURCE_PROPERTY}${candidate.propertyId}`,
+ label: candidate.name,
+ disabled: taken,
+ helper: taken
+ ? `Mapped to ${targetLabel(elsewhere.target, definitions)}`
+ : (VALUE_TYPE_LABEL[candidate.valueType] ?? candidate.valueType)
+ };
+ });
+}
+
+function AlwaysTag() {
+ return (
+ <span className="flex items-center gap-1.5 px-1 text-sm text-muted-foreground">
+ <LuLock aria-hidden className="size-3.5" />
+ Always
+ </span>
+ );
+}
+
+function ModeSelect({
+ mode,
+ label,
+ disabled,
+ cascades = false,
+ onChange
+}: {
+ mode: MappingMode;
+ label: string;
+ disabled: boolean;
+ cascades?: boolean;
+ onChange: (mode: MappingMode) => void;
+}) {
+ return (
+ <Select
+ value={mode}
+ onValueChange={(value) => onChange(value as MappingMode)}
+ disabled={disabled}
+ >
+ <SelectTrigger
+ size="sm"
+ className={`w-full ${PANEL_CONTROL}`}
+ aria-label={label}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent className="min-w-[300px]">
+ {MAPPING_MODES.map((value) => (
+ <SelectItem
+ key={value}
+ value={value}
+ helper={modeHelper(value, cascades)}
+ >
+ {MODE_LABEL[value]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function DefaultValueSelect({
+ options,
+ value,
+ label,
+ disabled,
+ onChange
+}: {
+ options: SelectOption[];
+ value: string;
+ label: string;
+ disabled: boolean;
+ onChange: (value: string) => void;
+}) {
+ return (
+ <Select value={value} onValueChange={onChange} disabled={disabled}>
+ <SelectTrigger
+ size="sm"
+ className={`w-full ${PANEL_CONTROL}`}
+ aria-label={label}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent className="min-w-[220px]">
+ {options.map((option) => (
+ <SelectItem
+ key={option.value}
+ value={option.value}
+ helper={option.helper}
+ >
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function targetLabel(
+ target: PropertyMapTarget,
+ definitions: PlanCustomFieldDefinition[]
+): string {
+ if (target.kind === "item") {
+ return standardField(target.field)?.label ?? target.field;
+ }
+ return (
+ definitions.find((definition) => definition.id === target.fieldId)?.name ??
+ "Deleted field"
+ );
+}
+
+function rowErrors(errors: string[] | undefined): ReactNode {
+ return errors?.map((message) => (
+ <p key={message} className="text-xs text-destructive">
+ {message}
+ </p>
+ ));
+}
+
+// Amber while an Onshape option has no Carbon value. `fallback` is the push
+// default: what a new item gets when Onshape gives no value.
+function ValuesButton({
+ entry,
+ property,
+ field,
+ units,
+ disabled,
+ fallback,
+ onEdit
+}: {
+ entry: FieldsDraftEntry;
+ property: PanelFieldsProperty | undefined;
+ field: StandardField;
+ units: PlanUnitOfMeasure[];
+ disabled: boolean;
+ fallback?: {
+ options: SelectOption[];
+ value: string;
+ onChange: (value: string) => void;
+ };
+ onEdit: (
+ patch: Partial<Pick<FieldsDraftEntry, "mode" | "translations">>
+ ) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const options = onshapeValueOptions(entry.valueType, property?.options);
+ const translations = entry.translations ?? [];
+ const untranslated = options
+ ? untranslatedOptions(field, options, translations, units)
+ : [];
+ const summary = options
+ ? `Values: ${options.length - untranslated.length} of ${options.length} mapped`
+ : `Values: ${translations.length}`;
+ return (
+ <>
+ <IconButton
+ aria-label={summary}
+ title={summary}
+ icon={untranslated.length > 0 ? <LuTriangleAlert /> : <LuListChecks />}
+ variant="ghost"
+ size="sm"
+ className={
+ untranslated.length > 0
+ ? "text-amber-600 dark:text-amber-400"
+ : undefined
+ }
+ isDisabled={disabled}
+ onClick={() => setOpen(true)}
+ />
+ {open ? (
+ <ValuesModal
+ title={`${entry.onshapeName} → ${field.label}`}
+ field={field}
+ options={options}
+ translations={translations}
+ units={units}
+ fallback={fallback}
+ onApply={(next, fallbackValue) => {
+ onEdit({ translations: next });
+ if (fallback && fallbackValue !== undefined) {
+ fallback.onChange(fallbackValue);
+ }
+ setOpen(false);
+ }}
+ onClose={() => setOpen(false)}
+ />
+ ) : null}
+ </>
+ );
+}
+
+// Unmapped, the control is the push default's value. Mapped, it is the mode, and
+// a list field's default moves into its values window.
+function ItemFieldRow({
+ row,
+ defaults,
+ entry,
+ property,
+ candidates,
+ mappingOf,
+ definitions,
+ units,
+ errors,
+ disabled,
+ onSource,
+ onDefault,
+ onEdit
+}: {
+ row: (typeof ITEM_FIELD_ROWS)[number];
+ defaults: OnshapePushDefaults;
+ entry: FieldsDraftEntry | undefined;
+ property: PanelFieldsProperty | undefined;
+ candidates: PanelFieldsProperty[];
+ mappingOf: Map<string, FieldsDraftEntry>;
+ definitions: PlanCustomFieldDefinition[];
+ units: PlanUnitOfMeasure[];
+ errors: string[] | undefined;
+ disabled: boolean;
+ onSource: (property: PanelFieldsProperty | null) => void;
+ onDefault: (patch: Partial<OnshapePushDefaults>) => void;
+ onEdit: (
+ patch: Partial<Pick<FieldsDraftEntry, "mode" | "translations">>
+ ) => void;
+}) {
+ const field = row.field ? standardField(row.field) : undefined;
+ const defaultOptions = defaultValueOptions(row.key, defaults, units);
+ const defaultValue = defaultValueKey(row.key, defaults);
+ const setDefault = (value: string) => onDefault(defaultPatch(row.key, value));
+ const source = field ? (
+ <SourceSelect
+ value={
+ entry ? `${SOURCE_PROPERTY}${entry.onshapePropertyId}` : SOURCE_DEFAULT
+ }
+ label={`${row.label}: source`}
+ groups={[
+ {
+ options: [
+ {
+ value: SOURCE_DEFAULT,
+ label: "Default",
+ helper: "The value you pick on this row"
+ }
+ ]
+ },
+ {
+ label: "Onshape property",
+ options: propertyOptions(candidates, entry, mappingOf, definitions)
+ }
+ ]}
+ disabled={disabled}
+ onChange={(value) => {
+ if (value === SOURCE_DEFAULT) {
+ if (entry) onSource(null);
+ return;
+ }
+ const chosen = candidates.find(
+ (c) => c.propertyId === value.slice(SOURCE_PROPERTY.length)
+ );
+ if (chosen) onSource(chosen);
+ }}
+ />
+ ) : (
+ <SourceText>Default</SourceText>
+ );
+ return (
+ <FieldRow
+ source={source}
+ carbon={row.label}
+ control={
+ entry ? (
+ <ModeSelect
+ mode={entry.mode}
+ label={`${row.label}: when Onshape writes it`}
+ disabled={disabled}
+ cascades={field?.cascades}
+ onChange={(mode) => onEdit({ mode })}
+ />
+ ) : (
+ <DefaultValueSelect
+ options={defaultOptions}
+ value={defaultValue}
+ label={`${row.label}: default`}
+ disabled={disabled}
+ onChange={setDefault}
+ />
+ )
+ }
+ action={
+ entry && field?.kind === "list" ? (
+ <ValuesButton
+ entry={entry}
+ property={property}
+ field={field}
+ units={units}
+ disabled={disabled}
+ fallback={{
+ options: defaultOptions,
+ value: defaultValue,
+ onChange: setDefault
+ }}
+ onEdit={onEdit}
+ />
+ ) : null
+ }
+ notes={rowErrors(errors)}
+ />
+ );
+}
+
+/** A mapped field with no push default: MPN, Sourcing, a part custom field. */
+function MappingRow({
+ entry,
+ property,
+ candidates,
+ mappingOf,
+ definitions,
+ units,
+ errors,
+ disabled,
+ onSource,
+ onEdit
+}: {
+ entry: FieldsDraftEntry;
+ /** Absent when the property is mapped from another element. */
+ property: PanelFieldsProperty | undefined;
+ candidates: PanelFieldsProperty[];
+ mappingOf: Map<string, FieldsDraftEntry>;
+ definitions: PlanCustomFieldDefinition[];
+ units: PlanUnitOfMeasure[];
+ errors: string[] | undefined;
+ disabled: boolean;
+ onSource: (property: PanelFieldsProperty | null) => void;
+ onEdit: (
+ patch: Partial<Pick<FieldsDraftEntry, "mode" | "translations">>
+ ) => void;
+}) {
+ const itemField =
+ entry.target.kind === "item"
+ ? standardField(entry.target.field)
+ : undefined;
+ const carbon = targetLabel(entry.target, definitions);
+ return (
+ <FieldRow
+ source={
+ <SourceSelect
+ value={`${SOURCE_PROPERTY}${entry.onshapePropertyId}`}
+ label={`${carbon}: source`}
+ groups={[
+ {
+ options: [
+ {
+ value: SOURCE_NONE,
+ label: "Not mapped",
+ helper: "Removes this row"
+ }
+ ]
+ },
+ {
+ label: "Onshape property",
+ options: propertyOptions(
+ candidates,
+ entry,
+ mappingOf,
+ definitions
+ )
+ }
+ ]}
+ disabled={disabled}
+ onChange={(value) => {
+ if (value === SOURCE_NONE) {
+ onSource(null);
+ return;
+ }
+ const chosen = candidates.find(
+ (c) => c.propertyId === value.slice(SOURCE_PROPERTY.length)
+ );
+ if (chosen) onSource(chosen);
+ }}
+ />
+ }
+ carbon={carbon}
+ control={
+ <ModeSelect
+ mode={entry.mode}
+ label={`${carbon}: when Onshape writes it`}
+ disabled={disabled}
+ cascades={itemField?.cascades}
+ onChange={(mode) => onEdit({ mode })}
+ />
+ }
+ action={
+ itemField?.kind === "list" ? (
+ <ValuesButton
+ entry={entry}
+ property={property}
+ field={itemField}
+ units={units}
+ disabled={disabled}
+ onEdit={onEdit}
+ />
+ ) : null
+ }
+ notes={rowErrors(errors)}
+ />
+ );
+}
+
+function AddMappingRow({
+ properties,
+ mappedFrom,
+ definitions,
+ disabled,
+ onAdd,
+ onCancel
+}: {
+ properties: PanelFieldsProperty[];
+ mappedFrom: Map<string, FieldsDraftEntry>;
+ definitions: PlanCustomFieldDefinition[];
+ disabled: boolean;
+ onAdd: (property: PanelFieldsProperty, selection: string) => void;
+ onCancel: () => void;
+}) {
+ const [propertyId, setPropertyId] = useState<string | null>(null);
+ const property = properties.find((entry) => entry.propertyId === propertyId);
+ const allowed = property ? mappableTypesFor(property.valueType) : [];
+ const customOptions = property
+ ? definitions.filter((definition) =>
+ allowed.includes(definition.dataTypeId)
+ )
+ : [];
+ const itemOptions = property
+ ? STANDARD_FIELDS.filter(
+ (field) =>
+ !ITEM_FIELD_ROW_FIELDS.has(field.id) &&
+ field.valueTypes.includes(property.valueType)
+ )
+ : [];
+ // A field another property holds stays listed, disabled, so the clash shows before the save.
+ const targetOption = (key: string, label: string) => {
+ const holder = mappedFrom.get(key)?.onshapeName ?? null;
+ return {
+ value: key,
+ label,
+ disabled: holder !== null,
+ helper: holder ? `Mapped from ${holder}` : undefined
+ };
+ };
+ const neededTypes = allowed
+ .map((dataTypeId) => CUSTOM_FIELD_TYPE_LABELS[dataTypeId])
+ .filter(Boolean)
+ .join(" or ");
+ const noTarget =
+ !!property && itemOptions.length === 0 && customOptions.length === 0;
+ return (
+ <FieldRow
+ source={
+ <SourceSelect
+ value={propertyId ?? undefined}
+ placeholder="Onshape property"
+ label="Onshape property"
+ groups={[
+ {
+ options: properties.map((entry) => ({
+ value: entry.propertyId,
+ label: entry.name,
+ helper: VALUE_TYPE_LABEL[entry.valueType] ?? entry.valueType
+ }))
+ }
+ ]}
+ disabled={disabled}
+ onChange={setPropertyId}
+ />
+ }
+ carbon={
+ <SourceSelect
+ // Remounts on a new property, so no stale field stays picked.
+ key={propertyId ?? ""}
+ value={undefined}
+ placeholder="Carbon field"
+ label="Carbon field"
+ groups={[
+ {
+ label: "Item fields",
+ options: itemOptions.map((field) =>
+ targetOption(
+ targetKey({ kind: "item", field: field.id }),
+ field.label
+ )
+ )
+ },
+ {
+ label: "Custom fields",
+ options: customOptions.map((definition) =>
+ targetOption(
+ targetKey({ kind: "customField", fieldId: definition.id }),
+ definition.name
+ )
+ )
+ }
+ ]}
+ disabled={disabled || !property || noTarget}
+ onChange={(value) => property && onAdd(property, value)}
+ />
+ }
+ action={
+ <IconButton
+ aria-label="Cancel the new mapping"
+ icon={<LuX />}
+ variant="ghost"
+ size="sm"
+ onClick={onCancel}
+ />
+ }
+ notes={
+ noTarget && property ? (
+ <p className="text-xs text-muted-foreground">
+ No Carbon field takes a {property.valueType} value
+ {neededTypes
+ ? `. Add a ${neededTypes} part custom field in Carbon to map it.`
+ : "."}
+ </p>
+ ) : null
+ }
+ />
+ );
+}
+
+type ValuesDraftRow = {
+ onshape: string;
+ /** A Carbon value, null for "No value", or TRANSLATION_UNSET for no row. */
+ carbon: string | null;
+ /** One of the Onshape list's own options. */
+ fixed: boolean;
+};
+
+// Each known Onshape option is a fixed row; one left "Not mapped" gets no
+// translation, so the review flags it. Typed rows cover values the options lack.
+function ValuesModal({
+ title,
+ field,
+ options,
+ translations,
+ units,
+ fallback,
+ onApply,
+ onClose
+}: {
+ title: string;
+ field: StandardField;
+ options: string[] | null;
+ translations: ValueTranslation[];
+ units: PlanUnitOfMeasure[];
+ fallback?: { options: SelectOption[]; value: string };
+ onApply: (translations: ValueTranslation[], fallback?: string) => void;
+ onClose: () => void;
+}) {
+ const [fallbackValue, setFallbackValue] = useState(fallback?.value);
+ const [repeated, setRepeated] = useState<number[]>([]);
+ const [rows, setRows] = useState<ValuesDraftRow[]>(() => [
+ ...(options ?? []).map((option) => {
+ const saved = translations.find((row) => sameText(row.onshape, option));
+ return {
+ onshape: option,
+ carbon: saved ? saved.carbon : TRANSLATION_UNSET,
+ fixed: true
+ };
+ }),
+ ...translations
+ .filter(
+ (row) =>
+ !(options ?? []).some((option) => sameText(option, row.onshape))
+ )
+ .map((row) => ({ ...row, fixed: false }))
+ ]);
+ const values = standardFieldValues(field, units);
+ const unitName = new Map(units.map((unit) => [unit.code, unit.name]));
+ const isUnit = field.id === "unitOfMeasureCode";
+ const update = (index: number, patch: Partial<ValuesDraftRow>) => {
+ setRepeated([]);
+ setRows((current) =>
+ current.map((row, at) => (at === index ? { ...row, ...patch } : row))
+ );
+ };
+ const apply = () => {
+ // The save refuses two rows for one value; stop it here, on the row.
+ const repeats = repeatedTranslationRows(rows);
+ if (repeats.length > 0) {
+ setRepeated(repeats);
+ return;
+ }
+ onApply(
+ rows
+ .filter(
+ (row) => row.carbon !== TRANSLATION_UNSET && row.onshape.trim() !== ""
+ )
+ .map((row) => ({ onshape: row.onshape.trim(), carbon: row.carbon })),
+ fallbackValue
+ );
+ };
+ const unsetHelper = fallback
+ ? "Uses the default, with a review warning"
+ : "Not written, with a review warning";
+ const noValueHelper = fallback ? "Uses the default" : "Not written";
+ const valueOptions: ComboboxOption[] = values.map((value) => ({
+ value,
+ label: unitName.get(value) ? `${value} · ${unitName.get(value)}` : value
+ }));
+ // A unit option with no row still lands on the unit its code or name matches;
+ // the row shows that unit muted, marked "(matched)".
+ const optionsFor = (row: ValuesDraftRow): ComboboxOption[] => {
+ const match = isUnit ? matchingUnit(row.onshape, units) : null;
+ return [
+ ...(row.fixed
+ ? [
+ match
+ ? {
+ value: TRANSLATION_UNSET,
+ label: (
+ <span className="text-muted-foreground">
+ {`${match.unit.code} · ${match.unit.name} (matched)`}
+ </span>
+ ),
+ helper: `By unit ${match.by}`
+ }
+ : {
+ value: TRANSLATION_UNSET,
+ label: "Not mapped",
+ helper: unsetHelper
+ }
+ ]
+ : []),
+ { value: TRANSLATION_NO_VALUE, label: "No value", helper: noValueHelper },
+ ...valueOptions
+ ];
+ };
+ return (
+ <Modal open onOpenChange={(open) => (open ? undefined : onClose())}>
+ <ModalContent size="medium" aria-describedby={undefined}>
+ <ModalHeader>
+ <ModalTitle>{title}</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex w-full flex-col gap-3">
+ <div className="flex w-full flex-col gap-1">
+ <div
+ className={cn(
+ VALUES_ROW_GRID,
+ "px-3 text-xs font-medium text-muted-foreground"
+ )}
+ >
+ <span className="px-1">Onshape value</span>
+ <span />
+ <span>Carbon value</span>
+ <span />
+ </div>
+ <ul className="flex w-full flex-col divide-y divide-border rounded-lg border border-border">
+ {rows.map((row, index) => (
+ // Rows have no id of their own; their order is stable while editing.
+ <li
+ key={index}
+ className={cn(VALUES_ROW_GRID, "px-3 py-1.5")}
+ >
+ {row.fixed ? (
+ <SourceText>{row.onshape}</SourceText>
+ ) : (
+ <Input
+ size="sm"
+ value={row.onshape}
+ placeholder="Onshape value"
+ aria-label={`Onshape value ${index + 1}`}
+ onChange={(event) =>
+ update(index, { onshape: event.target.value })
+ }
+ />
+ )}
+ <LuArrowRight
+ aria-hidden
+ className="size-3.5 justify-self-center text-muted-foreground"
+ />
+ <Combobox
+ size="sm"
+ className={`min-w-[160px] ${PANEL_CONTROL}`}
+ value={
+ row.carbon === TRANSLATION_UNSET
+ ? TRANSLATION_UNSET
+ : (row.carbon ?? TRANSLATION_NO_VALUE)
+ }
+ options={optionsFor(row)}
+ aria-label={`Carbon value for ${row.onshape || "this row"}`}
+ onChange={(value) => {
+ if (!value) return;
+ update(index, {
+ carbon: value === TRANSLATION_NO_VALUE ? null : value
+ });
+ }}
+ />
+ <div className="flex size-8 items-center justify-center">
+ {row.fixed ? null : (
+ <IconButton
+ aria-label={`Remove ${row.onshape || "row"}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ setRows((current) =>
+ current.filter((_, at) => at !== index)
+ )
+ }
+ />
+ )}
+ </div>
+ {repeated.includes(index) ? (
+ <span className="col-span-full px-1 text-xs text-destructive">
+ "{row.onshape.trim()}" is already listed above
+ </span>
+ ) : null}
+ </li>
+ ))}
+ {fallback ? (
+ <li className={cn(VALUES_ROW_GRID, "px-3 py-1.5")}>
+ <span className="px-1 text-sm text-muted-foreground">
+ No Onshape value or unmapped value: new items get
+ </span>
+ <LuArrowRight
+ aria-hidden
+ className="size-3.5 justify-self-center text-muted-foreground"
+ />
+ <DefaultValueSelect
+ options={fallback.options}
+ value={fallbackValue ?? fallback.value}
+ label="Value a new item gets when Onshape gives none or an unmapped one"
+ disabled={false}
+ onChange={setFallbackValue}
+ />
+ <span />
+ </li>
+ ) : null}
+ </ul>
+ </div>
+ <Button
+ variant="secondary"
+ size="sm"
+ className="self-start"
+ leftIcon={<LuPlus />}
+ onClick={() =>
+ setRows((current) => [
+ ...current,
+ { onshape: "", carbon: null, fixed: false }
+ ])
+ }
+ >
+ Add value
+ </Button>
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button onClick={apply}>Apply</Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+// The Carbon value column is wider: a unit reads "FOOT · Foot (matched)".
+const VALUES_ROW_GRID =
+ "grid w-full grid-cols-[minmax(0,2fr)_16px_minmax(0,3fr)_32px] items-center gap-x-2";
+
+type ReviewSectionProps<R extends ReviewState> = {
+ review: R;
+ onCancel: () => void;
+ onApply: () => void;
+ onReplan: () => void;
+ onEditItem: (key: string, patch: Partial<ItemFieldSnapshot>) => void;
+ replanning: boolean;
+};
+
+// -bottom-4 cancels the body's p-4: sticky pins to the scrollport inset by its
+// padding, so bottom-0 leaves a strip below the bar where rows scroll past.
+function PanelActionBar({ children }: { children: ReactNode }) {
+ return (
+ <div className="sticky -bottom-4 -mx-4 mt-1 w-[calc(100%+--spacing(8))] border-t border-border bg-card px-4 py-2">
+ {children}
+ </div>
+ );
+}
+
+function ReviewActionBar({
+ review,
+ replanning,
+ onApply
+}: {
+ review: ReviewState;
+ replanning: boolean;
+ onApply: () => void;
+}) {
+ const count = applyCount(review);
+ return (
+ <PanelActionBar>
+ <Button
+ className="w-full"
+ onClick={onApply}
+ isDisabled={review.applying || review.expired || count === 0}
+ isLoading={review.applying || replanning}
+ >
+ {count === 0 ? "Nothing to push" : `Push ${count} to Carbon`}
+ </Button>
+ </PanelActionBar>
+ );
+}
+
+function ReviewError({
+ review,
+ replanning,
+ onReplan
+}: {
+ review: ReviewState;
+ replanning: boolean;
+ onReplan: () => void;
+}) {
+ if (!review.error) return null;
+ return (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>Couldn't push</AlertTitle>
+ <AlertDescription>{review.error}</AlertDescription>
+ {review.expired ? (
+ <HStack className="mt-2">
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={onReplan}
+ isDisabled={replanning}
+ isLoading={replanning}
+ >
+ Review again
+ </Button>
+ </HStack>
+ ) : null}
+ </Alert>
+ );
+}
+
+function ReviewHeader({
+ busy,
+ onCancel
+}: {
+ busy: boolean;
+ onCancel: () => void;
+}) {
+ return (
+ <HStack className="w-full justify-between">
+ <span className="text-sm font-medium">Review → Carbon</span>
+ <Button variant="ghost" size="sm" onClick={onCancel} isDisabled={busy}>
+ Cancel
+ </Button>
+ </HStack>
+ );
+}
+
+function ReviewSummary({ counts }: { counts: Array<[number, string]> }) {
+ const parts = counts
+ .filter(([n]) => n > 0)
+ .map(([n, label]) => `${n} ${label}`);
+ return (
+ <p className="w-full text-sm">
+ {parts.length > 0 ? parts.join(" · ") : "Nothing to change"}
+ </p>
+ );
+}
+
+// The selects' seed: what an "everyPush" mapping sets, else the item's current
+// values, else the create proposal. Null for a row with no item.
+function fieldBaseline(row: {
+ proposed?: ProposedItem | null;
+ current?: ItemFieldSnapshot | null;
+ target?: ItemFieldSnapshot;
+}): ItemFieldSnapshot | null {
+ if (row.target) return row.target;
+ if (row.current) return row.current;
+ if (row.proposed) {
+ return {
+ replenishmentSystem: row.proposed.replenishmentSystem,
+ defaultMethodType: row.proposed.defaultMethodType,
+ itemTrackingType: row.proposed.itemTrackingType
+ };
+ }
+ return null;
+}
+
+const TEXT_FIELD_LABEL: Record<OwnedFieldChange["field"], string> = {
+ name: "short description",
+ description: "long description"
+};
+
+function textChangeLine(changes: OwnedFieldChange[]): string {
+ return changes
+ .map(
+ (change) =>
+ `${TEXT_FIELD_LABEL[change.field]}: ${change.from ?? "—"} → ${change.to ?? "—"}`
+ )
+ .join(" · ");
+}
+
+function TextChanges({ changes }: { changes: OwnedFieldChange[] | undefined }) {
+ if (!changes?.length) return null;
+ const line = textChangeLine(changes);
+ return (
+ <p className="mt-1 truncate text-xs text-muted-foreground" title={line}>
+ {line}
+ </p>
+ );
+}
+
+function RowMappedFields({
+ isCreate,
+ row
+}: {
+ isCreate: boolean;
+ row: MappedRowPlan;
+}) {
+ const lines: Array<{ key: string; text: string; tone: "muted" | "warn" }> =
+ [];
+ if (isCreate) {
+ for (const field of row.itemFields ?? []) {
+ lines.push({
+ key: `item:${field.field}`,
+ text: mappedValueText(field),
+ tone: "muted"
+ });
+ }
+ } else {
+ for (const change of row.itemFieldChanges ?? []) {
+ lines.push({
+ key: `change:${change.field}`,
+ text: itemFieldChangeText(change),
+ tone: "muted"
+ });
+ }
+ }
+ for (const field of row.customFields ?? []) {
+ lines.push({
+ key: `custom:${field.fieldId}`,
+ text: isCreate
+ ? `${field.name}: ${customFieldDisplayValue(field)} · from Onshape "${field.onshapeName}"`
+ : customFieldChangeText(field),
+ tone: "muted"
+ });
+ }
+ if (!isCreate) {
+ for (const kept of row.keptDifferences ?? []) {
+ lines.push({
+ key: `kept:${kept.label}`,
+ text: keptDifferenceText(kept),
+ tone: "muted"
+ });
+ }
+ }
+ // A value the push cannot write is reported and skipped.
+ for (const problem of row.mappedFieldProblems ?? []) {
+ lines.push({ key: `problem:${problem}`, text: problem, tone: "warn" });
+ }
+ if (lines.length === 0) return null;
+ return (
+ <div className="mt-1 w-full">
+ {lines.map((line) => (
+ <p
+ key={line.key}
+ className={cn(
+ "w-full text-xs",
+ line.tone === "warn"
+ ? "text-amber-600 dark:text-amber-400"
+ : "truncate text-muted-foreground"
+ )}
+ title={line.text}
+ >
+ {line.text}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+// An "update" with nothing listed re-exports the model and changes no field.
+function rowHasDetails(row: PartPlanRow): boolean {
+ return (
+ row.changes.length > 0 ||
+ (row.itemFieldChanges?.length ?? 0) > 0 ||
+ (row.customFields?.length ?? 0) > 0 ||
+ (row.keptDifferences?.length ?? 0) > 0 ||
+ (row.mappedFieldProblems?.length ?? 0) > 0
+ );
+}
+
+function CarbonOnlyNote() {
+ return (
+ <p className="w-full text-xs text-muted-foreground">{CARBON_ONLY_NOTE}</p>
+ );
+}
+
+function PartPlanBadge({ row }: { row: PartPlanRow }) {
+ switch (row.action) {
+ case "released":
+ return (
+ <Status color="purple" disableTooltip>
+ Released
+ </Status>
+ );
+ case "create":
+ return (
+ <Status color="blue" disableTooltip>
+ Create
+ </Status>
+ );
+ case "adopt":
+ return (
+ <Status color="red" disableTooltip>
+ Conflict
+ </Status>
+ );
+ case "update":
+ return (
+ <Status color="green" disableTooltip>
+ Update
+ </Status>
+ );
+ case "unchanged":
+ return (
+ <Status color="gray" disableTooltip>
+ Up to date
+ </Status>
+ );
+ case "skip-no-part-number":
+ return (
+ <Status color="gray" disableTooltip>
+ Skipped
+ </Status>
+ );
+ }
+}
+
+function PartReviewSection({
+ review,
+ onCancel,
+ onApply,
+ onReplan,
+ onEditItem,
+ replanning
+}: ReviewSectionProps<PartReview>) {
+ const { plan } = review;
+ const busy = review.applying || replanning;
+ const count = (action: PartPlanRow["action"]) =>
+ plan.rows.filter((row) => row.action === action).length;
+ const conflicts = plan.rows.filter((row) => row.action === "adopt");
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <ReviewHeader busy={busy} onCancel={onCancel} />
+ <ReviewError
+ review={review}
+ replanning={replanning}
+ onReplan={onReplan}
+ />
+
+ {plan.rows.length === 0 ? (
+ <PanelEmpty>None of the selected parts are in this element</PanelEmpty>
+ ) : (
+ <>
+ <ReviewSummary
+ counts={[
+ [count("create"), "created"],
+ [count("adopt"), "linked"],
+ [count("update"), "updated"],
+ [count("unchanged"), "up to date"],
+ [count("released"), "released"],
+ [count("skip-no-part-number"), "skipped"]
+ ]}
+ />
+
+ {conflicts.length > 0 ? (
+ <CappedWarningList
+ variant="destructive"
+ title={(n) =>
+ n === 1
+ ? "1 part matches an existing Carbon item"
+ : `${n} parts match existing Carbon items`
+ }
+ description="Same part number. Pushing links them; renumber any that are different parts."
+ lines={conflicts.map(
+ (row) =>
+ `${row.partNumber} · ${row.item?.name ?? row.name} in Carbon`
+ )}
+ />
+ ) : null}
+
+ {count("skip-no-part-number") > 0 ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ {count("skip-no-part-number") === 1
+ ? "1 part has no part number"
+ : `${count("skip-no-part-number")} parts have no part number`}
+ </AlertTitle>
+ <AlertDescription>
+ Set a part number in Onshape, then review again.
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {plan.rows.map((row) => (
+ <li key={row.partId} className="bg-card px-3 py-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <p className="truncate text-sm" title={row.name}>
+ {row.name}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {row.partNumber ?? "No part number"}
+ {row.revision ? ` · Rev ${row.revision}` : ""}
+ </p>
+ </div>
+ <div className="shrink-0">
+ <PartPlanBadge row={row} />
+ </div>
+ </div>
+ {row.action === "update" || row.action === "adopt" ? (
+ <TextChanges changes={row.changes} />
+ ) : null}
+ {(() => {
+ const baseline = fieldBaseline(row);
+ return baseline ? (
+ <ItemFieldSelects
+ baseline={baseline}
+ existing={!!row.current}
+ edit={review.edits[row.partId]}
+ disabled={busy}
+ onChange={(patch) => onEditItem(row.partId, patch)}
+ />
+ ) : null;
+ })()}
+ {row.action === "update" && !rowHasDetails(row) ? (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Only the model is exported again.
+ </p>
+ ) : null}
+ {row.action === "released" ? (
+ <ReleasedNote revision={row.item?.revision} />
+ ) : null}
+ {row.action !== "skip-no-part-number" ? (
+ <RowMappedFields
+ isCreate={row.action === "create"}
+ row={row}
+ />
+ ) : null}
+ </li>
+ ))}
+ </ul>
+
+ <CarbonOnlyNote />
+ <ReviewActionBar
+ review={review}
+ replanning={replanning}
+ onApply={onApply}
+ />
+ </>
+ )}
+ </VStack>
+ );
+}
+
+function AssemblyReviewSection({
+ review,
+ onCancel,
+ onApply,
+ onReplan,
+ onEditItem,
+ replanning
+}: ReviewSectionProps<AssemblyReview>) {
+ const { plan } = review;
+ const busy = review.applying || replanning;
+
+ const created =
+ plan.items.filter((item) => item.action === "create").length +
+ (plan.root.action === "create" ? 1 : 0);
+ const conflicts = [
+ ...(plan.root.conflict
+ ? [`${plan.root.partNumber} · ${plan.root.name ?? "this assembly"}`]
+ : []),
+ ...plan.items
+ .filter((item) => item.conflict)
+ .map((item) =>
+ item.name ? `${item.partNumber} · ${item.name}` : item.partNumber
+ )
+ ];
+ const reused =
+ plan.items.filter((item) => item.action === "reuse" && !item.conflict)
+ .length + (plan.root.action === "reuse" && !plan.root.conflict ? 1 : 0);
+
+ const described = plan.methods.map((method) =>
+ describeMethod(method, review.excluded)
+ );
+ const wontWrite = [
+ ...described.filter((d) => d.tone === "warning").map((d) => d.text),
+ ...plan.skipped
+ ];
+ const drafts = plan.methods.filter(
+ (_, index) => described[index]?.tone === "notice"
+ );
+ const newDrafts = drafts.filter(
+ (method) => method.reusedDraftVersion == null
+ ).length;
+ // A hand-added line for a part Onshape lists is taken over (quantity follows
+ // Onshape; operation and scrap stay). Others, and an excluded part's, stay.
+ const writtenMethods = plan.methods.filter(
+ (method) =>
+ method.status !== "missing" &&
+ !review.excluded.has(method.parentPartNumber)
+ );
+ const takenOver = writtenMethods.flatMap((method) =>
+ method.takesOver
+ .filter((line) => !review.excluded.has(line.readableId))
+ .map(
+ (line) =>
+ `${method.parentPartNumber}: ${line.readableId} ×${line.quantity}` +
+ (line.quantity === line.onshapeQuantity
+ ? ", quantity unchanged"
+ : ` → ×${line.onshapeQuantity}`)
+ )
+ );
+ const textChanges = [
+ ...(plan.root.changes?.length && !review.excluded.has(plan.root.partNumber)
+ ? [`${plan.root.partNumber}: ${textChangeLine(plan.root.changes)}`]
+ : []),
+ ...plan.items
+ .filter(
+ (item) => item.changes?.length && !review.excluded.has(item.partNumber)
+ )
+ .map(
+ (item) => `${item.partNumber}: ${textChangeLine(item.changes ?? [])}`
+ )
+ ];
+ const buyOrMake = replenishmentMismatches(
+ plan,
+ review.edits,
+ review.excluded
+ );
+ const keptManual = writtenMethods.flatMap((method) =>
+ [
+ ...method.keeps,
+ ...method.takesOver.filter((line) => review.excluded.has(line.readableId))
+ ].map(
+ (line) =>
+ `${method.parentPartNumber}: ${line.readableId} ×${line.quantity}`
+ )
+ );
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <ReviewHeader busy={busy} onCancel={onCancel} />
+ <ReviewError
+ review={review}
+ replanning={replanning}
+ onReplan={onReplan}
+ />
+
+ <ReviewSummary
+ counts={[
+ [created, "created"],
+ [conflicts.length, "matched by part number"],
+ [reused, "already in Carbon"],
+ [plan.methods.length, plan.methods.length === 1 ? "BOM" : "BOMs"]
+ ]}
+ />
+
+ {conflicts.length > 0 ? (
+ <CappedWarningList
+ variant="destructive"
+ title={(n) =>
+ n === 1
+ ? "1 part matches an existing Carbon item"
+ : `${n} parts match existing Carbon items`
+ }
+ description="Same part number. The push uses them in the BOM; renumber any that are different parts."
+ lines={conflicts}
+ />
+ ) : null}
+ {wontWrite.length > 0 ? (
+ <CappedWarningList
+ title={(n) =>
+ n === 1
+ ? "1 thing won't be written"
+ : `${n} things won't be written`
+ }
+ lines={wontWrite}
+ />
+ ) : null}
+ {drafts.length > 0 ? (
+ <Alert variant="info">
+ <LuInfo />
+ <AlertTitle>
+ {newDrafts === drafts.length
+ ? drafts.length === 1
+ ? "1 released method gets a new Draft version"
+ : `${drafts.length} released methods get new Draft versions`
+ : newDrafts === 0
+ ? drafts.length === 1
+ ? "1 released method is written into its Draft version"
+ : `${drafts.length} released methods are written into their Draft versions`
+ : `${drafts.length} released methods are written into Draft versions, ${newDrafts} of them new`}
+ </AlertTitle>
+ <AlertDescription>
+ Nothing live changes until someone releases them in Carbon.
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
+ {buyOrMake.length > 0 ? (
+ <CappedWarningList
+ title={(n) =>
+ n === 1
+ ? "1 item's Buy or Make doesn't match Onshape"
+ : `${n} items' Buy or Make doesn't match Onshape`
+ }
+ description="Pushed as shown. Change it below or in Onshape."
+ lines={buyOrMake}
+ />
+ ) : null}
+
+ {textChanges.length > 0 ? (
+ <CappedWarningList
+ title={(n) =>
+ n === 1
+ ? "1 item takes Onshape's short and long descriptions"
+ : `${n} items take Onshape's short and long descriptions`
+ }
+ description="Their descriptions are set to Update on every push."
+ lines={textChanges}
+ />
+ ) : null}
+
+ {takenOver.length > 0 ? (
+ <CappedWarningList
+ title={(n) =>
+ n === 1
+ ? "1 line added by hand in Carbon will follow Onshape"
+ : `${n} lines added by hand in Carbon will follow Onshape`
+ }
+ description="Quantity follows Onshape; operation and scrap stay."
+ lines={takenOver}
+ />
+ ) : null}
+
+ {keptManual.length > 0 ? (
+ <CappedWarningList
+ title={(n) =>
+ n === 1
+ ? "1 line added by hand in Carbon stays"
+ : `${n} lines added by hand in Carbon stay`
+ }
+ description="Not in Onshape's BOM, so these BOMs won't match it."
+ lines={keptManual}
+ />
+ ) : null}
+
+ {plan.depth === "top" && plan.deeper ? (
+ <Alert variant="info">
+ <LuInfo />
+ <AlertTitle>
+ {plan.deeper.partCount > 0
+ ? `This level only — ${plan.deeper.partCount} parts below are not in this push`
+ : "This level only"}
+ </AlertTitle>
+ {plan.deeper.subAssemblies.length > 0 ? (
+ <AlertDescription>
+ Not included: {plan.deeper.subAssemblies.join(", ")}
+ </AlertDescription>
+ ) : null}
+ </Alert>
+ ) : null}
+
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ <li className="bg-card px-3 py-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <p
+ className="truncate text-sm font-medium"
+ title={plan.root.name ?? plan.root.partNumber}
+ >
+ {plan.root.name ?? plan.root.partNumber}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {plan.root.partNumber}
+ {plan.root.revision ? ` · Rev ${plan.root.revision}` : ""}
+ {" · this assembly"}
+ </p>
+ </div>
+ {/* Create/Reuse is not actionable, so it is not shown. */}
+ {plan.root.conflict ? (
+ <div className="shrink-0">
+ <ItemActionBadge action="reuse" conflict />
+ </div>
+ ) : plan.root.released ? (
+ <div className="shrink-0">
+ <PartStateBadge state="released" />
+ </div>
+ ) : null}
+ </div>
+ {plan.root.released ? (
+ <ReleasedNote revision={plan.root.released.revision} />
+ ) : null}
+ {(() => {
+ const baseline = fieldBaseline(plan.root);
+ return baseline ? (
+ <ItemFieldSelects
+ baseline={baseline}
+ existing={!!plan.root.current}
+ edit={review.edits[plan.root.partNumber]}
+ disabled={busy}
+ onChange={(patch) => onEditItem(plan.root.partNumber, patch)}
+ />
+ ) : null;
+ })()}
+ <TextChanges changes={plan.root.changes} />
+ <RowMappedFields
+ isCreate={plan.root.action === "create"}
+ row={plan.root}
+ />
+ </li>
+ {plan.items.map((item) => (
+ <li key={item.partNumber} className="bg-card px-3 py-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <p
+ className="truncate text-sm"
+ title={item.name ?? item.partNumber}
+ >
+ {item.name ?? item.partNumber}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {item.partNumber}
+ {item.revision ? ` · Rev ${item.revision}` : ""}
+ {item.shownAsUnit ? " · one unit in Onshape" : ""}
+ {item.isAssembly ? " · assembly" : ""}
+ </p>
+ </div>
+ {item.conflict ? (
+ <div className="shrink-0">
+ <ItemActionBadge action="reuse" conflict />
+ </div>
+ ) : item.released ? (
+ <div className="shrink-0">
+ <PartStateBadge state="released" />
+ </div>
+ ) : null}
+ </div>
+ {item.released ? (
+ <ReleasedNote revision={item.released.revision} />
+ ) : null}
+ <TextChanges changes={item.changes} />
+ {(() => {
+ const baseline = fieldBaseline(item);
+ return baseline ? (
+ <ItemFieldSelects
+ baseline={baseline}
+ existing={!!item.current}
+ edit={review.edits[item.partNumber]}
+ disabled={busy}
+ onChange={(patch) => onEditItem(item.partNumber, patch)}
+ />
+ ) : null;
+ })()}
+ <RowMappedFields isCreate={item.action === "create"} row={item} />
+ </li>
+ ))}
+ </ul>
+
+ <CarbonOnlyNote />
+ <ReviewActionBar
+ review={review}
+ replanning={replanning}
+ onApply={onApply}
+ />
+ </VStack>
+ );
+}
+
+function releaseItemLabel(item: ReleasePlanItem): string {
+ switch (item.action) {
+ case "revision":
+ return `Rev ${item.revision} from Rev ${item.baseRevision ?? "?"}`;
+ case "create":
+ return "new item";
+ case "reuse":
+ return `already Rev ${item.revision}`;
+ case "drawing":
+ return `drawing → ${item.drawingOf?.partNumber ?? item.partNumber}${
+ item.drawingOf?.revision ? ` Rev ${item.drawingOf.revision}` : ""
+ }`;
+ case "drawing-unmatched":
+ return item.drawingOf
+ ? `drawing → ${item.drawingOf.partNumber}${
+ item.drawingOf.revision ? ` Rev ${item.drawingOf.revision}` : ""
+ } isn't in Carbon; push its release first`
+ : "drawing has no model item";
+ }
+}
+
+function ReleasePlanBadge({ item }: { item: ReleasePlanItem }) {
+ switch (item.action) {
+ case "revision":
+ return (
+ <Status color="blue" disableTooltip>
+ New revision
+ </Status>
+ );
+ case "create":
+ return (
+ <Status color="blue" disableTooltip>
+ Create
+ </Status>
+ );
+ case "reuse":
+ return (
+ <Status color="green" disableTooltip>
+ In Carbon
+ </Status>
+ );
+ case "drawing":
+ case "drawing-unmatched":
+ return (
+ <Status color="gray" disableTooltip>
+ Drawing
+ </Status>
+ );
+ }
+}
+
+function ReleaseReviewSection({
+ review,
+ onCancel,
+ onApply,
+ onReplan,
+ onEditItem,
+ replanning
+}: ReviewSectionProps<ReleaseReview>) {
+ const { plan } = review;
+ const busy = review.applying || replanning;
+ const count = (action: ReleasePlanItem["action"]) =>
+ plan.items.filter((item) => item.action === action).length;
+ const childrenCreated = plan.children.filter(
+ (child) => child.action === "create"
+ ).length;
+ const activeCount = plan.items.filter(
+ (item) => item.methodStatus === "active"
+ ).length;
+ const outcomes = [
+ review.changeNotice
+ ? review.plan.existingChangeNotice
+ ? `Adds to change notice ${review.plan.existingChangeNotice}, which an earlier push of this release made`
+ : `Records change notice "${review.changeNotice.name}"`
+ : null,
+ review.changeNotice
+ ? "New revisions stay inactive until it is released in Carbon"
+ : count("revision") + count("create") > 0
+ ? "New revisions become the default"
+ : null
+ ].filter((line): line is string => !!line);
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <ReviewHeader busy={busy} onCancel={onCancel} />
+ <ReviewError
+ review={review}
+ replanning={replanning}
+ onReplan={onReplan}
+ />
+
+ <p className="w-full text-xs text-muted-foreground">
+ {plan.releaseName ?? "Release"}
+ </p>
+ <ReviewSummary
+ counts={[
+ [
+ count("revision"),
+ count("revision") === 1 ? "new revision" : "new revisions"
+ ],
+ [count("create") + childrenCreated, "created"],
+ [count("reuse"), "already in Carbon"],
+ [count("drawing"), count("drawing") === 1 ? "drawing" : "drawings"]
+ ]}
+ />
+ {outcomes.length > 0 ? (
+ <p className="w-full text-xs text-muted-foreground">
+ {outcomes.join(" · ")}
+ </p>
+ ) : null}
+
+ {/* Not a failure: the apply leaves a method whose BOM could not be read as it is. */}
+ {review.warnings.length > 0 ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ {review.warnings.length === 1
+ ? "Couldn't read 1 BOM from Onshape"
+ : `Couldn't read ${review.warnings.length} BOMs from Onshape`}
+ </AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc space-y-1 pl-4">
+ {review.warnings.map((warning) => (
+ <li key={warning}>{warning}</li>
+ ))}
+ </ul>
+ <p className="mt-1">
+ Their BOM lines stay as they are. Review again to retry.
+ </p>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ {activeCount > 0 ? (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ {activeCount === 1
+ ? "1 item is released in Carbon"
+ : `${activeCount} items are released in Carbon`}
+ </AlertTitle>
+ <AlertDescription>
+ Their BOM lines won't change. Use a change notice in Carbon.
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {plan.items.map((item) => (
+ <li
+ key={`${item.elementId}:${item.partNumber}:${item.revision}`}
+ className="bg-card px-3 py-2"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <p className="truncate text-sm">
+ {item.partNumber}
+ <span className="text-muted-foreground">
+ {" "}
+ Rev {item.revision}
+ </span>
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {releaseItemLabel(item)}
+ </p>
+ </div>
+ <ReleasePlanBadge item={item} />
+ </div>
+ {item.methodStatus === "active" ? (
+ <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
+ Released — BOM lines won't change
+ </p>
+ ) : null}
+ {(() => {
+ const baseline = fieldBaseline(item);
+ return baseline ? (
+ <ItemFieldSelects
+ baseline={baseline}
+ existing={!!item.current}
+ edit={review.edits[item.partNumber]}
+ disabled={busy}
+ onChange={(patch) => onEditItem(item.partNumber, patch)}
+ />
+ ) : null;
+ })()}
+ <TextChanges changes={item.changes} />
+ {item.action === "create" ||
+ item.action === "reuse" ||
+ item.action === "revision" ? (
+ <RowMappedFields isCreate={item.action === "create"} row={item} />
+ ) : null}
+ {item.action === "revision" &&
+ (item.customFields?.length ?? 0) > 0 ? (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Custom fields belong to the part, not to one revision, so this
+ change shows on every revision now.
+ </p>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+
+ {plan.children.length > 0 ? (
+ <VStack spacing={1} className="w-full">
+ <span className="text-xs font-medium">
+ BOM children not in this release
+ </span>
+ <ul className="w-full divide-y divide-border rounded-md border border-border">
+ {plan.children.map((child) => (
+ <li key={child.partNumber} className="bg-card px-3 py-2">
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <p
+ className="truncate text-sm"
+ title={child.name ?? child.partNumber}
+ >
+ {child.name ?? child.partNumber}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {child.partNumber}
+ {child.revision ? ` · Rev ${child.revision}` : ""}
+ </p>
+ </div>
+ <ItemActionBadge
+ action={child.action === "create" ? "create" : "reuse"}
+ />
+ </div>
+ {child.missingRevision ? (
+ <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
+ Rev {child.missingRevision} isn't in Carbon, so the line
+ uses Rev {child.itemRevision ?? "0"}. Push the release that
+ has Rev {child.missingRevision} first.
+ </p>
+ ) : null}
+ {(() => {
+ const baseline = fieldBaseline(child);
+ return baseline ? (
+ <ItemFieldSelects
+ baseline={baseline}
+ existing={!!child.current}
+ edit={review.edits[child.partNumber]}
+ disabled={busy}
+ onChange={(patch) => onEditItem(child.partNumber, patch)}
+ />
+ ) : null;
+ })()}
+ <RowMappedFields
+ isCreate={child.action === "create"}
+ row={child}
+ />
+ </li>
+ ))}
+ </ul>
+ </VStack>
+ ) : null}
+
+ <CarbonOnlyNote />
+ <ReviewActionBar
+ review={review}
+ replanning={replanning}
+ onApply={onApply}
+ />
+ </VStack>
+ );
+}
+
+// disableTooltip: Status otherwise wraps each badge in a Radix Tooltip repeating
+// its label, and a review can run to hundreds of rows.
+function ReleaseStateBadge({ state }: { state: PanelRelease["state"] }) {
+ if (state === "pushed")
+ return (
+ <Status color="green" disableTooltip>
+ In Carbon
+ </Status>
+ );
+ if (state === "partial")
+ return (
+ <Status color="yellow" disableTooltip>
+ Partial
+ </Status>
+ );
+ return (
+ <Status color="gray" disableTooltip>
+ Not in Carbon
+ </Status>
+ );
+}
+
+/** A row a workspace push leaves alone because a release push made a revision of it. */
+function ReleasedNote({ revision }: { revision: string | null | undefined }) {
+ return (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Released in Onshape as Rev {revision ?? "?"}. Its fields change only
+ through a release.
+ </p>
+ );
+}
+
+function PartStateBadge({ state }: { state: PanelPartStatus["state"] }) {
+ if (state === "released")
+ return (
+ <Status
+ color="purple"
+ tooltip="Released in Onshape. A workspace push leaves it as it is; its changes come through a release."
+ >
+ Released
+ </Status>
+ );
+ if (state === "linked")
+ return (
+ <Status color="green" disableTooltip>
+ Linked
+ </Status>
+ );
+ if (state === "matched")
+ return (
+ <Status
+ color="red"
+ tooltip="Carbon already has an item with this part number, not linked to this one in Onshape. Pushing uses that item."
+ >
+ Conflict
+ </Status>
+ );
+ return (
+ <Status color="gray" disableTooltip>
+ Unlinked
+ </Status>
+ );
+}
+
+function ItemActionBadge({
+ action,
+ conflict
+}: {
+ action: "create" | "reuse";
+ conflict?: boolean;
+}) {
+ if (action === "reuse" && conflict) {
+ return (
+ <Status color="red" disableTooltip>
+ Conflict
+ </Status>
+ );
+ }
+ return action === "create" ? (
+ <Status color="blue" disableTooltip>
+ Create
+ </Status>
+ ) : (
+ <Status color="green" disableTooltip>
+ Reuse
+ </Status>
+ );
+}
+
+// The panel is served from the app's origin, so the mark's absolute path resolves
+// without bundling an asset.
+function PanelSignIn({
+ onSignIn,
+ disabled
+}: {
+ onSignIn: () => void;
+ disabled: boolean;
+}) {
+ return (
+ <div className="flex w-full max-w-[220px] flex-col items-center gap-6">
+ <img
+ src={CONTROLLED_ENVIRONMENT ? "/flag.png" : "/carbon-mark-light.svg"}
+ alt="Carbon"
+ className="w-24 dark:hidden"
+ />
+ <img
+ src={CONTROLLED_ENVIRONMENT ? "/flag.png" : "/carbon-mark-dark.svg"}
+ alt="Carbon"
+ className="hidden w-24 dark:block"
+ />
+ <Button className="w-full" onClick={onSignIn} isDisabled={disabled}>
+ Sign in to Carbon
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/ee/src/onshape/panel/bom-view.test.ts b/packages/ee/src/onshape/panel/bom-view.test.ts
new file mode 100644
index 0000000000..556e729887
--- /dev/null
+++ b/packages/ee/src/onshape/panel/bom-view.test.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { BomViewLine } from "./bom-view";
+import {
+ bomParentIndexes,
+ bomViewLevel,
+ buildBomViewTree,
+ visibleBomRows
+} from "./bom-view";
+
+function line(
+ index: string,
+ partNumber: string | null,
+ quantity = 1
+): BomViewLine {
+ return { index, partNumber, quantity };
+}
+
+// A sub-assembly, and a bracket listed both inside it and at the top level.
+const lines: BomViewLine[] = [
+ line("1", "PLATE-1", 2),
+ line("2", "SUB-1", 3),
+ line("2.1", "BRACKET", 4),
+ line("2.2", "SCREW", 10),
+ line("3", "BRACKET", 1)
+];
+
+describe("bomViewLevel", () => {
+ it("counts the dots", () => {
+ expect(bomViewLevel("1")).toBe(1);
+ expect(bomViewLevel("2.1")).toBe(2);
+ expect(bomViewLevel("2.1.3")).toBe(3);
+ });
+
+ it("treats an empty index as top level", () => {
+ expect(bomViewLevel("")).toBe(1);
+ });
+});
+
+describe("buildBomViewTree", () => {
+ it("nests children under the parent named by their index", () => {
+ const tree = buildBomViewTree(lines);
+ expect(tree.map((node) => node.line.index)).toEqual(["1", "2", "3"]);
+ expect(tree[1]?.children.map((node) => node.line.index)).toEqual([
+ "2.1",
+ "2.2"
+ ]);
+ });
+
+ it("orders rows numerically, not lexically", () => {
+ const tree = buildBomViewTree([
+ line("10", "TEN"),
+ line("2", "TWO"),
+ line("1", "ONE")
+ ]);
+ expect(tree.map((node) => node.line.partNumber)).toEqual([
+ "ONE",
+ "TWO",
+ "TEN"
+ ]);
+ });
+
+ it("builds the same tree whatever order the lines arrive in", () => {
+ const shuffled = [
+ line("2.1", "BRACKET", 4),
+ line("3", "BRACKET", 1),
+ line("1", "PLATE-1", 2),
+ line("2.2", "SCREW", 10),
+ line("2", "SUB-1", 3)
+ ];
+ expect(buildBomViewTree(shuffled)).toEqual(buildBomViewTree(lines));
+ });
+
+ it("keeps a line whose parent never appeared, at the top level", () => {
+ const tree = buildBomViewTree([line("1", "A"), line("4.2", "ORPHAN")]);
+ expect(tree.map((node) => node.line.index)).toEqual(["1", "4.2"]);
+ });
+});
+
+describe("visibleBomRows", () => {
+ it("shows only the top level when nothing is open", () => {
+ const rows = visibleBomRows(buildBomViewTree(lines), new Set());
+ expect(rows.map((row) => row.line.index)).toEqual(["1", "2", "3"]);
+ expect(rows.map((row) => row.level)).toEqual([1, 1, 1]);
+ });
+
+ it("marks a sub-assembly with what opening it reveals", () => {
+ const rows = visibleBomRows(buildBomViewTree(lines), new Set());
+ const sub = rows.find((row) => row.line.index === "2");
+ expect(sub).toMatchObject({
+ hasChildren: true,
+ descendantCount: 2,
+ open: false
+ });
+ expect(rows[0]).toMatchObject({ hasChildren: false, descendantCount: 0 });
+ });
+
+ it("reveals the subtree of an open sub-assembly, indented", () => {
+ const rows = visibleBomRows(buildBomViewTree(lines), new Set(["2"]));
+ expect(rows.map((row) => [row.line.index, row.level])).toEqual([
+ ["1", 1],
+ ["2", 1],
+ ["2.1", 2],
+ ["2.2", 2],
+ ["3", 1]
+ ]);
+ });
+
+ it("ignores an open index inside a closed parent", () => {
+ const deep = [...lines, line("2.1.1", "PIN")];
+ const rows = visibleBomRows(buildBomViewTree(deep), new Set(["2.1"]));
+ expect(rows.map((row) => row.line.index)).toEqual(["1", "2", "3"]);
+ });
+
+ it("counts descendants at every depth", () => {
+ const deep = [...lines, line("2.1.1", "PIN"), line("2.1.2", "WASHER")];
+ const rows = visibleBomRows(buildBomViewTree(deep), new Set(["2"]));
+ expect(rows.find((row) => row.line.index === "2")?.descendantCount).toBe(4);
+ expect(rows.find((row) => row.line.index === "2.1")?.descendantCount).toBe(
+ 2
+ );
+ });
+});
+
+describe("bomParentIndexes", () => {
+ it("lists every sub-assembly, at any depth", () => {
+ const deep = [...lines, line("2.1.1", "PIN")];
+ expect(bomParentIndexes(buildBomViewTree(deep))).toEqual(["2", "2.1"]);
+ });
+
+ it("is empty for a flat BOM", () => {
+ expect(bomParentIndexes(buildBomViewTree([line("1", "A")]))).toEqual([]);
+ });
+});
diff --git a/packages/ee/src/onshape/panel/bom-view.ts b/packages/ee/src/onshape/panel/bom-view.ts
new file mode 100644
index 0000000000..5063735a26
--- /dev/null
+++ b/packages/ee/src/onshape/panel/bom-view.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * The panel's structured BOM view, rebuilt from the dotted item numbers the
+ * status route returns. A malformed index (skipped level, missing parent)
+ * becomes a top-level row rather than a dropped line.
+ */
+
+export type BomViewLine = {
+ index: string;
+ partNumber: string | null;
+ quantity: number;
+};
+
+export type BomViewNode<T extends BomViewLine> = {
+ line: T;
+ children: BomViewNode<T>[];
+};
+
+export function bomViewLevel(index: string): number {
+ if (!index) return 1;
+ return index.split(".").length;
+}
+
+function byIndex(a: { index: string }, b: { index: string }): number {
+ return a.index.localeCompare(b.index, undefined, { numeric: true });
+}
+
+export function buildBomViewTree<T extends BomViewLine>(
+ lines: T[]
+): BomViewNode<T>[] {
+ const nodes = new Map<string, BomViewNode<T>>();
+ const roots: BomViewNode<T>[] = [];
+
+ // Shallowest first, so a parent is in the map before its children.
+ const ordered = [...lines].sort(
+ (a, b) => bomViewLevel(a.index) - bomViewLevel(b.index) || byIndex(a, b)
+ );
+
+ for (const line of ordered) {
+ const node: BomViewNode<T> = { line, children: [] };
+ nodes.set(line.index, node);
+ const dot = line.index.lastIndexOf(".");
+ const parent = dot === -1 ? undefined : nodes.get(line.index.slice(0, dot));
+ if (parent) parent.children.push(node);
+ else roots.push(node);
+ }
+
+ const sortRec = (list: BomViewNode<T>[]) => {
+ list.sort((a, b) => byIndex(a.line, b.line));
+ for (const node of list) sortRec(node.children);
+ };
+ sortRec(roots);
+ return roots;
+}
+
+export type BomViewRow<T extends BomViewLine> = {
+ line: T;
+ /** 1-based. */
+ level: number;
+ hasChildren: boolean;
+ /** Lines beneath it at any depth. */
+ descendantCount: number;
+ open: boolean;
+};
+
+/** The top level plus the subtrees of open sub-assemblies. */
+export function visibleBomRows<T extends BomViewLine>(
+ nodes: BomViewNode<T>[],
+ open: ReadonlySet<string>
+): BomViewRow<T>[] {
+ const out: BomViewRow<T>[] = [];
+ const walk = (list: BomViewNode<T>[], level: number) => {
+ for (const node of list) {
+ const hasChildren = node.children.length > 0;
+ const isOpen = hasChildren && open.has(node.line.index);
+ out.push({
+ line: node.line,
+ level,
+ hasChildren,
+ descendantCount: hasChildren ? countDescendants(node) : 0,
+ open: isOpen
+ });
+ if (isOpen) walk(node.children, level + 1);
+ }
+ };
+ walk(nodes, 1);
+ return out;
+}
+
+function countDescendants<T extends BomViewLine>(node: BomViewNode<T>): number {
+ let total = 0;
+ for (const child of node.children) total += 1 + countDescendants(child);
+ return total;
+}
+
+/** Every sub-assembly's index, for Expand all. */
+export function bomParentIndexes<T extends BomViewLine>(
+ nodes: BomViewNode<T>[]
+): string[] {
+ const out: string[] = [];
+ const walk = (list: BomViewNode<T>[]) => {
+ for (const node of list) {
+ if (node.children.length === 0) continue;
+ out.push(node.line.index);
+ walk(node.children);
+ }
+ };
+ walk(nodes);
+ return out;
+}
diff --git a/packages/ee/src/onshape/panel/bom.test.ts b/packages/ee/src/onshape/panel/bom.test.ts
new file mode 100644
index 0000000000..c3c9fada6f
--- /dev/null
+++ b/packages/ee/src/onshape/panel/bom.test.ts
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ firstOwnAssemblyPart,
+ flattenBomTree,
+ missingBomColumnsMessage,
+ parseBomTree,
+ withoutProperties
+} from "./bom";
+
+const H = [
+ { id: "h-item", name: "Item" },
+ { id: "h-pn", name: "Part number" },
+ { id: "h-rev", name: "Revision" },
+ { id: "h-name", name: "Name" },
+ { id: "h-qty", name: "Quantity" },
+ { id: "h-pl", name: "Purchasing Level" }
+];
+
+const row = (
+ item: string,
+ pn: string | null,
+ qty: unknown,
+ purchasing = "Made",
+ extra: Record<string, unknown> = {}
+) => ({
+ headerIdToValue: {
+ "h-item": item,
+ "h-pn": pn,
+ "h-rev": { displayName: "A" },
+ "h-name": `Name ${item}`,
+ "h-qty": qty,
+ "h-pl": purchasing
+ },
+ ...extra
+});
+
+describe("parseBomTree", () => {
+ it("builds the tree from dotted indexes and separates the root row", () => {
+ const { root, lines } = parseBomTree({
+ headers: H,
+ rows: [
+ row("0", "WB-100", 1),
+ row("1.1", "LEG-003", 4),
+ row("1", "SUB-001", 2),
+ row("2", "TOP-001", 1, "Purchased")
+ ]
+ });
+
+ expect(root?.partNumber).toBe("WB-100");
+ expect(lines.map((l) => l.index)).toEqual(["1", "2"]);
+ expect(lines[0]?.children.map((c) => c.partNumber)).toEqual(["LEG-003"]);
+ expect(lines[0]?.quantity).toBe(2);
+ expect(lines[0]?.revision).toBe("A");
+ });
+
+ it("keeps each row's non-empty cells as properties", () => {
+ const { lines } = parseBomTree({
+ headers: [...H, { id: "p-make", name: "Make or buy", valueType: "ENUM" }],
+ rows: [
+ {
+ headerIdToValue: {
+ "h-item": "1",
+ "h-pn": "BRG-6203",
+ "h-qty": 2,
+ "h-pl": "",
+ "p-make": { displayName: "Buy" }
+ }
+ }
+ ]
+ });
+ expect(lines[0]?.properties).toEqual([
+ { propertyId: "h-item", name: "Item", valueType: "STRING", value: "1" },
+ {
+ propertyId: "h-pn",
+ name: "Part number",
+ valueType: "STRING",
+ value: "BRG-6203"
+ },
+ { propertyId: "h-qty", name: "Quantity", valueType: "STRING", value: 2 },
+ {
+ propertyId: "p-make",
+ name: "Make or buy",
+ valueType: "ENUM",
+ value: { displayName: "Buy" }
+ }
+ ]);
+ expect(withoutProperties(lines)[0]).not.toHaveProperty("properties");
+ });
+
+ it("drops a cell Onshape fills with N/A, a property the row does not have", () => {
+ const { lines } = parseBomTree({
+ headers: [
+ ...H,
+ { id: "p-make", name: "Make or Buy", valueType: "ENUM" },
+ { id: "p-mpn", name: "MPN", valueType: "STRING" }
+ ],
+ rows: [
+ {
+ headerIdToValue: {
+ "h-item": "1",
+ "h-pn": "ASM-100",
+ "h-qty": 1,
+ "h-pl": "",
+ "p-make": "N/A",
+ "p-mpn": "N/A"
+ }
+ }
+ ]
+ });
+ expect(lines[0]?.properties?.map((property) => property.name)).toEqual([
+ "Item",
+ "Part number",
+ "Quantity"
+ ]);
+ });
+
+ it("does not read the Purchasing Level column as Buy", () => {
+ const { lines } = parseBomTree({
+ headers: H,
+ rows: [row("1", "TOP-001", 1, "Purchased")]
+ });
+ expect(lines[0]).not.toHaveProperty("purchased");
+ });
+
+ it("marks a row from Standard content", () => {
+ const { lines } = parseBomTree({
+ headers: H,
+ rows: [
+ row("1", "SCREW-M4", 8, "", {
+ itemSource: { documentId: "d", isStandardContent: true }
+ }),
+ row("2", "SCREW-M5", 8, "", { isStandardContent: true }),
+ row("3", "BRACKET-1", 1)
+ ]
+ });
+ expect(lines.map((line) => line.standardContent)).toEqual([
+ true,
+ true,
+ undefined
+ ]);
+ });
+
+ it("defaults a missing or bad quantity to 1 and survives missing columns", () => {
+ const { lines } = parseBomTree({
+ headers: H,
+ rows: [row("1", null, "not-a-number"), row("2", "X-1", null)]
+ });
+ expect(lines[0]?.quantity).toBe(1);
+ expect(lines[0]?.partNumber).toBeNull();
+ expect(lines[1]?.quantity).toBe(1);
+ });
+
+ it("keeps itemSource when present and flattens depth-first", () => {
+ const { lines } = parseBomTree({
+ headers: H,
+ rows: [
+ row("1", "A-1", 1, "Made", {
+ itemSource: { documentId: "d1", elementId: "e1", partId: "p1" }
+ }),
+ row("1.1", "A-2", 3),
+ row("2", "B-1", 1)
+ ]
+ });
+ expect(lines[0]?.itemSource?.partId).toBe("p1");
+ expect(flattenBomTree(lines).map((n) => n.index)).toEqual([
+ "1",
+ "1.1",
+ "2"
+ ]);
+ });
+
+ it("keeps the row's configuration, which a configured part's identity needs", () => {
+ const { lines } = parseBomTree({
+ headers: H,
+ rows: [
+ row("1", "A-1", 1, "Made", {
+ itemSource: {
+ documentId: "d1",
+ elementId: "e1",
+ partId: "p1",
+ configuration: "List_abc=Large"
+ }
+ })
+ ]
+ });
+ expect(lines[0]?.itemSource?.configuration).toBe("List_abc=Large");
+ });
+
+ it("tolerates an empty payload", () => {
+ const { root, lines, missingColumns } = parseBomTree(null);
+ expect(root).toBeNull();
+ expect(lines).toEqual([]);
+ expect(missingColumns).toEqual([]);
+ });
+
+ it("names a missing Item column instead of returning an empty tree as if valid", () => {
+ // Without "Item" every row reads as the root; the lines come back empty.
+ const { lines, missingColumns } = parseBomTree({
+ headers: H.filter((header) => header.name !== "Item"),
+ rows: [row("1", "A-1", 1), row("2", "B-1", 1)]
+ });
+ expect(lines).toEqual([]);
+ expect(missingColumns).toEqual(["Item"]);
+ });
+
+ it("names every missing required column", () => {
+ const { missingColumns } = parseBomTree({
+ headers: H.filter(
+ (header) => header.name !== "Item" && header.name !== "Part number"
+ ),
+ rows: [row("1", "A-1", 1)]
+ });
+ expect(missingColumns).toEqual(["Item", "Part number"]);
+ expect(missingBomColumnsMessage(missingColumns)).toContain(
+ '"Item" and "Part number"'
+ );
+ });
+
+ it("names a missing Quantity column instead of pushing every line as 1", () => {
+ const { missingColumns } = parseBomTree({
+ headers: H.filter((header) => header.name !== "Quantity"),
+ rows: [row("1", "A-1", 3)]
+ });
+ expect(missingColumns).toEqual(["Quantity"]);
+ });
+
+ it("lists three missing columns", () => {
+ expect(
+ missingBomColumnsMessage(["Item", "Part number", "Quantity"])
+ ).toContain('"Item", "Part number", and "Quantity"');
+ });
+
+ it("does not flag the headers of a BOM with no rows", () => {
+ expect(parseBomTree({ headers: [], rows: [] }).missingColumns).toEqual([]);
+ expect(
+ parseBomTree({ headers: H, rows: [row("1", "A-1", 1)] }).missingColumns
+ ).toEqual([]);
+ });
+});
+
+describe("parseBomTree Subassembly BOM behavior", () => {
+ const headers = [...H, { id: "h-sbb", name: "Subassembly BOM behavior" }];
+ const withBehavior = (item: string, pn: string, behavior: string) => {
+ const r = row(item, pn, 1);
+ return {
+ ...r,
+ headerIdToValue: { ...r.headerIdToValue, "h-sbb": behavior }
+ };
+ };
+
+ it("marks a sub-assembly Onshape shows as one unit, for structure only", () => {
+ const { lines } = parseBomTree({
+ headers,
+ rows: [
+ withBehavior("1", "ASM-009", "Show Assembly only"),
+ withBehavior("2", "ASM-008", "Show Assembly and components"),
+ withBehavior("3", "PAD-005", "N/A")
+ ]
+ });
+ expect(lines.map((line) => [line.partNumber, line.shownAsUnit])).toEqual([
+ ["ASM-009", true],
+ ["ASM-008", undefined],
+ ["PAD-005", undefined]
+ ]);
+ });
+});
+
+describe("firstOwnAssemblyPart", () => {
+ const part = (extra: Record<string, unknown>) => ({
+ documentId: "d1",
+ elementId: "e1",
+ partId: "JHD",
+ ...extra
+ });
+
+ it("takes the first part that is not Standard content, at its linked version", () => {
+ expect(
+ firstOwnAssemblyPart({
+ parts: [
+ part({ partId: "NUT", isStandardContent: true }),
+ part({ documentVersion: "v1", documentMicroversion: "m1" })
+ ]
+ })
+ ).toEqual({
+ documentId: "d1",
+ wvm: "v",
+ wvmId: "v1",
+ elementId: "e1",
+ partId: "JHD"
+ });
+ });
+
+ it("names no version for a part in the same document", () => {
+ expect(firstOwnAssemblyPart({ parts: [part({})] })).toEqual({
+ documentId: "d1",
+ wvm: null,
+ wvmId: null,
+ elementId: "e1",
+ partId: "JHD"
+ });
+ });
+
+ it("skips malformed entries and is null when no part is left", () => {
+ expect(
+ firstOwnAssemblyPart({
+ parts: [
+ part({ partId: "" }),
+ "garbage",
+ part({ isStandardContent: true })
+ ]
+ })
+ ).toBeNull();
+ expect(firstOwnAssemblyPart({})).toBeNull();
+ expect(firstOwnAssemblyPart(null)).toBeNull();
+ });
+});
diff --git a/packages/ee/src/onshape/panel/bom.ts b/packages/ee/src/onshape/panel/bom.ts
new file mode 100644
index 0000000000..0fc75a993a
--- /dev/null
+++ b/packages/ee/src/onshape/panel/bom.ts
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * Onshape indented BOM → typed tree. Columns are addressed by display name;
+ * nesting comes from the dotted "Item" index ("1.1.2"). Non-empty cells are
+ * kept as properties keyed by column id, so a row resolves through the
+ * company's property map like a part.
+ */
+
+import { isNotApplicable, type OnshapePropertyValue } from "./properties";
+
+export type OnshapeBomNode = {
+ /** Dotted position, e.g. "1.2". */
+ index: string;
+ level: number;
+ partNumber: string | null;
+ revision: string | null;
+ name: string | null;
+ description: string | null;
+ quantity: number;
+ /** "Show Assembly only": one line, no components. Not a make/buy signal. */
+ shownAsUnit?: true;
+ standardContent?: true;
+ /** Non-empty cells, one per column. Dropped before a plan is stored. */
+ properties?: OnshapePropertyValue[];
+ itemSource: {
+ documentId?: string;
+ elementId?: string;
+ partId?: string;
+ wvmType?: string;
+ wvmId?: string;
+ /** Onshape's configuration string; "default" for the default one. */
+ configuration?: string;
+ } | null;
+ children: OnshapeBomNode[];
+};
+
+type BomHeader = { id: string; name: string; valueType?: unknown };
+type BomRow = {
+ headerIdToValue?: Record<string, unknown>;
+ itemSource?: Record<string, unknown>;
+ isStandardContent?: unknown;
+};
+
+/** "Subassembly BOM behavior" label; the API returns it as text. */
+const SHOWN_AS_UNIT = "show assembly only";
+
+function cell(value: unknown): string | null {
+ if (value == null) return null;
+ if (typeof value === "object") {
+ const display = (value as Record<string, unknown>).displayName;
+ return typeof display === "string" && display.trim() !== ""
+ ? display
+ : null;
+ }
+ const text = String(value).trim();
+ return text === "" ? null : text;
+}
+
+/**
+ * Without "Item" every row reads as the root and a push would apply an empty
+ * BOM. "Part number" is the join key to Carbon. Without "Quantity" every line
+ * would push as 1.
+ */
+export const BOM_REQUIRED_COLUMNS = [
+ "Item",
+ "Part number",
+ "Quantity"
+] as const;
+
+export function parseBomTree(payload: unknown): {
+ /** The assembly's own row (index "0"), when the export included it. */
+ root: OnshapeBomNode | null;
+ lines: OnshapeBomNode[];
+ /** Non-empty: callers refuse to plan from `lines`. */
+ missingColumns: string[];
+} {
+ const bom = (payload ?? {}) as {
+ headers?: BomHeader[];
+ rows?: BomRow[];
+ };
+ const headers = Array.isArray(bom.headers) ? bom.headers : [];
+ const rows = Array.isArray(bom.rows) ? bom.rows : [];
+
+ const headerIdByName = new Map(headers.map((h) => [h.name, h.id]));
+ const missingColumns =
+ rows.length === 0
+ ? []
+ : BOM_REQUIRED_COLUMNS.filter((name) => !headerIdByName.has(name));
+ const get = (row: BomRow, name: string) => {
+ const id = headerIdByName.get(name);
+ return id ? cell(row.headerIdToValue?.[id]) : null;
+ };
+
+ const nodes: OnshapeBomNode[] = rows.map((row) => {
+ const index = get(row, "Item") ?? "";
+ const quantityText = get(row, "Quantity");
+ const quantity = quantityText ? Number(quantityText) : Number.NaN;
+ const source = row.itemSource ?? null;
+ const shownAsUnit =
+ get(row, "Subassembly BOM behavior")?.toLowerCase() === SHOWN_AS_UNIT;
+ const standardContent =
+ row.isStandardContent === true || source?.isStandardContent === true;
+ const properties: OnshapePropertyValue[] = [];
+ for (const header of headers) {
+ const value = row.headerIdToValue?.[header.id];
+ if (cell(value) === null || isNotApplicable(value)) continue;
+ properties.push({
+ propertyId: header.id,
+ name: header.name,
+ valueType:
+ typeof header.valueType === "string" ? header.valueType : "STRING",
+ value
+ });
+ }
+ return {
+ index,
+ level: index === "" ? 0 : index.split(".").length,
+ partNumber: get(row, "Part number"),
+ revision: get(row, "Revision"),
+ name: get(row, "Name"),
+ description: get(row, "Description"),
+ quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 1,
+ ...(shownAsUnit ? { shownAsUnit: true as const } : {}),
+ ...(standardContent ? { standardContent: true as const } : {}),
+ ...(properties.length > 0 ? { properties } : {}),
+ itemSource: source
+ ? {
+ documentId: cell(source.documentId) ?? undefined,
+ elementId: cell(source.elementId) ?? undefined,
+ partId: cell(source.partId) ?? undefined,
+ wvmType: cell(source.wvmType) ?? undefined,
+ wvmId: cell(source.wvmId) ?? undefined,
+ configuration: cell(source.configuration) ?? undefined
+ }
+ : null,
+ children: []
+ };
+ });
+
+ const byIndex = new Map<string, OnshapeBomNode>();
+ const lines: OnshapeBomNode[] = [];
+ let root: OnshapeBomNode | null = null;
+
+ // Sort by depth so parents exist before children regardless of row order.
+ for (const node of [...nodes].sort((a, b) => a.level - b.level)) {
+ if (node.index === "" || node.index === "0") {
+ root = node;
+ continue;
+ }
+ byIndex.set(node.index, node);
+ const dot = node.index.lastIndexOf(".");
+ if (dot === -1) {
+ lines.push(node);
+ } else {
+ const parent = byIndex.get(node.index.substring(0, dot));
+ if (parent) {
+ parent.children.push(node);
+ } else {
+ lines.push(node);
+ }
+ }
+ }
+
+ const sortRec = (list: OnshapeBomNode[]) => {
+ list.sort((a, b) =>
+ a.index.localeCompare(b.index, undefined, { numeric: true })
+ );
+ for (const item of list) sortRec(item.children);
+ };
+ sortRec(lines);
+
+ return { root, lines, missingColumns };
+}
+
+export type AssemblyPartSource = {
+ documentId: string;
+ /** "v" for a part linked from a version; null for one in this document. */
+ wvm: "v" | null;
+ wvmId: string | null;
+ elementId: string;
+ partId: string;
+};
+
+/**
+ * First non-Standard-content part of an assembly definition: its metadata
+ * lists the part-scoped properties an assembly's metadata lacks.
+ */
+export function firstOwnAssemblyPart(
+ definition: unknown
+): AssemblyPartSource | null {
+ const parts =
+ definition && typeof definition === "object"
+ ? (definition as { parts?: unknown }).parts
+ : null;
+ if (!Array.isArray(parts)) return null;
+ for (const part of parts) {
+ if (!part || typeof part !== "object") continue;
+ const entry = part as Record<string, unknown>;
+ if (entry.isStandardContent === true) continue;
+ const { documentId, elementId, partId, documentVersion } = entry;
+ if (
+ typeof documentId !== "string" ||
+ typeof elementId !== "string" ||
+ typeof partId !== "string" ||
+ documentId === "" ||
+ elementId === "" ||
+ partId === ""
+ ) {
+ continue;
+ }
+ const version =
+ typeof documentVersion === "string" && documentVersion !== ""
+ ? documentVersion
+ : null;
+ return {
+ documentId,
+ wvm: version ? "v" : null,
+ wvmId: version,
+ elementId,
+ partId
+ };
+ }
+ return null;
+}
+
+export function withoutProperties(nodes: OnshapeBomNode[]): OnshapeBomNode[] {
+ return nodes.map(({ properties: _properties, children, ...node }) => ({
+ ...node,
+ children: withoutProperties(children)
+ }));
+}
+
+export function missingBomColumnsMessage(missingColumns: string[]): string {
+ const names = new Intl.ListFormat("en", {
+ style: "long",
+ type: "conjunction"
+ }).format(missingColumns.map((name) => `"${name}"`));
+ const plural = missingColumns.length > 1;
+ return `Onshape's BOM for this assembly has no ${names} column${
+ plural ? "s" : ""
+ }. Add ${plural ? "them" : "it"} back to the assembly's BOM table in Onshape, then try again.`;
+}
+
+export function flattenBomTree(lines: OnshapeBomNode[]): OnshapeBomNode[] {
+ const out: OnshapeBomNode[] = [];
+ const walk = (list: OnshapeBomNode[]) => {
+ for (const node of list) {
+ out.push(node);
+ walk(node.children);
+ }
+ };
+ walk(lines);
+ return out;
+}
+
+/** Non-empty string value of a named property in Onshape metadata. */
+export function metadataProperty(
+ payload: unknown,
+ name: string
+): string | null {
+ const properties = (payload as { properties?: unknown })?.properties;
+ if (!Array.isArray(properties)) return null;
+ for (const property of properties) {
+ const p = property as { name?: unknown; value?: unknown };
+ if (p.name === name) {
+ const value = p.value;
+ if (typeof value === "string" && value.trim() !== "") return value;
+ return null;
+ }
+ }
+ return null;
+}
diff --git a/packages/ee/src/onshape/panel/item-values.ts b/packages/ee/src/onshape/panel/item-values.ts
new file mode 100644
index 0000000000..d5e7582a22
--- /dev/null
+++ b/packages/ee/src/onshape/panel/item-values.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// Copies of the item enums (packages/database, apps/erp shared.models). A leaf
+// module: plan.ts imports standard-fields.ts, so they cannot live in plan.ts.
+
+export const ITEM_REPLENISHMENT_SYSTEMS = [
+ "Buy",
+ "Make",
+ "Buy and Make"
+] as const;
+export const ITEM_METHOD_TYPES = [
+ "Make to Order",
+ "Pull from Inventory",
+ "Purchase to Order"
+] as const;
+export const ITEM_TRACKING_TYPES = [
+ "Inventory",
+ "Non-Inventory",
+ "Serial",
+ "Batch"
+] as const;
+export const ITEM_SOURCING_TYPES = [
+ "Specified",
+ "Drop Ship",
+ "Ship from Inventory"
+] as const;
+
+export type ItemReplenishmentSystem =
+ (typeof ITEM_REPLENISHMENT_SYSTEMS)[number];
+export type ItemMethodType = (typeof ITEM_METHOD_TYPES)[number];
+export type ItemTrackingType = (typeof ITEM_TRACKING_TYPES)[number];
+export type ItemSourcingType = (typeof ITEM_SOURCING_TYPES)[number];
+
+/**
+ * A copy of `validMethodTypesByReplenishment` (apps/erp shared.models):
+ * @carbon/ee cannot import the app.
+ */
+export const VALID_METHOD_TYPES_BY_REPLENISHMENT: Record<
+ ItemReplenishmentSystem,
+ readonly ItemMethodType[]
+> = {
+ Buy: ["Pull from Inventory", "Purchase to Order"],
+ Make: ["Pull from Inventory", "Make to Order"],
+ "Buy and Make": ["Pull from Inventory", "Purchase to Order"]
+};
diff --git a/packages/ee/src/onshape/panel/messages.test.ts b/packages/ee/src/onshape/panel/messages.test.ts
new file mode 100644
index 0000000000..79fd9168d6
--- /dev/null
+++ b/packages/ee/src/onshape/panel/messages.test.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ isOnshapeServerOrigin,
+ isPanelSessionMessage,
+ parsePanelContext
+} from "./messages";
+
+describe("isOnshapeServerOrigin", () => {
+ it("accepts cad, enterprise and dev origins", () => {
+ expect(isOnshapeServerOrigin("https://cad.onshape.com")).toBe(true);
+ expect(isOnshapeServerOrigin("https://acme.onshape.com")).toBe(true);
+ expect(isOnshapeServerOrigin("https://demo-c.dev.onshape.com")).toBe(true);
+ });
+
+ it("rejects look-alikes, http and paths", () => {
+ expect(isOnshapeServerOrigin("https://onshape.com.evil.io")).toBe(false);
+ expect(isOnshapeServerOrigin("http://cad.onshape.com")).toBe(false);
+ expect(isOnshapeServerOrigin("https://cad.onshape.com/x")).toBe(false);
+ expect(isOnshapeServerOrigin(null)).toBe(false);
+ });
+});
+
+describe("parsePanelContext", () => {
+ it("reads the action-url parameters and the Onshape-appended ones", () => {
+ const { context, serverOrigin } = parsePanelContext(
+ new URLSearchParams(
+ "documentId=d1&wv=w&wvId=w1&elementId=e1&partNumber=&revision=&nodeId=n1&occurrencePath=&configuration=default&server=https://cad.onshape.com&companyId=c1&userId=u1&locale=en_US&clientId=abc"
+ )
+ );
+ expect(context.documentId).toBe("d1");
+ expect(context.wv).toBe("w");
+ expect(context.wvId).toBe("w1");
+ expect(context.elementId).toBe("e1");
+ expect(context.partNumber).toBeNull();
+ expect(context.nodeId).toBe("n1");
+ expect(context.configuration).toBe("default");
+ expect(context.companyId).toBe("c1");
+ expect(serverOrigin).toBe("https://cad.onshape.com");
+ });
+
+ it("treats an unresolved placeholder as absent", () => {
+ const { context } = parsePanelContext(
+ new URLSearchParams(
+ "partNumber=%7B%24partNumber%7D&revision=%7B%24revision%7D&configuration=%7B%24configuration%7D&nodeId=n1"
+ )
+ );
+ expect(context.partNumber).toBeNull();
+ expect(context.revision).toBeNull();
+ expect(context.configuration).toBeNull();
+ expect(context.nodeId).toBe("n1");
+ });
+
+ it("drops an untrusted server and an unknown wv", () => {
+ const { context, serverOrigin } = parsePanelContext(
+ new URLSearchParams("wv=x&server=https://evil.example")
+ );
+ expect(context.wv).toBeNull();
+ expect(serverOrigin).toBeNull();
+ });
+});
+
+describe("isPanelSessionMessage", () => {
+ it("requires the type and a string token", () => {
+ expect(
+ isPanelSessionMessage({
+ type: "carbon_onshape_panel_session",
+ token: "cps_x"
+ })
+ ).toBe(true);
+ expect(
+ isPanelSessionMessage({ type: "carbon_onshape_panel_session" })
+ ).toBe(false);
+ expect(isPanelSessionMessage("carbon_onshape_panel_session")).toBe(false);
+ });
+});
diff --git a/packages/ee/src/onshape/panel/messages.ts b/packages/ee/src/onshape/panel/messages.ts
new file mode 100644
index 0000000000..690ad463c6
--- /dev/null
+++ b/packages/ee/src/onshape/panel/messages.ts
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// The Onshape iframe contract: context arrives as query parameters, messages
+// over postMessage, and every Onshape message must come from the `server`
+// origin the panel was loaded with. Client-safe: no server imports.
+
+/** cad.onshape.com, enterprise `<name>.onshape.com`, and Onshape's dev stacks. */
+const ONSHAPE_SERVER_PATTERN = /^https:\/\/([a-z0-9-]+\.)*onshape\.com$/i;
+
+export function isOnshapeServerOrigin(value: unknown): value is string {
+ return typeof value === "string" && ONSHAPE_SERVER_PATTERN.test(value);
+}
+
+/** The query parameters the dev-portal action URL asks Onshape to substitute. */
+export type OnshapePanelContext = {
+ documentId: string | null;
+ /** `w` workspace, `v` version, `m` microversion. */
+ wv: "w" | "v" | "m" | null;
+ wvId: string | null;
+ elementId: string | null;
+ partNumber: string | null;
+ revision: string | null;
+ nodeId: string | null;
+ occurrencePath: string | null;
+ configuration: string | null;
+ /** Appended by Onshape itself. */
+ companyId: string | null;
+ userId: string | null;
+ locale: string | null;
+ clientId: string | null;
+};
+
+function param(searchParams: URLSearchParams, name: string) {
+ const value = searchParams.get(name);
+ if (value === null) return null;
+ const trimmed = value.trim();
+ // Onshape sends an unresolved parameter as its literal placeholder
+ // (`{$partNumber}` with nothing selected) or as the empty string.
+ if (trimmed === "" || /^\{\$[A-Za-z]+\}$/.test(trimmed)) return null;
+ return trimmed;
+}
+
+export function parsePanelContext(searchParams: URLSearchParams): {
+ context: OnshapePanelContext;
+ serverOrigin: string | null;
+} {
+ const wv = param(searchParams, "wv");
+ const server = param(searchParams, "server");
+
+ return {
+ context: {
+ documentId: param(searchParams, "documentId"),
+ wv: wv === "w" || wv === "v" || wv === "m" ? wv : null,
+ wvId: param(searchParams, "wvId"),
+ elementId: param(searchParams, "elementId"),
+ partNumber: param(searchParams, "partNumber"),
+ revision: param(searchParams, "revision"),
+ nodeId: param(searchParams, "nodeId"),
+ occurrencePath: param(searchParams, "occurrencePath"),
+ configuration: param(searchParams, "configuration"),
+ companyId: param(searchParams, "companyId"),
+ userId: param(searchParams, "userId"),
+ locale: param(searchParams, "locale"),
+ clientId: param(searchParams, "clientId")
+ },
+ // Anything else means Onshape did not open the page.
+ serverOrigin: isOnshapeServerOrigin(server) ? server : null
+ };
+}
+
+/** Sent once the panel is ready; Onshape sends SELECTION after it. */
+export function postApplicationInit(
+ context: OnshapePanelContext,
+ serverOrigin: string
+) {
+ window.parent.postMessage(
+ {
+ documentId: context.documentId,
+ workspaceId: context.wvId,
+ elementId: context.elementId,
+ messageName: "applicationInit"
+ },
+ serverOrigin
+ );
+}
+
+/** A message from the Onshape client. Only `messageName` is guaranteed. */
+export type OnshapeClientMessage = { messageName: string } & Record<
+ string,
+ unknown
+>;
+
+export function isOnshapeClientMessage(
+ data: unknown
+): data is OnshapeClientMessage {
+ return (
+ typeof data === "object" &&
+ data !== null &&
+ typeof (data as Record<string, unknown>).messageName === "string"
+ );
+}
+
+/** The auth popup posts the panel session token with this; same origin only. */
+export const PANEL_SESSION_MESSAGE = "carbon_onshape_panel_session" as const;
+
+export type PanelSessionMessage = {
+ type: typeof PANEL_SESSION_MESSAGE;
+ token: string;
+};
+
+export function isPanelSessionMessage(
+ data: unknown
+): data is PanelSessionMessage {
+ return (
+ typeof data === "object" &&
+ data !== null &&
+ (data as Record<string, unknown>).type === PANEL_SESSION_MESSAGE &&
+ typeof (data as Record<string, unknown>).token === "string"
+ );
+}
diff --git a/packages/ee/src/onshape/panel/method-version.test.ts b/packages/ee/src/onshape/panel/method-version.test.ts
new file mode 100644
index 0000000000..85f08d7692
--- /dev/null
+++ b/packages/ee/src/onshape/panel/method-version.test.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ correlateCopiedLines,
+ pairOwnedCopiedLines,
+ pickReusableDraft
+} from "./method-version";
+
+const line = (id: string, itemId: string | null, order: number | null) => ({
+ id,
+ itemId,
+ order
+});
+
+describe("correlateCopiedLines", () => {
+ it("pairs each source line with the copy of the same component", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", 1), line("s2", "item-b", 2)],
+ [line("t1", "item-a", 1), line("t2", "item-b", 2)]
+ );
+ expect(paired.get("s1")).toBe("t1");
+ expect(paired.get("s2")).toBe("t2");
+ });
+
+ it("keeps repeated components distinct, in order", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", 1), line("s2", "item-a", 5)],
+ [line("t2", "item-a", 5), line("t1", "item-a", 1)]
+ );
+ expect(paired.get("s1")).toBe("t1");
+ expect(paired.get("s2")).toBe("t2");
+ });
+
+ it("ignores a component the copy does not contain", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", 1), line("s2", "item-gone", 2)],
+ [line("t1", "item-a", 1)]
+ );
+ expect(paired.get("s1")).toBe("t1");
+ expect(paired.has("s2")).toBe(false);
+ });
+
+ it("leaves the surplus unmapped when the copy has fewer of a component", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", 1), line("s2", "item-a", 2)],
+ [line("t1", "item-a", 1)]
+ );
+ expect(paired.get("s1")).toBe("t1");
+ expect(paired.has("s2")).toBe(false);
+ expect(paired.size).toBe(1);
+ });
+
+ it("never maps two source lines onto the same copy", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", 1), line("s2", "item-a", 1)],
+ [line("t1", "item-a", 1), line("t2", "item-a", 1)]
+ );
+ expect(new Set(paired.values()).size).toBe(paired.size);
+ });
+
+ it("skips lines with no component rather than guessing", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", null, 1)],
+ [line("t1", null, 1)]
+ );
+ expect(paired.size).toBe(0);
+ });
+
+ it("tolerates a null order on either side", () => {
+ const paired = correlateCopiedLines(
+ [line("s1", "item-a", null)],
+ [line("t1", "item-a", null)]
+ );
+ expect(paired.get("s1")).toBe("t1");
+ });
+});
+
+describe("pairOwnedCopiedLines", () => {
+ const owned = (id: string, itemId: string, order: number, quantity = 1) => ({
+ id,
+ itemId,
+ order,
+ quantity
+ });
+
+ it("does not let an owned line take a manual line's copy", () => {
+ // Manual m1 sits before owned o1 on the same component.
+ const paired = pairOwnedCopiedLines(
+ [owned("m1", "item-a", 1), owned("o1", "item-a", 2)],
+ [line("t1", "item-a", 1), line("t2", "item-a", 2)],
+ new Set(["o1"])
+ );
+ expect(paired.get("o1")).toBe("t2");
+ expect(paired.has("m1")).toBe(false);
+ });
+
+ it("skips source lines the copy dropped for a zero quantity", () => {
+ const paired = pairOwnedCopiedLines(
+ [owned("z1", "item-a", 1, 0), owned("o1", "item-a", 2)],
+ [line("t1", "item-a", 2)],
+ new Set(["z1", "o1"])
+ );
+ expect(paired.get("o1")).toBe("t1");
+ expect(paired.has("z1")).toBe(false);
+ });
+
+ it("keeps a null quantity, which the copy keeps too", () => {
+ const paired = pairOwnedCopiedLines(
+ [{ id: "o1", itemId: "item-a", order: 1, quantity: null }],
+ [line("t1", "item-a", 1)],
+ new Set(["o1"])
+ );
+ expect(paired.get("o1")).toBe("t1");
+ });
+});
+
+describe("pickReusableDraft", () => {
+ const draft = (
+ id: string,
+ version: number,
+ changeOrderId: string | null = null
+ ) => ({
+ id,
+ version,
+ changeOrderId
+ });
+
+ it("reuses the newest Draft this integration made from the Active method", () => {
+ const chosen = pickReusableDraft(
+ [draft("d2", 2), draft("d3", 3)],
+ [
+ { draftId: "d2", sourceMethodId: "active" },
+ { draftId: "d3", sourceMethodId: "active" }
+ ],
+ "active"
+ );
+ expect(chosen?.id).toBe("d3");
+ });
+
+ it("never reuses a Draft without a marker (a person's, or a failed copy)", () => {
+ expect(pickReusableDraft([draft("d2", 2)], [], "active")).toBeNull();
+ });
+
+ it("never reuses a change notice's Draft", () => {
+ expect(
+ pickReusableDraft(
+ [draft("d2", 2, "co-1")],
+ [{ draftId: "d2", sourceMethodId: "active" }],
+ "active"
+ )
+ ).toBeNull();
+ });
+
+ it("never reuses a Draft copied from an older Active version", () => {
+ expect(
+ pickReusableDraft(
+ [draft("d2", 2)],
+ [{ draftId: "d2", sourceMethodId: "older-active" }],
+ "active"
+ )
+ ).toBeNull();
+ });
+});
diff --git a/packages/ee/src/onshape/panel/method-version.ts b/packages/ee/src/onshape/panel/method-version.ts
new file mode 100644
index 0000000000..83ea37482b
--- /dev/null
+++ b/packages/ee/src/onshape/panel/method-version.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * Pairs a Draft copy's lines with the Active method's so push-ownership
+ * mappings survive the copy, which has new line ids and no back-pointer.
+ * Pairs by component item, then `order`; an unpaired line reads as manual.
+ */
+
+export type CorrelatableLine = {
+ id: string;
+ itemId: string | null;
+ order: number | null;
+};
+
+export function correlateCopiedLines(
+ source: CorrelatableLine[],
+ target: CorrelatableLine[]
+): Map<string, string> {
+ const byItem = new Map<string, CorrelatableLine[]>();
+ for (const line of target) {
+ if (!line.itemId) continue;
+ const list = byItem.get(line.itemId) ?? [];
+ list.push(line);
+ byItem.set(line.itemId, list);
+ }
+ // A copy may not keep row order, so both sides sort by `order`, then id.
+ for (const list of byItem.values()) list.sort(byOrderThenId);
+
+ const consumed = new Map<string, number>();
+ const paired = new Map<string, string>();
+ for (const line of [...source].sort(byOrderThenId)) {
+ if (!line.itemId) continue;
+ const candidates = byItem.get(line.itemId);
+ if (!candidates) continue;
+ const taken = consumed.get(line.itemId) ?? 0;
+ const match = candidates[taken];
+ if (!match) continue;
+ consumed.set(line.itemId, taken + 1);
+ paired.set(line.id, match.id);
+ }
+ return paired;
+}
+
+function byOrderThenId(a: CorrelatableLine, b: CorrelatableLine): number {
+ const left = a.order ?? Number.MAX_SAFE_INTEGER;
+ const right = b.order ?? Number.MAX_SAFE_INTEGER;
+ if (left !== right) return left - right;
+ return a.id.localeCompare(b.id);
+}
+
+/** entityType of the mapping row that marks a Draft the push made. */
+export const DRAFT_MARKER_ENTITY_TYPE = "makeMethod";
+
+export type DraftCandidate = {
+ id: string;
+ version: number | null;
+ /** Set when a change notice owns the Draft. */
+ changeOrderId: string | null;
+};
+
+export type DraftMarker = {
+ draftId: string;
+ sourceMethodId: string | null;
+};
+
+/**
+ * Newest Draft the push made from the current Active method that no change
+ * notice holds: a person's Draft or a half-built copy has no marker to match.
+ */
+export function pickReusableDraft(
+ drafts: DraftCandidate[],
+ markers: DraftMarker[],
+ activeMethodId: string
+): DraftCandidate | null {
+ const madeFromActive = new Set(
+ markers
+ .filter((marker) => marker.sourceMethodId === activeMethodId)
+ .map((marker) => marker.draftId)
+ );
+ let chosen: DraftCandidate | null = null;
+ for (const draft of drafts) {
+ if (draft.changeOrderId || !madeFromActive.has(draft.id)) continue;
+ if (!chosen || (draft.version ?? 0) > (chosen.version ?? 0)) chosen = draft;
+ }
+ return chosen;
+}
+
+/**
+ * Pairs over every source line so an owned line cannot claim a manual line's
+ * copy on the same component; returns owned lines only. Zero-quantity lines
+ * are skipped because the copy drops them.
+ */
+export function pairOwnedCopiedLines(
+ source: Array<CorrelatableLine & { quantity: number | null }>,
+ target: CorrelatableLine[],
+ ownedIds: ReadonlySet<string>
+): Map<string, string> {
+ // Only a real 0: the copy keeps a null quantity (it reads as 1).
+ const paired = correlateCopiedLines(
+ source.filter((line) => line.quantity !== 0),
+ target
+ );
+ for (const sourceId of paired.keys()) {
+ if (!ownedIds.has(sourceId)) paired.delete(sourceId);
+ }
+ return paired;
+}
diff --git a/packages/ee/src/onshape/panel/plan.test.ts b/packages/ee/src/onshape/panel/plan.test.ts
new file mode 100644
index 0000000000..c059bf9d4e
--- /dev/null
+++ b/packages/ee/src/onshape/panel/plan.test.ts
@@ -0,0 +1,2347 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { OnshapeBomNode } from "./bom";
+import {
+ assemblyTextChanges,
+ bomLineItemType,
+ buildAssemblyPlan,
+ buildPartPlan,
+ buildReleasePlan,
+ changeNoticeDescriptionJson,
+ currentItemFields,
+ defaultUnitOfMeasureCode,
+ mergeChangeNoticeEdit,
+ mergeEditsForCreates,
+ mergeExistingItemEdits,
+ mergeItemEdits,
+ pairManualLines,
+ pickAdoptTarget,
+ pickBomChildRow,
+ pickLatestRow,
+ pickReuseRow,
+ pickRevisionBase,
+ planCreatedItem,
+ planExistingItem,
+ proposeItem,
+ proposeMappedItem,
+ reconcileMethodForReplenishment,
+ withRefusedMethods
+} from "./plan";
+import { DEFAULT_PUSH_DEFAULTS } from "./preferences";
+import type { PlanItemField, PropertyMapEntry } from "./properties";
+import type { PanelRelease } from "./releases";
+
+const options = {
+ unitsOfMeasure: [
+ { code: "EA", name: "Each" },
+ { code: "M", name: "Meter" }
+ ],
+ defaults: DEFAULT_PUSH_DEFAULTS
+};
+
+const node = (over: Partial<OnshapeBomNode> = {}): OnshapeBomNode => ({
+ index: "1",
+ level: 1,
+ partNumber: "PAD-005",
+ revision: null,
+ name: "Foot pad",
+ description: null,
+ quantity: 1,
+ itemSource: null,
+ children: [],
+ ...over
+});
+
+describe("proposeItem", () => {
+ it("defaults an in-house part to Make / Make to Order / Inventory / EA", () => {
+ expect(
+ proposeItem({ partNumber: "PAD-005", name: "Foot pad" }, options)
+ ).toEqual({
+ readableId: "PAD-005",
+ revision: "0",
+ name: "Foot pad",
+ description: null,
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory",
+ unitOfMeasureCode: "EA"
+ });
+ });
+
+ it("defaults a Standard content BOM row to Buy / Pull from Inventory", () => {
+ const item = proposeItem(
+ {
+ partNumber: "HDW-010",
+ name: null,
+ standardContent: true,
+ revision: "B"
+ },
+ options
+ );
+ expect(item.replenishmentSystem).toBe("Buy");
+ expect(item.defaultMethodType).toBe("Pull from Inventory");
+ expect(item.name).toBe("HDW-010");
+ expect(item.revision).toBe("B");
+ });
+
+ it("never proposes a unit the company lacks", () => {
+ expect(
+ defaultUnitOfMeasureCode({
+ unitsOfMeasure: [{ code: "PC", name: "x" }],
+ defaults: DEFAULT_PUSH_DEFAULTS
+ })
+ ).toBe("PC");
+ expect(
+ defaultUnitOfMeasureCode({
+ unitsOfMeasure: [],
+ defaults: DEFAULT_PUSH_DEFAULTS
+ })
+ ).toBe("EA");
+ });
+});
+
+describe("mergeItemEdits", () => {
+ const proposed = proposeItem(
+ { partNumber: "PAD-005", name: "Foot pad" },
+ options
+ );
+
+ it("applies valid edits and trims text", () => {
+ const merged = mergeItemEdits(
+ proposed,
+ {
+ name: " Rubber foot pad ",
+ description: " Nitrile ",
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Purchase to Order",
+ itemTrackingType: "Batch",
+ unitOfMeasureCode: "M"
+ },
+ options
+ );
+ expect(merged).toEqual({
+ ok: true,
+ item: {
+ ...proposed,
+ name: "Rubber foot pad",
+ description: "Nitrile",
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Purchase to Order",
+ itemTrackingType: "Batch",
+ unitOfMeasureCode: "M"
+ }
+ });
+ });
+
+ it("refuses an empty name, unknown enums and foreign units", () => {
+ const merged = mergeItemEdits(
+ proposed,
+ {
+ name: " ",
+ replenishmentSystem: "Steal" as never,
+ defaultMethodType: "Wish" as never,
+ itemTrackingType: "Lot" as never,
+ unitOfMeasureCode: "KG"
+ },
+ options
+ );
+ expect(merged.ok).toBe(false);
+ if (merged.ok) return;
+ expect(merged.errors).toEqual([
+ "Name is required",
+ "Replenishment system is not valid",
+ "Default method type is not valid",
+ "Tracking type is not valid",
+ "Unit of measure is not one of the company's units"
+ ]);
+ });
+
+ it("holds the merged pair to the replenishment/method interlock", () => {
+ const merged = mergeItemEdits(
+ proposed,
+ { defaultMethodType: "Purchase to Order" },
+ options
+ );
+ expect(merged).toEqual({
+ ok: false,
+ errors: ["Purchase to Order is not a valid method for Make items"]
+ });
+ // Changing both sides together is fine.
+ expect(
+ mergeItemEdits(
+ proposed,
+ { replenishmentSystem: "Buy", defaultMethodType: "Purchase to Order" },
+ options
+ ).ok
+ ).toBe(true);
+ });
+
+ it("ignores locked and unknown keys", () => {
+ const merged = mergeItemEdits(
+ proposed,
+ { readableId: "HACK", revision: "Z", foo: 1 } as never,
+ options
+ );
+ expect(merged).toEqual({ ok: true, item: proposed });
+ });
+
+ it("merges edits for many creates, reporting errors per key", () => {
+ const { items, errors } = mergeEditsForCreates(
+ [
+ { key: "a", proposed },
+ { key: "b", proposed }
+ ],
+ { a: { name: "A" }, b: { name: "" } },
+ options
+ );
+ expect(items.get("a")?.name).toBe("A");
+ expect(items.has("b")).toBe(false);
+ expect(errors).toEqual([{ key: "b", errors: ["Name is required"] }]);
+ });
+});
+
+describe("reconcileMethodForReplenishment", () => {
+ it("keeps a legal method and swaps an illegal one for the first allowed", () => {
+ expect(reconcileMethodForReplenishment("Make", "Make to Order")).toBe(
+ "Make to Order"
+ );
+ expect(reconcileMethodForReplenishment("Buy", "Make to Order")).toBe(
+ "Pull from Inventory"
+ );
+ });
+});
+
+describe("currentItemFields", () => {
+ it("coerces an item's stored fields to the enums", () => {
+ expect(
+ currentItemFields({
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Serial"
+ })
+ ).toEqual({
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Serial"
+ });
+ });
+
+ it("falls back for missing values and reconciles an illegal pair", () => {
+ expect(
+ currentItemFields({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: null
+ })
+ ).toEqual({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Pull from Inventory",
+ itemTrackingType: "Inventory"
+ });
+ });
+});
+
+describe("mergeExistingItemEdits", () => {
+ const current = {
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory"
+ } as const;
+
+ it("returns no changes for an empty edit", () => {
+ const result = mergeExistingItemEdits(current, undefined);
+ expect(result).toEqual({ ok: true, values: current, changed: {} });
+ });
+
+ it("returns only the fields that differ from the current values", () => {
+ const result = mergeExistingItemEdits(current, {
+ replenishmentSystem: "Make",
+ itemTrackingType: "Serial"
+ });
+ expect(result).toEqual({
+ ok: true,
+ values: { ...current, itemTrackingType: "Serial" },
+ changed: { itemTrackingType: "Serial" }
+ });
+ });
+
+ it("refuses a method the replenishment system does not allow", () => {
+ const result = mergeExistingItemEdits(current, {
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Make to Order"
+ });
+ expect(result.ok).toBe(false);
+ });
+
+ it("ignores name, description and unit on an existing edit", () => {
+ const result = mergeExistingItemEdits(current, {
+ name: "Ignored",
+ description: "Ignored",
+ unitOfMeasureCode: "M"
+ });
+ expect(result).toEqual({ ok: true, values: current, changed: {} });
+ });
+});
+
+describe("mergeChangeNoticeEdit", () => {
+ it("applies a name and clears an empty description", () => {
+ expect(
+ mergeChangeNoticeEdit(
+ { name: "Onshape release A", description: "x" },
+ { name: " ECO-12 ", description: " " }
+ )
+ ).toEqual({
+ ok: true,
+ changeNotice: { name: "ECO-12", description: null }
+ });
+ });
+
+ it("refuses an empty name", () => {
+ expect(
+ mergeChangeNoticeEdit({ name: "n", description: null }, { name: "" })
+ ).toEqual({ ok: false, errors: ["Change notice name is required"] });
+ });
+});
+
+describe("buildPartPlan", () => {
+ const parts = [
+ {
+ partId: "p1",
+ name: "Foot pad",
+ partNumber: "PAD-005",
+ revision: null,
+ description: "Rubber",
+ microversionId: "m2"
+ },
+ { partId: "p2", name: "Stud", partNumber: "STD-006", revision: "A" },
+ { partId: "p3", name: "Nameless", partNumber: null, revision: null },
+ { partId: "p4", name: "Top", partNumber: "TOP-001", revision: null }
+ ];
+ const items = [
+ {
+ id: "item-1",
+ readableId: "PAD-005",
+ revision: "0",
+ name: "Foot pad (old)",
+ description: null
+ },
+ { id: "item-2", readableId: "STD-006", revision: "0", name: "Stud" }
+ ];
+
+ it("classifies create / adopt / update / unchanged / skip in request order", () => {
+ const rows = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts,
+ requestedPartIds: ["p4", "p1", "p2", "p3", "missing"],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: "d:e:p1",
+ lastSyncedAt: null,
+ metadata: { microversionId: "m1" }
+ }
+ ],
+ items,
+ options
+ });
+ expect(rows.map((r) => [r.partId, r.action])).toEqual([
+ ["p4", "create"],
+ ["p1", "update"],
+ ["p2", "adopt"],
+ ["p3", "skip-no-part-number"]
+ ]);
+ expect(rows[0]?.proposed?.readableId).toBe("TOP-001");
+ expect(rows[1]?.itemId).toBe("item-1");
+ // Descriptions default to Set at creation: kept, shown as a difference.
+ expect(rows[1]?.changes).toEqual([]);
+ expect(rows[1]?.keptDifferences).toEqual([
+ {
+ label: "Short Description",
+ onshape: "Foot pad",
+ carbon: "Foot pad (old)"
+ },
+ { label: "Long Description", onshape: "Rubber", carbon: null }
+ ]);
+ expect(rows[2]?.item?.readableId).toBe("STD-006");
+ expect(rows[2]?.proposed).toBeNull();
+ });
+
+ it("overwrites the descriptions set to Update on every push", () => {
+ const rows = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts,
+ requestedPartIds: ["p1"],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: "d:e:p1",
+ lastSyncedAt: null,
+ metadata: { microversionId: "m1" }
+ }
+ ],
+ items,
+ options,
+ mapping: {
+ map: [],
+ definitions: [],
+ descriptionModes: { name: "everyPush", description: "create" },
+ heldCustomFields: new Map()
+ }
+ });
+ expect(rows[0]?.changes).toEqual([
+ { field: "name", from: "Foot pad (old)", to: "Foot pad" }
+ ]);
+ expect(rows[0]?.keptDifferences).toEqual([
+ { label: "Long Description", onshape: "Rubber", carbon: null }
+ ]);
+ });
+
+ it("reports unchanged when the mapping's microversion matches", () => {
+ const rows = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts,
+ requestedPartIds: ["p1"],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: "d:e:p1",
+ lastSyncedAt: null,
+ metadata: { microversionId: "m2" }
+ }
+ ],
+ items,
+ options
+ });
+ expect(rows[0]?.action).toBe("unchanged");
+ expect(rows[0]?.changes).toEqual([]);
+ });
+
+ it("treats a mapping whose item is gone as no link", () => {
+ const rows = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts,
+ requestedPartIds: ["p1"],
+ mappings: [
+ { entityId: "deleted", externalId: "d:e:p1", lastSyncedAt: null }
+ ],
+ items,
+ options
+ });
+ expect(rows[0]?.action).toBe("adopt");
+ });
+});
+
+describe("buildAssemblyPlan", () => {
+ const nodes: OnshapeBomNode[] = [
+ node({
+ index: "1",
+ partNumber: "ASM-008",
+ name: "Foot assembly",
+ quantity: 4,
+ children: [
+ node({ index: "1.1", level: 2, partNumber: "LEG-003", name: "Leg" }),
+ node({
+ index: "1.2",
+ level: 2,
+ partNumber: "HDW-010",
+ name: "Bolt",
+ standardContent: true,
+ quantity: 2
+ }),
+ node({ index: "1.3", level: 2, partNumber: null, name: "Unnamed" })
+ ]
+ }),
+ node({ index: "2", partNumber: "TOP-001", name: "Top" })
+ ];
+
+ describe("released methods", () => {
+ const build = (
+ reusableDraftByItemId?: Map<
+ string,
+ { id: string; version: number | null }
+ >
+ ) =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],
+ items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],
+ methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),
+ mappedLinesByMethodId: new Map([
+ ["active", [{ readableId: "OLD-1", quantity: 1 }]],
+ ["draft", [{ readableId: "DRAFT-1", quantity: 2 }]]
+ ]),
+ manualLinesByMethodId: new Map(),
+ options,
+ reusableDraftByItemId
+ });
+
+ it("counts the Active method's lines when the push will copy a new Draft", () => {
+ const [method] = build().methods;
+ expect(method?.status).toBe("active");
+ expect(method?.reusedDraftVersion).toBeUndefined();
+ expect(method?.replaces).toEqual([{ readableId: "OLD-1", quantity: 1 }]);
+ });
+
+ it("takes a refused method out and lists it with its reason", () => {
+ const plan = withRefusedMethods(
+ build(),
+ new Map([["root", "its make method is a Draft on change notice CN-1."]])
+ );
+ expect(plan.methods).toEqual([]);
+ expect(plan.skipped).toContain(
+ "WB-100: its make method is a Draft on change notice CN-1."
+ );
+ });
+
+ it("does not refuse an Active method the push leaves unchanged", () => {
+ const built = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],
+ items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],
+ methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),
+ mappedLinesByMethodId: new Map([
+ ["active", [{ readableId: "TOP-001", quantity: 1 }]]
+ ]),
+ manualLinesByMethodId: new Map(),
+ options
+ });
+ expect(built.methods[0]?.unchanged).toBe(true);
+ expect(withRefusedMethods(built, new Map([["root", "released"]]))).toBe(
+ built
+ );
+ });
+
+ it("counts the reused Draft's lines and names its version", () => {
+ const [method] = build(
+ new Map([["root", { id: "draft", version: 3 }]])
+ ).methods;
+ expect(method?.reusedDraftVersion).toBe(3);
+ expect(method?.replaces).toEqual([
+ { readableId: "DRAFT-1", quantity: 2 }
+ ]);
+ });
+ });
+
+ describe("depth", () => {
+ const build = (depth: "all" | "top") =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes,
+ items: [],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ depth
+ });
+
+ it("defaults to the whole tree, and says so", () => {
+ const plan = build("all");
+ expect(plan.depth).toBe("all");
+ expect(plan.deeper).toBeUndefined();
+ expect(plan.methods.map((m) => m.parentPartNumber)).toEqual([
+ "WB-100",
+ "ASM-008"
+ ]);
+ expect(plan.items.map((i) => i.partNumber).sort()).toEqual([
+ "ASM-008",
+ "HDW-010",
+ "LEG-003",
+ "TOP-001"
+ ]);
+ });
+
+ it("writes one method and only the top level's items at top depth", () => {
+ const plan = build("top");
+ expect(plan.methods).toHaveLength(1);
+ const [rootMethod] = plan.methods;
+ expect(rootMethod?.parentPartNumber).toBe("WB-100");
+ // The sub-assembly is still a line of the root.
+ expect(rootMethod?.writes.map((w) => w.partNumber)).toEqual([
+ "ASM-008",
+ "TOP-001"
+ ]);
+ expect(plan.items.map((i) => i.partNumber).sort()).toEqual([
+ "ASM-008",
+ "TOP-001"
+ ]);
+ });
+
+ it("still classifies an unexploded sub-assembly as an assembly", () => {
+ const item = build("top").items.find((i) => i.partNumber === "ASM-008");
+ expect(item?.isAssembly).toBe(true);
+ expect(item?.proposed?.replenishmentSystem).toBe("Make");
+ });
+
+ it("reports what a top-level push leaves out", () => {
+ const plan = build("top");
+ expect(plan.deeper?.subAssemblies).toEqual(["ASM-008"]);
+ // LEG-003 and HDW-010; the unnamed row has no part number.
+ expect(plan.deeper?.partCount).toBe(2);
+ });
+ });
+
+ it("plans creates, reuses, methods and the line diff", () => {
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes,
+ items: [
+ { id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },
+ { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" }
+ ],
+ methodByItemId: new Map([["wb", { id: "m-wb", status: "Draft" }]]),
+ mappedLinesByMethodId: new Map([
+ ["m-wb", [{ readableId: "ASM-008", quantity: 4 }]]
+ ]),
+ manualLinesByMethodId: new Map([
+ ["m-wb", [{ readableId: "PAD-005", quantity: 99 }]]
+ ]),
+ options
+ });
+
+ expect(plan.root.action).toBe("reuse");
+ expect(plan.root.itemId).toBe("wb");
+ expect(
+ plan.items.map((i) => [i.partNumber, i.action, i.isAssembly])
+ ).toEqual([
+ ["ASM-008", "create", true],
+ ["LEG-003", "create", false],
+ ["HDW-010", "reuse", false],
+ ["TOP-001", "create", false]
+ ]);
+ expect(plan.items[0]?.proposed?.replenishmentSystem).toBe("Make");
+ expect(plan.skipped).toEqual(["Unnamed: no part number in Onshape"]);
+
+ expect(plan.methods.map((m) => [m.parentPartNumber, m.status])).toEqual([
+ ["WB-100", "draft"],
+ ["ASM-008", "new"]
+ ]);
+ const root = plan.methods[0];
+ expect(root?.writes.map((w) => w.partNumber)).toEqual([
+ "ASM-008",
+ "TOP-001"
+ ]);
+ expect(root?.replaces).toEqual([{ readableId: "ASM-008", quantity: 4 }]);
+ expect(root?.keeps).toEqual([{ readableId: "PAD-005", quantity: 99 }]);
+ const sub = plan.methods[1];
+ expect(sub?.writes.map((w) => w.partNumber)).toEqual([
+ "LEG-003",
+ "HDW-010"
+ ]);
+ expect(sub?.replaces).toEqual([]);
+ });
+
+ it("skips a child whose Carbon item can never be a BOM line", () => {
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: null,
+ description: null,
+ revision: null
+ },
+ nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],
+ items: [
+ {
+ id: "tool",
+ readableId: "TOP-001",
+ revision: "0",
+ name: "Top",
+ type: "Tool"
+ }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options
+ });
+ expect(plan.items).toEqual([]);
+ expect(plan.methods[0]?.writes).toEqual([]);
+ expect(plan.skipped).toEqual([
+ "TOP-001: Carbon has it as a Tool item, which cannot be a BOM line"
+ ]);
+ });
+
+ it("reuses the Part when a Tool shares its number", () => {
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: null,
+ description: null,
+ revision: null
+ },
+ nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],
+ items: [
+ {
+ id: "tool",
+ readableId: "TOP-001",
+ revision: "0",
+ name: "Top",
+ type: "Tool"
+ },
+ {
+ id: "part",
+ readableId: "TOP-001",
+ revision: "0",
+ name: "Top",
+ type: "Part"
+ }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options
+ });
+ expect(plan.skipped).toEqual([]);
+ expect(plan.items.map((item) => item.itemId)).toEqual(["part"]);
+ expect(plan.methods[0]?.writes.map((w) => w.partNumber)).toEqual([
+ "TOP-001"
+ ]);
+ });
+
+ it("flags released and missing methods on reused parents", () => {
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: null,
+ description: null,
+ revision: null
+ },
+ nodes,
+ items: [
+ { id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },
+ { id: "asm", readableId: "ASM-008", revision: "0", name: "Foot" }
+ ],
+ methodByItemId: new Map([["wb", { id: "m-wb", status: "Active" }]]),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options
+ });
+ expect(plan.methods.map((m) => [m.parentPartNumber, m.status])).toEqual([
+ ["WB-100", "active"],
+ ["ASM-008", "missing"]
+ ]);
+ expect(plan.root.proposed).toBeNull();
+ });
+
+ describe("conflicts", () => {
+ const conflictNodes = [
+ node({
+ index: "1",
+ partNumber: "LEG-003",
+ name: "Leg",
+ itemSource: { documentId: "d2", elementId: "ps", partId: "JHD" }
+ }),
+ node({
+ index: "2",
+ partNumber: "HDW-010",
+ name: "Bolt",
+ itemSource: { documentId: "d2", elementId: "ps", partId: "JKD" }
+ }),
+ node({ index: "3", partNumber: "PAD-005", name: "Pad" }),
+ node({ index: "4", partNumber: "TOP-001", name: "Top" })
+ ];
+ const build = (links: Array<[string, string]>) =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: null,
+ description: null,
+ revision: null
+ },
+ nodes: conflictNodes,
+ items: [
+ { id: "wb", readableId: "WB-100", revision: "0", name: "Workbench" },
+ { id: "leg", readableId: "LEG-003", revision: "0", name: "Leg" },
+ { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" },
+ { id: "pad", readableId: "PAD-005", revision: "0", name: "Pad" }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ linkedItemIdByExternalId: new Map(links)
+ });
+
+ it("marks a reuse found by part number alone, never a linked one or a create", () => {
+ const plan = build([
+ ["d:e:assembly", "wb"],
+ ["d2:ps:JHD", "leg"],
+ // Linked, but to a different item than the number resolves to.
+ ["d2:ps:JKD", "someone-else"]
+ ]);
+ expect(plan.root.conflict).toBeUndefined();
+ expect(
+ Object.fromEntries(plan.items.map((i) => [i.partNumber, i.conflict]))
+ ).toEqual({
+ "LEG-003": undefined,
+ "HDW-010": true,
+ // No itemSource, so nothing to link through.
+ "PAD-005": true,
+ "TOP-001": undefined
+ });
+ });
+
+ it("treats an unlinked reused root as a conflict", () => {
+ expect(build([]).root.conflict).toBe(true);
+ });
+
+ it("keeps a part linked when a release added a higher revision the mapping does not point at", () => {
+ // A release made Rev B the default and left the mappings on the Rev A
+ // items; a link to Rev A is still a link to the part.
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: null,
+ description: null,
+ revision: null
+ },
+ nodes: conflictNodes,
+ items: [
+ {
+ id: "wb-a",
+ readableId: "WB-100",
+ revision: "A",
+ name: "Workbench"
+ },
+ {
+ id: "wb-b",
+ readableId: "WB-100",
+ revision: "B",
+ name: "Workbench"
+ },
+ { id: "leg-a", readableId: "LEG-003", revision: "A", name: "Leg" },
+ { id: "leg-b", readableId: "LEG-003", revision: "B", name: "Leg" },
+ { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" },
+ { id: "pad", readableId: "PAD-005", revision: "0", name: "Pad" }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ linkedItemIdByExternalId: new Map([
+ ["d:e:assembly", "wb-a"],
+ ["d2:ps:JHD", "leg-a"]
+ ])
+ });
+ expect(plan.root.conflict).toBeUndefined();
+ expect(
+ Object.fromEntries(plan.items.map((i) => [i.partNumber, i.conflict]))
+ ).toEqual({
+ "LEG-003": undefined,
+ // Linked to no item: a conflict.
+ "HDW-010": true,
+ "PAD-005": true,
+ "TOP-001": undefined
+ });
+ });
+ });
+});
+
+describe("buildReleasePlan", () => {
+ const release: PanelRelease = {
+ releaseId: "rel-1",
+ releaseName: "Release WB-100 A",
+ createdAt: "2026-08-26T00:00:00Z",
+ state: "not-pushed",
+ items: [
+ {
+ partNumber: "WB-100",
+ revision: "A",
+ elementType: 1,
+ documentId: "d",
+ versionId: "v1",
+ elementId: "e-wb",
+ partId: null,
+ configuration: null,
+ obsolete: false,
+ state: "missing",
+ itemId: null
+ },
+ {
+ partNumber: "PAD-005",
+ revision: "A",
+ elementType: 0,
+ documentId: "d",
+ versionId: "v1",
+ elementId: "e-ps",
+ partId: null,
+ configuration: null,
+ obsolete: false,
+ state: "missing",
+ itemId: null
+ },
+ {
+ partNumber: "NEW-999",
+ revision: "A",
+ elementType: 0,
+ documentId: "d",
+ versionId: "v1",
+ elementId: "e-ps",
+ partId: null,
+ configuration: null,
+ obsolete: false,
+ state: "missing",
+ itemId: null
+ },
+ {
+ partNumber: "WB-100",
+ revision: "A",
+ elementType: 2,
+ documentId: "d",
+ versionId: "v1",
+ elementId: "e-drw",
+ partId: null,
+ configuration: null,
+ obsolete: false,
+ state: "missing",
+ itemId: null
+ },
+ {
+ partNumber: "LONE-DRW",
+ revision: "A",
+ elementType: 2,
+ documentId: "d",
+ versionId: "v1",
+ elementId: "e-drw2",
+ partId: null,
+ configuration: null,
+ obsolete: false,
+ state: "missing",
+ itemId: null
+ }
+ ]
+ };
+
+ it("classifies reuse / revision / create, children and drawings", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release,
+ items: [
+ { id: "pad-0", readableId: "PAD-005", revision: "0", name: "Foot pad" },
+ { id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" },
+ { id: "hdw", readableId: "HDW-010", revision: "0", name: "Bolt" }
+ ],
+ bomLinesByElementId: {
+ "e-wb": [
+ node({ partNumber: "PAD-005", name: "Foot pad" }),
+ node({ index: "2", partNumber: "NEW-999", name: "Bracket" }),
+ node({
+ index: "3",
+ partNumber: "HDW-010",
+ name: "Bolt",
+ standardContent: true
+ }),
+ node({
+ index: "4",
+ partNumber: "HDW-011",
+ name: "Nut",
+ standardContent: true
+ })
+ ]
+ },
+ methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Active" }]]),
+ options
+ });
+
+ expect(plan.items.map((i) => [i.partNumber, i.action])).toEqual([
+ ["WB-100", "reuse"],
+ ["PAD-005", "revision"],
+ ["NEW-999", "create"],
+ ["WB-100", "drawing"],
+ ["LONE-DRW", "drawing-unmatched"]
+ ]);
+ expect(plan.items[0]?.methodStatus).toBe("active");
+ expect(plan.items[1]?.baseItemId).toBe("pad-0");
+ expect(plan.items[1]?.baseRevision).toBe("0");
+ // The release list carries only part numbers: the name comes from the BOM.
+ expect(plan.items[2]?.proposed?.name).toBe("Bracket");
+ expect(plan.items[2]?.proposed?.revision).toBe("A");
+
+ expect(plan.children.map((c) => [c.partNumber, c.action])).toEqual([
+ ["HDW-010", "reuse"],
+ ["HDW-011", "create"]
+ ]);
+ expect(plan.children[1]?.proposed?.replenishmentSystem).toBe("Buy");
+
+ expect(plan.changeNotice).toEqual({
+ name: "Release WB-100 A",
+ description: null
+ });
+ expect(plan.makeDefault).toBe(true);
+ expect(plan.alreadyPushed).toBe(false);
+ });
+
+ it("ties a drawing numbered apart from its model through the release package", () => {
+ const drawingOnly: PanelRelease = {
+ ...release,
+ items: [
+ {
+ ...release.items[4]!,
+ partNumber: "WB-100-DWG",
+ revision: "C",
+ elementId: "e-drw"
+ },
+ {
+ ...release.items[4]!,
+ partNumber: "PAD-005-DWG",
+ revision: "C",
+ elementId: "e-drw3"
+ }
+ ]
+ };
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: drawingOnly,
+ items: [
+ { id: "wb-b", readableId: "WB-100", revision: "B", name: "Workbench" },
+ { id: "wb-c", readableId: "WB-100", revision: "C", name: "Workbench" }
+ ],
+ bomLinesByElementId: {},
+ methodByItemId: new Map(),
+ options,
+ drawingModelByElementId: new Map([
+ ["e-drw", { partNumber: "WB-100", revision: "C" }],
+ // Carbon has no PAD-005 Rev C: nothing to attach to.
+ ["e-drw3", { partNumber: "PAD-005", revision: "C" }]
+ ])
+ });
+ expect(
+ plan.items.map((i) => [i.partNumber, i.action, i.drawingOf])
+ ).toEqual([
+ [
+ "WB-100-DWG",
+ "drawing",
+ { partNumber: "WB-100", revision: "C", itemId: "wb-c" }
+ ],
+ [
+ "PAD-005-DWG",
+ "drawing-unmatched",
+ { partNumber: "PAD-005", revision: "C" }
+ ]
+ ]);
+ expect(plan.changeNotice).toBeNull();
+ });
+
+ it("prefers the model with the drawing's own number in the release", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release,
+ items: [],
+ bomLinesByElementId: {},
+ methodByItemId: new Map(),
+ options,
+ drawingModelByElementId: new Map([
+ ["e-drw", { partNumber: "OTHER-1", revision: "A" }]
+ ])
+ });
+ const drawing = plan.items.find((i) => i.elementId === "e-drw");
+ expect(drawing?.action).toBe("drawing");
+ expect(drawing?.drawingOf).toEqual({ partNumber: "WB-100", revision: "A" });
+ });
+
+ it("proposes no change notice when everything is already at its letter", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: { ...release, items: release.items.slice(0, 2) },
+ items: [
+ { id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" },
+ { id: "pad-a", readableId: "PAD-005", revision: "A", name: "Foot pad" }
+ ],
+ bomLinesByElementId: {},
+ methodByItemId: new Map(),
+ options
+ });
+ expect(plan.alreadyPushed).toBe(true);
+ expect(plan.changeNotice).toBeNull();
+ expect(plan.items[0]?.methodStatus).toBe("missing");
+ });
+
+ it("is not already pushed when only a BOM child is missing, and proposes no notice for it", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: { ...release, items: release.items.slice(0, 1) },
+ items: [
+ { id: "wb-a", readableId: "WB-100", revision: "A", name: "Workbench" }
+ ],
+ bomLinesByElementId: {
+ "e-wb": [
+ node({
+ partNumber: "HDW-011",
+ name: "Nut",
+ standardContent: true
+ })
+ ]
+ },
+ methodByItemId: new Map([["wb-a", { id: "m-wb-a", status: "Draft" }]]),
+ options
+ });
+ expect(plan.children.map((c) => [c.partNumber, c.action])).toEqual([
+ ["HDW-011", "create"]
+ ]);
+ expect(plan.alreadyPushed).toBe(false);
+ // The apply records only created release items on the notice.
+ expect(plan.changeNotice).toBeNull();
+ });
+
+ it("copies a new revision from the newest one, even while it waits in its notice", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: {
+ ...release,
+ items: [{ ...release.items[1]!, revision: "B" }]
+ },
+ items: [
+ {
+ id: "pad-0",
+ readableId: "PAD-005",
+ revision: "0",
+ active: true,
+ name: "Foot pad"
+ },
+ {
+ id: "pad-a",
+ readableId: "PAD-005",
+ revision: "A",
+ active: false,
+ name: "Foot pad"
+ }
+ ],
+ bomLinesByElementId: {},
+ methodByItemId: new Map(),
+ options
+ });
+ expect(plan.items[0]).toMatchObject({
+ action: "revision",
+ baseItemId: "pad-a",
+ baseRevision: "A"
+ });
+ });
+
+ it("points a BOM child at the revision the BOM names, and says when Carbon lacks it", () => {
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: { ...release, items: release.items.slice(0, 1) },
+ items: [
+ { id: "wb-0", readableId: "WB-100", revision: "0", name: "Workbench" },
+ {
+ id: "leg-0",
+ readableId: "ASM-008",
+ revision: "0",
+ active: true,
+ name: "Leg assembly"
+ },
+ {
+ id: "leg-a",
+ readableId: "ASM-008",
+ revision: "A",
+ active: false,
+ name: "Leg assembly"
+ },
+ {
+ id: "top-0",
+ readableId: "ASM-007",
+ revision: "0",
+ active: true,
+ name: "Top assembly"
+ }
+ ],
+ bomLinesByElementId: {
+ "e-wb": [
+ node({ partNumber: "ASM-008", name: "Leg assembly", revision: "A" }),
+ node({
+ index: "2",
+ partNumber: "ASM-007",
+ name: "Top assembly",
+ revision: "B"
+ })
+ ]
+ },
+ methodByItemId: new Map(),
+ options
+ });
+ expect(
+ plan.children.map((child) => [
+ child.partNumber,
+ child.itemId,
+ child.itemRevision,
+ child.missingRevision
+ ])
+ ).toEqual([
+ ["ASM-008", "leg-a", "A", undefined],
+ ["ASM-007", "top-0", "0", "B"]
+ ]);
+ });
+
+ it("carries each released part's partId and configuration to the export", () => {
+ const released = release.items[1]!;
+ const plan = buildReleasePlan({
+ documentId: "d",
+ release: {
+ ...release,
+ items: [{ ...released, partId: "JHD", configuration: "size%3DLarge" }]
+ },
+ items: [],
+ bomLinesByElementId: {},
+ methodByItemId: new Map(),
+ options
+ });
+ expect(plan.items[0]).toMatchObject({
+ partNumber: "PAD-005",
+ partId: "JHD",
+ configuration: "size%3DLarge"
+ });
+ });
+});
+
+describe("pickAdoptTarget", () => {
+ const rows = [
+ {
+ id: "mat",
+ readableId: "X-1",
+ revision: "0",
+ name: "m",
+ type: "Material"
+ },
+ { id: "p0", readableId: "X-1", revision: "0", name: "p", type: "Part" },
+ { id: "pA", readableId: "X-1", revision: "A", name: "p", type: "Part" }
+ ];
+ it("prefers the Part at the Onshape revision, then the latest Part, never another type", () => {
+ expect(pickAdoptTarget(rows, "A")?.id).toBe("pA");
+ expect(pickAdoptTarget(rows, null)?.id).toBe("p0");
+ expect(pickAdoptTarget(rows, "Z")?.id).toBe("pA");
+ expect(
+ pickAdoptTarget([rows[0] as (typeof rows)[number]], "0")
+ ).toBeUndefined();
+ });
+});
+
+describe("assemblyTextChanges", () => {
+ it("writes only the descriptions Onshape gives that differ", () => {
+ expect(
+ assemblyTextChanges(
+ { name: "Foot assembly (Carbon BOM)", description: "ours" },
+ { name: "Foot assembly", description: null }
+ )
+ ).toEqual([
+ { field: "name", from: "Foot assembly (Carbon BOM)", to: "Foot assembly" }
+ ]);
+ expect(
+ assemblyTextChanges(
+ { name: "Pad", description: null },
+ { name: "Pad", description: "Rubber pad" }
+ )
+ ).toEqual([{ field: "description", from: null, to: "Rubber pad" }]);
+ });
+});
+
+describe("released parts in workspace pushes", () => {
+ const released = new Map([["TOP-001", { itemId: "top-c", revision: "C" }]]);
+
+ it("leaves a released part alone in a part push, even when it is linked", () => {
+ const rows = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts: [
+ { partId: "p1", name: "Top", partNumber: "TOP-001", revision: "C" }
+ ],
+ requestedPartIds: ["p1"],
+ mappings: [
+ {
+ entityId: "top-0",
+ externalId: "d:e:p1",
+ lastSyncedAt: null,
+ metadata: { microversionId: "m1" }
+ }
+ ],
+ items: [
+ { id: "top-0", readableId: "TOP-001", revision: "0", name: "Top" },
+ { id: "top-c", readableId: "TOP-001", revision: "C", name: "Top" }
+ ],
+ options,
+ released
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ action: "released",
+ itemId: "top-c",
+ item: { revision: "C" }
+ });
+ expect(rows[0]?.current).toBeUndefined();
+ });
+
+ it("writes no fields to a released root or child in an assembly push", () => {
+ const plan = buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: "New text",
+ revision: "B"
+ },
+ nodes: [node({ index: "1", partNumber: "TOP-001", name: "Top" })],
+ items: [
+ { id: "wb-b", readableId: "WB-100", revision: "B", name: "Old text" },
+ { id: "top-c", readableId: "TOP-001", revision: "C", name: "Old" }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ mapping: {
+ map: [],
+ definitions: [],
+ descriptionModes: { name: "everyPush", description: "everyPush" },
+ heldCustomFields: new Map()
+ },
+ released: new Map([
+ ["WB-100", { itemId: "wb-b", revision: "B" }],
+ ["TOP-001", { itemId: "top-c", revision: "C" }]
+ ])
+ });
+ expect(plan.root).toMatchObject({
+ action: "reuse",
+ itemId: "wb-b",
+ released: { revision: "B" }
+ });
+ expect(plan.root.changes).toBeUndefined();
+ expect(plan.root.current).toBeUndefined();
+ expect(plan.items[0]).toMatchObject({
+ action: "reuse",
+ itemId: "top-c",
+ released: { revision: "C" }
+ });
+ expect(plan.items[0]?.conflict).toBeUndefined();
+ expect(plan.items[0]?.current).toBeUndefined();
+ });
+});
+
+describe("buildAssemblyPlan unchanged released methods", () => {
+ const build = (
+ lines: Array<{ readableId: string; quantity: number }>,
+ reusableDraftByItemId = new Map<
+ string,
+ { id: string; version: number | null }
+ >()
+ ) =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes: [
+ node({ index: "1", partNumber: "TOP-001", name: "Top", quantity: 1 }),
+ node({ index: "2", partNumber: "LEG-003", name: "Leg", quantity: 4 })
+ ],
+ items: [{ id: "root", readableId: "WB-100", revision: "0", name: "W" }],
+ methodByItemId: new Map([["root", { id: "active", status: "Active" }]]),
+ mappedLinesByMethodId: new Map([["active", lines]]),
+ manualLinesByMethodId: new Map(),
+ options,
+ reusableDraftByItemId
+ }).methods[0];
+
+ it("needs no Draft when the released method already has Onshape's lines", () => {
+ expect(
+ build([
+ { readableId: "TOP-001", quantity: 1 },
+ { readableId: "LEG-003", quantity: 4 }
+ ])?.unchanged
+ ).toBe(true);
+ });
+
+ it("needs a Draft when a quantity, a line or the order differs", () => {
+ expect(
+ build([
+ { readableId: "TOP-001", quantity: 1 },
+ { readableId: "LEG-003", quantity: 2 }
+ ])?.unchanged
+ ).toBeUndefined();
+ expect(
+ build([{ readableId: "TOP-001", quantity: 1 }])?.unchanged
+ ).toBeUndefined();
+ expect(
+ build([
+ { readableId: "LEG-003", quantity: 4 },
+ { readableId: "TOP-001", quantity: 1 }
+ ])?.unchanged
+ ).toBeUndefined();
+ });
+
+ it("writes into a reused Draft as before", () => {
+ expect(
+ build(
+ [
+ { readableId: "TOP-001", quantity: 1 },
+ { readableId: "LEG-003", quantity: 4 }
+ ],
+ new Map([["root", { id: "draft", version: 2 }]])
+ )?.unchanged
+ ).toBeUndefined();
+ });
+});
+
+describe("buildAssemblyPlan descriptions", () => {
+ const source = (partId: string) => ({
+ documentId: "d2",
+ elementId: "ps",
+ partId
+ });
+ const everyPush = {
+ map: [],
+ definitions: [],
+ descriptionModes: { name: "everyPush", description: "everyPush" } as const,
+ heldCustomFields: new Map()
+ };
+ const build = (
+ linkedItemIds?: Set<string>,
+ links = new Map<string, string>(),
+ mapping: typeof everyPush | null = everyPush
+ ) =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes: [
+ node({
+ index: "1",
+ partNumber: "LEG-003",
+ name: "Leg tube",
+ itemSource: source("JND")
+ }),
+ node({
+ index: "2",
+ partNumber: "PLT-004",
+ name: "Mounting plate",
+ itemSource: source("JQD")
+ }),
+ node({
+ index: "3",
+ partNumber: "HDW-010",
+ name: "Hex nut",
+ itemSource: source("JHD")
+ })
+ ],
+ items: [
+ {
+ id: "wb",
+ readableId: "WB-100",
+ revision: "0",
+ name: "Workbench (Carbon)"
+ },
+ {
+ id: "leg",
+ readableId: "LEG-003",
+ revision: "0",
+ name: "Leg (Carbon)"
+ },
+ {
+ id: "plt",
+ readableId: "PLT-004",
+ revision: "0",
+ name: "Plate (Carbon)"
+ },
+ {
+ id: "hdw",
+ readableId: "HDW-010",
+ revision: "0",
+ name: "Nut (Carbon)"
+ }
+ ],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ linkedItemIdByExternalId: links,
+ linkedItemIds,
+ mapping: mapping ?? undefined
+ });
+
+ it("writes the root's and every child's this push links, not one linked elsewhere", () => {
+ // LEG-003 is already linked to its row; PLT-004 is linked to another
+ // Onshape part, so it keeps that link; HDW-010 is linked nowhere.
+ const plan = build(
+ new Set(["leg", "plt"]),
+ new Map([["d2:ps:JND", "leg"]])
+ );
+ expect(plan.root.changes).toEqual([
+ { field: "name", from: "Workbench (Carbon)", to: "Workbench" }
+ ]);
+ const byNumber = new Map(plan.items.map((item) => [item.partNumber, item]));
+ expect(byNumber.get("LEG-003")?.changes).toEqual([
+ { field: "name", from: "Leg (Carbon)", to: "Leg tube" }
+ ]);
+ expect(byNumber.get("PLT-004")?.changes).toBeUndefined();
+ expect(byNumber.get("HDW-010")?.changes).toEqual([
+ { field: "name", from: "Nut (Carbon)", to: "Hex nut" }
+ ]);
+ });
+
+ it("only writes children already linked to their row when it can't tell what else is linked", () => {
+ const plan = build(undefined, new Map([["d2:ps:JND", "leg"]]));
+ const byNumber = new Map(plan.items.map((item) => [item.partNumber, item]));
+ expect(byNumber.get("LEG-003")?.changes).toHaveLength(1);
+ expect(byNumber.get("HDW-010")?.changes).toBeUndefined();
+ });
+
+ it("keeps Carbon's text when the descriptions are Set at creation", () => {
+ const plan = build(new Set(["leg"]), new Map([["d2:ps:JND", "leg"]]), null);
+ expect(plan.root.changes).toBeUndefined();
+ expect(plan.root.keptDifferences).toEqual([
+ {
+ label: "Short Description",
+ onshape: "Workbench",
+ carbon: "Workbench (Carbon)"
+ }
+ ]);
+ const leg = plan.items.find((item) => item.partNumber === "LEG-003");
+ expect(leg?.changes).toBeUndefined();
+ expect(leg?.keptDifferences).toHaveLength(1);
+ });
+});
+
+describe("pairManualLines", () => {
+ it("keeps a manual line for another item type that shares the number", () => {
+ const { takesOver, keeps } = pairManualLines(
+ [{ partNumber: "X-1", quantity: 2, itemType: "Part" }],
+ [],
+ [
+ { readableId: "X-1", quantity: 5, itemType: "Material" },
+ { readableId: "X-1", quantity: 1, itemType: "Part" }
+ ]
+ );
+ expect(takesOver).toEqual([
+ { readableId: "X-1", quantity: 1, itemType: "Part", onshapeQuantity: 2 }
+ ]);
+ expect(keeps).toEqual([
+ { readableId: "X-1", quantity: 5, itemType: "Material" }
+ ]);
+ });
+
+ it("takes over a manual line Onshape also lists, after the lines a push owns", () => {
+ const { takesOver, keeps } = pairManualLines(
+ [
+ { partNumber: "PAD-005", quantity: 1 },
+ { partNumber: "HDW-010", quantity: 1 },
+ { partNumber: "HDW-011", quantity: 1 },
+ { partNumber: "STD-006", quantity: 1 }
+ ],
+ [{ readableId: "STD-006", quantity: 1 }],
+ [
+ { readableId: "PAD-005", quantity: 2 },
+ { readableId: "HDW-010", quantity: 1 },
+ { readableId: "GLUE-01", quantity: 1 },
+ { readableId: "STD-006", quantity: 3 }
+ ]
+ );
+ expect(takesOver).toEqual([
+ { readableId: "PAD-005", quantity: 2, onshapeQuantity: 1 },
+ { readableId: "HDW-010", quantity: 1, onshapeQuantity: 1 }
+ ]);
+ // STD-006 pairs with the line a push already owns; its manual line stays.
+ expect(keeps).toEqual([
+ { readableId: "GLUE-01", quantity: 1 },
+ { readableId: "STD-006", quantity: 3 }
+ ]);
+ });
+
+ it("takes over one manual line per Onshape row of a part", () => {
+ const { takesOver, keeps } = pairManualLines(
+ [{ partNumber: "BOLT", quantity: 4 }],
+ [],
+ [
+ { readableId: "BOLT", quantity: 2 },
+ { readableId: "BOLT", quantity: 2 }
+ ]
+ );
+ expect(takesOver).toEqual([
+ { readableId: "BOLT", quantity: 2, onshapeQuantity: 4 }
+ ]);
+ expect(keeps).toEqual([{ readableId: "BOLT", quantity: 2 }]);
+ });
+});
+
+describe("pickReuseRow", () => {
+ it("prefers the latest Part, then any row that can be a BOM line", () => {
+ const tool = { id: "t", revision: "B", type: "Tool" };
+ const material = { id: "m", revision: "A", type: "Material" };
+ const part = { id: "p", revision: "0", type: "Part" };
+ expect(pickReuseRow([tool, material, part])?.id).toBe("p");
+ expect(pickReuseRow([tool, material])?.id).toBe("m");
+ expect(pickReuseRow([tool])?.id).toBe("t");
+ });
+});
+
+describe("pickLatestRow", () => {
+ it("orders revisions by sequence, not as text", () => {
+ expect(
+ pickLatestRow([{ revision: "9" }, { revision: "10" }])?.revision
+ ).toBe("10");
+ expect(
+ pickLatestRow([{ revision: "Y" }, { revision: "AA" }])?.revision
+ ).toBe("AA");
+ });
+
+ it("prefers an active revision over a newer inactive one", () => {
+ expect(
+ pickLatestRow([
+ { revision: "B", active: true },
+ { revision: "C", active: false }
+ ])?.revision
+ ).toBe("B");
+ expect(pickLatestRow([{ revision: "C", active: false }])?.revision).toBe(
+ "C"
+ );
+ });
+});
+
+describe("pickRevisionBase", () => {
+ it("copies from the newest revision below the released one, released or not", () => {
+ const rows = [
+ { id: "0", revision: "0", active: true },
+ { id: "A", revision: "A", active: false },
+ { id: "C", revision: "C", active: false }
+ ];
+ expect(pickRevisionBase(rows, "B")?.id).toBe("A");
+ expect(pickRevisionBase(rows, "A")?.id).toBe("0");
+ expect(pickRevisionBase(rows, "D")?.id).toBe("C");
+ });
+
+ it("falls back to the latest row when none is below the released revision", () => {
+ expect(
+ pickRevisionBase(
+ [
+ { id: "C", revision: "C", active: true },
+ { id: "D", revision: "D", active: false }
+ ],
+ "B"
+ )?.id
+ ).toBe("C");
+ expect(pickRevisionBase([], "A")).toBeUndefined();
+ });
+});
+
+describe("pickBomChildRow", () => {
+ const rows = [
+ { id: "0", revision: "0", active: true, type: "Part" },
+ { id: "A", revision: "A", active: false, type: "Part" }
+ ];
+
+ it("takes the revision the BOM names, even one still waiting in its notice", () => {
+ expect(pickBomChildRow(rows, "A")).toEqual({
+ row: rows[1],
+ missingRevision: null
+ });
+ expect(pickBomChildRow(rows, " a ").row?.id).toBe("A");
+ });
+
+ it("falls back to the latest row and names the revision Carbon lacks", () => {
+ expect(pickBomChildRow(rows, "B")).toEqual({
+ row: rows[0],
+ missingRevision: "B"
+ });
+ });
+
+ it("takes the latest row when the BOM names no revision", () => {
+ expect(pickBomChildRow(rows, null)).toEqual({
+ row: rows[0],
+ missingRevision: null
+ });
+ expect(pickBomChildRow([], "B")).toEqual({
+ row: undefined,
+ missingRevision: null
+ });
+ });
+
+ it("prefers the Part when another item type shares the number and revision", () => {
+ expect(
+ pickBomChildRow(
+ [
+ { id: "tool", revision: "A", type: "Tool" },
+ { id: "part", revision: "A", type: "Part" }
+ ],
+ "A"
+ ).row?.id
+ ).toBe("part");
+ });
+});
+
+describe("bomLineItemType", () => {
+ it("maps reusable item types onto methodMaterial.itemType", () => {
+ expect(bomLineItemType({ type: "Part" })).toBe("Part");
+ expect(bomLineItemType({ type: "Material" })).toBe("Material");
+ expect(bomLineItemType({ type: null })).toBe("Part");
+ expect(bomLineItemType({ type: "Tool" })).toBeNull();
+ });
+});
+
+describe("changeNoticeDescriptionJson", () => {
+ it("wraps text as a tiptap document and keeps empty as null", () => {
+ expect(changeNoticeDescriptionJson(null)).toBeNull();
+ expect(changeNoticeDescriptionJson("Pushed from Onshape")).toEqual({
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Pushed from Onshape" }]
+ }
+ ]
+ });
+ });
+});
+
+describe("buildAssemblyPlan Show Assembly only", () => {
+ const unitPlan = (
+ mapping?: Parameters<typeof buildAssemblyPlan>[0]["mapping"]
+ ) =>
+ buildAssemblyPlan({
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "WB-100",
+ name: "Workbench",
+ description: null,
+ revision: null
+ },
+ nodes: [
+ node({
+ index: "1",
+ partNumber: "ASM-009",
+ name: "Foot assembly",
+ shownAsUnit: true,
+ properties: [
+ {
+ propertyId: "p-make",
+ name: "Make or buy",
+ valueType: "ENUM",
+ value: "Buy"
+ }
+ ]
+ })
+ ],
+ items: [],
+ methodByItemId: new Map(),
+ mappedLinesByMethodId: new Map(),
+ manualLinesByMethodId: new Map(),
+ options,
+ mapping
+ });
+
+ it("reads Show Assembly only as structure: no BOM, and Make by default", () => {
+ const plan = unitPlan();
+ expect(plan.items[0]).toMatchObject({
+ partNumber: "ASM-009",
+ shownAsUnit: true,
+ isAssembly: false,
+ proposed: {
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order"
+ }
+ });
+ expect(plan.methods.map((m) => m.parentPartNumber)).toEqual(["WB-100"]);
+ });
+
+ it("takes Buy for a one-unit sub-assembly only from a mapped property", () => {
+ const plan = unitPlan({
+ map: [
+ {
+ onshapePropertyId: "p-make",
+ onshapeName: "Make or buy",
+ valueType: "ENUM",
+ target: { kind: "item", field: "replenishmentSystem" },
+ mode: "create",
+ translations: [
+ { onshape: "Buy", carbon: "Buy" },
+ { onshape: "Make", carbon: "Make" }
+ ]
+ }
+ ],
+ definitions: [],
+ descriptionModes: { name: "create", description: "create" },
+ heldCustomFields: new Map()
+ });
+ expect(plan.items[0]?.proposed).toMatchObject({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Pull from Inventory"
+ });
+ expect(plan.items[0]?.itemFields).toEqual([
+ {
+ field: "replenishmentSystem",
+ label: "Replenishment",
+ value: "Buy",
+ mode: "create",
+ onshapeName: "Make or buy"
+ }
+ ]);
+ });
+});
+
+const itemField = (
+ field: PlanItemField["field"],
+ value: string | null,
+ mode: PlanItemField["mode"] = "everyPush",
+ onshapeName = "Make or buy"
+): PlanItemField => ({
+ field,
+ label:
+ {
+ mpn: "Manufacturer Part Number",
+ replenishmentSystem: "Replenishment",
+ defaultMethodType: "Default Method Type",
+ sourcingType: "Sourcing",
+ itemTrackingType: "Tracking Type",
+ unitOfMeasureCode: "Unit of Measure"
+ }[field] ?? field,
+ value,
+ mode,
+ onshapeName
+});
+
+describe("proposeMappedItem — precedence for a new item", () => {
+ it("puts a mapped value above children, Standard content and the defaults", () => {
+ const made = proposeMappedItem(
+ {
+ partNumber: "ASM-1",
+ name: null,
+ hasChildren: true,
+ mapped: { replenishmentSystem: "Buy" }
+ },
+ options
+ );
+ expect(made.proposed.replenishmentSystem).toBe("Buy");
+ // A mapped Buy with no mapped method takes the push default for Buy.
+ expect(made.proposed.defaultMethodType).toBe("Pull from Inventory");
+ expect(made.problems).toEqual([]);
+ });
+
+ it("makes a row with children Make, and a Standard content row Buy", () => {
+ const buyDefaults = {
+ ...options,
+ defaults: {
+ ...DEFAULT_PUSH_DEFAULTS,
+ replenishmentSystem: "Buy" as const,
+ methodTypeForMake: "Pull from Inventory" as const
+ }
+ };
+ expect(
+ proposeItem(
+ { partNumber: "A", name: null, hasChildren: true },
+ buyDefaults
+ )
+ ).toMatchObject({
+ replenishmentSystem: "Make",
+ defaultMethodType: "Pull from Inventory"
+ });
+ expect(
+ proposeItem(
+ { partNumber: "B", name: null, standardContent: true },
+ options
+ )
+ ).toMatchObject({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Pull from Inventory"
+ });
+ expect(
+ proposeItem({ partNumber: "C", name: null }, buyDefaults)
+ ).toMatchObject({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Pull from Inventory"
+ });
+ });
+
+ it("refuses a mapped method the replenishment does not allow", () => {
+ const { proposed, problems } = proposeMappedItem(
+ {
+ partNumber: "P",
+ name: null,
+ mapped: {
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Make to Order"
+ }
+ },
+ options
+ );
+ expect(proposed.defaultMethodType).toBe("Pull from Inventory");
+ expect(problems).toEqual([
+ "Default Method Type: Make to Order is not a method for Buy items. Not written."
+ ]);
+ });
+
+ it("writes Sourcing only on a Buy and Make item, with the method it sets", () => {
+ const dropShip = proposeMappedItem(
+ {
+ partNumber: "P",
+ name: null,
+ mapped: {
+ replenishmentSystem: "Buy and Make",
+ sourcingType: "Drop Ship"
+ }
+ },
+ options
+ );
+ expect(dropShip.proposed).toMatchObject({
+ replenishmentSystem: "Buy and Make",
+ sourcingType: "Drop Ship",
+ defaultMethodType: "Purchase to Order"
+ });
+ const onMake = proposeMappedItem(
+ { partNumber: "P", name: null, mapped: { sourcingType: "Drop Ship" } },
+ options
+ );
+ expect(onMake.proposed.sourcingType).toBeUndefined();
+ expect(onMake.problems).toEqual([
+ "Sourcing applies only to Buy and Make items. Not written."
+ ]);
+ });
+
+ it("carries a mapped MPN, tracking type and unit", () => {
+ expect(
+ proposeItem(
+ {
+ partNumber: "P",
+ name: null,
+ mapped: {
+ mpn: "SKF-6203",
+ itemTrackingType: "Serial",
+ unitOfMeasureCode: "M"
+ }
+ },
+ options
+ )
+ ).toMatchObject({
+ mpn: "SKF-6203",
+ itemTrackingType: "Serial",
+ unitOfMeasureCode: "M"
+ });
+ });
+});
+
+describe("planExistingItem — modes", () => {
+ const current = currentItemFields({
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory",
+ sourcingType: "Specified",
+ unitOfMeasureCode: "EA",
+ mpn: null
+ });
+ const plan = (itemFields: PlanItemField[]) =>
+ planExistingItem({
+ current,
+ item: { name: "Bracket", description: null },
+ onshape: { name: "Bracket", description: null },
+ resolved: { fields: [], itemFields, problems: [] },
+ heldCustomFields: {},
+ descriptionModes: { name: "create", description: "create" },
+ units: options.unitsOfMeasure
+ });
+
+ it("writes an every-push Buy with the method the item page sets", () => {
+ const planned = plan([itemField("replenishmentSystem", "Buy")]);
+ expect(planned.target).toMatchObject({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Purchase to Order"
+ });
+ expect(planned.itemFieldChanges).toEqual([
+ {
+ field: "replenishmentSystem",
+ label: "Replenishment",
+ from: "Make",
+ to: "Buy",
+ onshapeName: "Make or buy"
+ },
+ {
+ field: "defaultMethodType",
+ label: "Default Method Type",
+ from: "Make to Order",
+ to: "Purchase to Order",
+ onshapeName: null
+ }
+ ]);
+ expect(planned.keptDifferences).toBeUndefined();
+ });
+
+ it("keeps Carbon's value for a Set at creation mapping and says so", () => {
+ const planned = plan([itemField("replenishmentSystem", "Buy", "create")]);
+ expect(planned.target).toBeUndefined();
+ expect(planned.itemFieldChanges).toBeUndefined();
+ expect(planned.keptDifferences).toEqual([
+ { label: "Replenishment", onshape: "Buy", carbon: "Make" }
+ ]);
+ });
+
+ it("writes nothing for an empty or matching value", () => {
+ const planned = plan([
+ itemField("replenishmentSystem", null),
+ itemField("itemTrackingType", "Inventory", "everyPush", "Tracking")
+ ]);
+ expect(planned.target).toBeUndefined();
+ expect(planned.keptDifferences).toBeUndefined();
+ });
+
+ it("orders the interlock: replenishment, then method, then sourcing", () => {
+ const planned = plan([
+ itemField("replenishmentSystem", "Buy and Make"),
+ itemField(
+ "defaultMethodType",
+ "Pull from Inventory",
+ "everyPush",
+ "Method"
+ ),
+ itemField("sourcingType", "Drop Ship", "everyPush", "Sourcing")
+ ]);
+ expect(planned.target).toMatchObject({
+ replenishmentSystem: "Buy and Make",
+ sourcingType: "Drop Ship",
+ defaultMethodType: "Purchase to Order"
+ });
+ expect(planned.mappedFieldProblems).toBeUndefined();
+ });
+
+ it("moves Make to Order off an every-push Buy and Make, so apply accepts the pair", () => {
+ // Make / Make to Order item; Onshape maps Replenishment to Buy and Make.
+ const planned = plan([itemField("replenishmentSystem", "Buy and Make")]);
+ expect(planned.target).toMatchObject({
+ replenishmentSystem: "Buy and Make",
+ defaultMethodType: "Pull from Inventory"
+ });
+ expect(planned.mappedFieldProblems).toBeUndefined();
+ const applied = mergeExistingItemEdits(current, null, planned.target);
+ expect(applied.ok).toBe(true);
+ });
+
+ it("lists only the mapped values a new item takes", () => {
+ const created = planCreatedItem(
+ { partNumber: "P", name: null },
+ {
+ fields: [],
+ itemFields: [
+ itemField("sourcingType", "Drop Ship", "create", "Sourcing"),
+ itemField("mpn", "MPN-1", "create", "MPN")
+ ],
+ problems: []
+ },
+ options
+ );
+ expect(created.proposed.sourcingType).toBeUndefined();
+ expect(created.itemFields?.map((field) => field.field)).toEqual(["mpn"]);
+ expect(created.mappedFieldProblems).toEqual([
+ "Sourcing applies only to Buy and Make items. Not written."
+ ]);
+ });
+
+ it("skips Sourcing on a Make item, and a method Make does not allow", () => {
+ const planned = plan([
+ itemField("sourcingType", "Drop Ship", "everyPush", "Sourcing"),
+ itemField("defaultMethodType", "Purchase to Order", "everyPush", "Method")
+ ]);
+ expect(planned.target).toBeUndefined();
+ expect(planned.mappedFieldProblems).toEqual([
+ "Default Method Type: Purchase to Order is not a method for Make items. Not written.",
+ "Sourcing applies only to Buy and Make items. Not written."
+ ]);
+ });
+
+ it("lists a method that goes with another change after it, and credits a mapping only for its own value", () => {
+ const planned = plan([
+ itemField("replenishmentSystem", "Buy and Make"),
+ itemField(
+ "defaultMethodType",
+ "Pull from Inventory",
+ "everyPush",
+ "Method"
+ ),
+ itemField("sourcingType", "Drop Ship", "everyPush", "Sourcing")
+ ]);
+ expect(
+ planned.itemFieldChanges?.map((change) => [
+ change.field,
+ change.onshapeName
+ ])
+ ).toEqual([
+ ["replenishmentSystem", "Make or buy"],
+ ["sourcingType", "Sourcing"],
+ ["defaultMethodType", null]
+ ]);
+ });
+
+ it("names the method Carbon holds, not the one the editor starts from", () => {
+ // Carbon stores Make to Order on a Buy and Make item; the snapshot
+ // reconciles it to a method the pair allows.
+ const row = {
+ name: "Bracket",
+ description: null,
+ replenishmentSystem: "Buy and Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory",
+ sourcingType: "Specified"
+ };
+ const planned = planExistingItem({
+ current: currentItemFields(row),
+ item: row,
+ onshape: { name: "Bracket", description: null },
+ resolved: {
+ fields: [],
+ itemFields: [
+ itemField("sourcingType", "Drop Ship", "everyPush", "Sourcing")
+ ],
+ problems: []
+ },
+ heldCustomFields: {},
+ descriptionModes: { name: "create", description: "create" },
+ units: options.unitsOfMeasure
+ });
+ expect(
+ planned.itemFieldChanges?.find(
+ (change) => change.field === "defaultMethodType"
+ )
+ ).toMatchObject({ from: "Make to Order", to: "Purchase to Order" });
+ });
+
+ it("writes every-push custom fields and keeps Set at creation ones out", () => {
+ const field = (
+ fieldId: string,
+ mode: "create" | "everyPush",
+ value: string
+ ) => ({
+ fieldId,
+ name: fieldId,
+ mode,
+ dataTypeId: 5,
+ listOptions: null,
+ value,
+ onshapeName: fieldId
+ });
+ const planned = planExistingItem({
+ current,
+ item: { name: "Bracket" },
+ onshape: { name: "Bracket", description: null },
+ resolved: {
+ fields: [
+ field("Finish", "everyPush", "Anodized"),
+ field("Coating", "create", "Zinc")
+ ],
+ itemFields: [],
+ problems: []
+ },
+ heldCustomFields: { Finish: "Raw", Coating: "None" },
+ descriptionModes: { name: "create", description: "create" },
+ units: options.unitsOfMeasure
+ });
+ expect(planned.customFields?.map((f) => f.fieldId)).toEqual(["Finish"]);
+ expect(planned.keptDifferences).toEqual([
+ { label: "Coating", onshape: "Zinc", carbon: "None" }
+ ]);
+ });
+});
+
+describe("buildPartPlan — mapped fields", () => {
+ const map: PropertyMapEntry[] = [
+ {
+ onshapePropertyId: "p-make",
+ onshapeName: "Make or buy",
+ valueType: "ENUM",
+ target: { kind: "item", field: "replenishmentSystem" },
+ mode: "everyPush",
+ translations: [
+ { onshape: "Buy", carbon: "Buy" },
+ { onshape: "Make", carbon: "Make" }
+ ]
+ }
+ ];
+ const mapping = {
+ map,
+ definitions: [],
+ descriptionModes: { name: "create", description: "create" } as const,
+ heldCustomFields: new Map()
+ };
+ const props = (value: string) =>
+ new Map([
+ [
+ "p1",
+ [
+ {
+ propertyId: "p-make",
+ name: "Make or buy",
+ valueType: "ENUM",
+ value
+ }
+ ]
+ ]
+ ]);
+ const build = (value: string, microversionId: string) =>
+ buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts: [
+ {
+ partId: "p1",
+ name: "Bracket",
+ partNumber: "BR-1",
+ revision: null,
+ microversionId: "m1"
+ }
+ ],
+ requestedPartIds: ["p1"],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: "d:e:p1",
+ lastSyncedAt: null,
+ metadata: { microversionId }
+ }
+ ],
+ items: [
+ {
+ id: "item-1",
+ readableId: "BR-1",
+ revision: "0",
+ name: "Bracket",
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory"
+ }
+ ],
+ options,
+ mapping,
+ propertiesByPartId: props(value)
+ });
+
+ it("turns an unchanged part into an update when an every-push value differs", () => {
+ const [row] = build("Buy", "m1");
+ expect(row?.action).toBe("update");
+ expect(row?.cadUnchanged).toBe(true);
+ expect(row?.target?.replenishmentSystem).toBe("Buy");
+ });
+
+ it("leaves an unchanged part unchanged when Carbon already agrees", () => {
+ const [row] = build("Make", "m1");
+ expect(row?.action).toBe("unchanged");
+ expect(row?.cadUnchanged).toBeUndefined();
+ });
+
+ it("gives a created part the mapped value", () => {
+ const [row] = buildPartPlan({
+ documentId: "d",
+ elementId: "e",
+ parts: [
+ { partId: "p1", name: "Bracket", partNumber: "BR-2", revision: null }
+ ],
+ requestedPartIds: ["p1"],
+ mappings: [],
+ items: [],
+ options,
+ mapping,
+ propertiesByPartId: props("Buy")
+ });
+ expect(row?.action).toBe("create");
+ expect(row?.proposed?.replenishmentSystem).toBe("Buy");
+ expect(row?.itemFields?.[0]?.onshapeName).toBe("Make or buy");
+ });
+});
+
+describe("mergeExistingItemEdits on top of mapped values", () => {
+ it("lays the reviewer's edit over the mapped target and reports changes against Carbon", () => {
+ const current = currentItemFields({
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory"
+ });
+ const target = {
+ ...current,
+ replenishmentSystem: "Buy" as const,
+ defaultMethodType: "Purchase to Order" as const
+ };
+ const kept = mergeExistingItemEdits(current, {}, target);
+ expect(kept.ok && kept.changed).toEqual({
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Purchase to Order"
+ });
+ const overridden = mergeExistingItemEdits(
+ current,
+ { replenishmentSystem: "Make", defaultMethodType: "Make to Order" },
+ target
+ );
+ expect(overridden.ok && overridden.changed).toEqual({});
+ });
+});
diff --git a/packages/ee/src/onshape/panel/plan.ts b/packages/ee/src/onshape/panel/plan.ts
new file mode 100644
index 0000000000..f4039e5ee0
--- /dev/null
+++ b/packages/ee/src/onshape/panel/plan.ts
@@ -0,0 +1,2244 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { OnshapeElementPart } from "../lib/client";
+import type { OnshapeBomNode } from "./bom";
+import type {
+ ItemMethodType,
+ ItemReplenishmentSystem,
+ ItemSourcingType,
+ ItemTrackingType
+} from "./item-values";
+import {
+ ITEM_METHOD_TYPES,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_SOURCING_TYPES,
+ ITEM_TRACKING_TYPES,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./item-values";
+import type { OnshapePushDefaults } from "./preferences";
+import type {
+ DescriptionModes,
+ OnshapePropertyValue,
+ PlanCustomField,
+ PlanCustomFieldDefinition,
+ PlanItemField,
+ PropertyMapEntry,
+ UnmappedProperty
+} from "./properties";
+import {
+ customFieldDisplayValue,
+ customFieldKeptDifferences,
+ customFieldWrites,
+ DEFAULT_DESCRIPTION_MODES,
+ resolveMappedFields
+} from "./properties";
+import type { PanelRelease, PanelReleaseItem } from "./releases";
+import { isModelReleaseItem } from "./releases";
+import { compareRevisions } from "./revision";
+import type { StandardFieldId } from "./standard-fields";
+import { standardField } from "./standard-fields";
+import {
+ externalIdForAssembly,
+ externalIdForBomLine,
+ externalIdForPart,
+ normalizeConfiguration,
+ type ReleasedRevision
+} from "./status";
+
+/**
+ * Plan builders for panel pushes. APPLY runs the stored plan plus the user's
+ * edits without reading Onshape again, so these stay pure.
+ */
+
+export type {
+ ItemMethodType,
+ ItemReplenishmentSystem,
+ ItemSourcingType,
+ ItemTrackingType
+} from "./item-values";
+export {
+ ITEM_METHOD_TYPES,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_SOURCING_TYPES,
+ ITEM_TRACKING_TYPES,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./item-values";
+
+export const ITEM_NAME_MAX_LENGTH = 255;
+export const ITEM_DESCRIPTION_MAX_LENGTH = 2000;
+
+export type PlanUnitOfMeasure = { code: string; name: string };
+export type PlanOptions = {
+ unitsOfMeasure: PlanUnitOfMeasure[];
+ defaults: OnshapePushDefaults;
+};
+
+export type ProposedItem = {
+ readableId: string;
+ /** "0" when Onshape has no revision. */
+ revision: string;
+ name: string;
+ description: string | null;
+ replenishmentSystem: ItemReplenishmentSystem;
+ defaultMethodType: ItemMethodType;
+ itemTrackingType: ItemTrackingType;
+ unitOfMeasureCode: string;
+ /** Mapped only; apply writes both after the insert (`createdItemExtras`). */
+ mpn?: string | null;
+ sourcingType?: ItemSourcingType | null;
+};
+
+export const EDITABLE_ITEM_FIELDS = [
+ "name",
+ "description",
+ "replenishmentSystem",
+ "defaultMethodType",
+ "itemTrackingType",
+ "unitOfMeasureCode"
+] as const;
+
+export type ItemEdit = Partial<
+ Pick<ProposedItem, (typeof EDITABLE_ITEM_FIELDS)[number]>
+>;
+
+export type PlanMappingRow = {
+ entityId: string;
+ externalId: string | null;
+ lastSyncedAt: string | null;
+ metadata?: Record<string, unknown> | null;
+};
+
+export type OwnedFieldChange = {
+ field: "name" | "description";
+ from: string | null;
+ to: string | null;
+};
+
+export type PlanItemRow = {
+ id: string;
+ readableId: string;
+ revision: string;
+ name: string;
+ description?: string | null;
+ type?: string | null;
+ /** False for a revision a change notice has not released. */
+ active?: boolean | null;
+ replenishmentSystem?: string | null;
+ defaultMethodType?: string | null;
+ itemTrackingType?: string | null;
+ unitOfMeasureCode?: string | null;
+ sourcingType?: string | null;
+ mpn?: string | null;
+};
+
+/** methodMaterial.itemType accepts only these (shared.models methodItemType). */
+export const BOM_LINE_ITEM_TYPES = ["Part", "Material", "Consumable"] as const;
+
+export function bomLineItemType(
+ item: Pick<PlanItemRow, "type">
+): (typeof BOM_LINE_ITEM_TYPES)[number] | null {
+ const type = item.type ?? "Part";
+ return (BOM_LINE_ITEM_TYPES as readonly string[]).includes(type)
+ ? (type as (typeof BOM_LINE_ITEM_TYPES)[number])
+ : null;
+}
+
+/** Latest revision, active rows first, whatever order the rows came in. */
+export function pickLatestRow<
+ T extends { revision: string | null; active?: boolean | null }
+>(rows: T[]): T | undefined {
+ const active = rows.filter((row) => row.active !== false);
+ let latest: T | undefined;
+ for (const row of active.length > 0 ? active : rows) {
+ if (!latest || compareRevisions(row.revision, latest.revision) > 0) {
+ latest = row;
+ }
+ }
+ return latest;
+}
+
+/**
+ * The newest revision below the released one, active or not: Rev B builds on
+ * a Rev A still in its change notice. With none below, the latest row.
+ */
+export function pickRevisionBase<
+ T extends { revision: string | null; active?: boolean | null }
+>(rows: T[], revision: string): T | undefined {
+ let base: T | undefined;
+ for (const row of rows) {
+ if (compareRevisions(row.revision, revision) >= 0) continue;
+ if (!base || compareRevisions(row.revision, base.revision) > 0) {
+ base = row;
+ }
+ }
+ return base ?? pickLatestRow(rows);
+}
+
+/**
+ * The revision the released BOM names when Carbon has it, else the latest row
+ * with the named revision in `missingRevision`.
+ */
+export function pickBomChildRow<
+ T extends {
+ revision: string | null;
+ active?: boolean | null;
+ type?: string | null;
+ }
+>(
+ rows: T[],
+ revision: string | null | undefined
+): { row: T | undefined; missingRevision: string | null } {
+ const named = revision?.trim() || null;
+ if (named) {
+ const match = pickReuseRow(
+ rows.filter((row) => compareRevisions(row.revision, named) === 0)
+ );
+ if (match) return { row: match, missingRevision: null };
+ }
+ const row = pickLatestRow(rows);
+ return { row, missingRevision: named && row ? named : null };
+}
+
+/**
+ * Pairs each Onshape line with a pushed line of its part number, else a manual
+ * line of the same item type, in order. Unpaired manual lines are kept.
+ */
+export function pairManualLines(
+ writes: Array<{ partNumber: string; quantity: number; itemType?: string }>,
+ owned: PlanLine[],
+ manual: PlanLine[]
+): {
+ takesOver: Array<PlanLine & { onshapeQuantity: number }>;
+ keeps: PlanLine[];
+} {
+ const ownedLeft = new Map<string, number>();
+ for (const line of owned) {
+ ownedLeft.set(line.readableId, (ownedLeft.get(line.readableId) ?? 0) + 1);
+ }
+ const manualLeft = [...manual];
+ const takesOver: Array<PlanLine & { onshapeQuantity: number }> = [];
+ for (const write of writes) {
+ const owns = ownedLeft.get(write.partNumber) ?? 0;
+ if (owns > 0) {
+ ownedLeft.set(write.partNumber, owns - 1);
+ continue;
+ }
+ // Item numbers are unique per type; a Material's line is not a Part's.
+ const index = manualLeft.findIndex(
+ (line) =>
+ line.readableId === write.partNumber &&
+ (!write.itemType || !line.itemType || line.itemType === write.itemType)
+ );
+ if (index === -1) continue;
+ const [line] = manualLeft.splice(index, 1);
+ if (line) takesOver.push({ ...line, onshapeQuantity: write.quantity });
+ }
+ return { takesOver, keeps: manualLeft };
+}
+
+/** The latest Part, else the latest row that can be a BOM line, else any. */
+export function pickReuseRow<
+ T extends {
+ revision: string | null;
+ active?: boolean | null;
+ type?: string | null;
+ }
+>(rows: T[]): T | undefined {
+ const parts = rows.filter((row) => (row.type ?? "Part") === "Part");
+ if (parts.length > 0) return pickLatestRow(parts);
+ const usable = rows.filter((row) => bomLineItemType(row) !== null);
+ return pickLatestRow(usable.length > 0 ? usable : rows);
+}
+
+/** A Part at the same revision, else the latest Part; never another type. */
+export function pickAdoptTarget(
+ rows: PlanItemRow[],
+ revision: string | null
+): PlanItemRow | undefined {
+ const parts = rows.filter((row) => (row.type ?? "Part") === "Part");
+ const wanted = (revision ?? "").trim() || "0";
+ return parts.find((row) => row.revision === wanted) ?? pickLatestRow(parts);
+}
+
+export type PlanMethodRow = {
+ id: string;
+ status: string;
+ /** Set when a change notice holds this method (a Draft it staged). */
+ changeOrderId?: string | null;
+};
+
+export type PlanLine = {
+ readableId: string;
+ quantity: number;
+ /** Manual lines only: a takeover must match it. */
+ itemType?: string | null;
+};
+
+/** Configured unit, else "EA", else the first; only codes the company has. */
+export function defaultUnitOfMeasureCode(options: PlanOptions): string {
+ const codes = options.unitsOfMeasure.map((u) => u.code);
+ const configured = options.defaults.unitOfMeasureCode;
+ if (configured && codes.includes(configured)) return configured;
+ if (codes.includes("EA")) return "EA";
+ return codes[0] ?? "EA";
+}
+
+export type ProposalInput = {
+ partNumber: string;
+ name: string | null;
+ description?: string | null;
+ revision?: string | null;
+ hasChildren?: boolean;
+ standardContent?: boolean;
+ mapped?: MappedItemValues;
+};
+
+export function proposeItem(
+ input: ProposalInput,
+ options: PlanOptions
+): ProposedItem {
+ return proposeMappedItem(input, options).proposed;
+}
+
+/**
+ * Per field, the first rule with a value wins: the mapped value, a BOM row with
+ * children is Make, a Standard content row is Buy, the push defaults. The
+ * reviewer's choice overrides all; also returns mapped values it cannot use.
+ */
+export function proposeMappedItem(
+ input: ProposalInput,
+ options: PlanOptions
+): { proposed: ProposedItem; problems: string[] } {
+ const name = (input.name ?? "").trim();
+ const description = (input.description ?? "").trim();
+ const defaults = options.defaults;
+ const defaultMethodFor = (
+ replenishment: ItemReplenishmentSystem
+ ): ItemMethodType =>
+ replenishment === "Make"
+ ? VALID_METHOD_TYPES_BY_REPLENISHMENT.Make.includes(
+ defaults.methodTypeForMake
+ )
+ ? defaults.methodTypeForMake
+ : "Make to Order"
+ : reconcileMethodForReplenishment(
+ replenishment,
+ defaults.methodTypeForBuy
+ );
+ const start: ItemFieldSnapshot = input.hasChildren
+ ? { ...pushDefaultFields(options), replenishmentSystem: "Make" }
+ : input.standardContent
+ ? { ...pushDefaultFields(options), replenishmentSystem: "Buy" }
+ : pushDefaultFields(options);
+ if (input.hasChildren || input.standardContent) {
+ start.defaultMethodType = defaultMethodFor(start.replenishmentSystem);
+ }
+ const { values, problems } = interlockItemFields(
+ start,
+ input.mapped ?? {},
+ defaultMethodFor
+ );
+ return {
+ proposed: {
+ readableId: input.partNumber,
+ revision: (input.revision ?? "").trim() || "0",
+ name: name === "" ? input.partNumber : name,
+ description: description === "" ? null : description,
+ replenishmentSystem: values.replenishmentSystem,
+ defaultMethodType: values.defaultMethodType,
+ itemTrackingType: values.itemTrackingType,
+ unitOfMeasureCode:
+ values.unitOfMeasureCode ?? defaultUnitOfMeasureCode(options),
+ ...(values.mpn ? { mpn: values.mpn } : {}),
+ ...(values.sourcingType ? { sourcingType: values.sourcingType } : {})
+ },
+ problems
+ };
+}
+
+function proposedHolds(proposed: ProposedItem, field: PlanItemField): boolean {
+ return (proposed as Record<string, unknown>)[field.field] === field.value;
+}
+
+function pushDefaultFields(options: PlanOptions): ItemFieldSnapshot {
+ return {
+ replenishmentSystem: options.defaults.replenishmentSystem,
+ defaultMethodType: options.defaults.methodTypeForMake,
+ itemTrackingType: options.defaults.itemTrackingType,
+ unitOfMeasureCode: defaultUnitOfMeasureCode(options)
+ };
+}
+
+export type MergeResult =
+ | { ok: true; item: ProposedItem }
+ | { ok: false; errors: string[] };
+
+/** Refuses what the Part form would; ignores unknown keys and locked fields. */
+export function mergeItemEdits(
+ proposed: ProposedItem,
+ edit: ItemEdit | null | undefined,
+ options: PlanOptions
+): MergeResult {
+ const errors: string[] = [];
+ const item: ProposedItem = { ...proposed };
+ if (!edit) return { ok: true, item };
+
+ if (edit.name !== undefined) {
+ const name = typeof edit.name === "string" ? edit.name.trim() : "";
+ if (name === "") errors.push("Name is required");
+ else if (name.length > ITEM_NAME_MAX_LENGTH)
+ errors.push(`Name is longer than ${ITEM_NAME_MAX_LENGTH} characters`);
+ else item.name = name;
+ }
+
+ if (edit.description !== undefined) {
+ const description =
+ typeof edit.description === "string" ? edit.description.trim() : "";
+ if (description.length > ITEM_DESCRIPTION_MAX_LENGTH)
+ errors.push(
+ `Description is longer than ${ITEM_DESCRIPTION_MAX_LENGTH} characters`
+ );
+ else item.description = description === "" ? null : description;
+ }
+
+ if (edit.replenishmentSystem !== undefined) {
+ if (
+ (ITEM_REPLENISHMENT_SYSTEMS as readonly string[]).includes(
+ edit.replenishmentSystem as string
+ )
+ ) {
+ item.replenishmentSystem = edit.replenishmentSystem;
+ } else {
+ errors.push("Replenishment system is not valid");
+ }
+ }
+
+ if (edit.defaultMethodType !== undefined) {
+ if (
+ (ITEM_METHOD_TYPES as readonly string[]).includes(
+ edit.defaultMethodType as string
+ )
+ ) {
+ item.defaultMethodType = edit.defaultMethodType;
+ } else {
+ errors.push("Default method type is not valid");
+ }
+ }
+
+ if (edit.itemTrackingType !== undefined) {
+ if (
+ (ITEM_TRACKING_TYPES as readonly string[]).includes(
+ edit.itemTrackingType as string
+ )
+ ) {
+ item.itemTrackingType = edit.itemTrackingType;
+ } else {
+ errors.push("Tracking type is not valid");
+ }
+ }
+
+ if (edit.unitOfMeasureCode !== undefined) {
+ const code =
+ typeof edit.unitOfMeasureCode === "string"
+ ? edit.unitOfMeasureCode.trim()
+ : "";
+ if (options.unitsOfMeasure.some((u) => u.code === code)) {
+ item.unitOfMeasureCode = code;
+ } else {
+ errors.push("Unit of measure is not one of the company's units");
+ }
+ }
+
+ // Checked on the merged pair, so an edit to one side still meets the rule.
+ if (
+ !VALID_METHOD_TYPES_BY_REPLENISHMENT[item.replenishmentSystem].includes(
+ item.defaultMethodType
+ )
+ ) {
+ errors.push(
+ `${item.defaultMethodType} is not a valid method for ${item.replenishmentSystem} items`
+ );
+ }
+
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, item };
+}
+
+/** A field the plan did not read is absent, and a push never writes it. */
+export type ItemFieldSnapshot = {
+ replenishmentSystem: ItemReplenishmentSystem;
+ defaultMethodType: ItemMethodType;
+ itemTrackingType: ItemTrackingType;
+ sourcingType?: ItemSourcingType;
+ unitOfMeasureCode?: string;
+ mpn?: string | null;
+};
+
+const SNAPSHOT_FIELDS = [
+ "replenishmentSystem",
+ "defaultMethodType",
+ "sourcingType",
+ "itemTrackingType",
+ "unitOfMeasureCode",
+ "mpn"
+] as const satisfies readonly StandardFieldId[];
+
+export type ItemFieldChange = {
+ field: StandardFieldId;
+ label: string;
+ from: string | null;
+ to: string | null;
+ /** Null when Carbon derived it: the method a Replenishment or Sourcing sets. */
+ onshapeName: string | null;
+};
+
+/** An Onshape value the push does not write to an existing item. */
+export type KeptDifference = {
+ label: string;
+ onshape: string;
+ carbon: string | null;
+};
+
+export type MappedRowPlan = {
+ customFields?: PlanCustomField[];
+ itemFields?: PlanItemField[];
+ /** Existing items only, as are `target` and `keptDifferences`. */
+ itemFieldChanges?: ItemFieldChange[];
+ /** After the mapped writes, before the reviewer's edits; absent if unchanged. */
+ target?: ItemFieldSnapshot;
+ keptDifferences?: KeptDifference[];
+ /** Shown in the review, never written. */
+ mappedFieldProblems?: string[];
+ unmappedProperties?: UnmappedProperty[];
+};
+
+export type PlanMappingContext = {
+ map: PropertyMapEntry[];
+ definitions: PlanCustomFieldDefinition[];
+ descriptionModes: DescriptionModes;
+ /** `part.customFields` per part number. */
+ heldCustomFields: ReadonlyMap<string, unknown>;
+};
+
+function coerceEnum<T extends string>(
+ value: unknown,
+ allowed: readonly T[],
+ fallback: T
+): T {
+ return typeof value === "string" &&
+ (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : fallback;
+}
+
+function isOneOf<T extends string>(
+ value: string,
+ allowed: readonly T[]
+): value is T {
+ return (allowed as readonly string[]).includes(value);
+}
+
+/** The Part form's rule: keep the method when allowed, else the first allowed. */
+export function reconcileMethodForReplenishment(
+ replenishment: ItemReplenishmentSystem,
+ method: ItemMethodType
+): ItemMethodType {
+ const allowed = VALID_METHOD_TYPES_BY_REPLENISHMENT[replenishment];
+ return allowed.includes(method) ? method : (allowed[0] ?? method);
+}
+
+/**
+ * Item page rule (`deriveItemMethodUpdate`): Make pins Make to Order, Buy pins
+ * Purchase to Order. Buy and Make keeps the method only when the pair allows
+ * it; the item page would keep Make to Order too, which apply refuses
+ * (`mergeExistingItemEdits`), so that one takes the Part form's rule.
+ */
+export function methodForReplenishment(
+ replenishment: ItemReplenishmentSystem,
+ method: ItemMethodType
+): ItemMethodType {
+ if (replenishment === "Make") return "Make to Order";
+ if (replenishment === "Buy") return "Purchase to Order";
+ return reconcileMethodForReplenishment(replenishment, method);
+}
+
+/** The method a Sourcing sets (`deriveItemMethodUpdate`); Specified leaves it. */
+function methodForSourcing(
+ sourcing: ItemSourcingType,
+ method: ItemMethodType
+): ItemMethodType {
+ if (sourcing === "Drop Ship") return "Purchase to Order";
+ if (sourcing === "Ship from Inventory") return "Pull from Inventory";
+ return method;
+}
+
+/** Coerced to legal values so the review always seeds a valid choice. */
+export function currentItemFields(row: {
+ replenishmentSystem?: string | null;
+ defaultMethodType?: string | null;
+ itemTrackingType?: string | null;
+ sourcingType?: string | null;
+ unitOfMeasureCode?: string | null;
+ mpn?: string | null;
+}): ItemFieldSnapshot {
+ const replenishmentSystem = coerceEnum(
+ row.replenishmentSystem,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ "Buy"
+ );
+ return {
+ replenishmentSystem,
+ defaultMethodType: reconcileMethodForReplenishment(
+ replenishmentSystem,
+ coerceEnum(
+ row.defaultMethodType,
+ ITEM_METHOD_TYPES,
+ "Pull from Inventory"
+ )
+ ),
+ itemTrackingType: coerceEnum(
+ row.itemTrackingType,
+ ITEM_TRACKING_TYPES,
+ "Inventory"
+ ),
+ ...(row.sourcingType !== undefined
+ ? {
+ sourcingType: coerceEnum(
+ row.sourcingType,
+ ITEM_SOURCING_TYPES,
+ "Specified"
+ )
+ }
+ : {}),
+ ...(typeof row.unitOfMeasureCode === "string"
+ ? { unitOfMeasureCode: row.unitOfMeasureCode }
+ : {}),
+ ...(row.mpn !== undefined ? { mpn: row.mpn } : {})
+ };
+}
+
+export type MappedItemValues = {
+ mpn?: string;
+ replenishmentSystem?: ItemReplenishmentSystem;
+ defaultMethodType?: ItemMethodType;
+ sourcingType?: ItemSourcingType;
+ itemTrackingType?: ItemTrackingType;
+ unitOfMeasureCode?: string;
+};
+
+/** A unit the company lacks is a problem: a translation can outlive its unit. */
+export function mappedItemValues(
+ itemFields: readonly PlanItemField[],
+ units: readonly PlanUnitOfMeasure[]
+): { values: MappedItemValues; problems: string[] } {
+ const values: MappedItemValues = {};
+ const problems: string[] = [];
+ for (const { field, value, label } of itemFields) {
+ if (value === null) continue;
+ switch (field) {
+ case "mpn":
+ values.mpn = value;
+ break;
+ case "replenishmentSystem":
+ if (isOneOf(value, ITEM_REPLENISHMENT_SYSTEMS)) {
+ values.replenishmentSystem = value;
+ }
+ break;
+ case "defaultMethodType":
+ if (isOneOf(value, ITEM_METHOD_TYPES)) values.defaultMethodType = value;
+ break;
+ case "sourcingType":
+ if (isOneOf(value, ITEM_SOURCING_TYPES)) values.sourcingType = value;
+ break;
+ case "itemTrackingType":
+ if (isOneOf(value, ITEM_TRACKING_TYPES))
+ values.itemTrackingType = value;
+ break;
+ case "unitOfMeasureCode":
+ if (units.some((unit) => unit.code === value)) {
+ values.unitOfMeasureCode = value;
+ } else {
+ problems.push(
+ `${label}: Carbon has no unit "${value}". ${label} not written.`
+ );
+ }
+ break;
+ }
+ }
+ return { values, problems };
+}
+
+/**
+ * Lays mapped values over an item's fields in the item page's order:
+ * Replenishment with `methodFor`'s method, the method if allowed, Sourcing
+ * (Buy and Make only) with its method, then tracking, unit and MPN.
+ */
+export function interlockItemFields(
+ start: ItemFieldSnapshot,
+ mapped: MappedItemValues,
+ methodFor: (
+ replenishment: ItemReplenishmentSystem,
+ method: ItemMethodType
+ ) => ItemMethodType
+): { values: ItemFieldSnapshot; problems: string[] } {
+ const values: ItemFieldSnapshot = { ...start };
+ const problems: string[] = [];
+ if (
+ mapped.replenishmentSystem &&
+ mapped.replenishmentSystem !== values.replenishmentSystem
+ ) {
+ values.replenishmentSystem = mapped.replenishmentSystem;
+ values.defaultMethodType = methodFor(
+ mapped.replenishmentSystem,
+ values.defaultMethodType
+ );
+ }
+ if (mapped.defaultMethodType) {
+ if (
+ VALID_METHOD_TYPES_BY_REPLENISHMENT[values.replenishmentSystem].includes(
+ mapped.defaultMethodType
+ )
+ ) {
+ values.defaultMethodType = mapped.defaultMethodType;
+ } else {
+ problems.push(
+ `Default Method Type: ${mapped.defaultMethodType} is not a method for ${values.replenishmentSystem} items. Not written.`
+ );
+ }
+ }
+ if (mapped.sourcingType) {
+ if (values.replenishmentSystem === "Buy and Make") {
+ values.sourcingType = mapped.sourcingType;
+ values.defaultMethodType = methodForSourcing(
+ mapped.sourcingType,
+ values.defaultMethodType
+ );
+ } else {
+ problems.push(
+ "Sourcing applies only to Buy and Make items. Not written."
+ );
+ }
+ }
+ if (mapped.itemTrackingType)
+ values.itemTrackingType = mapped.itemTrackingType;
+ if (mapped.unitOfMeasureCode) {
+ values.unitOfMeasureCode = mapped.unitOfMeasureCode;
+ }
+ if (mapped.mpn) values.mpn = mapped.mpn;
+ return { values, problems };
+}
+
+function fieldLabel(field: StandardFieldId): string {
+ return standardField(field)?.label ?? field;
+}
+
+export function changedItemFields(
+ current: ItemFieldSnapshot,
+ next: ItemFieldSnapshot
+): Partial<ItemFieldSnapshot> {
+ const changed: Partial<ItemFieldSnapshot> = {};
+ for (const field of SNAPSHOT_FIELDS) {
+ const value = next[field];
+ if (value === undefined) continue;
+ if ((current[field] ?? null) !== (value ?? null)) {
+ (changed as Record<string, unknown>)[field] = value;
+ }
+ }
+ return changed;
+}
+
+const DESCRIPTION_LABELS = {
+ name: "Short Description",
+ description: "Long Description"
+} as const;
+
+/**
+ * What a push does to an item it links or that is linked to its source:
+ * "everyPush" values are written (an empty custom field value clears Carbon's)
+ * and "create" values become kept differences.
+ */
+export function planExistingItem({
+ current,
+ item,
+ onshape,
+ resolved,
+ heldCustomFields,
+ descriptionModes,
+ units
+}: {
+ current: ItemFieldSnapshot;
+ item: {
+ name?: string | null;
+ description?: string | null;
+ /** The stored method, which `current` may have reconciled. */
+ defaultMethodType?: string | null;
+ };
+ onshape: { name: string | null; description: string | null };
+ resolved: {
+ fields: PlanCustomField[];
+ itemFields: PlanItemField[];
+ problems: string[];
+ } | null;
+ heldCustomFields: unknown;
+ descriptionModes: DescriptionModes;
+ units: readonly PlanUnitOfMeasure[];
+}): MappedRowPlan & { changes: OwnedFieldChange[] } {
+ const changes: OwnedFieldChange[] = [];
+ const kept: KeptDifference[] = [];
+ for (const change of assemblyTextChanges(
+ { name: item.name ?? "", description: item.description ?? null },
+ onshape
+ )) {
+ if (descriptionModes[change.field] === "everyPush") {
+ changes.push(change);
+ } else if (change.to !== null) {
+ kept.push({
+ label: DESCRIPTION_LABELS[change.field],
+ onshape: change.to,
+ carbon: change.from
+ });
+ }
+ }
+
+ const out: MappedRowPlan & { changes: OwnedFieldChange[] } = { changes };
+ if (resolved) {
+ const everyPush = resolved.itemFields.filter(
+ (field) => field.mode === "everyPush"
+ );
+ const mapped = mappedItemValues(everyPush, units);
+ const interlocked = interlockItemFields(
+ current,
+ mapped.values,
+ methodForReplenishment
+ );
+ const sourceByField = new Map(
+ everyPush
+ .filter((field) => field.value !== null)
+ .map((field) => [field.field, field.onshapeName])
+ );
+ const itemFieldChanges: ItemFieldChange[] = Object.entries(
+ changedItemFields(current, interlocked.values)
+ )
+ .map(([field, to]) => {
+ const id = field as StandardFieldId;
+ return {
+ field: id,
+ label: fieldLabel(id),
+ from:
+ (id === "defaultMethodType" ? item.defaultMethodType : null) ??
+ (current[field as keyof ItemFieldSnapshot] as string | null) ??
+ null,
+ to: (to as string | null) ?? null,
+ // Credited to a mapping only when the value is the mapped one.
+ onshapeName:
+ mapped.values[id] === to ? (sourceByField.get(id) ?? null) : null
+ };
+ })
+ // Derived changes list after the mapped ones.
+ .sort(
+ (a, b) =>
+ Number(a.onshapeName === null) - Number(b.onshapeName === null)
+ );
+ if (itemFieldChanges.length > 0) {
+ out.itemFieldChanges = itemFieldChanges;
+ out.target = interlocked.values;
+ }
+
+ for (const field of resolved.itemFields) {
+ if (field.mode !== "create" || field.value === null) continue;
+ if (!(SNAPSHOT_FIELDS as readonly string[]).includes(field.field)) {
+ continue;
+ }
+ const carbon =
+ (interlocked.values[field.field as keyof ItemFieldSnapshot] as
+ | string
+ | null
+ | undefined) ?? null;
+ if (carbon !== field.value) {
+ kept.push({ label: field.label, onshape: field.value, carbon });
+ }
+ }
+
+ const definitions = new Map(
+ resolved.fields.map((field) => [field.fieldId, field])
+ );
+ const held = (
+ typeof heldCustomFields === "object" && heldCustomFields !== null
+ ? heldCustomFields
+ : {}
+ ) as Record<string, unknown>;
+ const heldText = (field: PlanCustomField) => {
+ const heldValue = held[field.fieldId];
+ return heldValue === undefined || heldValue === null || heldValue === ""
+ ? null
+ : customFieldDisplayValue({
+ value: heldValue as string | number | boolean,
+ dataTypeId:
+ definitions.get(field.fieldId)?.dataTypeId ?? field.dataTypeId
+ });
+ };
+ for (const field of customFieldKeptDifferences(
+ heldCustomFields,
+ resolved.fields
+ )) {
+ kept.push({
+ label: field.name,
+ onshape: customFieldDisplayValue(field),
+ carbon: heldText(field)
+ });
+ }
+ const customFields = customFieldWrites(
+ heldCustomFields,
+ resolved.fields
+ ).map((field) => ({ ...field, replaces: heldText(field) }));
+ if (customFields.length > 0) out.customFields = customFields;
+
+ const itemFields = resolved.itemFields.filter(
+ (field) => field.value !== null
+ );
+ if (itemFields.length > 0) out.itemFields = itemFields;
+ const problems = [
+ ...resolved.problems,
+ ...mapped.problems,
+ ...interlocked.problems
+ ];
+ if (problems.length > 0) out.mappedFieldProblems = problems;
+ }
+ if (kept.length > 0) out.keptDifferences = kept;
+ return out;
+}
+
+export function planCreatedItem(
+ input: Omit<ProposalInput, "mapped">,
+ resolved: {
+ fields: PlanCustomField[];
+ itemFields: PlanItemField[];
+ problems: string[];
+ } | null,
+ options: PlanOptions
+): MappedRowPlan & { proposed: ProposedItem } {
+ if (!resolved) return { proposed: proposeItem(input, options) };
+ const mapped = mappedItemValues(resolved.itemFields, options.unitsOfMeasure);
+ const { proposed, problems } = proposeMappedItem(
+ { ...input, mapped: mapped.values },
+ options
+ );
+ const out: MappedRowPlan & { proposed: ProposedItem } = { proposed };
+ const customFields = resolved.fields.filter((field) => field.value !== null);
+ if (customFields.length > 0) out.customFields = customFields;
+ // A mapped value the interlock skipped is a problem, not a value.
+ const itemFields = resolved.itemFields.filter(
+ (field) => field.value !== null && proposedHolds(proposed, field)
+ );
+ if (itemFields.length > 0) out.itemFields = itemFields;
+ const allProblems = [...resolved.problems, ...mapped.problems, ...problems];
+ if (allProblems.length > 0) out.mappedFieldProblems = allProblems;
+ return out;
+}
+
+/**
+ * Fields `upsertPart` does not take, written after the insert: MPN, and
+ * Sourcing while the item is still Buy and Make after the reviewer's edits.
+ */
+export function createdItemExtras(
+ item: ProposedItem
+): Pick<ItemFieldSnapshot, "mpn" | "sourcingType"> {
+ return {
+ ...(item.mpn ? { mpn: item.mpn } : {}),
+ ...(item.sourcingType && item.replenishmentSystem === "Buy and Make"
+ ? { sourcingType: item.sourcingType }
+ : {})
+ };
+}
+
+/**
+ * `changed` diffs against `current`, so a push that changes nothing writes
+ * nothing and stamps no audit fields.
+ */
+export function mergeExistingItemEdits(
+ current: ItemFieldSnapshot,
+ edit: ItemEdit | null | undefined,
+ base: ItemFieldSnapshot = current
+):
+ | { ok: true; values: ItemFieldSnapshot; changed: Partial<ItemFieldSnapshot> }
+ | { ok: false; errors: string[] } {
+ const errors: string[] = [];
+ const values: ItemFieldSnapshot = { ...base };
+ if (edit?.replenishmentSystem !== undefined) {
+ if (
+ (ITEM_REPLENISHMENT_SYSTEMS as readonly string[]).includes(
+ edit.replenishmentSystem
+ )
+ ) {
+ values.replenishmentSystem =
+ edit.replenishmentSystem as ItemReplenishmentSystem;
+ } else {
+ errors.push("Replenishment system is not valid");
+ }
+ }
+ if (edit?.defaultMethodType !== undefined) {
+ if (
+ (ITEM_METHOD_TYPES as readonly string[]).includes(edit.defaultMethodType)
+ ) {
+ values.defaultMethodType = edit.defaultMethodType as ItemMethodType;
+ } else {
+ errors.push("Default method type is not valid");
+ }
+ }
+ if (edit?.itemTrackingType !== undefined) {
+ if (
+ (ITEM_TRACKING_TYPES as readonly string[]).includes(edit.itemTrackingType)
+ ) {
+ values.itemTrackingType = edit.itemTrackingType as ItemTrackingType;
+ } else {
+ errors.push("Tracking type is not valid");
+ }
+ }
+ if (
+ !VALID_METHOD_TYPES_BY_REPLENISHMENT[values.replenishmentSystem].includes(
+ values.defaultMethodType
+ )
+ ) {
+ errors.push(
+ `${values.defaultMethodType} is not a valid method for ${values.replenishmentSystem} items`
+ );
+ }
+ if (errors.length > 0) return { ok: false, errors };
+ return { ok: true, values, changed: changedItemFields(current, values) };
+}
+
+export type PartPlanAction =
+ | "create"
+ | "adopt"
+ | "update"
+ | "unchanged"
+ | "skip-no-part-number"
+ /** A release made a revision of this part number; the push writes nothing. */
+ | "released";
+
+export type PartPlanRow = MappedRowPlan & {
+ partId: string;
+ partNumber: string | null;
+ name: string;
+ description: string | null;
+ revision: string | null;
+ microversionId: string | null;
+ action: PartPlanAction;
+ itemId: string | null;
+ item: { readableId: string; revision: string; name: string } | null;
+ /** Create only. */
+ proposed: ProposedItem | null;
+ /** adopt/update/unchanged only: seeds the review's selects. */
+ current?: ItemFieldSnapshot | null;
+ /** Descriptions in "everyPush" mode that the push overwrites. */
+ changes: OwnedFieldChange[];
+ /** An update only for mapped values or descriptions; skips the model export. */
+ cadUnchanged?: true;
+};
+
+export type PartPlan = {
+ kind: "part";
+ documentId: string;
+ wv: "w" | "v";
+ wvId: string;
+ elementId: string;
+ /** Null for the default; part of every mapping key apply writes. */
+ configuration?: string | null;
+ rows: PartPlanRow[];
+ options: PlanOptions;
+};
+
+export function buildPartPlan({
+ documentId,
+ elementId,
+ configuration = null,
+ parts,
+ requestedPartIds,
+ mappings,
+ items,
+ options,
+ mapping,
+ propertiesByPartId,
+ released = new Map()
+}: {
+ documentId: string;
+ elementId: string;
+ configuration?: string | null;
+ parts: OnshapeElementPart[];
+ requestedPartIds: string[];
+ mappings: PlanMappingRow[];
+ items: PlanItemRow[];
+ options: PlanOptions;
+ /** `releasedRevisionsByPartNumber` over `items`. */
+ released?: ReadonlyMap<string, ReleasedRevision>;
+ /** Absent: only descriptions are planned. */
+ mapping?: PlanMappingContext;
+ propertiesByPartId?: ReadonlyMap<string, OnshapePropertyValue[]>;
+}): PartPlanRow[] {
+ const mappingByExternalId = new Map(
+ mappings.filter((m) => m.externalId).map((m) => [m.externalId as string, m])
+ );
+ const itemById = new Map(items.map((i) => [i.id, i]));
+ const itemsByReadableId = new Map<string, PlanItemRow[]>();
+ for (const item of items) {
+ const list = itemsByReadableId.get(item.readableId) ?? [];
+ list.push(item);
+ itemsByReadableId.set(item.readableId, list);
+ }
+ const descriptionModes =
+ mapping?.descriptionModes ?? DEFAULT_DESCRIPTION_MODES;
+ const resolve = (partId: string) =>
+ mapping && mapping.map.length > 0
+ ? resolveMappedFields({
+ properties: propertiesByPartId?.get(partId) ?? [],
+ map: mapping.map,
+ definitions: mapping.definitions,
+ units: options.unitsOfMeasure
+ })
+ : null;
+ const existingPlan = (item: PlanItemRow, part: OnshapeElementPart) => {
+ const resolved = resolve(part.partId);
+ const planned = planExistingItem({
+ current: currentItemFields(item),
+ item,
+ onshape: { name: part.name, description: part.description ?? null },
+ resolved,
+ heldCustomFields: mapping?.heldCustomFields.get(item.readableId),
+ descriptionModes,
+ units: options.unitsOfMeasure
+ });
+ return {
+ ...planned,
+ ...nonEmpty("unmappedProperties", resolved?.unmapped ?? [])
+ };
+ };
+
+ const rows: PartPlanRow[] = [];
+ for (const partId of requestedPartIds) {
+ const part = parts.find((p) => p.partId === partId);
+ if (!part) continue; // not in this element: the route reports it
+
+ const base = {
+ partId,
+ partNumber: part.partNumber ?? null,
+ name: part.name,
+ description: part.description ?? null,
+ revision: part.revision ?? null,
+ microversionId: part.microversionId ?? null,
+ itemId: null as string | null,
+ item: null as PartPlanRow["item"],
+ proposed: null as ProposedItem | null,
+ changes: [] as PartPlanRow["changes"]
+ };
+
+ const releasedRevision = part.partNumber
+ ? released.get(part.partNumber)
+ : undefined;
+ const releasedItem = releasedRevision
+ ? itemById.get(releasedRevision.itemId)
+ : undefined;
+ if (releasedItem) {
+ rows.push({
+ ...base,
+ action: "released",
+ itemId: releasedItem.id,
+ item: {
+ readableId: releasedItem.readableId,
+ revision: releasedItem.revision,
+ name: releasedItem.name
+ }
+ });
+ continue;
+ }
+
+ const mapped = mappingByExternalId.get(
+ externalIdForPart(documentId, elementId, partId, configuration)
+ );
+ // A mapping whose item is gone is not a link (entityId has no FK).
+ const linked = mapped ? itemById.get(mapped.entityId) : undefined;
+ if (mapped && linked) {
+ const lastMicroversion = mapped.metadata?.microversionId;
+ const unchanged =
+ !!part.microversionId &&
+ typeof lastMicroversion === "string" &&
+ part.microversionId === lastMicroversion;
+ const planned = existingPlan(linked, part);
+ const writes =
+ planned.changes.length > 0 ||
+ (planned.itemFieldChanges?.length ?? 0) > 0 ||
+ (planned.customFields?.length ?? 0) > 0;
+ rows.push({
+ ...base,
+ ...planned,
+ action: unchanged && !writes ? "unchanged" : "update",
+ ...(unchanged && writes ? { cadUnchanged: true as const } : {}),
+ itemId: linked.id,
+ item: {
+ readableId: linked.readableId,
+ revision: linked.revision,
+ name: linked.name
+ },
+ current: currentItemFields(linked)
+ });
+ continue;
+ }
+
+ if (!part.partNumber) {
+ rows.push({ ...base, action: "skip-no-part-number" });
+ continue;
+ }
+
+ const matched = pickAdoptTarget(
+ itemsByReadableId.get(part.partNumber) ?? [],
+ part.revision ?? null
+ );
+ if (matched) {
+ rows.push({
+ ...base,
+ ...existingPlan(matched, part),
+ action: "adopt",
+ itemId: matched.id,
+ item: {
+ readableId: matched.readableId,
+ revision: matched.revision,
+ name: matched.name
+ },
+ current: currentItemFields(matched)
+ });
+ continue;
+ }
+
+ const resolved = resolve(partId);
+ rows.push({
+ ...base,
+ ...planCreatedItem(
+ {
+ partNumber: part.partNumber,
+ name: part.name,
+ description: part.description ?? null,
+ revision: part.revision ?? null
+ },
+ resolved,
+ options
+ ),
+ ...nonEmpty("unmappedProperties", resolved?.unmapped ?? []),
+ action: "create"
+ });
+ }
+ return rows;
+}
+
+function nonEmpty<K extends string, T>(
+ key: K,
+ list: T[]
+): Partial<Record<K, T[]>> {
+ return list.length > 0 ? ({ [key]: list } as Record<K, T[]>) : {};
+}
+
+/**
+ * Only values Onshape gives count: Name and Description are optional BOM
+ * columns, so an empty cell must not blank Carbon's text.
+ */
+export function assemblyTextChanges(
+ item: Pick<PlanItemRow, "name" | "description">,
+ onshape: { name: string | null; description: string | null }
+): OwnedFieldChange[] {
+ const changes: OwnedFieldChange[] = [];
+ if (onshape.name && onshape.name !== item.name) {
+ changes.push({ field: "name", from: item.name ?? null, to: onshape.name });
+ }
+ if (
+ onshape.description &&
+ onshape.description !== (item.description ?? null)
+ ) {
+ changes.push({
+ field: "description",
+ from: item.description ?? null,
+ to: onshape.description
+ });
+ }
+ return changes;
+}
+
+export type AssemblyPlanItem = MappedRowPlan & {
+ partNumber: string;
+ name: string | null;
+ revision: string | null;
+ action: "create" | "reuse";
+ itemId: string | null;
+ /** Reuse only: matched by part number with no link to this Onshape part. */
+ conflict?: boolean;
+ /** Create only. */
+ proposed: ProposedItem | null;
+ /** Reuse only. */
+ current?: ItemFieldSnapshot | null;
+ /** Reuse only, when the item is or becomes linked to this BOM row. */
+ changes?: OwnedFieldChange[];
+ /**
+ * Reuse only: a release made a revision of this part number, so a workspace
+ * push writes no fields, link or model; BOM changes still go into a Draft.
+ */
+ released?: { revision: string };
+ isAssembly: boolean;
+ /** "Show Assembly only" in Onshape: the push writes no BOM for it. */
+ shownAsUnit?: true;
+};
+
+export type AssemblyPlanMethodStatus =
+ | "draft"
+ | "active"
+ /** The parent item will be created, and its method with it. */
+ | "new"
+ /** Existing item without a make method: refused. */
+ | "missing";
+
+export type AssemblyPlanMethod = {
+ parentPartNumber: string;
+ parentItemId: string | null;
+ status: AssemblyPlanMethodStatus;
+ /** `active` only: the panel's Draft this push writes into; absent, a new one. */
+ reusedDraftVersion?: number | null;
+ writes: Array<{
+ index: string;
+ partNumber: string;
+ name: string | null;
+ quantity: number;
+ }>;
+ /** Lines a previous push wrote. */
+ replaces: PlanLine[];
+ /** Manual lines taking Onshape's quantity; their operation and scrap stay. */
+ takesOver: Array<PlanLine & { onshapeQuantity: number }>;
+ keeps: PlanLine[];
+ /**
+ * `active` with no reusable Draft: Onshape's lines equal the method's and
+ * none is taken over, so no Draft is made. Apply rechecks child methods.
+ */
+ unchanged?: true;
+};
+
+export type AssemblyPlanRoot = MappedRowPlan & {
+ partNumber: string;
+ name: string | null;
+ description: string | null;
+ revision: string | null;
+ action: "create" | "reuse";
+ itemId: string | null;
+ /** `conflict`, `current`, `changes` and `released` as on AssemblyPlanItem. */
+ conflict?: boolean;
+ proposed: ProposedItem | null;
+ current?: ItemFieldSnapshot | null;
+ changes?: OwnedFieldChange[];
+ released?: { revision: string };
+};
+
+/**
+ * `all` writes every sub-assembly's method in one push. `top` writes only the
+ * root's: a line points at its child's own make method, so a multi-level
+ * structure composes from levels pushed separately.
+ */
+export type AssemblyPlanDepth = "all" | "top";
+
+export type AssemblyPlan = {
+ kind: "assembly";
+ documentId: string;
+ wv: "w" | "v";
+ wvId: string;
+ elementId: string;
+ configuration?: string | null;
+ root: AssemblyPlanRoot;
+ items: AssemblyPlanItem[];
+ methods: AssemblyPlanMethod[];
+ /** BOM rows the push cannot place ("<name>: no part number in Onshape"). */
+ skipped: string[];
+ options: PlanOptions;
+ depth: AssemblyPlanDepth;
+ /** `top` plans only: what the push leaves out. */
+ deeper?: {
+ subAssemblies: string[];
+ partCount: number;
+ };
+};
+
+export function flattenNodes(nodes: OnshapeBomNode[]): OnshapeBomNode[] {
+ const out: OnshapeBomNode[] = [];
+ const walk = (list: OnshapeBomNode[]) => {
+ for (const node of list) {
+ out.push(node);
+ walk(node.children);
+ }
+ };
+ walk(nodes);
+ return out;
+}
+
+export function buildAssemblyPlan({
+ documentId,
+ wv,
+ wvId,
+ elementId,
+ root,
+ nodes,
+ items,
+ methodByItemId,
+ mappedLinesByMethodId,
+ manualLinesByMethodId,
+ options,
+ depth = "all",
+ linkedItemIdByExternalId = new Map(),
+ linkedItemIds,
+ configuration = null,
+ reusableDraftByItemId = new Map(),
+ mapping,
+ rootProperties = null,
+ released = new Map()
+}: {
+ documentId: string;
+ wv: "w" | "v";
+ wvId: string;
+ elementId: string;
+ root: {
+ partNumber: string;
+ name: string | null;
+ description: string | null;
+ revision: string | null;
+ };
+ /** Top-level BOM lines with children nested (parseBomTree().lines). */
+ nodes: OnshapeBomNode[];
+ /** Carbon items whose readableId is any part number in the BOM or root. */
+ items: PlanItemRow[];
+ /** Active make method per existing item id (activeMakeMethods). */
+ methodByItemId: Map<string, PlanMethodRow>;
+ /** Lines a previous push wrote, per method id. */
+ mappedLinesByMethodId: Map<string, PlanLine[]>;
+ /** Lines no push wrote, per method id. */
+ manualLinesByMethodId: Map<string, PlanLine[]>;
+ options: PlanOptions;
+ depth?: AssemblyPlanDepth;
+ /** `onshape-v2` item mappings by externalId; a reuse without one conflicts. */
+ linkedItemIdByExternalId?: Map<string, string>;
+ /** Items with any Onshape link; one linked elsewhere is left as it is. */
+ linkedItemIds?: ReadonlySet<string>;
+ configuration?: string | null;
+ /** `loadReusableDrafts`: the Draft a push reuses per Active-method item. */
+ reusableDraftByItemId?: Map<string, { id: string; version: number | null }>;
+ mapping?: PlanMappingContext;
+ /** Element metadata; BOM rows carry their own. */
+ rootProperties?: OnshapePropertyValue[] | null;
+ released?: ReadonlyMap<string, ReleasedRevision>;
+}): AssemblyPlan {
+ const rowsByReadableId = new Map<string, PlanItemRow[]>();
+ // A link to any revision of a part is a link to that part.
+ const readableIdByItemId = new Map<string, string>();
+ for (const item of items) {
+ readableIdByItemId.set(item.id, item.readableId);
+ const list = rowsByReadableId.get(item.readableId) ?? [];
+ list.push(item);
+ rowsByReadableId.set(item.readableId, list);
+ }
+ // The pick apply makes.
+ const itemByReadableId = new Map<string, PlanItemRow>();
+ for (const [readableId, rows] of rowsByReadableId) {
+ const latest = pickReuseRow(rows);
+ if (latest) itemByReadableId.set(readableId, latest);
+ }
+ const everything = flattenNodes(nodes);
+ // At `top` only the root's children become items; `everything` still
+ // describes what is left out.
+ const all = depth === "top" ? nodes : everything;
+
+ // A node with children is made at every depth, exploded or not.
+ const madePartNumbers = new Set<string>([root.partNumber]);
+ for (const node of everything) {
+ if (node.partNumber && node.children.length > 0) {
+ madePartNumbers.add(node.partNumber);
+ }
+ }
+
+ // Linked when a row's source maps to any revision of its part number: a
+ // release repoints the default revision but leaves the part-studio mapping
+ // on the old one.
+ const linkedPartNumbers = new Set<string>();
+ for (const node of everything) {
+ if (!node.partNumber) continue;
+ const externalId = externalIdForBomLine(node.itemSource ?? null);
+ const linkedId = externalId
+ ? linkedItemIdByExternalId.get(externalId)
+ : undefined;
+ if (linkedId && readableIdByItemId.get(linkedId) === node.partNumber) {
+ linkedPartNumbers.add(node.partNumber);
+ }
+ }
+
+ const descriptionModes =
+ mapping?.descriptionModes ?? DEFAULT_DESCRIPTION_MODES;
+ const resolve = (
+ properties: OnshapePropertyValue[] | null | undefined,
+ matchByName: boolean
+ ) =>
+ mapping && mapping.map.length > 0 && properties
+ ? resolveMappedFields({
+ properties,
+ map: mapping.map,
+ definitions: mapping.definitions,
+ units: options.unitsOfMeasure,
+ matchByName
+ })
+ : null;
+ const existingPlan = (
+ item: PlanItemRow,
+ onshape: { name: string | null; description: string | null },
+ resolved: ReturnType<typeof resolve>
+ ) => {
+ const { changes, ...planned } = planExistingItem({
+ current: currentItemFields(item),
+ item,
+ onshape,
+ resolved,
+ heldCustomFields: mapping?.heldCustomFields.get(item.readableId),
+ descriptionModes,
+ units: options.unitsOfMeasure
+ });
+ return { ...planned, ...nonEmpty("changes", changes) };
+ };
+
+ const rootItem = itemByReadableId.get(root.partNumber);
+ const linkedRootId = linkedItemIdByExternalId.get(
+ externalIdForAssembly(documentId, elementId, configuration)
+ );
+ const rootConflict =
+ !!rootItem &&
+ (!linkedRootId || readableIdByItemId.get(linkedRootId) !== root.partNumber);
+ // BOM rows are not reported as unmapped: every column would be.
+ const rootResolved = resolve(rootProperties, false);
+ const rootIdentity = {
+ partNumber: root.partNumber,
+ name: root.name,
+ description: root.description,
+ revision: root.revision
+ };
+ // The pushed assembly is always linked, so it takes "everyPush" values,
+ // unless a release made a revision of it: then only its BOM is written.
+ const rootReleased = released.get(root.partNumber);
+ const planRoot: AssemblyPlanRoot = rootItem
+ ? rootReleased
+ ? {
+ ...rootIdentity,
+ action: "reuse",
+ itemId: rootItem.id,
+ released: { revision: rootReleased.revision },
+ proposed: null
+ }
+ : {
+ ...rootIdentity,
+ ...existingPlan(rootItem, root, rootResolved),
+ ...nonEmpty("unmappedProperties", rootResolved?.unmapped ?? []),
+ action: "reuse",
+ itemId: rootItem.id,
+ ...(rootConflict ? { conflict: true } : {}),
+ current: currentItemFields(rootItem),
+ proposed: null
+ }
+ : {
+ ...rootIdentity,
+ ...planCreatedItem(rootIdentity, rootResolved, options),
+ ...nonEmpty("unmappedProperties", rootResolved?.unmapped ?? []),
+ action: "create",
+ itemId: null
+ };
+
+ // As apply's `linkChildParts`: a row takes "everyPush" values when linked to
+ // it already, or when neither item nor source is linked anywhere and the
+ // source carries one part number.
+ const numbersBySource = new Map<string, Set<string>>();
+ for (const node of everything) {
+ const externalId = externalIdForBomLine(node.itemSource ?? null);
+ if (!externalId || !node.partNumber) continue;
+ const numbers = numbersBySource.get(externalId) ?? new Set<string>();
+ numbers.add(node.partNumber);
+ numbersBySource.set(externalId, numbers);
+ }
+ const pushWrites = (node: OnshapeBomNode, item: PlanItemRow) => {
+ if (!node.partNumber) return false;
+ if (linkedPartNumbers.has(node.partNumber)) return true;
+ if (!linkedItemIds || linkedItemIds.has(item.id)) return false;
+ const externalId = externalIdForBomLine(node.itemSource ?? null);
+ return (
+ !!externalId &&
+ !linkedItemIdByExternalId.has(externalId) &&
+ (numbersBySource.get(externalId)?.size ?? 0) === 1
+ );
+ };
+
+ const planItems: AssemblyPlanItem[] = [];
+ const seen = new Set<string>([root.partNumber]);
+ const skipped: string[] = [];
+ // Items that cannot be a BOM line (a Tool): skipped, as apply refuses them.
+ const unusable = new Set<string>();
+ for (const node of all) {
+ if (!node.partNumber) {
+ skipped.push(`${node.name ?? node.index}: no part number in Onshape`);
+ continue;
+ }
+ if (seen.has(node.partNumber)) continue;
+ seen.add(node.partNumber);
+ const existing = itemByReadableId.get(node.partNumber);
+ if (existing && bomLineItemType(existing) === null) {
+ unusable.add(node.partNumber);
+ skipped.push(
+ `${node.partNumber}: Carbon has it as a ${existing.type ?? "non-part"} item, which cannot be a BOM line`
+ );
+ continue;
+ }
+ const identity = {
+ partNumber: node.partNumber,
+ name: node.name,
+ revision: node.revision,
+ isAssembly: node.children.length > 0,
+ ...(node.shownAsUnit ? { shownAsUnit: true as const } : {})
+ };
+ const childReleased = existing ? released.get(node.partNumber) : undefined;
+ if (existing && childReleased) {
+ planItems.push({
+ ...identity,
+ action: "reuse",
+ itemId: existing.id,
+ released: { revision: childReleased.revision },
+ proposed: null
+ });
+ continue;
+ }
+ if (existing) {
+ planItems.push({
+ ...identity,
+ ...(pushWrites(node, existing)
+ ? existingPlan(existing, node, resolve(node.properties, true))
+ : {}),
+ action: "reuse",
+ itemId: existing.id,
+ ...(!linkedPartNumbers.has(node.partNumber) ? { conflict: true } : {}),
+ current: currentItemFields(existing),
+ proposed: null
+ });
+ continue;
+ }
+ planItems.push({
+ ...identity,
+ ...planCreatedItem(
+ {
+ partNumber: node.partNumber,
+ name: node.name,
+ description: node.description,
+ revision: node.revision,
+ hasChildren: madePartNumbers.has(node.partNumber),
+ standardContent: node.standardContent === true
+ },
+ resolve(node.properties, true),
+ options
+ ),
+ action: "create",
+ itemId: null
+ });
+ }
+
+ // One method per made part number, in tree order; the root first.
+ const methods: AssemblyPlanMethod[] = [];
+ const methodSeen = new Set<string>();
+ const addMethod = (
+ parentPartNumber: string,
+ parentItemId: string | null,
+ children: OnshapeBomNode[]
+ ) => {
+ if (methodSeen.has(parentPartNumber)) return;
+ methodSeen.add(parentPartNumber);
+ const method = parentItemId ? methodByItemId.get(parentItemId) : undefined;
+ const status: AssemblyPlanMethodStatus = !parentItemId
+ ? "new"
+ : !method
+ ? "missing"
+ : method.status === "Active"
+ ? "active"
+ : "draft";
+ // An Active method is written through a Draft: the reused Draft's lines,
+ // or the Active method's, which a new Draft copies with their ownership.
+ const reusedDraft =
+ status === "active" && parentItemId
+ ? reusableDraftByItemId.get(parentItemId)
+ : undefined;
+ const linesMethodId = reusedDraft?.id ?? method?.id;
+ const writes = children
+ .filter((child) => !!child.partNumber && !unusable.has(child.partNumber))
+ .map((child) => ({
+ index: child.index,
+ partNumber: child.partNumber as string,
+ name: child.name,
+ quantity: child.quantity
+ }));
+ const replaces = linesMethodId
+ ? (mappedLinesByMethodId.get(linesMethodId) ?? [])
+ : [];
+ const manual = linesMethodId
+ ? (manualLinesByMethodId.get(linesMethodId) ?? [])
+ : [];
+ // The type of the item each write points at; a new item is a Part.
+ const { takesOver, keeps } = pairManualLines(
+ writes.map((write) => {
+ const existing = itemByReadableId.get(write.partNumber);
+ return {
+ ...write,
+ itemType: existing ? (bomLineItemType(existing) ?? undefined) : "Part"
+ };
+ }),
+ replaces,
+ manual
+ );
+ const unchanged =
+ status === "active" &&
+ !reusedDraft &&
+ takesOver.length === 0 &&
+ writes.length === replaces.length &&
+ writes.every(
+ (write, index) =>
+ replaces[index]?.readableId === write.partNumber &&
+ replaces[index]?.quantity === write.quantity
+ );
+ methods.push({
+ parentPartNumber,
+ parentItemId,
+ status,
+ ...(reusedDraft ? { reusedDraftVersion: reusedDraft.version } : {}),
+ writes,
+ replaces,
+ takesOver,
+ keeps,
+ ...(unchanged ? { unchanged: true as const } : {})
+ });
+ for (const child of children) {
+ if (child.partNumber && child.children.length > 0) {
+ addMethod(
+ child.partNumber,
+ itemByReadableId.get(child.partNumber)?.id ?? null,
+ child.children
+ );
+ }
+ }
+ };
+ addMethod(root.partNumber, rootItem?.id ?? null, nodes);
+
+ if (depth === "all") {
+ return {
+ kind: "assembly",
+ documentId,
+ wv,
+ wvId,
+ elementId,
+ configuration: normalizeConfiguration(configuration),
+ root: planRoot,
+ items: planItems,
+ methods,
+ skipped,
+ options,
+ depth
+ };
+ }
+
+ const topLevelPartNumbers = new Set(
+ nodes.map((node) => node.partNumber).filter((n): n is string => !!n)
+ );
+ const deeperPartNumbers = new Set(
+ everything
+ .map((node) => node.partNumber)
+ .filter(
+ (n): n is string =>
+ !!n && !topLevelPartNumbers.has(n) && n !== root.partNumber
+ )
+ );
+
+ return {
+ kind: "assembly",
+ documentId,
+ wv,
+ wvId,
+ elementId,
+ configuration: normalizeConfiguration(configuration),
+ root: planRoot,
+ items: planItems,
+ // `addMethod` recursed; keep only the root's method.
+ methods: methods.slice(0, 1),
+ skipped,
+ options,
+ depth,
+ deeper: {
+ subAssemblies: nodes
+ .filter((node) => !!node.partNumber && node.children.length > 0)
+ .map((node) => node.partNumber as string),
+ partCount: deeperPartNumbers.size
+ }
+ };
+}
+
+/**
+ * Takes out the methods the push must not write (a change notice's Draft, a
+ * locked revision) and lists each under `skipped` with its reason, keyed by
+ * parent item id. An Active method that stays unchanged writes nothing, so it
+ * is not refused. Apply checks again before it writes.
+ */
+export function withRefusedMethods(
+ plan: AssemblyPlan,
+ reasonByItemId: ReadonlyMap<string, string>
+): AssemblyPlan {
+ const reasonFor = (method: AssemblyPlanMethod) =>
+ method.parentItemId && !method.unchanged
+ ? reasonByItemId.get(method.parentItemId)
+ : undefined;
+ const refused = plan.methods.filter((method) => reasonFor(method));
+ if (refused.length === 0) return plan;
+ return {
+ ...plan,
+ methods: plan.methods.filter((method) => !reasonFor(method)),
+ skipped: [
+ ...plan.skipped,
+ ...refused.map(
+ (method) => `${method.parentPartNumber}: ${reasonFor(method)}`
+ )
+ ]
+ };
+}
+
+export type ReleasePlanItemAction =
+ /** An item already exists at the released letter. */
+ | "reuse"
+ | "revision"
+ | "create"
+ /** A released drawing with a model item to attach to. */
+ | "drawing"
+ | "drawing-unmatched";
+
+export type ReleasePlanItem = MappedRowPlan & {
+ partNumber: string;
+ revision: string;
+ elementType: number;
+ elementId: string;
+ versionId: string;
+ /** Part Studio items: the part the export translates; without one, none. */
+ partId?: string | null;
+ configuration?: string | null;
+ action: ReleasePlanItemAction;
+ baseItemId: string | null;
+ baseRevision: string | null;
+ existingItemId: string | null;
+ /** Create only. */
+ proposed: ProposedItem | null;
+ /** reuse/revision only: the reused item's fields, or the base's. */
+ current?: ItemFieldSnapshot | null;
+ /** reuse/revision only. */
+ changes?: OwnedFieldChange[];
+ /** Released assemblies only; a reused item's Active method is refused. */
+ methodStatus: "draft" | "active" | "new" | "missing" | null;
+ /**
+ * Drawings only: the release's model item with the drawing's number, else
+ * the model the package lists, with `itemId` when Carbon has it outside the
+ * release at the package's revision.
+ */
+ drawingOf?: {
+ partNumber: string;
+ revision: string | null;
+ itemId?: string | null;
+ } | null;
+};
+
+/** A BOM child of a released assembly that is not itself in the release. */
+export type ReleasePlanChild = MappedRowPlan & {
+ partNumber: string;
+ name: string | null;
+ revision: string | null;
+ action: "create" | "reuse";
+ itemId: string | null;
+ /** Reuse only: the Carbon revision the line points at. */
+ itemRevision?: string | null;
+ /** Reuse only: the revision the BOM names that Carbon lacks. */
+ missingRevision?: string;
+ proposed: ProposedItem | null;
+ current?: ItemFieldSnapshot | null;
+};
+
+export type ReleasePlan = {
+ kind: "release";
+ documentId: string;
+ releaseId: string;
+ releaseName: string | null;
+ createdAt: string | null;
+ items: ReleasePlanItem[];
+ children: ReleasePlanChild[];
+ /** Null when the push creates no release item; BOM children do not count. */
+ changeNotice: { name: string; description: string | null } | null;
+ /** An open notice an earlier push of this release made; the push adds to it. */
+ existingChangeNotice?: string | null;
+ makeDefault: boolean;
+ alreadyPushed: boolean;
+ options: PlanOptions;
+};
+
+export function buildReleasePlan({
+ documentId,
+ release,
+ items,
+ bomLinesByElementId,
+ methodByItemId,
+ options,
+ mapping,
+ propertiesByPartNumber,
+ drawingModelByElementId = new Map()
+}: {
+ documentId: string;
+ release: PanelRelease;
+ /** Every Carbon revision row for the release's and the BOMs' part numbers. */
+ items: PlanItemRow[];
+ /**
+ * Keyed by `releaseBomKey` (element plus configuration). Null when the read
+ * failed; apply then leaves that method alone.
+ */
+ bomLinesByElementId: Record<string, OnshapeBomNode[] | null>;
+ methodByItemId: Map<string, PlanMethodRow>;
+ options: PlanOptions;
+ mapping?: PlanMappingContext;
+ /** Model items' properties at the released version; BOM rows carry theirs. */
+ propertiesByPartNumber?: ReadonlyMap<string, OnshapePropertyValue[]>;
+ /** `drawingModels` over the release package, per drawing element. */
+ drawingModelByElementId?: ReadonlyMap<
+ string,
+ { partNumber: string; revision: string | null }
+ >;
+}): ReleasePlan {
+ const descriptionModes =
+ mapping?.descriptionModes ?? DEFAULT_DESCRIPTION_MODES;
+ const resolve = (
+ properties: OnshapePropertyValue[] | null | undefined,
+ matchByName: boolean
+ ) =>
+ mapping && mapping.map.length > 0 && properties
+ ? resolveMappedFields({
+ properties,
+ map: mapping.map,
+ definitions: mapping.definitions,
+ units: options.unitsOfMeasure,
+ matchByName
+ })
+ : null;
+ // A new revision copies its base, then takes the "everyPush" values.
+ const existingPlan = (
+ item: PlanItemRow,
+ onshape: { name: string | null; description: string | null },
+ partNumber: string
+ ) => {
+ const resolved = resolve(propertiesByPartNumber?.get(partNumber), false);
+ const { changes, ...planned } = planExistingItem({
+ current: currentItemFields(item),
+ item,
+ onshape,
+ resolved,
+ heldCustomFields: mapping?.heldCustomFields.get(item.readableId),
+ descriptionModes,
+ units: options.unitsOfMeasure
+ });
+ return {
+ ...planned,
+ ...nonEmpty("changes", changes),
+ ...nonEmpty("unmappedProperties", resolved?.unmapped ?? [])
+ };
+ };
+ const byReadable = new Map<string, PlanItemRow[]>();
+ for (const row of items) {
+ const list = byReadable.get(row.readableId) ?? [];
+ list.push(row);
+ byReadable.set(row.readableId, list);
+ }
+ const letterRowFor = (partNumber: string, revision: string) =>
+ (byReadable.get(partNumber) ?? []).find((row) => row.revision === revision);
+
+ const modelItems = release.items.filter(isModelReleaseItem);
+ const modelPartNumbers = new Set(modelItems.map((item) => item.partNumber));
+
+ // Fallback text for release items: the revisions list has part numbers only.
+ const bomNodeByPartNumber = new Map<string, OnshapeBomNode>();
+ for (const lines of Object.values(bomLinesByElementId)) {
+ for (const node of lines ?? []) {
+ if (node.partNumber && !bomNodeByPartNumber.has(node.partNumber)) {
+ bomNodeByPartNumber.set(node.partNumber, node);
+ }
+ }
+ }
+
+ const planItems: ReleasePlanItem[] = [];
+ for (const item of release.items) {
+ if (!isModelReleaseItem(item)) {
+ const model = modelPartNumbers.has(item.partNumber)
+ ? { partNumber: item.partNumber, revision: item.revision }
+ : (drawingModelByElementId.get(item.elementId) ?? null);
+ const inRelease = !!model && modelPartNumbers.has(model.partNumber);
+ const carbonRow =
+ model && !inRelease && model.revision
+ ? letterRowFor(model.partNumber, model.revision)
+ : undefined;
+ const attaches = inRelease || !!carbonRow;
+ planItems.push({
+ ...releaseIdentity(item),
+ action: attaches ? "drawing" : "drawing-unmatched",
+ baseItemId: null,
+ baseRevision: null,
+ existingItemId: null,
+ proposed: null,
+ methodStatus: null,
+ drawingOf: model
+ ? { ...model, ...(carbonRow ? { itemId: carbonRow.id } : {}) }
+ : null
+ });
+ continue;
+ }
+
+ const isAssembly = item.elementType === 1;
+ const node = bomNodeByPartNumber.get(item.partNumber);
+ const properties = propertiesByPartNumber?.get(item.partNumber);
+ const onshapeText = {
+ name: propertyText(properties, "Name") ?? node?.name ?? null,
+ description:
+ propertyText(properties, "Description") ?? node?.description ?? null
+ };
+ const existingLetter = letterRowFor(item.partNumber, item.revision);
+ if (existingLetter) {
+ const method = methodByItemId.get(existingLetter.id);
+ planItems.push({
+ ...releaseIdentity(item),
+ ...existingPlan(existingLetter, onshapeText, item.partNumber),
+ action: "reuse",
+ baseItemId: null,
+ baseRevision: null,
+ existingItemId: existingLetter.id,
+ proposed: null,
+ current: currentItemFields(existingLetter),
+ methodStatus: !isAssembly
+ ? null
+ : !method
+ ? "missing"
+ : method.status === "Active"
+ ? "active"
+ : "draft"
+ });
+ continue;
+ }
+
+ const base = pickRevisionBase(
+ byReadable.get(item.partNumber) ?? [],
+ item.revision
+ );
+ if (base) {
+ planItems.push({
+ ...releaseIdentity(item),
+ ...existingPlan(base, onshapeText, item.partNumber),
+ action: "revision",
+ baseItemId: base.id,
+ baseRevision: base.revision,
+ existingItemId: null,
+ proposed: null,
+ current: currentItemFields(base),
+ methodStatus: isAssembly ? "new" : null
+ });
+ continue;
+ }
+
+ const resolved = resolve(properties, false);
+ planItems.push({
+ ...releaseIdentity(item),
+ ...planCreatedItem(
+ {
+ partNumber: item.partNumber,
+ name: onshapeText.name,
+ description: onshapeText.description,
+ revision: item.revision,
+ hasChildren: isAssembly
+ },
+ resolved,
+ options
+ ),
+ ...nonEmpty("unmappedProperties", resolved?.unmapped ?? []),
+ action: "create",
+ baseItemId: null,
+ baseRevision: null,
+ existingItemId: null,
+ methodStatus: isAssembly ? "new" : null
+ });
+ }
+
+ // Level-1 BOM children outside the release: reused when Carbon has any
+ // revision, else created. A reused child is not linked, so takes no values.
+ const children: ReleasePlanChild[] = [];
+ const childSeen = new Set<string>();
+ for (const lines of Object.values(bomLinesByElementId)) {
+ for (const node of lines ?? []) {
+ if (!node.partNumber || modelPartNumbers.has(node.partNumber)) continue;
+ if (childSeen.has(node.partNumber)) continue;
+ childSeen.add(node.partNumber);
+ const { row: existing, missingRevision } = pickBomChildRow(
+ byReadable.get(node.partNumber) ?? [],
+ node.revision
+ );
+ const identity = {
+ partNumber: node.partNumber,
+ name: node.name,
+ revision: node.revision
+ };
+ if (existing) {
+ children.push({
+ ...identity,
+ action: "reuse",
+ itemId: existing.id,
+ itemRevision: existing.revision,
+ ...(missingRevision ? { missingRevision } : {}),
+ current: currentItemFields(existing),
+ proposed: null
+ });
+ continue;
+ }
+ children.push({
+ ...identity,
+ ...planCreatedItem(
+ {
+ partNumber: node.partNumber,
+ name: node.name,
+ description: node.description,
+ revision: node.revision,
+ hasChildren: node.children.length > 0,
+ standardContent: node.standardContent === true
+ },
+ resolve(node.properties, true),
+ options
+ ),
+ action: "create",
+ itemId: null
+ });
+ }
+ }
+
+ // The notice gets one affected row per created release item and none for
+ // BOM children, so only release items propose one.
+ const createsReleaseItems = planItems.some(
+ (item) => item.action === "revision" || item.action === "create"
+ );
+ // A release whose items are all in Carbon can still create a BOM child.
+ const createsAnything =
+ createsReleaseItems || children.some((child) => child.action === "create");
+
+ return {
+ kind: "release",
+ documentId,
+ releaseId: release.releaseId,
+ releaseName: release.releaseName,
+ createdAt: release.createdAt,
+ items: planItems,
+ children,
+ changeNotice: createsReleaseItems
+ ? {
+ name: release.releaseName ?? `Onshape release ${release.releaseId}`,
+ description: null
+ }
+ : null,
+ makeDefault: true,
+ alreadyPushed: !createsAnything,
+ options
+ };
+}
+
+function propertyText(
+ properties: OnshapePropertyValue[] | undefined,
+ name: string
+): string | null {
+ const value = properties?.find((property) => property.name === name)?.value;
+ if (typeof value !== "string") return null;
+ const text = value.trim();
+ return text === "" ? null : text;
+}
+
+function releaseIdentity(item: PanelReleaseItem) {
+ return {
+ partNumber: item.partNumber,
+ revision: item.revision,
+ elementType: item.elementType,
+ elementId: item.elementId,
+ versionId: item.versionId,
+ partId: item.partId ?? null,
+ // Raw: the export sends it back to Onshape as the revision gave it.
+ configuration: item.configuration ?? null
+ };
+}
+
+export type ChangeNoticeEdit = {
+ name: string;
+ description: string | null;
+};
+
+export const CHANGE_NOTICE_NAME_MAX_LENGTH = 255;
+export const CHANGE_NOTICE_DESCRIPTION_MAX_LENGTH = 4000;
+
+export function mergeChangeNoticeEdit(
+ proposed: ChangeNoticeEdit,
+ edit: Partial<ChangeNoticeEdit> | null | undefined
+):
+ | { ok: true; changeNotice: ChangeNoticeEdit }
+ | { ok: false; errors: string[] } {
+ const errors: string[] = [];
+ const changeNotice: ChangeNoticeEdit = { ...proposed };
+ if (!edit) return { ok: true, changeNotice };
+ if (edit.name !== undefined) {
+ const name = typeof edit.name === "string" ? edit.name.trim() : "";
+ if (name === "") errors.push("Change notice name is required");
+ else if (name.length > CHANGE_NOTICE_NAME_MAX_LENGTH)
+ errors.push(
+ `Change notice name is longer than ${CHANGE_NOTICE_NAME_MAX_LENGTH} characters`
+ );
+ else changeNotice.name = name;
+ }
+ if (edit.description !== undefined) {
+ const description =
+ typeof edit.description === "string" ? edit.description.trim() : "";
+ if (description.length > CHANGE_NOTICE_DESCRIPTION_MAX_LENGTH)
+ errors.push(
+ `Change notice description is longer than ${CHANGE_NOTICE_DESCRIPTION_MAX_LENGTH} characters`
+ );
+ else changeNotice.description = description === "" ? null : description;
+ }
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, changeNotice };
+}
+
+/** changeOrder.description is a tiptap document; wraps text as the ERP form does. */
+export function changeNoticeDescriptionJson(text: string | null): {
+ type: "doc";
+ content: Array<{
+ type: "paragraph";
+ content: Array<{ type: "text"; text: string }>;
+ }>;
+} | null {
+ if (!text) return null;
+ return {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }]
+ };
+}
+
+/** Keyed as the plan is: partId for parts, part number otherwise. */
+export function mergeEditsForCreates(
+ creates: Array<{ key: string; proposed: ProposedItem }>,
+ edits: Record<string, ItemEdit> | null | undefined,
+ options: PlanOptions
+): {
+ items: Map<string, ProposedItem>;
+ errors: Array<{ key: string; errors: string[] }>;
+} {
+ const items = new Map<string, ProposedItem>();
+ const errors: Array<{ key: string; errors: string[] }> = [];
+ for (const { key, proposed } of creates) {
+ const merged = mergeItemEdits(proposed, edits?.[key], options);
+ if (merged.ok) items.set(key, merged.item);
+ else errors.push({ key, errors: merged.errors });
+ }
+ return { items, errors };
+}
diff --git a/packages/ee/src/onshape/panel/preferences.test.ts b/packages/ee/src/onshape/panel/preferences.test.ts
new file mode 100644
index 0000000000..85e2fabc3e
--- /dev/null
+++ b/packages/ee/src/onshape/panel/preferences.test.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { DEFAULT_PUSH_DEFAULTS, parsePushDefaults } from "./preferences";
+
+describe("parsePushDefaults", () => {
+ it("returns the documented defaults for anything that is not an object", () => {
+ for (const value of [null, undefined, "onshape", 7, []]) {
+ expect(parsePushDefaults(value)).toEqual(DEFAULT_PUSH_DEFAULTS);
+ }
+ });
+
+ it("ignores the integration's other metadata keys", () => {
+ expect(
+ parsePushDefaults({ credentials: { access_token: "x" }, propertyMap: [] })
+ ).toEqual(DEFAULT_PUSH_DEFAULTS);
+ });
+
+ it("reads a full set of stored preferences", () => {
+ expect(
+ parsePushDefaults({
+ defaultUnitOfMeasureCode: "KG",
+ defaultReplenishmentSystem: "Buy and Make",
+ defaultMethodTypeForMake: "Pull from Inventory",
+ defaultMethodTypeForBuy: "Purchase to Order",
+ defaultItemTrackingType: "Serial"
+ })
+ ).toEqual({
+ unitOfMeasureCode: "KG",
+ replenishmentSystem: "Buy and Make",
+ methodTypeForMake: "Pull from Inventory",
+ methodTypeForBuy: "Purchase to Order",
+ itemTrackingType: "Serial"
+ });
+ });
+
+ it("falls back per field, keeping the values that do parse", () => {
+ const parsed = parsePushDefaults({
+ defaultUnitOfMeasureCode: " ",
+ defaultReplenishmentSystem: "Borrow",
+ defaultItemTrackingType: "Serial"
+ });
+ expect(parsed.unitOfMeasureCode).toBeNull();
+ expect(parsed.replenishmentSystem).toBe("Make");
+ expect(parsed.itemTrackingType).toBe("Serial");
+ });
+
+ it("reconciles a method the replenishment system stopped allowing", () => {
+ const parsed = parsePushDefaults({
+ defaultReplenishmentSystem: "Buy",
+ defaultMethodTypeForMake: "Make to Order",
+ defaultMethodTypeForBuy: "Make to Order"
+ });
+ expect(parsed.methodTypeForMake).toBe("Pull from Inventory");
+ expect(parsed.methodTypeForBuy).toBe("Pull from Inventory");
+ });
+
+ it("keeps a method that is still legal for its replenishment system", () => {
+ const parsed = parsePushDefaults({
+ defaultReplenishmentSystem: "Make",
+ defaultMethodTypeForMake: "Make to Order"
+ });
+ expect(parsed.methodTypeForMake).toBe("Make to Order");
+ });
+});
diff --git a/packages/ee/src/onshape/panel/preferences.ts b/packages/ee/src/onshape/panel/preferences.ts
new file mode 100644
index 0000000000..b6d8d9941f
--- /dev/null
+++ b/packages/ee/src/onshape/panel/preferences.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// The push defaults, stored as `default*` keys on the integration metadata.
+// Parsing is total: a value that does not parse falls back to the default, so
+// a plan always builds.
+
+import type {
+ ItemMethodType,
+ ItemReplenishmentSystem,
+ ItemTrackingType
+} from "./plan";
+import {
+ ITEM_METHOD_TYPES,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_TRACKING_TYPES,
+ VALID_METHOD_TYPES_BY_REPLENISHMENT
+} from "./plan";
+
+export type OnshapePushDefaults = {
+ /** Null: resolved from the company's units at plan time. */
+ unitOfMeasureCode: string | null;
+ /** Replenishment when no mapping and no BOM rule decides it. */
+ replenishmentSystem: ItemReplenishmentSystem;
+ /** Default method for an item created as Make, or with the default above. */
+ methodTypeForMake: ItemMethodType;
+ /** Default method for an item a mapping or Standard content makes Buy. */
+ methodTypeForBuy: ItemMethodType;
+ itemTrackingType: ItemTrackingType;
+};
+
+export const DEFAULT_PUSH_DEFAULTS: OnshapePushDefaults = {
+ unitOfMeasureCode: null,
+ replenishmentSystem: "Make",
+ methodTypeForMake: "Make to Order",
+ methodTypeForBuy: "Pull from Inventory",
+ itemTrackingType: "Inventory"
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function pickEnum<T extends string>(
+ value: unknown,
+ allowed: readonly T[],
+ fallback: T
+): T {
+ return typeof value === "string" &&
+ (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : fallback;
+}
+
+function pickTrimmedString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed === "" ? null : trimmed;
+}
+
+export function parsePushDefaults(metadata: unknown): OnshapePushDefaults {
+ if (!isRecord(metadata)) return { ...DEFAULT_PUSH_DEFAULTS };
+
+ const replenishmentSystem = pickEnum(
+ metadata.defaultReplenishmentSystem,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ DEFAULT_PUSH_DEFAULTS.replenishmentSystem
+ );
+ const methodTypeForMake = pickEnum(
+ metadata.defaultMethodTypeForMake,
+ ITEM_METHOD_TYPES,
+ DEFAULT_PUSH_DEFAULTS.methodTypeForMake
+ );
+ const methodTypeForBuy = pickEnum(
+ metadata.defaultMethodTypeForBuy,
+ ITEM_METHOD_TYPES,
+ DEFAULT_PUSH_DEFAULTS.methodTypeForBuy
+ );
+
+ return reconcilePushDefaults({
+ unitOfMeasureCode: pickTrimmedString(metadata.defaultUnitOfMeasureCode),
+ replenishmentSystem,
+ methodTypeForMake,
+ methodTypeForBuy,
+ itemTrackingType: pickEnum(
+ metadata.defaultItemTrackingType,
+ ITEM_TRACKING_TYPES,
+ DEFAULT_PUSH_DEFAULTS.itemTrackingType
+ )
+ });
+}
+
+/**
+ * Replenishment and method are saved independently, so a pair the Part form
+ * would refuse resolves to a method the replenishment allows.
+ */
+export function reconcilePushDefaults(
+ defaults: OnshapePushDefaults
+): OnshapePushDefaults {
+ return {
+ ...defaults,
+ methodTypeForMake: reconcileMethodType(
+ defaults.replenishmentSystem,
+ defaults.methodTypeForMake,
+ DEFAULT_PUSH_DEFAULTS.methodTypeForMake
+ ),
+ methodTypeForBuy: reconcileMethodType(
+ "Buy",
+ defaults.methodTypeForBuy,
+ DEFAULT_PUSH_DEFAULTS.methodTypeForBuy
+ )
+ };
+}
+
+function reconcileMethodType(
+ replenishment: ItemReplenishmentSystem,
+ configured: ItemMethodType,
+ fallback: ItemMethodType
+): ItemMethodType {
+ const allowed = VALID_METHOD_TYPES_BY_REPLENISHMENT[replenishment];
+ if (allowed.includes(configured)) return configured;
+ if (allowed.includes(fallback)) return fallback;
+ // Unreachable: the readonly index type only adds `undefined`.
+ return allowed[0] ?? DEFAULT_PUSH_DEFAULTS.methodTypeForMake;
+}
diff --git a/packages/ee/src/onshape/panel/properties.test.ts b/packages/ee/src/onshape/panel/properties.test.ts
new file mode 100644
index 0000000000..2b488dc40f
--- /dev/null
+++ b/packages/ee/src/onshape/panel/properties.test.ts
@@ -0,0 +1,789 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { PropertyMapEntry } from "./properties";
+import {
+ CUSTOM_FIELD_DATA_TYPES,
+ coerceOnshapeValue,
+ customFieldKeptDifferences,
+ customFieldWrites,
+ MAPPABLE_VALUE_TYPES,
+ mappedFieldValues,
+ mergeCustomFieldValues,
+ parseDescriptionModes,
+ parseProperties,
+ parsePropertyMap,
+ partPropertiesFromElementMetadata,
+ propertyDisplayValue,
+ propertyMapEqual,
+ resolveMappedFields
+} from "./properties";
+
+const textField = {
+ id: "cf_text",
+ name: "Coating",
+ dataTypeId: 5,
+ listOptions: null
+};
+const numField = {
+ id: "cf_num",
+ name: "Mass",
+ dataTypeId: 4,
+ listOptions: null
+};
+
+describe("parseProperties", () => {
+ it("normalises the metadata property array and drops malformed rows", () => {
+ const properties = parseProperties({
+ properties: [
+ {
+ propertyId: "p1",
+ name: "Vendor",
+ valueType: "STRING",
+ value: "ACME"
+ },
+ { propertyId: "p2", name: "No type", value: 4 },
+ { name: "no id", valueType: "STRING", value: "x" },
+ "garbage"
+ ]
+ });
+ expect(properties).toEqual([
+ {
+ propertyId: "p1",
+ name: "Vendor",
+ valueType: "STRING",
+ value: "ACME",
+ editable: undefined
+ },
+ {
+ propertyId: "p2",
+ name: "No type",
+ valueType: "STRING",
+ value: 4,
+ editable: undefined
+ }
+ ]);
+ });
+
+ it("reads a list value as its option's label, the text the BOM shows", () => {
+ const [state, unit, unknown] = parseProperties({
+ properties: [
+ {
+ propertyId: "p1",
+ name: "State",
+ valueType: "ENUM",
+ value: "2",
+ enumValues: [
+ { label: "In progress", value: "0" },
+ { label: "Released", value: "2" }
+ ]
+ },
+ {
+ propertyId: "p2",
+ name: "Unit of measure",
+ valueType: "ENUM",
+ value: "Each",
+ enumValues: [{ label: null, value: "Each" }]
+ },
+ {
+ propertyId: "p3",
+ name: "Finish",
+ valueType: "ENUM",
+ value: "9",
+ enumValues: [{ label: "Painted", value: "1" }]
+ }
+ ]
+ });
+ expect(state?.value).toBe("Released");
+ expect(unit?.value).toBe("Each");
+ expect(unknown?.value).toBe("9");
+ });
+
+ it("lists a list's options as labels, the value where a label is empty", () => {
+ const [state, unit, text] = parseProperties({
+ properties: [
+ {
+ propertyId: "p1",
+ name: "State",
+ valueType: "ENUM",
+ value: "0",
+ enumValues: [
+ { label: "In progress", value: "0" },
+ { label: "Released", value: "2" }
+ ]
+ },
+ {
+ propertyId: "p2",
+ name: "Unit of measure",
+ valueType: "ENUM",
+ value: "Each",
+ enumValues: [{ label: "", value: "Each" }, "garbage"]
+ },
+ { propertyId: "p3", name: "MPN", valueType: "STRING", value: "X" }
+ ]
+ });
+ expect(state?.options).toEqual(["In progress", "Released"]);
+ expect(unit?.options).toEqual(["Each"]);
+ expect(text?.options).toBeUndefined();
+ });
+
+ it("reads N/A as no value, as a BOM row does", () => {
+ const [mpn] = parseProperties({
+ properties: [
+ { propertyId: "p1", name: "MPN", valueType: "STRING", value: "N/A" }
+ ]
+ });
+ expect(mpn?.value).toBeNull();
+ });
+});
+
+describe("partPropertiesFromElementMetadata", () => {
+ it("returns per-part properties when depth nests parts, else null", () => {
+ const nested = partPropertiesFromElementMetadata({
+ parts: {
+ items: [
+ {
+ partId: "JHD",
+ properties: [
+ {
+ propertyId: "p1",
+ name: "Vendor",
+ valueType: "STRING",
+ value: "ACME"
+ }
+ ]
+ }
+ ]
+ }
+ });
+ expect(nested?.get("JHD")?.[0]?.value).toBe("ACME");
+ expect(partPropertiesFromElementMetadata({ properties: [] })).toBeNull();
+ expect(
+ partPropertiesFromElementMetadata({ parts: { items: [] } })
+ ).toBeNull();
+ });
+});
+
+describe("coerceOnshapeValue / propertyDisplayValue", () => {
+ it("coerces each Carbon type and reports what cannot coerce", () => {
+ expect(coerceOnshapeValue("ACME", 5, null)).toEqual({
+ ok: true,
+ value: "ACME"
+ });
+ expect(coerceOnshapeValue({ displayName: "Steel 4140" }, 5, null)).toEqual({
+ ok: true,
+ value: "Steel 4140"
+ });
+ expect(coerceOnshapeValue(true, 1, null)).toEqual({
+ ok: true,
+ value: "on"
+ });
+ expect(coerceOnshapeValue("Yes", 1, null)).toEqual({
+ ok: true,
+ value: "on"
+ });
+ expect(coerceOnshapeValue(false, 1, null)).toEqual({
+ ok: true,
+ value: null
+ });
+ expect(coerceOnshapeValue("No", 1, null)).toEqual({
+ ok: true,
+ value: null
+ });
+ expect(coerceOnshapeValue("maybe", 1, null).ok).toBe(false);
+ expect(coerceOnshapeValue("2026-08-31T00:00:00Z", 2, null)).toEqual({
+ ok: true,
+ value: "2026-08-31"
+ });
+ expect(coerceOnshapeValue("soon", 2, null).ok).toBe(false);
+ expect(coerceOnshapeValue("2026-13-40", 2, null).ok).toBe(false);
+ expect(coerceOnshapeValue("2026-02-30", 2, null).ok).toBe(false);
+ expect(coerceOnshapeValue(12.5, 4, null)).toEqual({
+ ok: true,
+ value: 12.5
+ });
+ expect(coerceOnshapeValue("12.5", 4, null)).toEqual({
+ ok: true,
+ value: 12.5
+ });
+ expect(coerceOnshapeValue("heavy", 4, null).ok).toBe(false);
+ expect(coerceOnshapeValue("C", 3, ["A", "B"])).toEqual({
+ ok: true,
+ value: "C"
+ });
+ expect(coerceOnshapeValue("", 5, null)).toEqual({ ok: true, value: null });
+ expect(coerceOnshapeValue(null, 4, null)).toEqual({
+ ok: true,
+ value: null
+ });
+ expect(propertyDisplayValue({ name: "Al 6061" })).toBe("Al 6061");
+ });
+});
+
+describe("parsePropertyMap", () => {
+ it("reads the earlier shape: carbonFieldId is a custom field, owned is every push", () => {
+ expect(
+ parsePropertyMap({
+ propertyMap: [
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Vendor",
+ valueType: "STRING",
+ carbonFieldId: "cf_text",
+ mode: "owned"
+ },
+ {
+ onshapePropertyId: "p2",
+ onshapeName: "Finish",
+ valueType: "ENUM",
+ carbonFieldId: "cf_list",
+ mode: "default"
+ },
+ {
+ onshapePropertyId: "p3",
+ onshapeName: "Coating",
+ valueType: "STRING",
+ carbonFieldId: "cf_other"
+ }
+ ]
+ })
+ ).toEqual([
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Vendor",
+ valueType: "STRING",
+ target: { kind: "customField", fieldId: "cf_text" },
+ mode: "everyPush"
+ },
+ {
+ onshapePropertyId: "p2",
+ onshapeName: "Finish",
+ valueType: "ENUM",
+ target: { kind: "customField", fieldId: "cf_list" },
+ mode: "create"
+ },
+ {
+ onshapePropertyId: "p3",
+ onshapeName: "Coating",
+ valueType: "STRING",
+ target: { kind: "customField", fieldId: "cf_other" },
+ mode: "create"
+ }
+ ]);
+ expect(parsePropertyMap(null)).toEqual([]);
+ expect(parsePropertyMap({ credentials: {} })).toEqual([]);
+ });
+
+ it("reads item targets with their translation", () => {
+ expect(
+ parsePropertyMap({
+ propertyMap: [
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Make or buy",
+ valueType: "ENUM",
+ target: { kind: "item", field: "replenishmentSystem" },
+ mode: "everyPush",
+ translations: [
+ { onshape: "Purchased", carbon: "Buy" },
+ { onshape: "Unknown", carbon: null }
+ ]
+ }
+ ]
+ })
+ ).toEqual([
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Make or buy",
+ valueType: "ENUM",
+ target: { kind: "item", field: "replenishmentSystem" },
+ mode: "everyPush",
+ translations: [
+ { onshape: "Purchased", carbon: "Buy" },
+ { onshape: "Unknown", carbon: null }
+ ]
+ }
+ ]);
+ });
+
+ it("gives a list item field with no stored translation the default rows", () => {
+ const [entry] = parsePropertyMap({
+ propertyMap: [
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Tracking",
+ valueType: "STRING",
+ target: { kind: "item", field: "itemTrackingType" },
+ mode: "create"
+ }
+ ]
+ });
+ expect(entry?.translations?.map((row) => row.onshape)).toEqual([
+ "Inventory",
+ "Non-Inventory",
+ "Serial",
+ "Batch"
+ ]);
+ });
+
+ it("drops an entry with an unknown target", () => {
+ expect(
+ parsePropertyMap({
+ propertyMap: [
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Price",
+ valueType: "DOUBLE",
+ target: { kind: "item", field: "unitCost" },
+ mode: "create"
+ }
+ ]
+ })
+ ).toEqual([]);
+ });
+});
+
+describe("parseDescriptionModes", () => {
+ it("defaults each description to Set at creation", () => {
+ expect(parseDescriptionModes(null)).toEqual({
+ name: "create",
+ description: "create"
+ });
+ expect(
+ parseDescriptionModes({
+ descriptionModes: { name: "everyPush", description: "owned" }
+ })
+ ).toEqual({ name: "everyPush", description: "create" });
+ });
+});
+
+describe("resolveMappedFields", () => {
+ const map = [
+ {
+ onshapePropertyId: "p1",
+ onshapeName: "Vendor",
+ valueType: "STRING",
+ target: { kind: "customField" as const, fieldId: "cf_text" },
+ mode: "everyPush" as const
+ },
+ {
+ onshapePropertyId: "p2",
+ onshapeName: "Mass",
+ valueType: "DOUBLE",
+ target: { kind: "customField" as const, fieldId: "cf_num" },
+ mode: "create" as const
+ },
+ {
+ onshapePropertyId: "p3",
+ onshapeName: "Gone",
+ valueType: "STRING",
+ target: { kind: "customField" as const, fieldId: "cf_deleted" },
+ mode: "everyPush" as const
+ }
+ ];
+ const properties = [
+ { propertyId: "p1", name: "Vendor", valueType: "STRING", value: "ACME" },
+ {
+ propertyId: "p2",
+ name: "Mass",
+ valueType: "DOUBLE",
+ value: "not a number"
+ },
+ { propertyId: "p3", name: "Gone", valueType: "STRING", value: "x" },
+ { propertyId: "p4", name: "Project", valueType: "STRING", value: "Apollo" },
+ { propertyId: "p5", name: "Name", valueType: "STRING", value: "Lamp base" },
+ { propertyId: "p6", name: "Empty", valueType: "STRING", value: "" }
+ ];
+
+ it("maps, reports problems, and lists valued unmapped properties", () => {
+ const { fields, problems, unmapped } = resolveMappedFields({
+ properties,
+ map,
+ definitions: [textField, numField]
+ });
+ expect(fields).toEqual([
+ {
+ fieldId: "cf_text",
+ name: "Coating",
+ mode: "everyPush",
+ dataTypeId: 5,
+ listOptions: null,
+ value: "ACME",
+ onshapeName: "Vendor"
+ }
+ ]);
+ expect(problems).toEqual([
+ 'Mass → Mass: "not a number" is not a number',
+ "Gone: the mapped Carbon field no longer exists"
+ ]);
+ // Reserved (Name) and empty properties never show as unmapped.
+ expect(unmapped).toEqual([
+ {
+ propertyId: "p4",
+ name: "Project",
+ valueType: "STRING",
+ value: "Apollo"
+ }
+ ]);
+ });
+});
+
+describe("resolveMappedFields — item fields", () => {
+ const units = [
+ { code: "EA", name: "Each" },
+ { code: "KG", name: "Kilogram" }
+ ];
+ const map: PropertyMapEntry[] = [
+ {
+ onshapePropertyId: "p-make",
+ onshapeName: "Make or buy",
+ valueType: "ENUM",
+ target: { kind: "item", field: "replenishmentSystem" },
+ mode: "create",
+ translations: [
+ { onshape: "Buy", carbon: "Buy" },
+ { onshape: "Make", carbon: "Make" },
+ { onshape: "Either", carbon: null }
+ ]
+ },
+ {
+ onshapePropertyId: "p-mpn",
+ onshapeName: "Vendor part",
+ valueType: "STRING",
+ target: { kind: "item", field: "mpn" },
+ mode: "everyPush"
+ },
+ {
+ onshapePropertyId: "p-unit",
+ onshapeName: "Unit",
+ valueType: "STRING",
+ target: { kind: "item", field: "unitOfMeasureCode" },
+ mode: "create",
+ translations: []
+ }
+ ];
+ const property = (propertyId: string, name: string, value: unknown) => ({
+ propertyId,
+ name,
+ valueType: "STRING",
+ value
+ });
+
+ it("translates list values and keeps text as it is, with its source", () => {
+ const { itemFields, problems } = resolveMappedFields({
+ properties: [
+ property("p-make", "Make or buy", " buy "),
+ property("p-mpn", "Vendor part", "SKF-6203"),
+ property("p-unit", "Unit", "kilogram")
+ ],
+ map,
+ definitions: [],
+ units
+ });
+ expect(problems).toEqual([]);
+ expect(itemFields).toEqual([
+ {
+ field: "replenishmentSystem",
+ label: "Replenishment",
+ value: "Buy",
+ mode: "create",
+ onshapeName: "Make or buy"
+ },
+ {
+ field: "mpn",
+ label: "Manufacturer Part Number",
+ value: "SKF-6203",
+ mode: "everyPush",
+ onshapeName: "Vendor part"
+ },
+ {
+ field: "unitOfMeasureCode",
+ label: "Unit of Measure",
+ value: "KG",
+ mode: "create",
+ onshapeName: "Unit"
+ }
+ ]);
+ });
+
+ it("reports a value no row matches, and gives No value for a row set to it", () => {
+ const outsourced = resolveMappedFields({
+ properties: [property("p-make", "Make or buy", "Outsourced")],
+ map,
+ definitions: [],
+ units
+ });
+ expect(outsourced.itemFields).toEqual([]);
+ expect(outsourced.problems).toEqual([
+ 'Make or buy: "Outsourced" has no Carbon value. Replenishment not written.'
+ ]);
+ const either = resolveMappedFields({
+ properties: [property("p-make", "Make or buy", "Either")],
+ map,
+ definitions: [],
+ units
+ });
+ expect(either.problems).toEqual([]);
+ expect(either.itemFields[0]?.value).toBeNull();
+ });
+
+ it("matches a BOM column by name when its id is not the property id", () => {
+ const { itemFields } = resolveMappedFields({
+ properties: [property("column-7", "Make or buy", "Make")],
+ map,
+ definitions: [],
+ units,
+ matchByName: true
+ });
+ expect(itemFields.map((field) => field.value)).toEqual(["Make"]);
+ expect(
+ resolveMappedFields({
+ properties: [property("column-7", "Make or buy", "Make")],
+ map,
+ definitions: [],
+ units
+ }).itemFields
+ ).toEqual([]);
+ });
+});
+
+describe("mappedFieldValues", () => {
+ const field = (
+ fieldId: string,
+ mode: "create" | "everyPush",
+ value: string | null
+ ) => ({
+ fieldId,
+ name: fieldId,
+ mode,
+ dataTypeId: 5,
+ listOptions: null,
+ value,
+ onshapeName: fieldId
+ });
+ const fields = [
+ field("cf_every", "everyPush", "Anodized"),
+ field("cf_emptied", "everyPush", null),
+ field("cf_create", "create", "Painted"),
+ field("cf_unset", "create", null)
+ ];
+
+ it("writes every value on a create, nulls left out", () => {
+ const { values, fieldIds } = mappedFieldValues(fields, true);
+ expect(values).toEqual({ cf_every: "Anodized", cf_create: "Painted" });
+ expect([...fieldIds]).toEqual(["cf_every", "cf_create"]);
+ });
+
+ it("writes only every-push values on an existing item, nulls included", () => {
+ const { values, fieldIds } = mappedFieldValues(fields, false);
+ expect(values).toEqual({ cf_every: "Anodized", cf_emptied: null });
+ expect([...fieldIds]).toEqual(["cf_every", "cf_emptied"]);
+ });
+});
+
+describe("customFieldWrites", () => {
+ const field = (
+ value: string | number | boolean | null,
+ mode: "create" | "everyPush" = "everyPush"
+ ) => ({
+ fieldId: "cf-title",
+ name: "Title",
+ mode,
+ dataTypeId: 5,
+ listOptions: null,
+ value,
+ onshapeName: "Description"
+ });
+
+ it("writes a newly mapped value that Carbon does not hold yet", () => {
+ expect(customFieldWrites({}, [field("Rubber pad")])).toHaveLength(1);
+ expect(customFieldWrites(null, [field("Rubber pad")])).toHaveLength(1);
+ });
+
+ it("writes nothing when Carbon already holds the value", () => {
+ expect(
+ customFieldWrites({ "cf-title": "Rubber pad" }, [field("Rubber pad")])
+ ).toEqual([]);
+ });
+
+ it("clears a value Onshape emptied, and only when Carbon holds one", () => {
+ expect(
+ customFieldWrites({ "cf-title": "Rubber pad" }, [field(null)])
+ ).toHaveLength(1);
+ expect(customFieldWrites({}, [field(null)])).toEqual([]);
+ expect(customFieldWrites({ "cf-title": "" }, [field(null)])).toEqual([]);
+ });
+
+ it("never writes a Set at creation field to an existing item", () => {
+ expect(customFieldWrites({}, [field("x", "create")])).toEqual([]);
+ });
+});
+
+describe("customFieldKeptDifferences", () => {
+ const field = (value: string | null, mode: "create" | "everyPush") => ({
+ fieldId: "cf-title",
+ name: "Title",
+ mode,
+ dataTypeId: 5,
+ listOptions: null,
+ value,
+ onshapeName: "Description"
+ });
+
+ it("lists a Set at creation value that differs from Carbon's", () => {
+ expect(
+ customFieldKeptDifferences({ "cf-title": "Ours" }, [
+ field("Theirs", "create")
+ ])
+ ).toHaveLength(1);
+ expect(
+ customFieldKeptDifferences({ "cf-title": "Same" }, [
+ field("Same", "create")
+ ])
+ ).toEqual([]);
+ expect(
+ customFieldKeptDifferences({}, [field("Theirs", "everyPush")])
+ ).toEqual([]);
+ expect(customFieldKeptDifferences({}, [field(null, "create")])).toEqual([]);
+ });
+});
+
+describe("mergeCustomFieldValues", () => {
+ it("clears an allowed key whose value is null", () => {
+ expect(
+ mergeCustomFieldValues(
+ { cf_text: "ACME", cf_keep: "ours" },
+ { cf_text: null, cf_keep: null },
+ new Set(["cf_text"])
+ )
+ ).toEqual({ cf_keep: "ours" });
+ });
+
+ it("touches only allowed keys and keeps Carbon-owned values", () => {
+ expect(
+ mergeCustomFieldValues(
+ { cf_keep: "ours", cf_text: "old" },
+ { cf_text: "ACME", cf_blocked: "no" },
+ new Set(["cf_text"])
+ )
+ ).toEqual({ cf_keep: "ours", cf_text: "ACME" });
+ expect(
+ mergeCustomFieldValues(null, { cf_text: "A" }, new Set(["cf_text"]))
+ ).toEqual({ cf_text: "A" });
+ });
+});
+
+describe("MAPPABLE_VALUE_TYPES", () => {
+ it("offers exactly one target per value type", () => {
+ expect(MAPPABLE_VALUE_TYPES).toEqual({
+ STRING: [CUSTOM_FIELD_DATA_TYPES.text],
+ ENUM: [CUSTOM_FIELD_DATA_TYPES.text],
+ BOOL: [CUSTOM_FIELD_DATA_TYPES.boolean],
+ INT: [CUSTOM_FIELD_DATA_TYPES.numeric],
+ DOUBLE: [CUSTOM_FIELD_DATA_TYPES.numeric],
+ DATE: [CUSTOM_FIELD_DATA_TYPES.date],
+ OBJECT: [CUSTOM_FIELD_DATA_TYPES.text]
+ });
+ });
+
+ it("never offers a List target, so no new map can constrain a value", () => {
+ for (const targets of Object.values(MAPPABLE_VALUE_TYPES)) {
+ expect(targets).not.toContain(CUSTOM_FIELD_DATA_TYPES.list);
+ }
+ });
+
+ it("leaves the unsupported types out rather than coercing them", () => {
+ for (const valueType of ["COMPUTED", "CATEGORY", "USER", "BLOB"]) {
+ expect(Object.hasOwn(MAPPABLE_VALUE_TYPES, valueType)).toBe(false);
+ }
+ });
+});
+
+describe("propertyMapEqual", () => {
+ const entry = (
+ onshapePropertyId: string,
+ fieldId: string,
+ mode: "create" | "everyPush" = "create"
+ ) => ({
+ onshapePropertyId,
+ target: { kind: "customField" as const, fieldId },
+ mode
+ });
+
+ it("ignores the order the entries arrive in", () => {
+ expect(
+ propertyMapEqual(
+ [entry("p1", "f1"), entry("p2", "f2")],
+ [entry("p2", "f2"), entry("p1", "f1")]
+ )
+ ).toBe(true);
+ });
+
+ it("notices a remapped field and a removed row", () => {
+ const base = [entry("p1", "f1"), entry("p2", "f2")];
+ expect(propertyMapEqual(base, [entry("p1", "f9"), entry("p2", "f2")])).toBe(
+ false
+ );
+ expect(propertyMapEqual(base, [entry("p1", "f1")])).toBe(false);
+ });
+
+ it("notices a changed mode and a changed translation", () => {
+ expect(
+ propertyMapEqual([entry("p1", "f1")], [entry("p1", "f1", "everyPush")])
+ ).toBe(false);
+ const item = (carbon: string | null) => ({
+ onshapePropertyId: "p1",
+ target: { kind: "item" as const, field: "replenishmentSystem" as const },
+ mode: "create" as const,
+ translations: [{ onshape: "Buy", carbon }]
+ });
+ expect(propertyMapEqual([item("Buy")], [item("Buy")])).toBe(true);
+ expect(propertyMapEqual([item("Buy")], [item(null)])).toBe(false);
+ });
+
+ it("notices a duplicated row on either side", () => {
+ const base = [entry("p1", "f1"), entry("p2", "f2")];
+ const doubled = [entry("p1", "f1"), entry("p1", "f1")];
+ expect(propertyMapEqual(base, doubled)).toBe(false);
+ expect(propertyMapEqual(doubled, base)).toBe(false);
+ });
+
+ it("notices a row mapped to a different property id", () => {
+ expect(propertyMapEqual([entry("p1", "f1")], [entry("p2", "f1")])).toBe(
+ false
+ );
+ });
+
+ it("ignores the display fields a load refreshes from Onshape", () => {
+ const stored: PropertyMapEntry[] = [
+ {
+ ...entry("p1", "f1"),
+ onshapeName: "Vendor",
+ valueType: "STRING"
+ }
+ ];
+ const renamed: PropertyMapEntry[] = [
+ {
+ ...entry("p1", "f1"),
+ onshapeName: "Supplier",
+ valueType: "ENUM"
+ }
+ ];
+ expect(propertyMapEqual(stored, renamed)).toBe(true);
+ });
+
+ it("holds for two empty maps", () => {
+ expect(propertyMapEqual([], [])).toBe(true);
+ });
+
+ it("does not call a duplicated key equal to two distinct ones", () => {
+ expect(
+ propertyMapEqual(
+ [entry("p1", "f1"), entry("p1", "f1")],
+ [entry("p1", "f1"), entry("p2", "f1")]
+ )
+ ).toBe(false);
+ });
+});
diff --git a/packages/ee/src/onshape/panel/properties.ts b/packages/ee/src/onshape/panel/properties.ts
new file mode 100644
index 0000000000..4469353104
--- /dev/null
+++ b/packages/ee/src/onshape/panel/properties.ts
@@ -0,0 +1,654 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+// Onshape properties → part custom fields and item fields, through the
+// company's property map (`propertyMap` on the integration metadata).
+
+import { parseDate } from "@internationalized/date";
+import type { PlanUnitOfMeasure } from "./plan";
+import type { StandardFieldId, ValueTranslation } from "./standard-fields";
+import {
+ defaultTranslations,
+ isStandardFieldId,
+ standardField,
+ translateValue
+} from "./standard-fields";
+
+export type OnshapePropertyValue = {
+ propertyId: string;
+ name: string;
+ valueType: string;
+ value: unknown;
+ editable?: boolean;
+ /** An ENUM's options as labels, when the metadata lists them. */
+ options?: string[];
+};
+
+/**
+ * "create" (Set at creation): written only to an item the push creates.
+ * "everyPush" (Update on every push): also replaces Carbon's value on an
+ * existing item the push links.
+ */
+export const MAPPING_MODES = ["create", "everyPush"] as const;
+export type MappingMode = (typeof MAPPING_MODES)[number];
+
+export type PropertyMapTarget =
+ | { kind: "customField"; fieldId: string }
+ | { kind: "item"; field: StandardFieldId };
+
+export type PropertyMapEntry = {
+ onshapePropertyId: string;
+ /** Display, and the BOM column fallback; the propertyId is the join. */
+ onshapeName: string;
+ valueType: string;
+ target: PropertyMapTarget;
+ mode: MappingMode;
+ /** List item fields only: Onshape value → Carbon value. */
+ translations?: ValueTranslation[];
+};
+
+export type DescriptionModes = {
+ /** Short Description (`item.name`). */
+ name: MappingMode;
+ /** Long Description (`item.description`). */
+ description: MappingMode;
+};
+
+export const DEFAULT_DESCRIPTION_MODES: DescriptionModes = {
+ name: "create",
+ description: "create"
+};
+
+export type PlanCustomFieldDefinition = {
+ id: string;
+ name: string;
+ /** A `CUSTOM_FIELD_DATA_TYPES` value. */
+ dataTypeId: number;
+ listOptions: string[] | null;
+};
+
+export type PlanCustomField = {
+ fieldId: string;
+ name: string;
+ mode: MappingMode;
+ dataTypeId: number;
+ listOptions: string[] | null;
+ /** Coerced to the Carbon type; null when Onshape holds no value. */
+ value: string | number | boolean | null;
+ onshapeName: string;
+ /** Existing items only: Carbon's current value as text, null when none. */
+ replaces?: string | null;
+};
+
+export type PlanItemField = {
+ field: StandardFieldId;
+ label: string;
+ /** After translation; null writes nothing. */
+ value: string | null;
+ mode: MappingMode;
+ onshapeName: string;
+};
+
+export type UnmappedProperty = {
+ propertyId: string;
+ name: string;
+ valueType: string;
+ value: string;
+};
+
+/**
+ * A ticked Yes/No custom field: the ERP checkbox's post value, and what its
+ * tables test for. A JSON `true` renders unticked; unticked is no key.
+ */
+export const BOOLEAN_TRUE = "on";
+
+export const CUSTOM_FIELD_DATA_TYPES = {
+ boolean: 1,
+ date: 2,
+ list: 3,
+ numeric: 4,
+ text: 5
+} as const;
+
+export const CUSTOM_FIELD_TYPE_LABELS: Record<number, string> = {
+ [CUSTOM_FIELD_DATA_TYPES.boolean]: "Yes/No",
+ [CUSTOM_FIELD_DATA_TYPES.date]: "Date",
+ [CUSTOM_FIELD_DATA_TYPES.list]: "List",
+ [CUSTOM_FIELD_DATA_TYPES.numeric]: "Numeric",
+ [CUSTOM_FIELD_DATA_TYPES.text]: "Text"
+};
+
+/**
+ * The custom field type each Onshape value type maps onto; absent types (USER,
+ * BLOB, …) are not mappable. Textual types land on Text, never List: Onshape
+ * owns the value and its options, so Carbon keeps an unconstrained copy.
+ */
+export const MAPPABLE_VALUE_TYPES: Record<string, readonly number[]> = {
+ STRING: [CUSTOM_FIELD_DATA_TYPES.text],
+ BOOL: [CUSTOM_FIELD_DATA_TYPES.boolean],
+ INT: [CUSTOM_FIELD_DATA_TYPES.numeric],
+ DOUBLE: [CUSTOM_FIELD_DATA_TYPES.numeric],
+ DATE: [CUSTOM_FIELD_DATA_TYPES.date],
+ ENUM: [CUSTOM_FIELD_DATA_TYPES.text],
+ // Material and similar objects map as their display name.
+ OBJECT: [CUSTOM_FIELD_DATA_TYPES.text]
+};
+
+/** Identity, description and lifecycle properties: never "not mapped". */
+const RESERVED_PROPERTY_NAMES = new Set([
+ "Name",
+ "Part number",
+ "Revision",
+ "Description",
+ "State",
+ "Exclude from BOM",
+ "Not revision managed"
+]);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * A list value as its option's label: the metadata API sends the stored value
+ * ("2"), a BOM cell the label ("Released"), and a mapping must see one text.
+ */
+function enumLabel(value: unknown, options: unknown): unknown {
+ if (typeof value !== "string" || !Array.isArray(options)) return value;
+ const option = options.find(
+ (entry) => isRecord(entry) && entry.value === value
+ );
+ const label = isRecord(option) ? option.label : null;
+ return typeof label === "string" && label.trim() !== "" ? label : value;
+}
+
+function enumOptions(options: unknown): string[] | null {
+ if (!Array.isArray(options)) return null;
+ const labels: string[] = [];
+ for (const option of options) {
+ if (!isRecord(option)) continue;
+ const label = enumLabel(option.value, options);
+ if (typeof label === "string" && label.trim() !== "") labels.push(label);
+ }
+ return labels.length > 0 ? labels : null;
+}
+
+/**
+ * "N/A" is Onshape's BOM text for a property the row does not have (a
+ * part-only property on an assembly row). Read as no value on every path.
+ */
+export function isNotApplicable(value: unknown): boolean {
+ return typeof value === "string" && value.trim() === "N/A";
+}
+
+export function parseProperties(payload: unknown): OnshapePropertyValue[] {
+ const properties = isRecord(payload) ? payload.properties : null;
+ if (!Array.isArray(properties)) return [];
+ const out: OnshapePropertyValue[] = [];
+ for (const property of properties) {
+ if (!isRecord(property)) continue;
+ const propertyId = property.propertyId;
+ const name = property.name;
+ const valueType = property.valueType;
+ if (typeof propertyId !== "string" || typeof name !== "string") continue;
+ const options =
+ valueType === "ENUM" ? enumOptions(property.enumValues) : null;
+ out.push({
+ propertyId,
+ name,
+ valueType: typeof valueType === "string" ? valueType : "STRING",
+ value: isNotApplicable(property.value)
+ ? null
+ : valueType === "ENUM"
+ ? enumLabel(property.value, property.enumValues)
+ : property.value,
+ editable:
+ typeof property.editable === "boolean" ? property.editable : undefined,
+ ...(options ? { options } : {})
+ });
+ }
+ return out;
+}
+
+/** Per-part properties from element metadata at `depth=2`; null if not nested. */
+export function partPropertiesFromElementMetadata(
+ payload: unknown
+): Map<string, OnshapePropertyValue[]> | null {
+ const parts = isRecord(payload) ? payload.parts : null;
+ const items = isRecord(parts) ? parts.items : null;
+ if (!Array.isArray(items) || items.length === 0) return null;
+ const byPartId = new Map<string, OnshapePropertyValue[]>();
+ for (const item of items) {
+ if (!isRecord(item)) continue;
+ const partId = item.partId;
+ if (typeof partId !== "string") continue;
+ byPartId.set(partId, parseProperties(item));
+ }
+ return byPartId.size > 0 ? byPartId : null;
+}
+
+export function propertyDisplayValue(value: unknown): string | null {
+ if (value === null || value === undefined) return null;
+ if (typeof value === "string") {
+ const text = value.trim();
+ return text === "" ? null : text;
+ }
+ if (typeof value === "number" || typeof value === "boolean") {
+ return String(value);
+ }
+ if (isRecord(value)) {
+ const display = value.displayName ?? value.name;
+ return typeof display === "string" && display.trim() !== ""
+ ? display
+ : null;
+ }
+ return null;
+}
+
+/** An absent value is `{ ok: true, value: null }`: not written, no problem. */
+export function coerceOnshapeValue(
+ value: unknown,
+ dataTypeId: number,
+ listOptions: string[] | null
+):
+ | { ok: true; value: string | number | boolean | null }
+ | { ok: false; reason: string } {
+ const text = propertyDisplayValue(value);
+ switch (dataTypeId) {
+ case CUSTOM_FIELD_DATA_TYPES.boolean: {
+ if (typeof value === "boolean") {
+ return { ok: true, value: value ? BOOLEAN_TRUE : null };
+ }
+ if (text === null) return { ok: true, value: null };
+ if (/^(true|yes|on)$/i.test(text)) {
+ return { ok: true, value: BOOLEAN_TRUE };
+ }
+ if (/^(false|no|off)$/i.test(text)) return { ok: true, value: null };
+ return { ok: false, reason: `"${text}" is not yes/no` };
+ }
+ case CUSTOM_FIELD_DATA_TYPES.date: {
+ if (text === null) return { ok: true, value: null };
+ const match = text.match(/^(\d{4})-(\d{2})-(\d{2})/);
+ if (!match) return { ok: false, reason: `"${text}" is not a date` };
+ const [, year, month, day] = match as unknown as [
+ string,
+ string,
+ string,
+ string
+ ];
+ // The regex passes "2026-13-40"; `parseDate` refuses it.
+ try {
+ return {
+ ok: true,
+ value: parseDate(`${year}-${month}-${day}`).toString()
+ };
+ } catch {
+ return { ok: false, reason: `"${text}" is not a date` };
+ }
+ }
+ case CUSTOM_FIELD_DATA_TYPES.numeric: {
+ if (typeof value === "number" && Number.isFinite(value)) {
+ return { ok: true, value };
+ }
+ if (text === null) return { ok: true, value: null };
+ const parsed = Number(text);
+ if (!Number.isFinite(parsed)) {
+ return { ok: false, reason: `"${text}" is not a number` };
+ }
+ return { ok: true, value: parsed };
+ }
+ case CUSTOM_FIELD_DATA_TYPES.list: {
+ if (text === null) return { ok: true, value: null };
+ // Not checked against listOptions: the text is written as it is.
+ return { ok: true, value: text };
+ }
+ case CUSTOM_FIELD_DATA_TYPES.text:
+ return { ok: true, value: text };
+ default:
+ return { ok: false, reason: "unsupported field type" };
+ }
+}
+
+function isMappingMode(value: unknown): value is MappingMode {
+ return value === "create" || value === "everyPush";
+}
+
+function parseTranslations(value: unknown): ValueTranslation[] | null {
+ if (!Array.isArray(value)) return null;
+ const out: ValueTranslation[] = [];
+ for (const row of value) {
+ if (!isRecord(row) || typeof row.onshape !== "string") continue;
+ out.push({
+ onshape: row.onshape,
+ carbon: typeof row.carbon === "string" ? row.carbon : null
+ });
+ }
+ return out;
+}
+
+/**
+ * Also reads a bare `carbonFieldId` as a custom field target and mode "owned"
+ * as "everyPush". A list item field stored without translations gets the
+ * default rows.
+ */
+export function parsePropertyMap(metadata: unknown): PropertyMapEntry[] {
+ const raw = isRecord(metadata) ? metadata.propertyMap : null;
+ if (!Array.isArray(raw)) return [];
+ const out: PropertyMapEntry[] = [];
+ for (const entry of raw) {
+ if (!isRecord(entry)) continue;
+ const { onshapePropertyId, onshapeName, valueType, carbonFieldId } = entry;
+ if (typeof onshapePropertyId !== "string") continue;
+ const type = typeof valueType === "string" ? valueType : "STRING";
+
+ let target: PropertyMapTarget | null = null;
+ const stored = isRecord(entry.target) ? entry.target : null;
+ if (stored?.kind === "customField" && typeof stored.fieldId === "string") {
+ target = { kind: "customField", fieldId: stored.fieldId };
+ } else if (stored?.kind === "item" && isStandardFieldId(stored.field)) {
+ target = { kind: "item", field: stored.field };
+ } else if (!stored && typeof carbonFieldId === "string") {
+ target = { kind: "customField", fieldId: carbonFieldId };
+ }
+ if (!target) continue;
+
+ const mode: MappingMode =
+ entry.mode === "everyPush" || entry.mode === "owned"
+ ? "everyPush"
+ : "create";
+ const mapped: PropertyMapEntry = {
+ onshapePropertyId,
+ onshapeName: typeof onshapeName === "string" ? onshapeName : "",
+ valueType: type,
+ target,
+ mode
+ };
+ if (target.kind === "item") {
+ const field = standardField(target.field);
+ if (field?.kind === "list") {
+ mapped.translations =
+ parseTranslations(entry.translations) ??
+ defaultTranslations(field, type);
+ }
+ }
+ out.push(mapped);
+ }
+ return out;
+}
+
+export function parseDescriptionModes(metadata: unknown): DescriptionModes {
+ const raw = isRecord(metadata) ? metadata.descriptionModes : null;
+ const modes = isRecord(raw) ? raw : {};
+ return {
+ name: isMappingMode(modes.name) ? modes.name : "create",
+ description: isMappingMode(modes.description) ? modes.description : "create"
+ };
+}
+
+/** The Carbon fields every push overwrites, for the item card. */
+export function everyPushTargets(metadata: unknown): {
+ descriptions: Array<keyof DescriptionModes>;
+ itemFields: StandardFieldId[];
+ customFieldIds: string[];
+} {
+ const modes = parseDescriptionModes(metadata);
+ const map = parsePropertyMap(metadata).filter(
+ (entry) => entry.mode === "everyPush"
+ );
+ return {
+ descriptions: (["name", "description"] as const).filter(
+ (field) => modes[field] === "everyPush"
+ ),
+ itemFields: map.flatMap((entry) =>
+ entry.target.kind === "item" ? [entry.target.field] : []
+ ),
+ customFieldIds: map.flatMap((entry) =>
+ entry.target.kind === "customField" ? [entry.target.fieldId] : []
+ )
+ };
+}
+
+export function targetKey(target: PropertyMapTarget): string {
+ return target.kind === "customField"
+ ? `customField:${target.fieldId}`
+ : `item:${target.field}`;
+}
+
+/**
+ * A map entry without `onshapeName` and `valueType`: both are re-read from
+ * Onshape on every load, so a change in either is not the user's decision.
+ */
+type PropertyMapDecision = {
+ onshapePropertyId: string;
+ target: PropertyMapTarget;
+ mode: MappingMode;
+ translations?: ValueTranslation[];
+};
+
+function decisionKey(entry: PropertyMapDecision): string {
+ return JSON.stringify([
+ targetKey(entry.target),
+ entry.mode,
+ (entry.translations ?? []).map((row) => [row.onshape, row.carbon])
+ ]);
+}
+
+/** Order is ignored: editing a row moves it to the end of the Fields draft. */
+export function propertyMapEqual(
+ a: readonly PropertyMapDecision[],
+ b: readonly PropertyMapDecision[]
+): boolean {
+ if (a.length !== b.length) return false;
+ const index = new Map(a.map((entry) => [entry.onshapePropertyId, entry]));
+ if (index.size !== a.length) return false;
+ // A key repeated in `b` can stand in for one it dropped.
+ const seen = new Set<string>();
+ for (const entry of b) {
+ if (seen.has(entry.onshapePropertyId)) return false;
+ seen.add(entry.onshapePropertyId);
+ const other = index.get(entry.onshapePropertyId);
+ if (!other) return false;
+ if (decisionKey(other) !== decisionKey(entry)) return false;
+ }
+ return true;
+}
+
+/**
+ * `matchByName` is for a BOM row: its cells are keyed by column, and a column
+ * whose id is not the property id still matches by the property's name.
+ */
+export function resolveMappedFields({
+ properties,
+ map,
+ definitions,
+ units = [],
+ matchByName = false
+}: {
+ properties: OnshapePropertyValue[];
+ map: PropertyMapEntry[];
+ definitions: PlanCustomFieldDefinition[];
+ units?: readonly PlanUnitOfMeasure[];
+ matchByName?: boolean;
+}): {
+ fields: PlanCustomField[];
+ itemFields: PlanItemField[];
+ problems: string[];
+ unmapped: UnmappedProperty[];
+} {
+ const definitionById = new Map(definitions.map((d) => [d.id, d]));
+ const propertyById = new Map(properties.map((p) => [p.propertyId, p]));
+ const propertyByName = new Map<string, OnshapePropertyValue>();
+ if (matchByName) {
+ for (const property of properties) {
+ if (!propertyByName.has(property.name)) {
+ propertyByName.set(property.name, property);
+ }
+ }
+ }
+ const fields: PlanCustomField[] = [];
+ const itemFields: PlanItemField[] = [];
+ const problems: string[] = [];
+ const used = new Set<string>();
+
+ for (const entry of map) {
+ const property =
+ propertyById.get(entry.onshapePropertyId) ??
+ (entry.onshapeName ? propertyByName.get(entry.onshapeName) : undefined);
+ if (!property) continue;
+ used.add(property.propertyId);
+
+ if (entry.target.kind === "item") {
+ const field = standardField(entry.target.field);
+ if (!field) continue;
+ const translated = translateValue({
+ field,
+ text: propertyDisplayValue(property.value),
+ // The map's type: a BOM column may not report one.
+ valueType: entry.valueType,
+ translations: entry.translations ?? [],
+ units
+ });
+ if (!translated.ok) {
+ problems.push(
+ `${property.name}: ${translated.reason}. ${field.label} not written.`
+ );
+ continue;
+ }
+ itemFields.push({
+ field: field.id,
+ label: field.label,
+ value: translated.value,
+ mode: entry.mode,
+ onshapeName: property.name
+ });
+ continue;
+ }
+
+ const definition = definitionById.get(entry.target.fieldId);
+ if (!definition) {
+ problems.push(
+ `${property.name}: the mapped Carbon field no longer exists`
+ );
+ continue;
+ }
+ const coerced = coerceOnshapeValue(
+ property.value,
+ definition.dataTypeId,
+ definition.listOptions
+ );
+ if (!coerced.ok) {
+ problems.push(`${property.name} → ${definition.name}: ${coerced.reason}`);
+ continue;
+ }
+ fields.push({
+ fieldId: definition.id,
+ name: definition.name,
+ mode: entry.mode,
+ dataTypeId: definition.dataTypeId,
+ listOptions: definition.listOptions,
+ value: coerced.value,
+ onshapeName: property.name
+ });
+ }
+
+ const unmapped: UnmappedProperty[] = [];
+ for (const property of properties) {
+ if (used.has(property.propertyId)) continue;
+ const value = propertyDisplayValue(property.value);
+ if (value !== null && !RESERVED_PROPERTY_NAMES.has(property.name)) {
+ unmapped.push({
+ propertyId: property.propertyId,
+ name: property.name,
+ valueType: property.valueType,
+ value
+ });
+ }
+ }
+ return { fields, itemFields, problems, unmapped };
+}
+
+/**
+ * A create takes every non-null value. An existing item takes the "everyPush"
+ * fields only, nulls included, so a property emptied in Onshape is cleared.
+ */
+export function mappedFieldValues(
+ fields: PlanCustomField[],
+ isCreate: boolean
+): {
+ values: Record<string, string | number | boolean | null>;
+ fieldIds: Set<string>;
+} {
+ const values: Record<string, string | number | boolean | null> = {};
+ const fieldIds = new Set<string>();
+ for (const field of fields) {
+ if (isCreate ? field.value === null : field.mode !== "everyPush") continue;
+ values[field.fieldId] = field.value;
+ fieldIds.add(field.fieldId);
+ }
+ return { values, fieldIds };
+}
+
+export function customFieldDisplayValue(
+ field: Pick<PlanCustomField, "value" | "dataTypeId">
+): string {
+ if (field.dataTypeId === CUSTOM_FIELD_DATA_TYPES.boolean) {
+ return field.value === BOOLEAN_TRUE || field.value === true ? "Yes" : "—";
+ }
+ if (field.value === null) return "—";
+ if (typeof field.value === "boolean") return field.value ? "Yes" : "No";
+ return String(field.value);
+}
+
+/** Only keys in `allowedFieldIds` change; a null deletes its key. */
+export function mergeCustomFieldValues(
+ current: unknown,
+ values: Record<string, string | number | boolean | null>,
+ allowedFieldIds: Set<string>
+): Record<string, unknown> {
+ const out: Record<string, unknown> = isRecord(current) ? { ...current } : {};
+ for (const [fieldId, value] of Object.entries(values)) {
+ if (!allowedFieldIds.has(fieldId)) continue;
+ if (value === null) delete out[fieldId];
+ else out[fieldId] = value;
+ }
+ return out;
+}
+
+/** The item forms save a blank custom field as `""`. */
+function isBlankCustomValue(value: unknown): boolean {
+ return value === undefined || value === null || value === "";
+}
+
+/**
+ * The "everyPush" fields whose value differs from Carbon's. A clear of a field
+ * Carbon does not hold is dropped, so the review says "Clears" only when
+ * something is.
+ */
+export function customFieldWrites(
+ current: unknown,
+ fields: PlanCustomField[]
+): PlanCustomField[] {
+ const held = isRecord(current) ? current : {};
+ return fields.filter((field) => {
+ if (field.mode !== "everyPush") return false;
+ const value = held[field.fieldId];
+ return field.value === null
+ ? !isBlankCustomValue(value)
+ : value !== field.value;
+ });
+}
+
+/** "create" fields Onshape holds another value for: shown, never written. */
+export function customFieldKeptDifferences(
+ current: unknown,
+ fields: PlanCustomField[]
+): PlanCustomField[] {
+ const held = isRecord(current) ? current : {};
+ return fields.filter(
+ (field) =>
+ field.mode === "create" &&
+ field.value !== null &&
+ held[field.fieldId] !== field.value
+ );
+}
diff --git a/packages/ee/src/onshape/panel/releases.test.ts b/packages/ee/src/onshape/panel/releases.test.ts
new file mode 100644
index 0000000000..594c88a874
--- /dev/null
+++ b/packages/ee/src/onshape/panel/releases.test.ts
@@ -0,0 +1,249 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { ReleaseRevisionLike } from "./releases";
+import {
+ drawingModels,
+ groupRevisionsIntoReleases,
+ releaseBomKey,
+ releaseDrawingFileName,
+ releaseExportSelection,
+ resolveReleaseStates
+} from "./releases";
+
+function revision(
+ over: Partial<ReleaseRevisionLike> = {}
+): ReleaseRevisionLike {
+ return {
+ partNumber: "WB-100",
+ revision: "A",
+ elementType: 1,
+ documentId: "d1",
+ versionId: "v1",
+ elementId: "e-asm",
+ releaseId: "rel-1",
+ releaseName: "Initial release",
+ releaseCreatedDate: "2026-08-28T10:00:00Z",
+ ...over
+ };
+}
+
+describe("groupRevisionsIntoReleases", () => {
+ it("groups by releaseId, newest release first, assemblies before parts before drawings", () => {
+ const releases = groupRevisionsIntoReleases([
+ revision({
+ partNumber: "PAD-005",
+ elementType: 0,
+ elementId: "e-ps"
+ }),
+ revision({
+ partNumber: "DRW-001",
+ elementType: 2,
+ elementId: "e-drw"
+ }),
+ revision(),
+ revision({
+ partNumber: "WB-100",
+ revision: "B",
+ releaseId: "rel-2",
+ releaseName: "Rev B",
+ releaseCreatedDate: "2026-08-29T10:00:00Z",
+ versionId: "v2"
+ })
+ ]);
+
+ expect(releases.map((r) => r.releaseId)).toEqual(["rel-2", "rel-1"]);
+ expect(releases[1]?.releaseName).toBe("Initial release");
+ expect(releases[1]?.items.map((i) => i.partNumber)).toEqual([
+ "WB-100",
+ "PAD-005",
+ "DRW-001"
+ ]);
+ });
+
+ it("falls back to a synthetic key when releaseId is missing", () => {
+ const releases = groupRevisionsIntoReleases([
+ revision({ releaseId: null, releaseName: null }),
+ revision({
+ partNumber: "PAD-005",
+ releaseId: null,
+ releaseName: null,
+ elementType: 0
+ })
+ ]);
+ expect(releases).toHaveLength(2);
+ expect(releases.map((r) => r.releaseId).sort()).toEqual([
+ "rev:PAD-005:A",
+ "rev:WB-100:A"
+ ]);
+ });
+});
+
+describe("resolveReleaseStates", () => {
+ const releases = groupRevisionsIntoReleases([
+ revision(),
+ revision({ partNumber: "PAD-005", elementType: 0, elementId: "e-ps" }),
+ revision({ partNumber: "DRW-001", elementType: 2, elementId: "e-drw" })
+ ]);
+
+ it("marks a release pushed only when every model item's letter exists", () => {
+ const partial = resolveReleaseStates(releases, [
+ { id: "item-1", readableId: "WB-100", revision: "A" },
+ // PAD-005 exists in Carbon, but not at the released letter.
+ { id: "item-2", readableId: "PAD-005", revision: "0" }
+ ]);
+ expect(partial[0]?.state).toBe("partial");
+ expect(
+ partial[0]?.items.find((i) => i.partNumber === "WB-100")?.state
+ ).toBe("in-carbon");
+ expect(
+ partial[0]?.items.find((i) => i.partNumber === "PAD-005")?.state
+ ).toBe("missing");
+
+ const pushed = resolveReleaseStates(
+ releases,
+ [
+ { id: "item-1", readableId: "WB-100", revision: "A" },
+ { id: "item-3", readableId: "PAD-005", revision: "A" }
+ ],
+ new Set(["DRW-001-A.pdf"])
+ );
+ expect(pushed[0]?.state).toBe("pushed");
+
+ expect(resolveReleaseStates(releases, [])[0]?.state).toBe("not-pushed");
+ });
+
+ it("counts a drawing as in Carbon once its PDF has landed", () => {
+ const models = [
+ { id: "item-1", readableId: "WB-100", revision: "A" },
+ { id: "item-3", readableId: "PAD-005", revision: "A" }
+ ];
+ // Models pushed, drawing export still running: partial until a refresh.
+ const pending = resolveReleaseStates(releases, models);
+ expect(pending[0]?.state).toBe("partial");
+ expect(
+ pending[0]?.items.find((i) => i.partNumber === "DRW-001")?.state
+ ).toBe("missing");
+
+ const landed = resolveReleaseStates(
+ releases,
+ models,
+ new Set([
+ releaseDrawingFileName({ partNumber: "DRW-001", revision: "A" })
+ ])
+ );
+ expect(landed[0]?.state).toBe("pushed");
+ const drawing = landed[0]?.items.find((i) => i.partNumber === "DRW-001");
+ expect(drawing?.state).toBe("in-carbon");
+ expect(drawing?.itemId).toBeNull();
+ });
+
+ it("reads a drawing-only release from its PDFs alone", () => {
+ const drawingOnly = groupRevisionsIntoReleases([
+ revision({ partNumber: "DRW-001", elementType: 2, elementId: "e-drw" })
+ ]);
+ expect(resolveReleaseStates(drawingOnly, [])[0]?.state).toBe("not-pushed");
+ expect(
+ resolveReleaseStates(drawingOnly, [], new Set(["DRW-001-A.pdf"]))[0]
+ ?.state
+ ).toBe("pushed");
+ });
+});
+
+describe("releaseExportSelection", () => {
+ it("exports a released part by its partId and configuration", () => {
+ expect(
+ releaseExportSelection({
+ elementType: 0,
+ partId: "JHD",
+ configuration: "size%3DLarge"
+ })
+ ).toEqual({ ok: true, partId: "JHD", configuration: "size%3DLarge" });
+ });
+
+ it("skips a Part Studio release that names no single part", () => {
+ expect(releaseExportSelection({ elementType: 0, partId: null }).ok).toBe(
+ false
+ );
+ expect(
+ releaseExportSelection({ elementType: 0, partId: "JHD,JKD" }).ok
+ ).toBe(false);
+ });
+
+ it("exports an assembly without a partId, dropping the default configuration", () => {
+ expect(
+ releaseExportSelection({ elementType: 1, configuration: "default" })
+ ).toEqual({ ok: true });
+ });
+});
+
+describe("drawingModels", () => {
+ const pkgItem = (
+ id: string,
+ parentId: string | null,
+ elementType: number,
+ partNumber: string | null,
+ revision: string | null = "C"
+ ) => ({
+ id,
+ parentId,
+ elementType,
+ elementId: `e-${id}`,
+ partNumber,
+ revision
+ });
+
+ it("maps each drawing to the first model listed under it", () => {
+ expect(
+ drawingModels([
+ pkgItem("drw", null, 2, "WB-100-DWG"),
+ pkgItem("asm", "drw", 1, "WB-100"),
+ pkgItem("prt", "asm", 0, "PAD-005"),
+ pkgItem("lone", null, 2, "LONE-DWG")
+ ])
+ ).toEqual(new Map([["e-drw", { partNumber: "WB-100", revision: "C" }]]));
+ });
+
+ it("skips a model under the drawing that has no part number", () => {
+ expect(
+ drawingModels([
+ pkgItem("drw", null, 2, "WB-100-DWG"),
+ pkgItem("asm", "drw", 1, null),
+ pkgItem("prt", "drw", 0, "PAD-005", null)
+ ])
+ ).toEqual(new Map([["e-drw", { partNumber: "PAD-005", revision: null }]]));
+ });
+});
+
+describe("releaseBomKey", () => {
+ it("keys the default configuration by the element id alone", () => {
+ expect(releaseBomKey({ elementId: "e-asm" })).toBe("e-asm");
+ expect(releaseBomKey({ elementId: "e-asm", configuration: null })).toBe(
+ "e-asm"
+ );
+ expect(
+ releaseBomKey({ elementId: "e-asm", configuration: " default " })
+ ).toBe("e-asm");
+ });
+
+ it("gives two configurations of one element different keys", () => {
+ const long = releaseBomKey({
+ elementId: "e-asm",
+ configuration: "Length=100+mm"
+ });
+ const short = releaseBomKey({
+ elementId: "e-asm",
+ configuration: "Length=50+mm"
+ });
+ expect(long).toBe("e-asm:Length=100+mm");
+ expect(short).not.toBe(long);
+ });
+
+ it("matches an encoded and a decoded configuration", () => {
+ expect(
+ releaseBomKey({ elementId: "e-asm", configuration: "Size%3DLarge" })
+ ).toBe(releaseBomKey({ elementId: "e-asm", configuration: "Size=Large" }));
+ });
+});
diff --git a/packages/ee/src/onshape/panel/releases.ts b/packages/ee/src/onshape/panel/releases.ts
new file mode 100644
index 0000000000..0edc56001a
--- /dev/null
+++ b/packages/ee/src/onshape/panel/releases.ts
@@ -0,0 +1,274 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * Onshape has no per-document release endpoint, so releases are rebuilt by
+ * grouping `GET /revisions/d/{did}` rows on releaseId.
+ */
+
+import { normalizeConfiguration } from "./status";
+
+export type ReleaseRevisionLike = {
+ partNumber: string;
+ revision: string;
+ /** 0 = Part Studio (a part), 1 = Assembly, 2 = Drawing. */
+ elementType: number;
+ documentId: string;
+ versionId: string;
+ elementId: string;
+ /** Part Studio releases: the released part, which the export needs. */
+ partId?: string | null;
+ releaseId?: string | null;
+ releaseName?: string | null;
+ releaseCreatedDate?: string | null;
+ createdAt?: string | null;
+ configuration?: string | null;
+ isObsolete?: boolean | null;
+};
+
+export type PanelReleaseItem = {
+ partNumber: string;
+ revision: string;
+ elementType: number;
+ documentId: string;
+ versionId: string;
+ elementId: string;
+ partId: string | null;
+ configuration: string | null;
+ obsolete: boolean;
+ /** "missing" until resolveReleaseStates fills it. */
+ state: "in-carbon" | "missing";
+ itemId: string | null;
+};
+
+export type PanelRelease = {
+ /** Onshape releaseId, or a synthetic key when the API omitted one. */
+ releaseId: string;
+ releaseName: string | null;
+ createdAt: string | null;
+ items: PanelReleaseItem[];
+ state: "pushed" | "partial" | "not-pushed";
+};
+
+const MODEL_ELEMENT_TYPES = new Set([0, 1]);
+
+export function isModelReleaseItem(
+ item: Pick<PanelReleaseItem, "elementType">
+) {
+ return MODEL_ELEMENT_TYPES.has(item.elementType);
+}
+
+export function releaseKeyFor(revision: ReleaseRevisionLike): string {
+ return (
+ revision.releaseId ?? `rev:${revision.partNumber}:${revision.revision}`
+ );
+}
+
+/**
+ * Key of a released assembly's BOM read. A release can hold two configurations
+ * of one assembly element, each with its own BOM; the default one keys by the
+ * element id alone.
+ */
+export function releaseBomKey(item: {
+ elementId: string;
+ configuration?: string | null;
+}): string {
+ const configuration = normalizeConfiguration(item.configuration);
+ return configuration ? `${item.elementId}:${configuration}` : item.elementId;
+}
+
+/** Assemblies, then parts, then drawings. */
+function itemSortWeight(elementType: number): number {
+ if (elementType === 1) return 0;
+ if (elementType === 0) return 1;
+ return 2;
+}
+
+export function groupRevisionsIntoReleases(
+ revisions: ReleaseRevisionLike[]
+): PanelRelease[] {
+ const byRelease = new Map<string, PanelRelease>();
+
+ for (const revision of revisions) {
+ const key = releaseKeyFor(revision);
+ let release = byRelease.get(key);
+ if (!release) {
+ release = {
+ releaseId: key,
+ releaseName: revision.releaseName ?? null,
+ createdAt: null,
+ items: [],
+ state: "not-pushed"
+ };
+ byRelease.set(key, release);
+ }
+ if (!release.releaseName && revision.releaseName) {
+ release.releaseName = revision.releaseName;
+ }
+ const stamp = revision.releaseCreatedDate ?? revision.createdAt ?? null;
+ if (stamp && (!release.createdAt || stamp > release.createdAt)) {
+ release.createdAt = stamp;
+ }
+ release.items.push({
+ partNumber: revision.partNumber,
+ revision: revision.revision,
+ elementType: revision.elementType,
+ documentId: revision.documentId,
+ versionId: revision.versionId,
+ elementId: revision.elementId,
+ partId: revision.partId ?? null,
+ configuration: revision.configuration ?? null,
+ obsolete: revision.isObsolete ?? false,
+ state: "missing",
+ itemId: null
+ });
+ }
+
+ const releases = [...byRelease.values()];
+ for (const release of releases) {
+ release.items.sort((a, b) => {
+ const weight =
+ itemSortWeight(a.elementType) - itemSortWeight(b.elementType);
+ if (weight !== 0) return weight;
+ return a.partNumber.localeCompare(b.partNumber);
+ });
+ }
+ // Newest first; releases without a date sink to the end.
+ releases.sort((a, b) => {
+ if (!a.createdAt && !b.createdAt) return 0;
+ if (!a.createdAt) return 1;
+ if (!b.createdAt) return -1;
+ return b.createdAt.localeCompare(a.createdAt);
+ });
+ return releases;
+}
+
+export type ReleaseCarbonItemRow = {
+ id: string;
+ readableId: string;
+ revision: string;
+};
+
+/**
+ * A model item is in Carbon when an item has its part number and release
+ * letter; a drawing when its PDF name is in `attachedDrawings`. Release state
+ * counts every item, so a running drawing export reads partial.
+ */
+export function resolveReleaseStates(
+ releases: PanelRelease[],
+ carbonItems: ReleaseCarbonItemRow[],
+ attachedDrawings: ReadonlySet<string> = new Set()
+): PanelRelease[] {
+ const byKey = new Map(
+ carbonItems.map((row) => [`${row.readableId}\u0000${row.revision}`, row])
+ );
+ return releases.map((release) => {
+ let inCarbonCount = 0;
+ const items = release.items.map((item) => {
+ if (isModelReleaseItem(item)) {
+ const match = byKey.get(`${item.partNumber}\u0000${item.revision}`);
+ if (match) inCarbonCount += 1;
+ return {
+ ...item,
+ state: match ? ("in-carbon" as const) : ("missing" as const),
+ itemId: match?.id ?? null
+ };
+ }
+ // A drawing attaches to a model item and has no item of its own.
+ const attached = attachedDrawings.has(releaseDrawingFileName(item));
+ if (attached) inCarbonCount += 1;
+ return {
+ ...item,
+ state: attached ? ("in-carbon" as const) : ("missing" as const),
+ itemId: null
+ };
+ });
+ const count = release.items.length;
+ return {
+ ...release,
+ items,
+ state:
+ count > 0 && inCarbonCount === count
+ ? ("pushed" as const)
+ : inCarbonCount > 0
+ ? ("partial" as const)
+ : ("not-pushed" as const)
+ };
+ });
+}
+
+/** Pushed drawing PDF name; the Releases tab reads drawings back by it. */
+export function releaseDrawingFileName(
+ item: Pick<PanelReleaseItem, "partNumber" | "revision">
+) {
+ return `${item.partNumber}-${item.revision}.pdf`;
+}
+
+export type ReleaseExportSelection =
+ | { ok: true; partId?: string; configuration?: string }
+ | { ok: false; reason: string };
+
+/**
+ * The export job refuses a Part Studio export without exactly one `partId`.
+ * A non-default configuration is sent as Onshape returned it.
+ */
+export function releaseExportSelection(item: {
+ elementType: number;
+ partId?: string | null;
+ configuration?: string | null;
+}): ReleaseExportSelection {
+ const configuration = normalizeConfiguration(item.configuration)
+ ? item.configuration?.trim()
+ : undefined;
+ if (item.elementType !== 0) {
+ return { ok: true, ...(configuration ? { configuration } : {}) };
+ }
+ const partId = item.partId?.trim();
+ if (!partId || /[,\s]/.test(partId)) {
+ return {
+ ok: false,
+ reason:
+ "Onshape didn't name the released part, so its model was not exported"
+ };
+ }
+ return { ok: true, partId, ...(configuration ? { configuration } : {}) };
+}
+
+export type ReleasePackageItemLike = {
+ id: string;
+ parentId: string | null;
+ elementType: number;
+ elementId: string | null;
+ partNumber: string | null;
+ revision: string | null;
+};
+
+/**
+ * Per drawing element, the first model the release package lists under it.
+ * Part numbers cannot tie the two: a drawing's may differ from its model's.
+ */
+export function drawingModels(
+ items: ReleasePackageItemLike[]
+): Map<string, { partNumber: string; revision: string | null }> {
+ const out = new Map<
+ string,
+ { partNumber: string; revision: string | null }
+ >();
+ for (const drawing of items) {
+ if (drawing.elementType !== 2 || !drawing.elementId) continue;
+ const model = items.find(
+ (item) =>
+ item.parentId === drawing.id &&
+ isModelReleaseItem(item) &&
+ !!item.partNumber
+ );
+ if (model?.partNumber && !out.has(drawing.elementId)) {
+ out.set(drawing.elementId, {
+ partNumber: model.partNumber,
+ revision: model.revision
+ });
+ }
+ }
+ return out;
+}
diff --git a/packages/ee/src/onshape/panel/review.test.ts b/packages/ee/src/onshape/panel/review.test.ts
new file mode 100644
index 0000000000..c91655f642
--- /dev/null
+++ b/packages/ee/src/onshape/panel/review.test.ts
@@ -0,0 +1,965 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type {
+ AssemblyPlan,
+ AssemblyPlanMethod,
+ PartPlan,
+ PartPlanRow,
+ ProposedItem,
+ ReleasePlan
+} from "./plan";
+import { DEFAULT_PUSH_DEFAULTS } from "./preferences";
+import type { PlanCustomField } from "./properties";
+import { BOOLEAN_TRUE, customFieldDisplayValue } from "./properties";
+import type { AssemblyReview, PartReview, ReleaseReview } from "./review";
+import {
+ applyCount,
+ applyRequestBody,
+ clearFieldErrors,
+ createReview,
+ customFieldChangeText,
+ defaultSelectedPartIds,
+ describeMethod,
+ editedItem,
+ indexFieldErrors,
+ itemFieldChangeText,
+ keptDifferenceText,
+ mappedValueText,
+ normalizeWarnings,
+ patchPartStatuses,
+ releaseResultText,
+ replenishmentMismatches
+} from "./review";
+import type { PanelPartStatus } from "./status";
+
+const options = {
+ unitsOfMeasure: [
+ { code: "EA", name: "Each" },
+ { code: "M", name: "Meter" }
+ ],
+ defaults: DEFAULT_PUSH_DEFAULTS
+};
+
+const proposed = (over: Partial<ProposedItem> = {}): ProposedItem => ({
+ readableId: "PAD-005",
+ revision: "0",
+ name: "Foot pad",
+ description: null,
+ replenishmentSystem: "Make",
+ defaultMethodType: "Make to Order",
+ itemTrackingType: "Inventory",
+ unitOfMeasureCode: "EA",
+ ...over
+});
+
+const partRow = (over: Partial<PartPlanRow> = {}): PartPlanRow => ({
+ partId: "p1",
+ partNumber: "PAD-005",
+ name: "Foot pad",
+ description: null,
+ revision: null,
+ microversionId: "m1",
+ action: "create",
+ itemId: null,
+ item: null,
+ proposed: proposed(),
+ changes: [],
+ ...over
+});
+
+const partPlan = (rows: PartPlanRow[]): PartPlan => ({
+ kind: "part",
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ rows,
+ options
+});
+
+const partReview = (rows: PartPlanRow[]): PartReview =>
+ createReview({
+ planId: "plan-1",
+ expiresAt: "2026-08-30T12:00:00Z",
+ scope: "d:w:w1:e",
+ plan: partPlan(rows)
+ }) as PartReview;
+
+const customField = (over: Partial<PlanCustomField> = {}): PlanCustomField => ({
+ fieldId: "cf-finish",
+ name: "Finish",
+ mode: "create",
+ dataTypeId: 5,
+ listOptions: null,
+ value: "Anodized",
+ onshapeName: "Surface finish",
+ ...over
+});
+
+const method = (
+ over: Partial<AssemblyPlanMethod> = {}
+): AssemblyPlanMethod => ({
+ parentPartNumber: "ASM-001",
+ parentItemId: null,
+ status: "new",
+ writes: [
+ {
+ index: "1",
+ partNumber: "PAD-005",
+ name: "Foot pad",
+ quantity: 4
+ },
+ {
+ index: "2",
+ partNumber: "HDW-010",
+ name: "Screw",
+ quantity: 8
+ }
+ ],
+ replaces: [],
+ takesOver: [],
+ keeps: [],
+ ...over
+});
+
+const assemblyPlan = (over: Partial<AssemblyPlan> = {}): AssemblyPlan => ({
+ kind: "assembly",
+ depth: "all",
+ documentId: "d",
+ wv: "w",
+ wvId: "w1",
+ elementId: "e",
+ root: {
+ partNumber: "ASM-001",
+ name: "Base",
+ description: null,
+ revision: null,
+ action: "create",
+ itemId: null,
+ proposed: proposed({ readableId: "ASM-001", name: "Base" })
+ },
+ items: [
+ {
+ partNumber: "PAD-005",
+ name: "Foot pad",
+ revision: null,
+ action: "create",
+ itemId: null,
+ proposed: proposed(),
+ isAssembly: false
+ },
+ {
+ partNumber: "HDW-010",
+ name: "Screw",
+ revision: null,
+ action: "reuse",
+ itemId: "item-hdw",
+ proposed: null,
+ isAssembly: false
+ }
+ ],
+ methods: [method()],
+ skipped: ["Loose bracket: no part number in Onshape"],
+ options,
+ ...over
+});
+
+const assemblyReview = (plan = assemblyPlan()): AssemblyReview =>
+ createReview({
+ planId: "plan-2",
+ expiresAt: "2026-08-30T12:00:00Z",
+ scope: "d:w:w1:e",
+ plan
+ }) as AssemblyReview;
+
+const releasePlan = (over: Partial<ReleasePlan> = {}): ReleasePlan => ({
+ kind: "release",
+ documentId: "d",
+ releaseId: "rel-1",
+ releaseName: "R1",
+ createdAt: null,
+ items: [
+ {
+ partNumber: "ASM-001",
+ revision: "A",
+ elementType: 1,
+ elementId: "e1",
+ versionId: "v1",
+ action: "revision",
+ baseItemId: "item-asm",
+ baseRevision: "0",
+ existingItemId: null,
+ proposed: null,
+ methodStatus: "new"
+ },
+ {
+ partNumber: "NEW-001",
+ revision: "A",
+ elementType: 0,
+ elementId: "e2",
+ versionId: "v1",
+ action: "create",
+ baseItemId: null,
+ baseRevision: null,
+ existingItemId: null,
+ proposed: proposed({ readableId: "NEW-001", revision: "A", name: "New" }),
+ methodStatus: null
+ },
+ {
+ partNumber: "ASM-001",
+ revision: "A",
+ elementType: 2,
+ elementId: "e3",
+ versionId: "v1",
+ action: "drawing",
+ baseItemId: null,
+ baseRevision: null,
+ existingItemId: null,
+ proposed: null,
+ methodStatus: null
+ }
+ ],
+ children: [
+ {
+ partNumber: "HDW-010",
+ name: "Screw",
+ revision: null,
+ action: "reuse",
+ itemId: "item-hdw",
+ proposed: null
+ },
+ {
+ partNumber: "PAD-005",
+ name: "Foot pad",
+ revision: null,
+ action: "create",
+ itemId: null,
+ proposed: proposed()
+ }
+ ],
+ changeNotice: { name: "Onshape release R1", description: null },
+ makeDefault: true,
+ alreadyPushed: false,
+ options,
+ ...over
+});
+
+const releaseReview = (
+ plan = releasePlan(),
+ warnings?: string[]
+): ReleaseReview =>
+ createReview({
+ planId: "plan-3",
+ expiresAt: "2026-08-30T12:00:00Z",
+ scope: "d",
+ plan,
+ warnings
+ }) as ReleaseReview;
+
+describe("createReview", () => {
+ it("opens a part review with the actionable rows selected and no edits", () => {
+ const review = partReview([
+ partRow({ partId: "p1", action: "create" }),
+ partRow({ partId: "p2", action: "adopt", itemId: "i2" }),
+ partRow({ partId: "p3", action: "update", itemId: "i3" }),
+ partRow({ partId: "p4", action: "unchanged", itemId: "i4" }),
+ partRow({ partId: "p5", action: "skip-no-part-number", partNumber: null })
+ ]);
+ expect(review.kind).toBe("part");
+ expect([...review.selected]).toEqual(["p1", "p2", "p3"]);
+ expect(review.edits).toEqual({});
+ expect(review.applying).toBe(false);
+ expect(review.error).toBeNull();
+ expect(review.fieldErrors).toEqual({});
+ expect(review.expired).toBe(false);
+ expect(review.scope).toBe("d:w:w1:e");
+ });
+
+ it("opens an assembly review with nothing excluded", () => {
+ const review = assemblyReview();
+ expect(review.kind).toBe("assembly");
+ expect(review.excluded.size).toBe(0);
+ });
+
+ it("copies the release plan's change notice and default flag, keeps warnings", () => {
+ const plan = releasePlan();
+ const review = releaseReview(plan, ["ASM-001: BOM could not be read"]);
+ expect(review.changeNotice).toEqual(plan.changeNotice);
+ expect(review.changeNotice).not.toBe(plan.changeNotice);
+ expect(review.makeDefault).toBe(true);
+ expect(review.warnings).toEqual(["ASM-001: BOM could not be read"]);
+ });
+
+ it("has no change notice to edit when the plan has none", () => {
+ const review = releaseReview(
+ releasePlan({ changeNotice: null, alreadyPushed: true })
+ );
+ expect(review.changeNotice).toBeNull();
+ expect(review.warnings).toEqual([]);
+ });
+});
+
+describe("defaultSelectedPartIds", () => {
+ it("selects create, adopt and update; leaves unchanged and skipped alone", () => {
+ expect([
+ ...defaultSelectedPartIds([
+ partRow({ partId: "a", action: "unchanged" }),
+ partRow({ partId: "b", action: "update" }),
+ partRow({ partId: "c", action: "skip-no-part-number" }),
+ partRow({ partId: "d", action: "adopt" }),
+ partRow({ partId: "e", action: "create" })
+ ])
+ ]).toEqual(["b", "d", "e"]);
+ });
+});
+
+describe("editedItem", () => {
+ it("returns the proposal itself when there is no edit", () => {
+ const item = proposed();
+ expect(editedItem(item, undefined)).toBe(item);
+ });
+
+ it("lays only the edited fields over the proposal", () => {
+ expect(
+ editedItem(proposed(), { name: "Pad", description: "Rubber" })
+ ).toEqual(proposed({ name: "Pad", description: "Rubber" }));
+ });
+});
+
+describe("customFieldDisplayValue", () => {
+ it("renders review text for every value shape", () => {
+ expect(customFieldDisplayValue(customField())).toBe("Anodized");
+ expect(
+ customFieldDisplayValue(customField({ value: 2.5, dataTypeId: 4 }))
+ ).toBe("2.5");
+ expect(customFieldDisplayValue(customField({ value: null }))).toBe("—");
+ });
+
+ it("renders a Yes/No field from the value the ERP stores", () => {
+ expect(
+ customFieldDisplayValue(
+ customField({ value: BOOLEAN_TRUE, dataTypeId: 1 })
+ )
+ ).toBe("Yes");
+ expect(
+ customFieldDisplayValue(customField({ value: null, dataTypeId: 1 }))
+ ).toBe("—");
+ });
+});
+
+describe("applyRequestBody", () => {
+ it("sends a part selection in plan order with edits only for selected creates", () => {
+ const review = partReview([
+ partRow({ partId: "p1", action: "create" }),
+ partRow({ partId: "p2", action: "create", partNumber: "PAD-006" }),
+ partRow({ partId: "p3", action: "adopt", itemId: "i3" })
+ ]);
+ const edited: PartReview = {
+ ...review,
+ selected: new Set(["p3", "p1"]),
+ edits: {
+ p1: { name: "Pad" },
+ p2: { name: "Dropped" },
+ p3: { name: "Never" }
+ }
+ };
+ expect(applyRequestBody(edited)).toEqual({
+ planId: "plan-1",
+ selected: ["p1", "p3"],
+ edits: { p1: { name: "Pad" } }
+ });
+ });
+
+ it("sends manufacturing edits for a selected existing part, but never its name", () => {
+ const review = partReview([
+ partRow({ partId: "p1", action: "adopt", itemId: "i1" }),
+ partRow({ partId: "p2", action: "update", itemId: "i2" })
+ ]);
+ const edited: PartReview = {
+ ...review,
+ selected: new Set(["p1", "p2"]),
+ edits: {
+ p1: { name: "Nope", replenishmentSystem: "Buy" },
+ p2: { itemTrackingType: "Serial" }
+ }
+ };
+ expect(applyRequestBody(edited)).toEqual({
+ planId: "plan-1",
+ selected: ["p1", "p2"],
+ edits: {
+ p1: { replenishmentSystem: "Buy" },
+ p2: { itemTrackingType: "Serial" }
+ }
+ });
+ });
+
+ it("sends assembly edits for the root and included creates, and the exclusions", () => {
+ const review = assemblyReview();
+ const edited: AssemblyReview = {
+ ...review,
+ excluded: new Set(["PAD-005"]),
+ edits: {
+ "ASM-001": { name: "Base plate" },
+ "PAD-005": { name: "Excluded" },
+ "HDW-010": { name: "Reused" }
+ }
+ };
+ expect(applyRequestBody(edited)).toEqual({
+ planId: "plan-2",
+ edits: { "ASM-001": { name: "Base plate" } },
+ excluded: ["PAD-005"]
+ });
+ });
+
+ it("drops root edits when the root is reused", () => {
+ const plan = assemblyPlan();
+ plan.root = {
+ ...plan.root,
+ action: "reuse",
+ itemId: "item-asm",
+ proposed: null
+ };
+ const edited: AssemblyReview = {
+ ...assemblyReview(plan),
+ edits: { "ASM-001": { name: "Nope" }, "PAD-005": { name: "Pad" } }
+ };
+ expect(applyRequestBody(edited)).toEqual({
+ planId: "plan-2",
+ edits: { "PAD-005": { name: "Pad" } },
+ excluded: []
+ });
+ });
+
+ it("sends release edits for created items and children, the change notice and the default flag", () => {
+ const edited: ReleaseReview = {
+ ...releaseReview(),
+ makeDefault: false,
+ changeNotice: { name: "ECO-12", description: "Tolerance change" },
+ edits: {
+ "NEW-001": { name: "New part" },
+ "PAD-005": { unitOfMeasureCode: "M" },
+ "HDW-010": { name: "Reused" },
+ "ASM-001": { name: "Revised" }
+ }
+ };
+ expect(applyRequestBody(edited)).toEqual({
+ planId: "plan-3",
+ edits: {
+ "NEW-001": { name: "New part" },
+ "PAD-005": { unitOfMeasureCode: "M" }
+ },
+ changeNotice: { name: "ECO-12", description: "Tolerance change" },
+ createChangeNotice: true,
+ makeDefault: false
+ });
+ });
+
+ it("drops the change notice when the review opted out of one", () => {
+ const review: ReleaseReview = {
+ ...releaseReview(),
+ createChangeNotice: false
+ };
+ expect(applyRequestBody(review)).toMatchObject({
+ changeNotice: null,
+ createChangeNotice: false
+ });
+ });
+
+ it("sends a null change notice when the plan has none", () => {
+ const review = releaseReview(
+ releasePlan({ changeNotice: null, alreadyPushed: true })
+ );
+ expect(applyRequestBody(review)).toMatchObject({ changeNotice: null });
+ });
+
+ it("leaves the notice decision to the apply when the plan proposed none", () => {
+ const review = releaseReview(
+ releasePlan({ changeNotice: null, alreadyPushed: true })
+ );
+ expect(applyRequestBody(review)).not.toHaveProperty("createChangeNotice");
+ });
+});
+
+describe("applyCount", () => {
+ it("counts selected parts", () => {
+ const review = partReview([
+ partRow({ partId: "p1", action: "create" }),
+ partRow({ partId: "p2", action: "unchanged", itemId: "i2" })
+ ]);
+ expect(applyCount(review)).toBe(1);
+ });
+
+ it("counts the root plus included assembly items", () => {
+ const review = assemblyReview();
+ expect(applyCount(review)).toBe(3);
+ expect(applyCount({ ...review, excluded: new Set(["PAD-005"]) })).toBe(2);
+ });
+
+ it("counts release model items, children and attached drawings", () => {
+ expect(applyCount(releaseReview())).toBe(5);
+ });
+
+ it("leaves out a drawing with no model to attach to", () => {
+ const plan = releasePlan();
+ const items = plan.items.map((item) =>
+ item.action === "drawing"
+ ? { ...item, action: "drawing-unmatched" as const }
+ : item
+ );
+ expect(applyCount(releaseReview({ ...plan, items }))).toBe(4);
+ });
+});
+
+describe("field errors", () => {
+ it("indexes the server's list by key and tolerates junk", () => {
+ expect(
+ indexFieldErrors([
+ { key: "p1", errors: ["Name is required"] },
+ { key: 3, errors: ["x"] } as unknown as {
+ key: string;
+ errors: string[];
+ },
+ null as unknown as { key: string; errors: string[] }
+ ])
+ ).toEqual({ p1: ["Name is required"] });
+ expect(indexFieldErrors(undefined)).toEqual({});
+ });
+
+ it("clears one key and returns the same object when there is nothing to clear", () => {
+ const errors = { p1: ["a"], p2: ["b"] };
+ expect(clearFieldErrors(errors, "p1")).toEqual({ p2: ["b"] });
+ expect(clearFieldErrors(errors, "p3")).toBe(errors);
+ });
+});
+
+describe("describeMethod", () => {
+ it("describes a draft method with its counts", () => {
+ const m = method({
+ status: "draft",
+ parentItemId: "item-asm",
+ replaces: [{ readableId: "OLD-1", quantity: 1 }],
+ keeps: [
+ { readableId: "MAN-1", quantity: 1 },
+ { readableId: "MAN-2", quantity: 2 }
+ ]
+ });
+ expect(describeMethod(m, new Set())).toEqual({
+ text: "ASM-001 · Draft: 2 added, 1 replaced, 2 manual kept",
+ tone: "normal"
+ });
+ });
+
+ it("counts manual lines taken over, and an excluded part's as kept", () => {
+ const m = method({
+ status: "draft",
+ parentItemId: "item-asm",
+ takesOver: [
+ { readableId: "TOP-001", quantity: 2, onshapeQuantity: 1 },
+ { readableId: "HDW-010", quantity: 8, onshapeQuantity: 8 }
+ ],
+ keeps: [{ readableId: "MAN-1", quantity: 1 }]
+ });
+ expect(describeMethod(m, new Set())).toEqual({
+ text: "ASM-001 · Draft: 2 added, 0 replaced, 2 manual taken over, 1 manual kept",
+ tone: "normal"
+ });
+ expect(describeMethod(m, new Set(["HDW-010"])).text).toBe(
+ "ASM-001 · Draft: 1 added, 0 replaced, 1 manual taken over, 2 manual kept"
+ );
+ });
+
+ it("labels a new method and subtracts excluded children", () => {
+ expect(describeMethod(method(), new Set(["HDW-010"]))).toEqual({
+ text: "ASM-001 · new method: 1 added, 0 replaced, 0 manual kept",
+ tone: "normal"
+ });
+ });
+
+ it("describes a released method as a new Draft version, with its counts", () => {
+ const described = describeMethod(method({ status: "active" }), new Set());
+ expect(described).toEqual({
+ text: "ASM-001 · released in Carbon — new Draft version: 2 added, 0 replaced, 0 manual kept",
+ tone: "notice"
+ });
+ expect(described.text).not.toMatch(/will not be applied/);
+ });
+
+ it("says a released method with no change needs no Draft", () => {
+ const unchanged = method({ status: "active", unchanged: true });
+ expect(describeMethod(unchanged, new Set())).toEqual({
+ text: "ASM-001 · released in Carbon — no change",
+ tone: "muted"
+ });
+ expect(describeMethod(unchanged, new Set(["PAD-005"])).tone).toBe("notice");
+ });
+
+ it("warns that a method missing in Carbon won't be written", () => {
+ expect(describeMethod(method({ status: "missing" }), new Set())).toEqual({
+ text: "ASM-001 · no make method in Carbon, so its lines won't be written",
+ tone: "warning"
+ });
+ });
+
+ it("mutes a method whose parent is excluded", () => {
+ expect(
+ describeMethod(
+ method({ parentPartNumber: "SUB-001", status: "new" }),
+ new Set(["SUB-001"])
+ )
+ ).toEqual({ text: "SUB-001 · excluded", tone: "muted" });
+ });
+});
+
+describe("patchPartStatuses", () => {
+ const status = (over: Partial<PanelPartStatus> = {}): PanelPartStatus => ({
+ partId: "p1",
+ name: "Foot pad",
+ partNumber: "PAD-005",
+ revision: null,
+ microversionId: "m1",
+ state: "missing",
+ item: null,
+ lastSyncedAt: null,
+ ...over
+ });
+
+ it("links a created part with the merged proposal's revision and name", () => {
+ const review: PartReview = {
+ ...partReview([partRow({ partId: "p1", action: "create" })]),
+ edits: { p1: { name: "Pad" } }
+ };
+ expect(
+ patchPartStatuses([status()], review, [
+ {
+ partId: "p1",
+ action: "created",
+ itemId: "item-1",
+ readableId: "PAD-005"
+ }
+ ])
+ ).toEqual([
+ status({
+ state: "linked",
+ item: {
+ id: "item-1",
+ readableId: "PAD-005",
+ revision: "0",
+ name: "Pad"
+ }
+ })
+ ]);
+ });
+
+ it("links an adopted part to the plan row's item with the Onshape name", () => {
+ const review = partReview([
+ partRow({
+ partId: "p1",
+ action: "adopt",
+ itemId: "item-9",
+ item: { readableId: "PAD-005", revision: "B", name: "Old name" },
+ proposed: null
+ })
+ ]);
+ expect(
+ patchPartStatuses(
+ [
+ status({
+ state: "matched",
+ item: {
+ id: "item-9",
+ readableId: "PAD-005",
+ revision: "B",
+ name: "Old name"
+ }
+ })
+ ],
+ review,
+ [{ partId: "p1", action: "adopted", itemId: "item-9" }]
+ )
+ ).toEqual([
+ status({
+ state: "linked",
+ item: {
+ id: "item-9",
+ readableId: "PAD-005",
+ revision: "B",
+ name: "Foot pad"
+ }
+ })
+ ]);
+ });
+
+ it("leaves unchanged, skipped, errored and unknown rows as they were", () => {
+ const rows = [
+ status({
+ partId: "p1",
+ state: "linked",
+ item: {
+ id: "i1",
+ readableId: "PAD-005",
+ revision: "0",
+ name: "Foot pad"
+ }
+ }),
+ status({ partId: "p2", partNumber: null }),
+ status({ partId: "p3" }),
+ status({ partId: "p4" })
+ ];
+ const review = partReview([
+ partRow({ partId: "p1", action: "unchanged", itemId: "i1" }),
+ partRow({
+ partId: "p2",
+ action: "skip-no-part-number",
+ partNumber: null
+ }),
+ partRow({ partId: "p3", action: "create" })
+ ]);
+ expect(
+ patchPartStatuses(rows, review, [
+ { partId: "p1", action: "unchanged", itemId: "i1" },
+ {
+ partId: "p2",
+ action: "skipped",
+ message: "Set a part number in Onshape first"
+ },
+ { partId: "p3", action: "error", message: "boom" },
+ { partId: "p4", action: "created", itemId: "i4" }
+ ])
+ ).toEqual(rows);
+ });
+});
+
+describe("normalizeWarnings", () => {
+ it("keeps strings and messages, drops the rest", () => {
+ expect(
+ normalizeWarnings([
+ "ASM-001: BOM could not be read",
+ { message: "x" },
+ { partNumber: "y" },
+ 3,
+ null
+ ])
+ ).toEqual(["ASM-001: BOM could not be read", "x"]);
+ expect(normalizeWarnings(undefined)).toEqual([]);
+ });
+});
+
+describe("replenishmentMismatches", () => {
+ const current = (replenishmentSystem: "Buy" | "Make" | "Buy and Make") => ({
+ replenishmentSystem,
+ defaultMethodType:
+ replenishmentSystem === "Buy"
+ ? ("Pull from Inventory" as const)
+ : ("Make to Order" as const),
+ itemTrackingType: "Inventory" as const
+ });
+ const reusedRoot = (replenishmentSystem: "Buy" | "Make" | "Buy and Make") =>
+ assemblyPlan({
+ root: {
+ partNumber: "ASM-001",
+ name: "Base",
+ description: null,
+ revision: null,
+ action: "reuse",
+ itemId: "item-asm",
+ proposed: null,
+ current: current(replenishmentSystem)
+ }
+ });
+
+ it("flags a Buy item the push writes a BOM into, until it is set to Make", () => {
+ const plan = reusedRoot("Buy");
+ expect(replenishmentMismatches(plan, {}, new Set())).toEqual([
+ "ASM-001 is Buy in Carbon, so the BOM written to it isn't used until it's set to Make"
+ ]);
+ expect(
+ replenishmentMismatches(
+ plan,
+ { "ASM-001": { replenishmentSystem: "Make" } },
+ new Set()
+ )
+ ).toEqual([]);
+ expect(
+ replenishmentMismatches(reusedRoot("Buy and Make"), {}, new Set())
+ ).toEqual([]);
+ });
+
+ it("reads the Replenishment an every-push mapping writes", () => {
+ const plan = reusedRoot("Make");
+ plan.root.target = current("Buy");
+ expect(replenishmentMismatches(plan, {}, new Set())).toEqual([
+ "ASM-001 is Buy in Carbon, so the BOM written to it isn't used until it's set to Make"
+ ]);
+ });
+
+ it("flags a Make item Onshape shows as one unit, but not a new one proposed as Buy", () => {
+ const plan = assemblyPlan({
+ items: [
+ {
+ partNumber: "ASM-009",
+ name: "Foot assembly",
+ revision: null,
+ action: "reuse",
+ itemId: "item-foot",
+ proposed: null,
+ current: current("Make"),
+ isAssembly: false,
+ shownAsUnit: true
+ },
+ {
+ partNumber: "ASM-010",
+ name: "Caster assembly",
+ revision: null,
+ action: "create",
+ itemId: null,
+ proposed: proposed({
+ readableId: "ASM-010",
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Pull from Inventory"
+ }),
+ isAssembly: false,
+ shownAsUnit: true
+ }
+ ]
+ });
+ expect(replenishmentMismatches(plan, {}, new Set())).toEqual([
+ "ASM-009 is one unit in Onshape (Show Assembly only), so no BOM is written for it, but Carbon makes it"
+ ]);
+ expect(replenishmentMismatches(plan, {}, new Set(["ASM-009"]))).toEqual([]);
+ });
+});
+
+describe("mapped value review text", () => {
+ it("names the value and the Onshape property it came from", () => {
+ expect(
+ mappedValueText({
+ field: "replenishmentSystem",
+ label: "Replenishment",
+ value: "Buy",
+ mode: "create",
+ onshapeName: "Make or buy"
+ })
+ ).toBe('Replenishment: Buy · from Onshape "Make or buy"');
+ });
+
+ it("says Carbon keeps its value for a Set at creation mapping", () => {
+ expect(
+ keptDifferenceText({
+ label: "Replenishment",
+ onshape: "Buy",
+ carbon: "Make"
+ })
+ ).toBe(
+ "Replenishment: Onshape has Buy. Carbon keeps Make (set at creation only)."
+ );
+ });
+
+ it("says an every-push mapping replaces Carbon's value", () => {
+ expect(
+ itemFieldChangeText({
+ field: "replenishmentSystem",
+ label: "Replenishment",
+ from: "Make",
+ to: "Buy",
+ onshapeName: "Make or buy"
+ })
+ ).toBe("Replenishment: Replaces Make with Buy (updated on every push).");
+ expect(
+ itemFieldChangeText({
+ field: "defaultMethodType",
+ label: "Default Method Type",
+ from: "Make to Order",
+ to: "Purchase to Order",
+ onshapeName: null
+ })
+ ).toBe(
+ "Default Method Type: Replaces Make to Order with Purchase to Order (goes with the change above)."
+ );
+ });
+
+ it("says what an every-push custom field write replaces or clears", () => {
+ const vendor = (
+ value: string | null,
+ replaces: string | null
+ ): PlanCustomField => ({
+ fieldId: "cf_vendor",
+ name: "Vendor",
+ mode: "everyPush",
+ dataTypeId: 5,
+ listOptions: null,
+ value,
+ onshapeName: "Vendor",
+ replaces
+ });
+ expect(customFieldChangeText(vendor("Acme Ltd", "Acme Co"))).toBe(
+ "Vendor: Replaces Acme Co with Acme Ltd (updated on every push)."
+ );
+ expect(customFieldChangeText(vendor("Acme Ltd", null))).toBe(
+ "Vendor: Sets Acme Ltd (updated on every push)."
+ );
+ expect(customFieldChangeText(vendor(null, "Acme Co"))).toBe(
+ "Vendor: Clears Acme Co (updated on every push)."
+ );
+ });
+});
+
+describe("releaseResultText", () => {
+ const base = {
+ revisionsCreated: 0,
+ itemsCreated: 0,
+ childrenCreated: 0,
+ linesWritten: 0,
+ methodsTouched: 0,
+ changeNotice: null
+ };
+
+ it("counts in the singular and leaves out zero counts", () => {
+ expect(
+ releaseResultText({
+ ...base,
+ revisionsCreated: 1,
+ changeNotice: "CN-000008"
+ })
+ ).toBe(
+ "1 new revision on change notice CN-000008, inactive until it is released in Carbon"
+ );
+ });
+
+ it("names what the notice holds, then BOM parts outside it, then the lines", () => {
+ expect(
+ releaseResultText({
+ ...base,
+ revisionsCreated: 3,
+ itemsCreated: 2,
+ childrenCreated: 1,
+ linesWritten: 4,
+ methodsTouched: 1,
+ changeNotice: "CN-000014"
+ })
+ ).toBe(
+ "3 new revisions and 2 new items on change notice CN-000014, inactive until it is released in Carbon · 1 BOM part added to Carbon · 4 BOM lines written"
+ );
+ });
+
+ it("mentions BOMs only when the release has one", () => {
+ expect(releaseResultText(base)).toBe("Already in Carbon");
+ expect(releaseResultText({ ...base, methodsTouched: 1 })).toBe(
+ "Already in Carbon · BOM unchanged"
+ );
+ });
+
+ it("reports drawings, and only drawings for a drawing-only release", () => {
+ expect(releaseResultText({ ...base, drawingsQueued: 1 })).toBe(
+ "Already in Carbon · 1 drawing sent to Carbon"
+ );
+ expect(
+ releaseResultText({ ...base, drawingsQueued: 2, drawingsOnly: true })
+ ).toBe("2 drawings sent to Carbon");
+ expect(releaseResultText({ ...base, drawingsOnly: true })).toBe(
+ "Nothing to push"
+ );
+ });
+});
diff --git a/packages/ee/src/onshape/panel/review.ts b/packages/ee/src/onshape/panel/review.ts
new file mode 100644
index 0000000000..880e1b1883
--- /dev/null
+++ b/packages/ee/src/onshape/panel/review.ts
@@ -0,0 +1,612 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type {
+ AssemblyPlan,
+ AssemblyPlanMethod,
+ ChangeNoticeEdit,
+ ItemEdit,
+ ItemFieldChange,
+ KeptDifference,
+ PartPlan,
+ PartPlanRow,
+ ProposedItem,
+ ReleasePlan
+} from "./plan";
+import type { PlanCustomField, PlanItemField } from "./properties";
+import { customFieldDisplayValue } from "./properties";
+import type { PanelPartStatus } from "./status";
+
+/**
+ * The panel's review state: a stored plan plus the user's sparse edits, keyed
+ * by partId for parts and by part number for assemblies and releases.
+ */
+
+type ReviewBase = {
+ planId: string;
+ expiresAt: string;
+ /** The element, or the document for a release; another drops the review. */
+ scope: string;
+ edits: Record<string, ItemEdit>;
+ applying: boolean;
+ error: string | null;
+ /** Per-row validation errors from a 422, keyed like `edits`. */
+ fieldErrors: Record<string, string[]>;
+ /** The stored plan is gone (410): only "Review again" can continue. */
+ expired: boolean;
+};
+
+export type PartReview = ReviewBase & {
+ kind: "part";
+ plan: PartPlan;
+ selected: Set<string>;
+};
+
+export type AssemblyReview = ReviewBase & {
+ kind: "assembly";
+ plan: AssemblyPlan;
+ excluded: Set<string>;
+};
+
+export type ReleaseReview = ReviewBase & {
+ kind: "release";
+ plan: ReleasePlan;
+ changeNotice: ChangeNoticeEdit | null;
+ createChangeNotice: boolean;
+ makeDefault: boolean;
+ /** Assemblies whose BOM the plan could not read; their lines are empty. */
+ warnings: string[];
+};
+
+export type ReviewState = PartReview | AssemblyReview | ReleaseReview;
+
+/** `unchanged` rows start unticked: the button counts what apply touches. */
+export function defaultSelectedPartIds(rows: PartPlanRow[]): Set<string> {
+ return new Set(
+ rows
+ .filter(
+ (row) =>
+ row.action === "create" ||
+ row.action === "adopt" ||
+ row.action === "update"
+ )
+ .map((row) => row.partId)
+ );
+}
+
+export function createReview(input: {
+ planId: string;
+ expiresAt: string;
+ scope: string;
+ plan: PartPlan | AssemblyPlan | ReleasePlan;
+ warnings?: string[];
+}): ReviewState {
+ const base: ReviewBase = {
+ planId: input.planId,
+ expiresAt: input.expiresAt,
+ scope: input.scope,
+ edits: {},
+ applying: false,
+ error: null,
+ fieldErrors: {},
+ expired: false
+ };
+ const plan = input.plan;
+ switch (plan.kind) {
+ case "part":
+ return {
+ ...base,
+ kind: "part",
+ plan,
+ selected: defaultSelectedPartIds(plan.rows)
+ };
+ case "assembly":
+ return { ...base, kind: "assembly", plan, excluded: new Set() };
+ case "release":
+ return {
+ ...base,
+ kind: "release",
+ plan,
+ changeNotice: plan.changeNotice ? { ...plan.changeNotice } : null,
+ createChangeNotice: plan.changeNotice !== null,
+ makeDefault: plan.makeDefault,
+ warnings: input.warnings ?? []
+ };
+ }
+}
+
+export function editedItem(
+ proposed: ProposedItem,
+ edit: ItemEdit | undefined
+): ProposedItem {
+ if (!edit) return proposed;
+ const item: ProposedItem = { ...proposed };
+ if (edit.name !== undefined) item.name = edit.name;
+ if (edit.description !== undefined) item.description = edit.description;
+ if (edit.replenishmentSystem !== undefined)
+ item.replenishmentSystem = edit.replenishmentSystem;
+ if (edit.defaultMethodType !== undefined)
+ item.defaultMethodType = edit.defaultMethodType;
+ if (edit.itemTrackingType !== undefined)
+ item.itemTrackingType = edit.itemTrackingType;
+ if (edit.unitOfMeasureCode !== undefined)
+ item.unitOfMeasureCode = edit.unitOfMeasureCode;
+ return item;
+}
+
+/**
+ * A Buy item the push writes a BOM into, and a Make item Onshape shows as one
+ * unit (no BOM), after mapped values and edits. The push writes both anyway.
+ */
+export function replenishmentMismatches(
+ plan: AssemblyPlan,
+ edits: Record<string, ItemEdit>,
+ excluded: ReadonlySet<string>
+): string[] {
+ const rows = new Map<
+ string,
+ {
+ current?: { replenishmentSystem: string } | null;
+ target?: { replenishmentSystem: string };
+ proposed: ProposedItem | null;
+ }
+ >([
+ [plan.root.partNumber, plan.root],
+ ...plan.items.map((item) => [item.partNumber, item] as const)
+ ]);
+ const replenishment = (partNumber: string) => {
+ const row = rows.get(partNumber);
+ return (
+ edits[partNumber]?.replenishmentSystem ??
+ row?.target?.replenishmentSystem ??
+ row?.current?.replenishmentSystem ??
+ row?.proposed?.replenishmentSystem
+ );
+ };
+ const lines: string[] = [];
+ for (const method of plan.methods) {
+ if (
+ method.status === "missing" ||
+ method.writes.length === 0 ||
+ excluded.has(method.parentPartNumber)
+ ) {
+ continue;
+ }
+ if (replenishment(method.parentPartNumber) === "Buy") {
+ lines.push(
+ `${method.parentPartNumber} is Buy in Carbon, so the BOM written to it isn't used until it's set to Make`
+ );
+ }
+ }
+ for (const item of plan.items) {
+ if (!item.shownAsUnit || excluded.has(item.partNumber)) continue;
+ if (replenishment(item.partNumber) === "Make") {
+ lines.push(
+ `${item.partNumber} is one unit in Onshape (Show Assembly only), so no BOM is written for it, but Carbon makes it`
+ );
+ }
+ }
+ return lines;
+}
+
+export const CARBON_ONLY_NOTE =
+ "Changes here apply to Carbon only. Onshape keeps its values.";
+
+export function mappedValueText(field: PlanItemField): string {
+ return `${field.label}: ${field.value ?? "—"} · from Onshape "${field.onshapeName}"`;
+}
+
+export function keptDifferenceText(kept: KeptDifference): string {
+ return `${kept.label}: Onshape has ${kept.onshape}. Carbon keeps ${
+ kept.carbon ?? "no value"
+ } (set at creation only).`;
+}
+
+export function customFieldChangeText(field: PlanCustomField): string {
+ const replaces = field.replaces ?? null;
+ const verb =
+ field.value === null
+ ? `Clears ${replaces ?? "the value"}`
+ : replaces === null
+ ? `Sets ${customFieldDisplayValue(field)}`
+ : `Replaces ${replaces} with ${customFieldDisplayValue(field)}`;
+ return `${field.name}: ${verb} (updated on every push).`;
+}
+
+export function itemFieldChangeText(change: ItemFieldChange): string {
+ const verb =
+ change.from === null
+ ? `Sets ${change.to ?? "no value"}`
+ : `Replaces ${change.from} with ${change.to ?? "no value"}`;
+ return `${change.label}: ${verb} (${
+ change.onshapeName === null
+ ? "goes with the change above"
+ : "updated on every push"
+ }).`;
+}
+
+export type PartApplyBody = {
+ planId: string;
+ selected: string[];
+ edits: Record<string, ItemEdit>;
+};
+
+export type AssemblyApplyBody = {
+ planId: string;
+ edits: Record<string, ItemEdit>;
+ excluded: string[];
+};
+
+export type ReleaseApplyBody = {
+ planId: string;
+ edits: Record<string, ItemEdit>;
+ changeNotice: ChangeNoticeEdit | null;
+ /**
+ * Sent only when the plan proposed a notice. Omitted, apply still records
+ * one for a create the plan did not foresee (a row gone since review).
+ */
+ createChangeNotice?: boolean;
+ makeDefault: boolean;
+};
+
+/** An existing item keeps only its manufacturing choices. */
+function scopeEdit(
+ edit: ItemEdit | undefined,
+ isCreate: boolean
+): ItemEdit | undefined {
+ if (!edit) return undefined;
+ if (isCreate) return edit;
+ const out: ItemEdit = {};
+ if (edit.replenishmentSystem !== undefined) {
+ out.replenishmentSystem = edit.replenishmentSystem;
+ }
+ if (edit.defaultMethodType !== undefined) {
+ out.defaultMethodType = edit.defaultMethodType;
+ }
+ if (edit.itemTrackingType !== undefined) {
+ out.itemTrackingType = edit.itemTrackingType;
+ }
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+function collectEdits(
+ edits: Record<string, ItemEdit>,
+ entries: Array<{ key: string; isCreate: boolean }>
+): Record<string, ItemEdit> {
+ const out: Record<string, ItemEdit> = {};
+ for (const { key, isCreate } of entries) {
+ const scoped = scopeEdit(edits[key], isCreate);
+ if (scoped) out[key] = scoped;
+ }
+ return out;
+}
+
+/** A deselected or excluded row sends nothing, even when edited. */
+export function applyRequestBody(
+ review: ReviewState
+): PartApplyBody | AssemblyApplyBody | ReleaseApplyBody {
+ switch (review.kind) {
+ case "part": {
+ const selectedRows = review.plan.rows.filter(
+ (row) =>
+ review.selected.has(row.partId) &&
+ row.action !== "skip-no-part-number"
+ );
+ return {
+ planId: review.planId,
+ selected: selectedRows.map((row) => row.partId),
+ edits: collectEdits(
+ review.edits,
+ selectedRows.map((row) => ({
+ key: row.partId,
+ isCreate: row.action === "create"
+ }))
+ )
+ };
+ }
+ case "assembly": {
+ const entries = [
+ {
+ key: review.plan.root.partNumber,
+ isCreate: review.plan.root.action === "create"
+ },
+ ...review.plan.items
+ .filter((item) => !review.excluded.has(item.partNumber))
+ .map((item) => ({
+ key: item.partNumber,
+ isCreate: item.action === "create"
+ }))
+ ];
+ return {
+ planId: review.planId,
+ edits: collectEdits(review.edits, entries),
+ excluded: [...review.excluded]
+ };
+ }
+ case "release": {
+ const entries = [
+ ...review.plan.items
+ .filter(
+ (item) =>
+ item.action === "create" ||
+ item.action === "reuse" ||
+ item.action === "revision"
+ )
+ .map((item) => ({
+ key: item.partNumber,
+ isCreate: item.action === "create"
+ })),
+ ...review.plan.children
+ .filter(
+ (child) => child.action === "create" || child.action === "reuse"
+ )
+ .map((child) => ({
+ key: child.partNumber,
+ isCreate: child.action === "create"
+ }))
+ ];
+ return {
+ planId: review.planId,
+ edits: collectEdits(review.edits, entries),
+ changeNotice:
+ review.plan.changeNotice && review.createChangeNotice
+ ? review.changeNotice
+ : null,
+ ...(review.plan.changeNotice !== null
+ ? { createChangeNotice: review.createChangeNotice }
+ : {}),
+ makeDefault: review.makeDefault
+ };
+ }
+ }
+}
+
+export function applyCount(review: ReviewState): number {
+ switch (review.kind) {
+ case "part":
+ return review.selected.size;
+ case "assembly":
+ return (
+ 1 +
+ review.plan.items.filter(
+ (item) => !review.excluded.has(item.partNumber)
+ ).length
+ );
+ case "release":
+ // An attached drawing is uploaded to its model, so a release of
+ // drawings alone still has something to push.
+ return (
+ review.plan.items.filter(
+ (item) =>
+ item.action === "reuse" ||
+ item.action === "revision" ||
+ item.action === "create" ||
+ item.action === "drawing"
+ ).length + review.plan.children.length
+ );
+ }
+}
+
+export type ApplyFieldError = { key: string; errors: string[] };
+
+export function indexFieldErrors(
+ list: ApplyFieldError[] | null | undefined
+): Record<string, string[]> {
+ const out: Record<string, string[]> = {};
+ for (const entry of list ?? []) {
+ if (entry && typeof entry.key === "string" && Array.isArray(entry.errors)) {
+ out[entry.key] = entry.errors.map(String);
+ }
+ }
+ return out;
+}
+
+/** Errors for `key` are stale once the user edits that row again. */
+export function clearFieldErrors(
+ fieldErrors: Record<string, string[]>,
+ key: string
+): Record<string, string[]> {
+ if (!(key in fieldErrors)) return fieldErrors;
+ const out = { ...fieldErrors };
+ delete out[key];
+ return out;
+}
+
+/** plan-release's unreadable-BOM warnings as text; anything else is dropped. */
+export function normalizeWarnings(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ const out: string[] = [];
+ for (const entry of value) {
+ if (typeof entry === "string") {
+ out.push(entry);
+ continue;
+ }
+ if (entry && typeof entry === "object") {
+ const message = (entry as { message?: unknown }).message;
+ if (typeof message === "string") out.push(message);
+ }
+ }
+ return out;
+}
+
+/**
+ * `warning`: the method is not written. `notice`: it is written into a Draft
+ * version, so nothing live changes until someone releases it.
+ */
+export type MethodDescription = {
+ text: string;
+ tone: "normal" | "muted" | "notice" | "warning";
+};
+
+/** Leaves out excluded children; an excluded parent's method is not applied. */
+export function describeMethod(
+ method: AssemblyPlanMethod,
+ excluded: Set<string>
+): MethodDescription {
+ const parent = method.parentPartNumber;
+ if (excluded.has(parent)) {
+ return { text: `${parent} · excluded`, tone: "muted" };
+ }
+ if (method.status === "missing") {
+ return {
+ text: `${parent} · no make method in Carbon, so its lines won't be written`,
+ tone: "warning"
+ };
+ }
+ const added = method.writes.filter(
+ (line) => !excluded.has(line.partNumber)
+ ).length;
+ const takenOver = method.takesOver.filter(
+ (line) => !excluded.has(line.readableId)
+ ).length;
+ const counts =
+ `${added} added, ${method.replaces.length} replaced, ` +
+ (takenOver > 0 ? `${takenOver} manual taken over, ` : "") +
+ `${method.keeps.length + method.takesOver.length - takenOver} manual kept`;
+ // A released method whose lines already match gets no Draft, unless the
+ // reviewer excluded one of its parts (that line would then go).
+ if (
+ method.status === "active" &&
+ method.unchanged &&
+ !method.writes.some((line) => excluded.has(line.partNumber))
+ ) {
+ return {
+ text: `${parent} · released in Carbon — no change`,
+ tone: "muted"
+ };
+ }
+ // The push writes a Draft version (`ensureDraftMakeMethod`): the one an
+ // earlier push made, or a new one.
+ if (method.status === "active") {
+ const draft =
+ method.reusedDraftVersion != null
+ ? `Draft version ${method.reusedDraftVersion}`
+ : "new Draft version";
+ return {
+ text: `${parent} · released in Carbon — ${draft}: ${counts}`,
+ tone: "notice"
+ };
+ }
+ const label = method.status === "new" ? "new method" : "Draft";
+ return { text: `${parent} · ${label}: ${counts}`, tone: "normal" };
+}
+
+export type ReleaseResultCounts = {
+ revisionsCreated: number;
+ itemsCreated: number;
+ childrenCreated?: number;
+ linesWritten: number;
+ methodsTouched: number;
+ changeNotice: string | null;
+ /** Drawings whose upload to their model item was queued. */
+ drawingsQueued?: number;
+ /** The release held drawings only, so there is no model to report on. */
+ drawingsOnly?: boolean;
+};
+
+const countOf = (count: number, noun: string) =>
+ `${count} ${noun}${count === 1 ? "" : "s"}`;
+
+/** BOM parts the push created are listed apart: they are not on the notice. */
+export function releaseResultText(s: ReleaseResultCounts): string {
+ const staged = [
+ s.revisionsCreated > 0 ? countOf(s.revisionsCreated, "new revision") : null,
+ s.itemsCreated > 0 ? countOf(s.itemsCreated, "new item") : null
+ ]
+ .filter(Boolean)
+ .join(" and ");
+ const parts: string[] = [];
+ if (staged) {
+ parts.push(
+ s.changeNotice
+ ? `${staged} on change notice ${s.changeNotice}, inactive until it is released in Carbon`
+ : staged
+ );
+ } else if (!s.drawingsOnly) {
+ parts.push("Already in Carbon");
+ }
+ const children = s.childrenCreated ?? 0;
+ if (children > 0) {
+ parts.push(`${countOf(children, "BOM part")} added to Carbon`);
+ }
+ if (s.methodsTouched > 0) {
+ parts.push(
+ s.linesWritten > 0
+ ? `${countOf(s.linesWritten, "BOM line")} written`
+ : "BOM unchanged"
+ );
+ }
+ const drawings = s.drawingsQueued ?? 0;
+ if (drawings > 0) {
+ parts.push(`${countOf(drawings, "drawing")} sent to Carbon`);
+ }
+ return parts.length > 0 ? parts.join(" · ") : "Nothing to push";
+}
+
+export type PartApplyResult = {
+ partId: string;
+ action: "created" | "adopted" | "updated" | "unchanged" | "skipped" | "error";
+ itemId?: string;
+ readableId?: string;
+ message?: string;
+};
+
+/**
+ * Marks pushed parts linked without another Onshape read. Identity comes from
+ * the result; revision and name from the plan, which is what the server wrote.
+ */
+export function patchPartStatuses(
+ rows: PanelPartStatus[],
+ review: PartReview,
+ results: PartApplyResult[]
+): PanelPartStatus[] {
+ const planRowByPartId = new Map(
+ review.plan.rows.map((row) => [row.partId, row])
+ );
+ const resultByPartId = new Map(results.map((r) => [r.partId, r]));
+ return rows.map((row) => {
+ const result = resultByPartId.get(row.partId);
+ const planRow = planRowByPartId.get(row.partId);
+ if (!result || !planRow || !result.itemId) return row;
+ if (
+ result.action !== "created" &&
+ result.action !== "adopted" &&
+ result.action !== "updated"
+ ) {
+ return row;
+ }
+ return {
+ ...row,
+ state: "linked",
+ item: {
+ id: result.itemId,
+ ...linkedItemFromPlan(planRow, review.edits[row.partId], result)
+ }
+ };
+ });
+}
+
+function linkedItemFromPlan(
+ planRow: PartPlanRow,
+ edit: ItemEdit | undefined,
+ result: Pick<PartApplyResult, "readableId">
+): Pick<
+ NonNullable<PanelPartStatus["item"]>,
+ "readableId" | "revision" | "name"
+> {
+ if (planRow.action === "create" && planRow.proposed) {
+ const merged = editedItem(planRow.proposed, edit);
+ return {
+ readableId: result.readableId ?? merged.readableId,
+ revision: merged.revision,
+ name: merged.name
+ };
+ }
+ return {
+ readableId:
+ result.readableId ?? planRow.item?.readableId ?? planRow.partNumber ?? "",
+ revision: planRow.item?.revision ?? planRow.revision ?? "0",
+ name: planRow.name
+ };
+}
diff --git a/packages/ee/src/onshape/panel/revision.test.ts b/packages/ee/src/onshape/panel/revision.test.ts
new file mode 100644
index 0000000000..d421441796
--- /dev/null
+++ b/packages/ee/src/onshape/panel/revision.test.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { compareRevisions } from "./revision";
+
+const sorted = (values: Array<string | null>) =>
+ [...values].sort(compareRevisions);
+
+describe("compareRevisions", () => {
+ it("orders numbers numerically", () => {
+ expect(sorted(["10", "9", "2", "0"])).toEqual(["0", "2", "9", "10"]);
+ });
+
+ it("orders letters by length, then alphabetically", () => {
+ expect(sorted(["AA", "Y", "B", "AB", "A"])).toEqual([
+ "A",
+ "B",
+ "Y",
+ "AA",
+ "AB"
+ ]);
+ });
+
+ it("puts numbers before letters and empty first", () => {
+ expect(sorted(["A", "0", null, "1"])).toEqual([null, "0", "1", "A"]);
+ });
+
+ it("ignores leading zeros when comparing numbers", () => {
+ expect(compareRevisions("11", "010")).toBeGreaterThan(0);
+ expect(compareRevisions("9", "010")).toBeLessThan(0);
+ });
+
+ it("sorts other schemes after both, naturally", () => {
+ expect(sorted(["A10", "A2", "Z"])).toEqual(["Z", "A2", "A10"]);
+ });
+});
diff --git a/packages/ee/src/onshape/panel/revision.ts b/packages/ee/src/onshape/panel/revision.ts
new file mode 100644
index 0000000000..498f64e304
--- /dev/null
+++ b/packages/ee/src/onshape/panel/revision.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * Revision order as `getNextRevision` counts: numbers by value (9 < 10),
+ * letters by length then alphabet (Z < AA). Empty first, then numbers,
+ * letters, other text.
+ */
+export function compareRevisions(
+ a: string | null | undefined,
+ b: string | null | undefined
+): number {
+ const left = (a ?? "").trim();
+ const right = (b ?? "").trim();
+ const rank = revisionRank(left) - revisionRank(right);
+ if (rank !== 0) return rank;
+
+ if (isNumeric(left) && isNumeric(right)) {
+ // By digits, not Number(): no precision limit on a long revision.
+ const l = left.replace(/^0+(?=\d)/, "");
+ const r = right.replace(/^0+(?=\d)/, "");
+ if (l.length !== r.length) return l.length - r.length;
+ if (l !== r) return l < r ? -1 : 1;
+ // "01" and "1" are the same number; keep the order stable anyway.
+ return left.localeCompare(right);
+ }
+ if (isLetters(left) && isLetters(right)) {
+ if (left.length !== right.length) return left.length - right.length;
+ return left.toUpperCase().localeCompare(right.toUpperCase());
+ }
+ return left.localeCompare(right, undefined, { numeric: true });
+}
+
+const isNumeric = (value: string) => /^\d+$/.test(value);
+const isLetters = (value: string) => /^[A-Za-z]+$/.test(value);
+
+function revisionRank(value: string): number {
+ if (!value) return 0;
+ if (isNumeric(value)) return 1;
+ if (isLetters(value)) return 2;
+ return 3;
+}
diff --git a/packages/ee/src/onshape/panel/session-policy.test.ts b/packages/ee/src/onshape/panel/session-policy.test.ts
new file mode 100644
index 0000000000..b71826def4
--- /dev/null
+++ b/packages/ee/src/onshape/panel/session-policy.test.ts
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { AuthSession } from "@carbon/auth";
+import { describe, expect, it } from "vitest";
+import {
+ PANEL_SESSION_TTL_SECONDS,
+ panelSessionFromAuthSession,
+ panelSessionRefusal,
+ panelSessionTtlSeconds
+} from "./session-policy";
+
+const NOW = 1_780_000_000_000;
+const HOUR = 60 * 60 * 1000;
+
+const authSession: AuthSession = {
+ accessToken: "access",
+ refreshToken: "refresh",
+ userId: "user-1",
+ companyId: "company-1",
+ companyGroupId: "group-1",
+ email: "[email protected]",
+ expiresIn: 3600,
+ expiresAt: NOW / 1000 + 3600,
+ createdAt: NOW - 2 * HOUR,
+ lastActiveAt: NOW - 1000,
+ mfaVerified: true,
+ console: "company-1"
+};
+
+describe("panelSessionFromAuthSession", () => {
+ it("keeps identity and drops every Supabase token and the console flag", () => {
+ const session = panelSessionFromAuthSession(authSession, NOW);
+ expect(session).toEqual({
+ userId: "user-1",
+ companyId: "company-1",
+ companyGroupId: "group-1",
+ email: "[email protected]",
+ mfaVerified: true,
+ createdAt: NOW - 2 * HOUR,
+ lastActiveAt: NOW
+ });
+ });
+});
+
+describe("panelSessionRefusal", () => {
+ const policy = {
+ controlled: true,
+ absoluteMaxMs: 12 * HOUR,
+ idleLockMs: 15 * 60 * 1000,
+ hasVerifiedTotpFactor: false
+ };
+ const fresh = {
+ createdAt: NOW - 2 * HOUR,
+ lastActiveAt: NOW - 60 * 1000,
+ mfaVerified: true
+ };
+
+ it("lets a fresh session continue", () => {
+ expect(panelSessionRefusal(fresh, NOW, policy)).toBeNull();
+ });
+
+ it("ends a session past the absolute cap in a controlled environment", () => {
+ const old = { ...fresh, createdAt: NOW - 13 * HOUR };
+ expect(panelSessionRefusal(old, NOW, policy)).toBe("expired");
+ expect(
+ panelSessionRefusal(old, NOW, { ...policy, controlled: false })
+ ).toBeNull();
+ });
+
+ it("locks an idle session in a controlled environment", () => {
+ const idle = { ...fresh, lastActiveAt: NOW - 20 * 60 * 1000 };
+ expect(panelSessionRefusal(idle, NOW, policy)).toBe("idle");
+ expect(
+ panelSessionRefusal(idle, NOW, { ...policy, controlled: false })
+ ).toBeNull();
+ });
+
+ it("sends a user who enrolled TOTP after minting through the challenge", () => {
+ const unverified = { ...fresh, mfaVerified: undefined };
+ expect(
+ panelSessionRefusal(unverified, NOW, {
+ ...policy,
+ controlled: false,
+ hasVerifiedTotpFactor: true
+ })
+ ).toBe("mfa");
+ expect(
+ panelSessionRefusal(unverified, NOW, { ...policy, controlled: false })
+ ).toBeNull();
+ });
+});
+
+describe("panelSessionTtlSeconds", () => {
+ const session = { createdAt: NOW - 2 * HOUR };
+
+ it("is the fixed TTL outside a controlled environment", () => {
+ expect(
+ panelSessionTtlSeconds(session, NOW, {
+ controlled: false,
+ absoluteMaxMs: 3 * HOUR
+ })
+ ).toBe(PANEL_SESSION_TTL_SECONDS);
+ });
+
+ it("stops at the ERP session's absolute cap in a controlled environment", () => {
+ expect(
+ panelSessionTtlSeconds(session, NOW, {
+ controlled: true,
+ absoluteMaxMs: 3 * HOUR
+ })
+ ).toBe(3600);
+ });
+
+ it("is zero once the cap has passed", () => {
+ expect(
+ panelSessionTtlSeconds(session, NOW, {
+ controlled: true,
+ absoluteMaxMs: HOUR
+ })
+ ).toBe(0);
+ });
+});
diff --git a/packages/ee/src/onshape/panel/session-policy.ts b/packages/ee/src/onshape/panel/session-policy.ts
new file mode 100644
index 0000000000..1f0e434b95
--- /dev/null
+++ b/packages/ee/src/onshape/panel/session-policy.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { AuthSession } from "@carbon/auth";
+
+export const PANEL_SESSION_TTL_SECONDS = 12 * 60 * 60;
+
+export type PanelSession = {
+ userId: string;
+ companyId: string;
+ companyGroupId: string;
+ email: string;
+ mfaVerified?: boolean;
+ ssoProviderId?: string;
+ /** Start of the source ERP session; the absolute cap counts from it. */
+ createdAt: number;
+ lastActiveAt: number;
+};
+
+/** Identity only: the cookie session's Supabase tokens are left behind. */
+export function panelSessionFromAuthSession(
+ authSession: AuthSession,
+ now: number
+): PanelSession {
+ return {
+ userId: authSession.userId,
+ companyId: authSession.companyId,
+ companyGroupId: authSession.companyGroupId,
+ email: authSession.email,
+ ...(authSession.mfaVerified ? { mfaVerified: true } : {}),
+ ...(authSession.ssoProviderId
+ ? { ssoProviderId: authSession.ssoProviderId }
+ : {}),
+ createdAt: authSession.createdAt ?? now,
+ lastActiveAt: now
+ };
+}
+
+/**
+ * The cookie session's policy: in a controlled environment the absolute cap
+ * and idle lock; everywhere, a TOTP factor enrolled after minting.
+ */
+export function panelSessionRefusal(
+ session: Pick<PanelSession, "createdAt" | "lastActiveAt" | "mfaVerified">,
+ now: number,
+ policy: {
+ controlled: boolean;
+ absoluteMaxMs: number;
+ idleLockMs: number;
+ hasVerifiedTotpFactor: boolean;
+ }
+): "expired" | "idle" | "mfa" | null {
+ if (policy.controlled && now - session.createdAt > policy.absoluteMaxMs) {
+ return "expired";
+ }
+ if (policy.controlled && now - session.lastActiveAt > policy.idleLockMs) {
+ return "idle";
+ }
+ if (!session.mfaVerified && policy.hasVerifiedTotpFactor) return "mfa";
+ return null;
+}
+
+/** Controlled environment: the TTL stops at the ERP session's absolute cap. */
+export function panelSessionTtlSeconds(
+ session: Pick<PanelSession, "createdAt">,
+ now: number,
+ { controlled, absoluteMaxMs }: { controlled: boolean; absoluteMaxMs: number }
+): number {
+ if (!controlled) return PANEL_SESSION_TTL_SECONDS;
+ const remainingMs = session.createdAt + absoluteMaxMs - now;
+ return Math.max(
+ 0,
+ Math.min(PANEL_SESSION_TTL_SECONDS, Math.floor(remainingMs / 1000))
+ );
+}
diff --git a/packages/ee/src/onshape/panel/session-storage.test.ts b/packages/ee/src/onshape/panel/session-storage.test.ts
new file mode 100644
index 0000000000..cfe7b0f639
--- /dev/null
+++ b/packages/ee/src/onshape/panel/session-storage.test.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ PANEL_FORBIDDEN_MESSAGE,
+ PanelTimeoutError,
+ PanelUnauthorizedError,
+ panelFetch
+} from "./session-storage";
+
+/** A fetch that never settles until its signal aborts. */
+function hang() {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ (_input: string, init: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () =>
+ reject(new DOMException("Aborted", "AbortError"))
+ );
+ })
+ )
+ );
+}
+
+function answer(body: string, status: number, contentType?: string) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(body, {
+ status,
+ headers: contentType ? { "Content-Type": contentType } : {}
+ })
+ )
+ );
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("panelFetch", () => {
+ it("sends the token as a bearer header", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ await panelFetch("cps_token", "/api/x");
+ const init = (fetchMock.mock.calls[0] as unknown[])[1] as RequestInit;
+ expect(new Headers(init.headers).get("Authorization")).toBe(
+ "Bearer cps_token"
+ );
+ });
+
+ it("throws on a 401 so the panel offers sign-in again", async () => {
+ answer("Unauthorized", 401);
+ await expect(panelFetch("t", "/api/x")).rejects.toBeInstanceOf(
+ PanelUnauthorizedError
+ );
+ });
+
+ it("turns a plain-text 403 into readable JSON", async () => {
+ answer("Forbidden", 403, "text/plain");
+ const response = await panelFetch("t", "/api/x");
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({
+ error: PANEL_FORBIDDEN_MESSAGE,
+ status: 403
+ });
+ });
+
+ it("uses the permission wording even when a 403 is JSON", async () => {
+ answer(JSON.stringify({ error: "nope" }), 403, "application/json");
+ expect((await (await panelFetch("t", "/api/x")).json()).error).toBe(
+ PANEL_FORBIDDEN_MESSAGE
+ );
+ });
+
+ it("turns an HTML error page into a sentence, not a parser message", async () => {
+ answer("<!doctype html><h1>502 Bad Gateway</h1>", 502, "text/html");
+ const response = await panelFetch("t", "/api/x");
+ expect(response.status).toBe(502);
+ const body = await response.json();
+ expect(body.error).toMatch(/unexpected response \(HTTP 502\)/);
+ });
+
+ it("passes a JSON error through untouched, so route messages survive", async () => {
+ answer(
+ JSON.stringify({ error: "Onshape is still building this BOM." }),
+ 504,
+ "application/json; charset=utf-8"
+ );
+ expect(await (await panelFetch("t", "/api/x")).json()).toEqual({
+ error: "Onshape is still building this BOM."
+ });
+ });
+
+ it("never touches a successful response", async () => {
+ answer("not json at all", 200, "text/plain");
+ expect(await (await panelFetch("t", "/api/x")).text()).toBe(
+ "not json at all"
+ );
+ });
+
+ it("gives up on a request that never settles", async () => {
+ hang();
+ await expect(panelFetch("t", "/api/x", {}, 10)).rejects.toBeInstanceOf(
+ PanelTimeoutError
+ );
+ });
+
+ it("reports a caller's own cancellation as itself, not as a timeout", async () => {
+ hang();
+ const caller = new AbortController();
+ const pending = panelFetch("t", "/api/x", { signal: caller.signal });
+ caller.abort();
+ const error = await pending.catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(DOMException);
+ expect(error).not.toBeInstanceOf(PanelTimeoutError);
+ });
+
+ it("waits indefinitely when the timeout is null", async () => {
+ vi.useFakeTimers();
+ try {
+ hang();
+ let settled = false;
+ const pending = panelFetch("t", "/api/x", {}, null).finally(() => {
+ settled = true;
+ });
+ pending.catch(() => {
+ // never settles; nothing to handle
+ });
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(settled).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/ee/src/onshape/panel/session-storage.ts b/packages/ee/src/onshape/panel/session-storage.ts
new file mode 100644
index 0000000000..1e45870f11
--- /dev/null
+++ b/packages/ee/src/onshape/panel/session-storage.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * The panel token lives in `sessionStorage`, partitioned by Onshape's top-level
+ * site and gone with the tab. Every access is guarded: storage throws in a
+ * sandboxed or storage-blocked frame and the panel must still render.
+ */
+
+const STORAGE_KEY = "carbon:onshape-panel-session";
+
+export function getPanelSessionToken(): string | null {
+ if (typeof window === "undefined") return null;
+ try {
+ return window.sessionStorage.getItem(STORAGE_KEY);
+ } catch {
+ return null;
+ }
+}
+
+export function setPanelSessionToken(token: string) {
+ try {
+ window.sessionStorage.setItem(STORAGE_KEY, token);
+ } catch {
+ // Storage blocked: the token lives only in React state for this load.
+ }
+}
+
+export function clearPanelSessionToken() {
+ try {
+ window.sessionStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // nothing to clear
+ }
+}
+
+export class PanelUnauthorizedError extends Error {
+ constructor() {
+ super("Panel session is missing or expired");
+ this.name = "PanelUnauthorizedError";
+ }
+}
+
+/**
+ * Long because Onshape builds an assembly's BOM on first request; finite so a
+ * stalled read shows a message and Refresh.
+ */
+export const PANEL_FETCH_TIMEOUT_MS = 60_000;
+
+export class PanelTimeoutError extends Error {
+ constructor(timeoutMs: number) {
+ super(
+ `Carbon didn't answer within ${timeoutMs / 1000} seconds. It may still be working; try Refresh in a moment.`
+ );
+ this.name = "PanelTimeoutError";
+ }
+}
+
+/**
+ * Bearer `fetch`. A 401 drops the token so the panel offers sign-in again.
+ * `timeoutMs: null` waits indefinitely, for pushes that keep writing anyway.
+ */
+export async function panelFetch(
+ token: string,
+ input: string,
+ init: RequestInit = {},
+ timeoutMs: number | null = PANEL_FETCH_TIMEOUT_MS
+): Promise<Response> {
+ const headers = new Headers(init.headers);
+ headers.set("Authorization", `Bearer ${token}`);
+
+ const controller = new AbortController();
+ const caller = init.signal;
+ const abortForCaller = () => controller.abort();
+ if (caller?.aborted) controller.abort();
+ caller?.addEventListener("abort", abortForCaller);
+ const timer =
+ timeoutMs === null ? null : setTimeout(() => controller.abort(), timeoutMs);
+
+ let response: Response;
+ try {
+ response = await fetch(input, {
+ ...init,
+ headers,
+ signal: controller.signal
+ });
+ } catch (error) {
+ // Only our own abort is a timeout; a caller's cancellation stays theirs.
+ if (timeoutMs !== null && controller.signal.aborted && !caller?.aborted) {
+ throw new PanelTimeoutError(timeoutMs);
+ }
+ throw error;
+ } finally {
+ if (timer) clearTimeout(timer);
+ caller?.removeEventListener("abort", abortForCaller);
+ }
+
+ if (response.status === 401) {
+ clearPanelSessionToken();
+ throw new PanelUnauthorizedError();
+ }
+ return normalizeErrorBody(response);
+}
+
+export const PANEL_FORBIDDEN_MESSAGE =
+ "Your Carbon account doesn't have permission for this. Ask an admin in Carbon to grant it.";
+
+/**
+ * Callers read a failure as `{ error }` JSON; a 403 (plain-text "Forbidden")
+ * or a gateway's HTML page is rewritten to that shape.
+ */
+async function normalizeErrorBody(response: Response): Promise<Response> {
+ if (response.ok) return response;
+ const isJson = (response.headers.get("Content-Type") ?? "").includes(
+ "application/json"
+ );
+ if (response.status !== 403 && isJson) return response;
+
+ const error =
+ response.status === 403
+ ? PANEL_FORBIDDEN_MESSAGE
+ : `Carbon returned an unexpected response (HTTP ${response.status}). Try again.`;
+ return new Response(JSON.stringify({ error, status: response.status }), {
+ status: response.status,
+ headers: { "Content-Type": "application/json" }
+ });
+}
diff --git a/packages/ee/src/onshape/panel/session.server.ts b/packages/ee/src/onshape/panel/session.server.ts
new file mode 100644
index 0000000000..d408c53bcf
--- /dev/null
+++ b/packages/ee/src/onshape/panel/session.server.ts
@@ -0,0 +1,236 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { randomBytes } from "node:crypto";
+import type { AuthSession } from "@carbon/auth";
+import { hasPermission } from "@carbon/auth";
+import { logAuthEvent } from "@carbon/auth/auth-events.server";
+import {
+ getCarbonServiceRole,
+ getUserScopedClient
+} from "@carbon/auth/client.server";
+import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
+import { getUserClaims } from "@carbon/auth/users.server";
+import type { Database } from "@carbon/database";
+import {
+ CONTROLLED_ENVIRONMENT,
+ SESSION_ABSOLUTE_MAX_MS,
+ SESSION_IDLE_LOCK_MS
+} from "@carbon/env";
+import { redis } from "@carbon/kv";
+import { getClientIp } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ type PanelSession,
+ panelSessionFromAuthSession,
+ panelSessionRefusal,
+ panelSessionTtlSeconds
+} from "./session-policy";
+
+export {
+ PANEL_SESSION_TTL_SECONDS,
+ type PanelSession
+} from "./session-policy";
+
+/**
+ * Opaque `cps_` bearer tokens for the Onshape iframe, which the SameSite=Lax
+ * cookie never reaches. Redis holds identity only: sharing the cookie's refresh
+ * token would rotate one chain, and GoTrue revokes the family on reuse.
+ */
+
+const ACTIVITY_STAMP_INTERVAL_MS = 60_000;
+
+const TOKEN_PREFIX = "cps_";
+// 24 random bytes → 32 base64url characters.
+const TOKEN_PATTERN = /^cps_[A-Za-z0-9_-]{32}$/;
+
+function keyFor(token: string) {
+ return `panel-session:${token}`;
+}
+
+export function isPanelSessionToken(value: unknown): value is string {
+ return typeof value === "string" && TOKEN_PATTERN.test(value);
+}
+
+export function panelSessionTokenFromRequest(request: Request): string | null {
+ const header = request.headers.get("authorization");
+ if (!header) return null;
+ const [scheme, token] = header.trim().split(/\s+/);
+ if (scheme?.toLowerCase() !== "bearer") return null;
+ return isPanelSessionToken(token) ? token : null;
+}
+
+/** Null when the ERP session has no time left or Redis did not store it. */
+export async function createPanelSession(
+ authSession: AuthSession
+): Promise<string | null> {
+ const now = Date.now();
+ const session = panelSessionFromAuthSession(authSession, now);
+ const ttl = panelSessionTtlSeconds(session, now, {
+ controlled: CONTROLLED_ENVIRONMENT,
+ absoluteMaxMs: SESSION_ABSOLUTE_MAX_MS
+ });
+ if (ttl <= 0) return null;
+
+ const token = `${TOKEN_PREFIX}${randomBytes(24).toString("base64url")}`;
+ const stored = await redis.set(
+ keyFor(token),
+ JSON.stringify(session),
+ "EX",
+ ttl
+ );
+ return stored === "OK" ? token : null;
+}
+
+async function loadPanelSession(token: string): Promise<PanelSession | null> {
+ const raw = await redis.get(keyFor(token));
+ if (!raw) return null;
+ try {
+ const session = JSON.parse(raw) as Partial<PanelSession> & {
+ accessToken?: string;
+ };
+ // An entry carrying a Supabase token or lacking identity is invalid.
+ if (session.accessToken || !session.userId || !session.createdAt) {
+ await redis.del(keyFor(token));
+ return null;
+ }
+ return session as PanelSession;
+ } catch {
+ await redis.del(keyFor(token));
+ return null;
+ }
+}
+
+async function stampActivity(token: string, session: PanelSession) {
+ // XX: a session deleted since it was read (logout, a refusal) stays deleted.
+ await redis.set(
+ keyFor(token),
+ JSON.stringify({ ...session, lastActiveAt: Date.now() }),
+ "KEEPTTL",
+ "XX"
+ );
+}
+
+export async function deletePanelSession(token: string): Promise<void> {
+ await redis.del(keyFor(token));
+}
+
+/**
+ * Every refusal is a 401; the sign-in popup's cookie path then routes the user
+ * through `/unlock` or `/mfa`.
+ */
+async function requirePanelSession(token: string): Promise<PanelSession> {
+ const session = await loadPanelSession(token);
+ if (!session) {
+ throw new Response("Unauthorized", { status: 401 });
+ }
+
+ const refusal = panelSessionRefusal(session, Date.now(), {
+ controlled: CONTROLLED_ENVIRONMENT,
+ absoluteMaxMs: SESSION_ABSOLUTE_MAX_MS,
+ idleLockMs: SESSION_IDLE_LOCK_MS,
+ hasVerifiedTotpFactor: session.mfaVerified
+ ? false
+ : await userHasVerifiedTotpFactor(session.userId)
+ });
+ if (refusal) {
+ await deletePanelSession(token);
+ throw new Response("Unauthorized", { status: 401 });
+ }
+ return session;
+}
+
+/**
+ * Panel counterpart of `requirePermissions` with the same return shape.
+ * Employees only, the acting user is always the session user, and failures are
+ * 401 or 403, never redirects, since every caller is an iframe fetch.
+ */
+export async function requireOnshapePanelPermissions(
+ request: Request,
+ requiredPermissions: {
+ view?: string | string[];
+ create?: string | string[];
+ update?: string | string[];
+ delete?: string | string[];
+ bypassRls?: boolean;
+ }
+): Promise<{
+ client: SupabaseClient<Database>;
+ companyId: string;
+ companyGroupId: string;
+ email: string;
+ userId: string;
+ sessionUserId: string;
+ consoleMode: boolean;
+}> {
+ const token = panelSessionTokenFromRequest(request);
+ if (!token) {
+ throw new Response("Unauthorized", { status: 401 });
+ }
+
+ const session = await requirePanelSession(token);
+ const { companyId, companyGroupId, email, userId } = session;
+
+ const myClaims = await getUserClaims(userId, companyId);
+
+ const deny = (reason: string) => {
+ logAuthEvent("permission_denied", {
+ userId,
+ actor: email,
+ companyId,
+ ip: getClientIp(request) ?? undefined,
+ reason: `onshape panel: ${reason}`
+ });
+ return new Response("Forbidden", { status: 403 });
+ };
+
+ if (myClaims.role !== "employee") {
+ throw deny(`${myClaims.role ?? "no"} role`);
+ }
+
+ const hasRequiredPermissions = Object.entries(requiredPermissions).every(
+ ([action, permission]) => {
+ if (action === "bypassRls") return true;
+ const permissions =
+ typeof permission === "string"
+ ? [permission]
+ : Array.isArray(permission)
+ ? permission
+ : null;
+ if (!permissions) return false;
+ // `hasPermission` honours the "0" all-companies scope.
+ return permissions.every((p) =>
+ hasPermission(
+ myClaims.permissions,
+ p,
+ action as "view" | "create" | "update" | "delete",
+ companyId
+ )
+ );
+ }
+ );
+
+ if (!hasRequiredPermissions) {
+ throw deny(JSON.stringify(requiredPermissions));
+ }
+
+ // Only an authorized request counts as activity.
+ if (Date.now() - session.lastActiveAt > ACTIVITY_STAMP_INTERVAL_MS) {
+ await stampActivity(token, session);
+ }
+
+ const client = requiredPermissions.bypassRls
+ ? getCarbonServiceRole()
+ : await getUserScopedClient(userId);
+
+ return {
+ client,
+ companyId,
+ companyGroupId,
+ email,
+ userId,
+ sessionUserId: userId,
+ consoleMode: false
+ };
+}
diff --git a/packages/ee/src/onshape/panel/standard-fields.test.ts b/packages/ee/src/onshape/panel/standard-fields.test.ts
new file mode 100644
index 0000000000..3c300b8642
--- /dev/null
+++ b/packages/ee/src/onshape/panel/standard-fields.test.ts
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { StandardField } from "./standard-fields";
+import {
+ defaultTranslations,
+ matchingUnit,
+ onshapeValueOptions,
+ repeatedTranslationRows,
+ STANDARD_FIELDS,
+ standardField,
+ translateValue,
+ translationErrors,
+ untranslatedOptions
+} from "./standard-fields";
+
+const units = [
+ { code: "EA", name: "Each" },
+ { code: "KG", name: "Kilogram" }
+];
+
+function field(id: string): StandardField {
+ const found = standardField(id);
+ if (!found) throw new Error(`no field ${id}`);
+ return found;
+}
+
+describe("the target list", () => {
+ it("holds the six item fields, each with a writer", () => {
+ expect(STANDARD_FIELDS.map((entry) => [entry.id, entry.writer])).toEqual([
+ ["mpn", "itemColumn"],
+ ["replenishmentSystem", "itemMethod"],
+ ["defaultMethodType", "itemMethod"],
+ ["sourcingType", "itemMethod"],
+ ["itemTrackingType", "itemTracking"],
+ ["unitOfMeasureCode", "itemColumn"]
+ ]);
+ });
+});
+
+describe("defaultTranslations", () => {
+ it("starts a fixed list with each Carbon value on both sides", () => {
+ expect(defaultTranslations(field("replenishmentSystem"), "ENUM")).toEqual([
+ { onshape: "Buy", carbon: "Buy" },
+ { onshape: "Make", carbon: "Make" },
+ { onshape: "Buy and Make", carbon: "Buy and Make" }
+ ]);
+ });
+
+ it("starts a BOOL property with Yes and No, both No value", () => {
+ expect(defaultTranslations(field("replenishmentSystem"), "BOOL")).toEqual([
+ { onshape: "Yes", carbon: null },
+ { onshape: "No", carbon: null }
+ ]);
+ });
+
+ it("starts the unit and text fields with no rows", () => {
+ expect(defaultTranslations(field("unitOfMeasureCode"), "STRING")).toEqual(
+ []
+ );
+ expect(defaultTranslations(field("mpn"), "STRING")).toEqual([]);
+ });
+
+ it("starts a list with known options with a row for each option that names a Carbon value", () => {
+ expect(
+ defaultTranslations(field("replenishmentSystem"), "ENUM", [
+ "Make",
+ "buy",
+ "Make or Buy",
+ "Buy and Make"
+ ])
+ ).toEqual([
+ { onshape: "Make", carbon: "Make" },
+ { onshape: "buy", carbon: "Buy" },
+ { onshape: "Buy and Make", carbon: "Buy and Make" }
+ ]);
+ });
+
+ it("gives a list whose options name no Carbon value no rows", () => {
+ expect(
+ defaultTranslations(field("replenishmentSystem"), "ENUM", [
+ "In progress",
+ "Released"
+ ])
+ ).toEqual([]);
+ });
+});
+
+describe("onshapeValueOptions", () => {
+ it("lists Yes and No for a BOOL and an ENUM's own options", () => {
+ expect(onshapeValueOptions("BOOL", undefined)).toEqual(["Yes", "No"]);
+ expect(onshapeValueOptions("ENUM", ["A", "B"])).toEqual(["A", "B"]);
+ });
+
+ it("has none for free text or an ENUM whose options are unknown", () => {
+ expect(onshapeValueOptions("STRING", ["A"])).toBeNull();
+ expect(onshapeValueOptions("ENUM", undefined)).toBeNull();
+ expect(onshapeValueOptions("ENUM", [])).toBeNull();
+ });
+});
+
+describe("untranslatedOptions", () => {
+ it("names the options no row matches", () => {
+ expect(
+ untranslatedOptions(
+ field("replenishmentSystem"),
+ ["Make", "Buy", "Make or Buy"],
+ [
+ { onshape: "make", carbon: "Make" },
+ { onshape: "Buy", carbon: null }
+ ],
+ units
+ )
+ ).toEqual(["Make or Buy"]);
+ });
+
+ it("counts a unit's code or name as a match without a row", () => {
+ expect(
+ untranslatedOptions(
+ field("unitOfMeasureCode"),
+ ["Each", "KG", "Inch"],
+ [],
+ units
+ )
+ ).toEqual(["Inch"]);
+ });
+});
+
+describe("translateValue", () => {
+ const replenishment = field("replenishmentSystem");
+ const rows = [
+ { onshape: "Purchased", carbon: "Buy" },
+ { onshape: "Made", carbon: "Make" },
+ { onshape: "Either", carbon: null }
+ ];
+ const translate = (text: string | null, valueType = "ENUM") =>
+ translateValue({
+ field: replenishment,
+ text,
+ valueType,
+ translations: rows,
+ units
+ });
+
+ it("matches a row, ignoring case and the spaces at the two ends", () => {
+ expect(translate(" purchased ")).toEqual({ ok: true, value: "Buy" });
+ expect(translate("MADE")).toEqual({ ok: true, value: "Make" });
+ });
+
+ it("gives No value for a row set to it", () => {
+ expect(translate("Either")).toEqual({ ok: true, value: null });
+ });
+
+ it("gives no value for an empty value, never a problem", () => {
+ expect(translate(null)).toEqual({ ok: true, value: null });
+ expect(translate(" ")).toEqual({ ok: true, value: null });
+ });
+
+ it("reports a value no row matches", () => {
+ expect(translate("Outsourced")).toEqual({
+ ok: false,
+ reason: '"Outsourced" has no Carbon value'
+ });
+ });
+
+ it("reads a BOOL value as the Yes or No a row names", () => {
+ const translations = [
+ { onshape: "Yes", carbon: "Buy" },
+ { onshape: "No", carbon: null }
+ ];
+ const bool = (text: string) =>
+ translateValue({
+ field: replenishment,
+ text,
+ valueType: "BOOL",
+ translations,
+ units
+ });
+ expect(bool("true")).toEqual({ ok: true, value: "Buy" });
+ expect(bool("false")).toEqual({ ok: true, value: null });
+ });
+
+ it("matches a unit by its code or its name", () => {
+ const unit = (text: string) =>
+ translateValue({
+ field: field("unitOfMeasureCode"),
+ text,
+ valueType: "STRING",
+ translations: [{ onshape: "pcs", carbon: "EA" }],
+ units
+ });
+ expect(unit("pcs")).toEqual({ ok: true, value: "EA" });
+ expect(unit("kg")).toEqual({ ok: true, value: "KG" });
+ expect(unit("Kilogram")).toEqual({ ok: true, value: "KG" });
+ expect(unit("Litre")).toEqual({
+ ok: false,
+ reason: '"Litre" has no Carbon value'
+ });
+ });
+
+ it("takes a text field's value as it is", () => {
+ expect(
+ translateValue({
+ field: field("mpn"),
+ text: " SKF-6203 ",
+ valueType: "STRING",
+ translations: [],
+ units
+ })
+ ).toEqual({ ok: true, value: "SKF-6203" });
+ });
+});
+
+describe("translationErrors", () => {
+ it("accepts the field's own values and No value", () => {
+ expect(
+ translationErrors(
+ field("sourcingType"),
+ [
+ { onshape: "Drop", carbon: "Drop Ship" },
+ { onshape: "Stock", carbon: null }
+ ],
+ units
+ )
+ ).toEqual([]);
+ });
+
+ it("refuses a value outside the list, a blank row and a repeated row", () => {
+ expect(
+ translationErrors(
+ field("itemTrackingType"),
+ [
+ { onshape: "Lot", carbon: "Lot" },
+ { onshape: " ", carbon: "Batch" },
+ { onshape: "Serial", carbon: "Serial" },
+ { onshape: "serial ", carbon: "Serial" }
+ ],
+ units
+ )
+ ).toEqual([
+ '"Lot" is not a Tracking Type value in Carbon',
+ "A translation row has no Onshape value",
+ '"serial" has two rows'
+ ]);
+ });
+
+ it("checks a unit row against the company's units", () => {
+ expect(
+ translationErrors(
+ field("unitOfMeasureCode"),
+ [{ onshape: "pcs", carbon: "PC" }],
+ units
+ )
+ ).toEqual(['"PC" is not a Unit of Measure value in Carbon']);
+ });
+});
+
+describe("repeatedTranslationRows", () => {
+ it("flags a typed row that repeats an option or an earlier row, ignoring case and spaces", () => {
+ expect(
+ repeatedTranslationRows([
+ { onshape: "Make", fixed: true },
+ { onshape: "Buy", fixed: true },
+ { onshape: " make ", fixed: false },
+ { onshape: "Outsourced", fixed: false },
+ { onshape: "OUTSOURCED", fixed: false },
+ { onshape: " ", fixed: false }
+ ])
+ ).toEqual([2, 4]);
+ });
+
+ it("flags nothing when every value is listed once", () => {
+ expect(
+ repeatedTranslationRows([
+ { onshape: "Make", fixed: true },
+ { onshape: "Purchased", fixed: false }
+ ])
+ ).toEqual([]);
+ });
+});
+
+describe("matchingUnit", () => {
+ it("matches a unit by code first, then by name", () => {
+ expect(matchingUnit("kg", units)).toEqual({
+ unit: { code: "KG", name: "Kilogram" },
+ by: "code"
+ });
+ expect(matchingUnit(" each ", units)).toEqual({
+ unit: { code: "EA", name: "Each" },
+ by: "name"
+ });
+ expect(matchingUnit("Inch", units)).toBeNull();
+ });
+});
diff --git a/packages/ee/src/onshape/panel/standard-fields.ts b/packages/ee/src/onshape/panel/standard-fields.ts
new file mode 100644
index 0000000000..785355d727
--- /dev/null
+++ b/packages/ee/src/onshape/panel/standard-fields.ts
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * The item fields an Onshape property can set. Each `writer` key has one
+ * function in the ERP's `STANDARD_FIELD_WRITERS` (onshape-push.server.ts),
+ * the item page's own write, so its cascades run.
+ */
+
+import {
+ ITEM_METHOD_TYPES,
+ ITEM_REPLENISHMENT_SYSTEMS,
+ ITEM_SOURCING_TYPES,
+ ITEM_TRACKING_TYPES
+} from "./item-values";
+import type { PlanUnitOfMeasure } from "./plan";
+
+export const STANDARD_FIELD_IDS = [
+ "mpn",
+ "replenishmentSystem",
+ "defaultMethodType",
+ "sourcingType",
+ "itemTrackingType",
+ "unitOfMeasureCode"
+] as const;
+
+export type StandardFieldId = (typeof STANDARD_FIELD_IDS)[number];
+
+/**
+ * - `itemColumn`: the column alone, as the Properties panel writes it.
+ * - `itemMethod`: replenishment, method, sourcing; cascades to Draft methods.
+ * - `itemTracking`: tracking type; cascades to open jobs, receipts, shipments.
+ */
+export type StandardFieldWriter = "itemColumn" | "itemMethod" | "itemTracking";
+
+export type StandardField = {
+ id: StandardFieldId;
+ label: string;
+ kind: "text" | "list";
+ /** Null for text, and for the unit: the company's units, read at plan time. */
+ values: readonly string[] | null;
+ valueTypes: readonly string[];
+ writer: StandardFieldWriter;
+ /** A write also changes Draft BOMs or open jobs; the Fields page says so. */
+ cascades: boolean;
+};
+
+const LIST_VALUE_TYPES = ["STRING", "ENUM", "BOOL"] as const;
+
+export const STANDARD_FIELDS: readonly StandardField[] = [
+ {
+ id: "mpn",
+ label: "Manufacturer Part Number",
+ kind: "text",
+ values: null,
+ valueTypes: ["STRING", "ENUM", "OBJECT"],
+ writer: "itemColumn",
+ cascades: false
+ },
+ {
+ id: "replenishmentSystem",
+ label: "Replenishment",
+ kind: "list",
+ values: ITEM_REPLENISHMENT_SYSTEMS,
+ valueTypes: LIST_VALUE_TYPES,
+ writer: "itemMethod",
+ cascades: true
+ },
+ {
+ id: "defaultMethodType",
+ label: "Default Method Type",
+ kind: "list",
+ values: ITEM_METHOD_TYPES,
+ valueTypes: LIST_VALUE_TYPES,
+ writer: "itemMethod",
+ cascades: true
+ },
+ {
+ id: "sourcingType",
+ label: "Sourcing",
+ kind: "list",
+ values: ITEM_SOURCING_TYPES,
+ valueTypes: LIST_VALUE_TYPES,
+ writer: "itemMethod",
+ cascades: true
+ },
+ {
+ id: "itemTrackingType",
+ label: "Tracking Type",
+ kind: "list",
+ values: ITEM_TRACKING_TYPES,
+ valueTypes: LIST_VALUE_TYPES,
+ writer: "itemTracking",
+ cascades: true
+ },
+ {
+ id: "unitOfMeasureCode",
+ label: "Unit of Measure",
+ kind: "list",
+ values: null,
+ valueTypes: ["STRING", "ENUM"],
+ writer: "itemColumn",
+ cascades: false
+ }
+];
+
+const FIELD_BY_ID = new Map<string, StandardField>(
+ STANDARD_FIELDS.map((field) => [field.id, field])
+);
+
+export function standardField(id: string): StandardField | undefined {
+ return FIELD_BY_ID.get(id);
+}
+
+export function isStandardFieldId(value: unknown): value is StandardFieldId {
+ return typeof value === "string" && FIELD_BY_ID.has(value);
+}
+
+export type ValueTranslation = {
+ onshape: string;
+ /** Null is "No value": the next precedence rule decides. */
+ carbon: string | null;
+};
+
+export function standardFieldValues(
+ field: StandardField,
+ units: readonly PlanUnitOfMeasure[]
+): string[] {
+ if (field.kind !== "list") return [];
+ return field.values ? [...field.values] : units.map((unit) => unit.code);
+}
+
+/** The fixed rows a translation can list; null when rows are typed by hand. */
+export function onshapeValueOptions(
+ valueType: string,
+ options: readonly string[] | undefined
+): string[] | null {
+ if (valueType === "BOOL") return ["Yes", "No"];
+ if (valueType === "ENUM" && options && options.length > 0) {
+ return [...options];
+ }
+ return null;
+}
+
+/**
+ * A new mapping's rows. Known Onshape options get a row only when they name a
+ * Carbon value, so the review flags the rest. Unknown options: one identity
+ * row per Carbon value. The unit gets none: values match a unit's code or name.
+ */
+export function defaultTranslations(
+ field: StandardField,
+ valueType: string,
+ options?: readonly string[]
+): ValueTranslation[] {
+ if (field.kind !== "list") return [];
+ if (valueType === "BOOL") {
+ return [
+ { onshape: "Yes", carbon: null },
+ { onshape: "No", carbon: null }
+ ];
+ }
+ if (!field.values) return [];
+ const values = field.values;
+ const listed = onshapeValueOptions(valueType, options);
+ if (listed) {
+ return listed.flatMap((option) => {
+ const carbon = values.find((value) => sameText(value, option));
+ return carbon ? [{ onshape: option, carbon }] : [];
+ });
+ }
+ return values.map((value) => ({ onshape: value, carbon: value }));
+}
+
+export function untranslatedOptions(
+ field: StandardField,
+ options: readonly string[],
+ translations: readonly ValueTranslation[],
+ units: readonly PlanUnitOfMeasure[]
+): string[] {
+ return options.filter(
+ (option) =>
+ !translateValue({
+ field,
+ text: option,
+ valueType: "ENUM",
+ translations,
+ units
+ }).ok
+ );
+}
+
+/**
+ * Typed rows that repeat a fixed option or an earlier row, so the values
+ * window stops what the save would refuse. An empty row is not a repeat.
+ */
+export function repeatedTranslationRows(
+ rows: readonly { onshape: string; fixed: boolean }[]
+): number[] {
+ const seen = new Set<string>();
+ const repeated: number[] = [];
+ rows.forEach((row, index) => {
+ const key = row.onshape.trim().toLowerCase();
+ if (key === "") return;
+ if (seen.has(key) && !row.fixed) repeated.push(index);
+ seen.add(key);
+ });
+ return repeated;
+}
+
+/** The unit a value matches with no translation row: by code, then by name. */
+export function matchingUnit(
+ text: string,
+ units: readonly PlanUnitOfMeasure[]
+): { unit: PlanUnitOfMeasure; by: "code" | "name" } | null {
+ const byCode = units.find((unit) => sameText(unit.code, text));
+ if (byCode) return { unit: byCode, by: "code" };
+ const byName = units.find((unit) => sameText(unit.name, text));
+ return byName ? { unit: byName, by: "name" } : null;
+}
+
+function sameText(a: string, b: string): boolean {
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
+}
+
+function booleanText(text: string): string {
+ if (/^(true|yes|on)$/i.test(text)) return "Yes";
+ if (/^(false|no|off)$/i.test(text)) return "No";
+ return text;
+}
+
+export type TranslatedValue =
+ | { ok: true; value: string | null }
+ | { ok: false; reason: string };
+
+/**
+ * Matching ignores case and surrounding spaces. An empty value is no value,
+ * never a problem; a list value nothing matches is a problem.
+ */
+export function translateValue({
+ field,
+ text,
+ valueType,
+ translations,
+ units
+}: {
+ field: StandardField;
+ text: string | null;
+ valueType: string;
+ translations: readonly ValueTranslation[];
+ units: readonly PlanUnitOfMeasure[];
+}): TranslatedValue {
+ if (text === null || text.trim() === "") return { ok: true, value: null };
+ const value = text.trim();
+ if (field.kind === "text") return { ok: true, value };
+
+ const onshape = valueType === "BOOL" ? booleanText(value) : value;
+ const row = translations.find((entry) => sameText(entry.onshape, onshape));
+ if (row) return { ok: true, value: row.carbon };
+
+ if (field.id === "unitOfMeasureCode") {
+ const unit =
+ units.find((entry) => sameText(entry.code, onshape)) ??
+ units.find((entry) => sameText(entry.name, onshape));
+ if (unit) return { ok: true, value: unit.code };
+ }
+ return { ok: false, reason: `"${value}" has no Carbon value` };
+}
+
+export function translationErrors(
+ field: StandardField,
+ translations: readonly ValueTranslation[],
+ units: readonly PlanUnitOfMeasure[]
+): string[] {
+ if (field.kind !== "list") {
+ return translations.length > 0
+ ? [`${field.label} takes the Onshape value as it is`]
+ : [];
+ }
+ const errors: string[] = [];
+ const allowed = standardFieldValues(field, units);
+ const seen = new Set<string>();
+ for (const row of translations) {
+ const key = row.onshape.trim().toLowerCase();
+ if (key === "") {
+ errors.push("A translation row has no Onshape value");
+ continue;
+ }
+ if (seen.has(key)) {
+ errors.push(`"${row.onshape.trim()}" has two rows`);
+ }
+ seen.add(key);
+ if (row.carbon !== null && !allowed.includes(row.carbon)) {
+ errors.push(`"${row.carbon}" is not a ${field.label} value in Carbon`);
+ }
+ }
+ return errors;
+}
diff --git a/packages/ee/src/onshape/panel/status.test.ts b/packages/ee/src/onshape/panel/status.test.ts
new file mode 100644
index 0000000000..12aa3b91f2
--- /dev/null
+++ b/packages/ee/src/onshape/panel/status.test.ts
@@ -0,0 +1,408 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ buildAssemblyLineStatuses,
+ buildPartStatuses,
+ externalIdForAssembly,
+ externalIdForBomLine,
+ externalIdForPart,
+ normalizeConfiguration,
+ releasedRevisionsByPartNumber
+} from "./status";
+
+const item = (id: string, readableId: string) => ({
+ id,
+ readableId,
+ revision: "0",
+ name: readableId
+});
+
+describe("buildPartStatuses", () => {
+ const documentId = "d1";
+ const elementId = "e1";
+
+ it("prefers a mapping over a part-number match and reports the rest", () => {
+ const statuses = buildPartStatuses({
+ documentId,
+ elementId,
+ parts: [
+ { partId: "p1", name: "Foot pad", partNumber: "WB-101", revision: "A" },
+ {
+ partId: "p2",
+ name: "Leg tube",
+ partNumber: "WB-102",
+ revision: null
+ },
+ { partId: "p3", name: "Stringer", partNumber: null, revision: null }
+ ],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: externalIdForPart(documentId, elementId, "p1"),
+ lastSyncedAt: "2026-08-28T00:00:00Z"
+ }
+ ],
+ items: [item("item-1", "OTHER-NUMBER"), item("item-2", "WB-102")]
+ });
+
+ expect(statuses.map((s) => s.state)).toEqual([
+ "linked",
+ "matched",
+ "missing"
+ ]);
+ expect(statuses[0]?.item?.id).toBe("item-1");
+ expect(statuses[0]?.lastSyncedAt).toBe("2026-08-28T00:00:00Z");
+ expect(statuses[1]?.item?.id).toBe("item-2");
+ expect(statuses[2]?.item).toBeNull();
+ });
+
+ it("treats a mapping whose item is gone as not linked", () => {
+ const statuses = buildPartStatuses({
+ documentId,
+ elementId,
+ parts: [
+ { partId: "p1", name: "Foot pad", partNumber: "WB-101", revision: "A" }
+ ],
+ mappings: [
+ {
+ entityId: "deleted-item",
+ externalId: externalIdForPart(documentId, elementId, "p1"),
+ lastSyncedAt: null
+ }
+ ],
+ items: [item("item-9", "WB-101")]
+ });
+
+ expect(statuses[0]?.state).toBe("matched");
+ expect(statuses[0]?.item?.id).toBe("item-9");
+ });
+
+ it("skips hidden parts and mappings from other elements", () => {
+ const statuses = buildPartStatuses({
+ documentId,
+ elementId,
+ parts: [
+ {
+ partId: "p1",
+ name: "Ghost",
+ partNumber: null,
+ revision: null,
+ isHidden: true
+ },
+ { partId: "p2", name: "Real", partNumber: null, revision: null }
+ ],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: externalIdForPart(documentId, "other-element", "p2"),
+ lastSyncedAt: null
+ }
+ ],
+ items: []
+ });
+
+ expect(statuses).toHaveLength(1);
+ expect(statuses[0]?.state).toBe("missing");
+ });
+});
+
+const line = (
+ index: string,
+ partNumber: string | null,
+ itemSource: {
+ documentId?: string;
+ elementId?: string;
+ partId?: string;
+ } | null
+) => ({
+ index,
+ level: 1,
+ partNumber,
+ name: partNumber,
+ quantity: 1,
+ itemSource
+});
+
+describe("buildAssemblyLineStatuses", () => {
+ it("links a line through its source part studio, not the assembly element", () => {
+ // The assembly being viewed is "asm-el"; the part lives in "ps-el".
+ const statuses = buildAssemblyLineStatuses({
+ lines: [
+ line("1", "WB-101", {
+ documentId: "d1",
+ elementId: "ps-el",
+ partId: "p1"
+ })
+ ],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: externalIdForPart("d1", "ps-el", "p1"),
+ lastSyncedAt: "2026-08-28T00:00:00Z"
+ }
+ ],
+ items: [item("item-1", "WB-101")]
+ });
+
+ expect(statuses[0]?.state).toBe("linked");
+ expect(statuses[0]?.itemId).toBe("item-1");
+ expect(statuses[0]?.lastSyncedAt).toBe("2026-08-28T00:00:00Z");
+ });
+
+ it("links across documents when the part was inserted from another one", () => {
+ const statuses = buildAssemblyLineStatuses({
+ lines: [
+ line("1", "HDW-010", {
+ documentId: "d2",
+ elementId: "ps-el",
+ partId: "JHD"
+ })
+ ],
+ mappings: [
+ {
+ entityId: "item-1",
+ externalId: externalIdForPart("d2", "ps-el", "JHD"),
+ lastSyncedAt: null
+ }
+ ],
+ items: [item("item-1", "HDW-010")]
+ });
+
+ expect(statuses[0]?.state).toBe("linked");
+ });
+
+ it("falls back to the part-number match when the row names no source", () => {
+ const statuses = buildAssemblyLineStatuses({
+ lines: [line("1", "WB-101", null), line("2", "WB-999", null)],
+ mappings: [],
+ items: [item("item-1", "WB-101")]
+ });
+
+ expect(statuses.map((s) => s.state)).toEqual(["matched", "missing"]);
+ expect(statuses[0]?.itemId).toBe("item-1");
+ });
+
+ it("does not link through a mapping whose item is gone", () => {
+ const statuses = buildAssemblyLineStatuses({
+ lines: [
+ line("1", "WB-101", {
+ documentId: "d1",
+ elementId: "ps-el",
+ partId: "p1"
+ })
+ ],
+ mappings: [
+ {
+ entityId: "deleted-item",
+ externalId: externalIdForPart("d1", "ps-el", "p1"),
+ lastSyncedAt: "2026-08-28T00:00:00Z"
+ }
+ ],
+ items: [item("item-1", "WB-101")]
+ });
+
+ expect(statuses[0]?.state).toBe("matched");
+ expect(statuses[0]?.itemId).toBe("item-1");
+ });
+
+ it("ignores a partial itemSource", () => {
+ expect(externalIdForBomLine({ documentId: "d1" })).toBeNull();
+ expect(externalIdForBomLine(null)).toBeNull();
+ expect(
+ externalIdForBomLine({
+ documentId: "d1",
+ elementId: "e1",
+ partId: "p1"
+ })
+ ).toBe(externalIdForPart("d1", "e1", "p1"));
+ });
+});
+
+describe("externalIdForBomLine", () => {
+ it("keys a sub-assembly row the way that assembly's own push keys it", () => {
+ expect(
+ externalIdForBomLine({ documentId: "d1", elementId: "sub-el" })
+ ).toBe(externalIdForAssembly("d1", "sub-el"));
+ });
+});
+
+describe("configurations in identity", () => {
+ it("reads the default configuration as no configuration, however it arrives", () => {
+ for (const value of [null, undefined, "", " ", "default", "Default"]) {
+ expect(normalizeConfiguration(value)).toBeNull();
+ }
+ });
+
+ it("decodes a configuration passed URL-encoded", () => {
+ expect(normalizeConfiguration("List_abc%3DLarge")).toBe("List_abc=Large");
+ expect(normalizeConfiguration("List_abc=Large")).toBe("List_abc=Large");
+ });
+
+ it("keeps the default key unchanged, so links written before still match", () => {
+ expect(externalIdForPart("d", "e", "p", "default")).toBe("d:e:p");
+ expect(externalIdForAssembly("d", "e", null)).toBe("d:e:assembly");
+ });
+
+ it("gives each configuration of one part its own key", () => {
+ const large = externalIdForBomLine({
+ documentId: "d",
+ elementId: "e",
+ partId: "RvED",
+ configuration: "List_abc=Large"
+ });
+ const standard = externalIdForBomLine({
+ documentId: "d",
+ elementId: "e",
+ partId: "RvED",
+ configuration: "default"
+ });
+ expect(large).toBe("d:e:RvED:List_abc=Large");
+ expect(standard).toBe("d:e:RvED");
+ expect(large).not.toBe(standard);
+ });
+
+ it("links two configurations of one part to their own items", () => {
+ const statuses = buildAssemblyLineStatuses({
+ lines: [
+ {
+ index: "1",
+ level: 1,
+ partNumber: "DOOR-L",
+ name: "Door",
+ quantity: 1,
+ itemSource: {
+ documentId: "d",
+ elementId: "e",
+ partId: "RvED",
+ configuration: "List_abc=Large"
+ }
+ },
+ {
+ index: "2",
+ level: 1,
+ partNumber: "DOOR-D",
+ name: "Door",
+ quantity: 1,
+ itemSource: {
+ documentId: "d",
+ elementId: "e",
+ partId: "RvED",
+ configuration: "default"
+ }
+ }
+ ],
+ mappings: [
+ {
+ entityId: "large",
+ externalId: "d:e:RvED:List_abc=Large",
+ lastSyncedAt: null
+ },
+ { entityId: "default", externalId: "d:e:RvED", lastSyncedAt: null }
+ ],
+ items: [item("large", "DOOR-L"), item("default", "DOOR-D")]
+ });
+ expect(
+ statuses.map((line) => [line.partNumber, line.state, line.itemId])
+ ).toEqual([
+ ["DOOR-L", "linked", "large"],
+ ["DOOR-D", "linked", "default"]
+ ]);
+ });
+
+ it("keys a Part Studio's parts by the configuration it is open in", () => {
+ const [part] = buildPartStatuses({
+ documentId: "d",
+ elementId: "e",
+ configuration: "List_abc=Large",
+ parts: [
+ {
+ partId: "RvED",
+ name: "Door",
+ partNumber: "DOOR-L",
+ isHidden: false
+ } as never
+ ],
+ mappings: [
+ { entityId: "default", externalId: "d:e:RvED", lastSyncedAt: null },
+ {
+ entityId: "large",
+ externalId: "d:e:RvED:List_abc=Large",
+ lastSyncedAt: null
+ }
+ ],
+ items: [item("large", "DOOR-L"), item("default", "DOOR-D")]
+ });
+ expect(part?.state).toBe("linked");
+ expect(part?.item?.id).toBe("large");
+ });
+});
+
+describe("released parts", () => {
+ const rows = [
+ { id: "top-0", readableId: "TOP-001", revision: "0", name: "Top" },
+ { id: "top-a", readableId: "TOP-001", revision: "A", name: "Top" },
+ { id: "top-c", readableId: "TOP-001", revision: "C", name: "Top" },
+ { id: "leg-0", readableId: "LEG-003", revision: "0", name: "Leg" }
+ ];
+ const released = releasedRevisionsByPartNumber(
+ rows,
+ new Set(["top-a", "top-c"])
+ );
+
+ it("names the newest revision a release push made, per part number", () => {
+ expect(released.get("TOP-001")).toEqual({
+ itemId: "top-c",
+ revision: "C"
+ });
+ expect(released.has("LEG-003")).toBe(false);
+ });
+
+ it("shows a released part as released, even when the workspace is linked", () => {
+ const [top, leg] = buildPartStatuses({
+ documentId: "d",
+ elementId: "e",
+ parts: [
+ { partId: "p1", name: "Top", partNumber: "TOP-001", revision: "C" },
+ { partId: "p2", name: "Leg", partNumber: "LEG-003", revision: null }
+ ],
+ mappings: [
+ {
+ entityId: "top-0",
+ externalId: externalIdForPart("d", "e", "p1"),
+ lastSyncedAt: null
+ }
+ ],
+ items: rows,
+ released
+ });
+ expect(top?.state).toBe("released");
+ expect(top?.item?.id).toBe("top-c");
+ expect(leg?.state).toBe("matched");
+ });
+
+ it("shows a released BOM line with its released revision", () => {
+ const [line] = buildAssemblyLineStatuses({
+ lines: [
+ {
+ index: "1",
+ level: 1,
+ partNumber: "TOP-001",
+ name: "Top",
+ quantity: 1,
+ itemSource: null
+ }
+ ],
+ mappings: [],
+ items: rows,
+ released
+ });
+ expect(line).toMatchObject({
+ state: "released",
+ itemId: "top-c",
+ releasedRevision: "C"
+ });
+ });
+});
diff --git a/packages/ee/src/onshape/panel/status.ts b/packages/ee/src/onshape/panel/status.ts
new file mode 100644
index 0000000000..6f12ff93fc
--- /dev/null
+++ b/packages/ee/src/onshape/panel/status.ts
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { OnshapeElementPart } from "../lib/client";
+import { compareRevisions } from "./revision";
+
+/**
+ * `linked`: a mapping row holds the part's key. `matched`: an item's readableId
+ * equals the part number. `released`: a release push made a revision of it.
+ */
+export type PanelPartStatus = {
+ partId: string;
+ name: string;
+ partNumber: string | null;
+ revision: string | null;
+ microversionId: string | null;
+ state: "linked" | "matched" | "missing" | "released";
+ item: {
+ id: string;
+ readableId: string;
+ revision: string;
+ name: string;
+ } | null;
+ lastSyncedAt: string | null;
+};
+
+/**
+ * One partId's configured variants can carry different part numbers, so a
+ * non-default configuration is part of identity. "default" and empty are null;
+ * launch parameters may arrive URL-encoded.
+ */
+export function normalizeConfiguration(
+ configuration: string | null | undefined
+): string | null {
+ if (typeof configuration !== "string") return null;
+ let value = configuration.trim();
+ try {
+ value = decodeURIComponent(value).trim();
+ } catch {
+ // Not URL-encoded (a stray "%"): use it as it came.
+ }
+ if (value === "" || value.toLowerCase() === "default") return null;
+ return value;
+}
+
+function withConfiguration(key: string, configuration?: string | null) {
+ const normalized = normalizeConfiguration(configuration);
+ return normalized ? `${key}:${normalized}` : key;
+}
+
+export function externalIdForAssembly(
+ documentId: string,
+ elementId: string,
+ configuration?: string | null
+) {
+ return withConfiguration(
+ `${documentId}:${elementId}:assembly`,
+ configuration
+ );
+}
+
+export function externalIdForPart(
+ documentId: string,
+ elementId: string,
+ partId: string,
+ configuration?: string | null
+) {
+ return withConfiguration(
+ `${documentId}:${elementId}:${partId}`,
+ configuration
+ );
+}
+
+export type PanelMappingRow = {
+ entityId: string;
+ externalId: string | null;
+ lastSyncedAt: string | null;
+};
+
+export type PanelItemRow = {
+ id: string;
+ readableId: string;
+ revision: string;
+ name: string;
+};
+
+export type ReleasedRevision = { itemId: string; revision: string };
+
+/** Per part number, the newest revision among items with a `release:` link. */
+export function releasedRevisionsByPartNumber(
+ items: Array<{ id: string; readableId: string; revision: string | null }>,
+ releasedItemIds: ReadonlySet<string>
+): Map<string, ReleasedRevision> {
+ const byPartNumber = new Map<string, ReleasedRevision>();
+ for (const item of items) {
+ if (!releasedItemIds.has(item.id)) continue;
+ const current = byPartNumber.get(item.readableId);
+ if (!current || compareRevisions(item.revision, current.revision) > 0) {
+ byPartNumber.set(item.readableId, {
+ itemId: item.id,
+ revision: item.revision ?? "0"
+ });
+ }
+ }
+ return byPartNumber;
+}
+
+export function buildPartStatuses({
+ documentId,
+ elementId,
+ configuration = null,
+ parts,
+ mappings,
+ items,
+ released = new Map()
+}: {
+ documentId: string;
+ elementId: string;
+ /** The Part Studio configuration the parts were read in. */
+ configuration?: string | null;
+ parts: OnshapeElementPart[];
+ mappings: PanelMappingRow[];
+ items: PanelItemRow[];
+ /** `releasedRevisionsByPartNumber` over the parts' items. */
+ released?: ReadonlyMap<string, ReleasedRevision>;
+}): PanelPartStatus[] {
+ const mappingByExternalId = new Map(
+ mappings.filter((m) => m.externalId).map((m) => [m.externalId as string, m])
+ );
+ const itemById = new Map(items.map((i) => [i.id, i]));
+ const itemByReadableId = new Map(items.map((i) => [i.readableId, i]));
+
+ return parts
+ .filter((part) => !part.isHidden)
+ .map((part) => {
+ const releasedRevision = part.partNumber
+ ? released.get(part.partNumber)
+ : undefined;
+ const releasedItem = releasedRevision
+ ? itemById.get(releasedRevision.itemId)
+ : undefined;
+ if (releasedItem) {
+ return {
+ partId: part.partId,
+ name: part.name,
+ partNumber: part.partNumber ?? null,
+ revision: part.revision ?? null,
+ microversionId: part.microversionId ?? null,
+ state: "released" as const,
+ item: releasedItem,
+ lastSyncedAt: null
+ };
+ }
+ const mapping = mappingByExternalId.get(
+ externalIdForPart(documentId, elementId, part.partId, configuration)
+ );
+ const linkedItem = mapping ? itemById.get(mapping.entityId) : undefined;
+ if (mapping && linkedItem) {
+ return {
+ partId: part.partId,
+ name: part.name,
+ partNumber: part.partNumber ?? null,
+ revision: part.revision ?? null,
+ microversionId: part.microversionId ?? null,
+ state: "linked" as const,
+ item: linkedItem,
+ lastSyncedAt: mapping.lastSyncedAt
+ };
+ }
+
+ const matched = part.partNumber
+ ? itemByReadableId.get(part.partNumber)
+ : undefined;
+ return {
+ partId: part.partId,
+ name: part.name,
+ partNumber: part.partNumber ?? null,
+ revision: part.revision ?? null,
+ microversionId: part.microversionId ?? null,
+ state: matched ? ("matched" as const) : ("missing" as const),
+ item: matched ?? null,
+ lastSyncedAt: null
+ };
+ });
+}
+
+/**
+ * States as {@link PanelPartStatus}. A line is keyed by its `itemSource`, as an
+ * assembly push writes it; a line without one can only reach `matched`.
+ */
+export type PanelAssemblyLineStatus = {
+ index: string;
+ level: number;
+ partNumber: string | null;
+ name: string | null;
+ quantity: number;
+ state: "linked" | "matched" | "missing" | "released";
+ itemId: string | null;
+ /** `released` only: the newest released revision. */
+ releasedRevision?: string;
+ lastSyncedAt: string | null;
+};
+
+export type PanelAssemblyLineInput = {
+ index: string;
+ level: number;
+ partNumber: string | null;
+ name: string | null;
+ quantity: number;
+ itemSource: {
+ documentId?: string;
+ elementId?: string;
+ partId?: string;
+ configuration?: string;
+ } | null;
+};
+
+/**
+ * A sub-assembly row has no partId and keys like a pushed assembly, so one key
+ * works from the parent's BOM and from the sub-assembly's own panel.
+ */
+export function externalIdForBomLine(
+ itemSource: PanelAssemblyLineInput["itemSource"]
+): string | null {
+ if (!itemSource?.documentId || !itemSource.elementId) return null;
+ return itemSource.partId
+ ? externalIdForPart(
+ itemSource.documentId,
+ itemSource.elementId,
+ itemSource.partId,
+ itemSource.configuration
+ )
+ : externalIdForAssembly(
+ itemSource.documentId,
+ itemSource.elementId,
+ itemSource.configuration
+ );
+}
+
+export function buildAssemblyLineStatuses({
+ lines,
+ mappings,
+ items,
+ released = new Map()
+}: {
+ lines: PanelAssemblyLineInput[];
+ mappings: PanelMappingRow[];
+ items: PanelItemRow[];
+ released?: ReadonlyMap<string, ReleasedRevision>;
+}): PanelAssemblyLineStatus[] {
+ const mappingByExternalId = new Map(
+ mappings.filter((m) => m.externalId).map((m) => [m.externalId as string, m])
+ );
+ const itemById = new Map(items.map((i) => [i.id, i]));
+ const itemByReadableId = new Map(items.map((i) => [i.readableId, i]));
+
+ return lines.map(({ itemSource, ...line }) => {
+ const releasedRevision = line.partNumber
+ ? released.get(line.partNumber)
+ : undefined;
+ if (releasedRevision && itemById.has(releasedRevision.itemId)) {
+ return {
+ ...line,
+ state: "released" as const,
+ itemId: releasedRevision.itemId,
+ releasedRevision: releasedRevision.revision,
+ lastSyncedAt: null
+ };
+ }
+ const externalId = externalIdForBomLine(itemSource);
+ const mapping = externalId
+ ? mappingByExternalId.get(externalId)
+ : undefined;
+ // entityId has no foreign key, so a mapping can outlive its item.
+ const linkedItem = mapping ? itemById.get(mapping.entityId) : undefined;
+ if (mapping && linkedItem) {
+ return {
+ ...line,
+ state: "linked" as const,
+ itemId: linkedItem.id,
+ lastSyncedAt: mapping.lastSyncedAt
+ };
+ }
+
+ const matched = line.partNumber
+ ? itemByReadableId.get(line.partNumber)
+ : undefined;
+ return {
+ ...line,
+ state: matched ? ("matched" as const) : ("missing" as const),
+ itemId: matched?.id ?? null,
+ lastSyncedAt: null
+ };
+ });
+}
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 4c5bb14409..f74f7eec72 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -134,6 +134,13 @@ export const ITAR_RIDER_PDF_PATH = "https://carbon.ms/itar-rider.pdf";
export const ONSHAPE_CLIENT_ID = getEnv("ONSHAPE_CLIENT_ID");
export const ONSHAPE_CLIENT_SECRET = getEnv("ONSHAPE_CLIENT_SECRET");
export const ONSHAPE_OAUTH_REDIRECT_URL = getEnv("ONSHAPE_OAUTH_REDIRECT_URL");
+// The panel (`onshape-v2`) is its own Onshape app: it shares no variable with
+// the sync integration above.
+export const ONSHAPE_V2_CLIENT_ID = getEnv("ONSHAPE_V2_CLIENT_ID");
+export const ONSHAPE_V2_CLIENT_SECRET = getEnv("ONSHAPE_V2_CLIENT_SECRET");
+export const ONSHAPE_V2_OAUTH_REDIRECT_URL = getEnv(
+ "ONSHAPE_V2_OAUTH_REDIRECT_URL"
+);
// Path to the native gltfpack binary (github.com/zeux/meshoptimizer), used to
// compress oversized Onshape GLTF exports into viewer-ready GLBs. Optional:
// when unset (and gltfpack isn't on PATH), oversized models are skipped
@@ -360,6 +367,7 @@ export function getBrowserEnv() {
MES_URL,
NODE_ENV,
ONSHAPE_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_ID,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
QUICKBOOKS_CLIENT_ID,
diff --git a/packages/env/src/schema.ts b/packages/env/src/schema.ts
index 9326d676ba..c73b2af038 100644
--- a/packages/env/src/schema.ts
+++ b/packages/env/src/schema.ts
@@ -14,6 +14,7 @@ export type Group =
| "quickbooks"
| "jira"
| "onshape"
+ | "onshapeV2"
| "ramp"
| "ai"
| "assembler"
@@ -30,6 +31,7 @@ export const FEATURES = {
quickbooks: "QuickBooks",
jira: "Jira",
onshape: "Onshape",
+ onshapeV2: "Onshape V2",
ramp: "Ramp",
ai: "AI",
assembler: "Assembler"
@@ -414,19 +416,38 @@ export const schema = define({
// ── onshape ───────────────────────────────────────────────────────────────
ONSHAPE_CLIENT_ID: {
group: "onshape",
- description: "Onshape app client id",
+ description: "Onshape sync app client id",
browser: true,
needed: true
},
ONSHAPE_CLIENT_SECRET: {
group: "onshape",
- description: "Onshape app client secret",
+ description: "Onshape sync app client secret",
secret: true,
needed: true
},
ONSHAPE_OAUTH_REDIRECT_URL: {
group: "onshape",
- description: "Onshape OAuth callback URL",
+ description: "Onshape sync app OAuth callback URL",
+ type: url
+ },
+
+ // ── onshapeV2 (the panel's own Onshape app) ───────────────────────────────
+ ONSHAPE_V2_CLIENT_ID: {
+ group: "onshapeV2",
+ description: "Onshape panel app client id",
+ browser: true,
+ needed: true
+ },
+ ONSHAPE_V2_CLIENT_SECRET: {
+ group: "onshapeV2",
+ description: "Onshape panel app client secret",
+ secret: true,
+ needed: true
+ },
+ ONSHAPE_V2_OAUTH_REDIRECT_URL: {
+ group: "onshapeV2",
+ description: "Onshape panel app OAuth callback URL",
type: url
},
diff --git a/packages/env/src/vercel-production.json b/packages/env/src/vercel-production.json
index 378be85368..74b8b6fb51 100644
--- a/packages/env/src/vercel-production.json
+++ b/packages/env/src/vercel-production.json
@@ -21,6 +21,7 @@
"ONSHAPE_CLIENT_ID",
"ONSHAPE_CLIENT_SECRET",
"ONSHAPE_OAUTH_REDIRECT_URL",
+ "ONSHAPE_V2_OAUTH_REDIRECT_URL",
"OPENAI_API_KEY",
"POSTHOG_API_HOST",
"POSTHOG_PROJECT_PUBLIC_KEY",
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 189f17f0e0..4c9e64cf18 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261016144058",
+ "schemaVersion": "20261016163158",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-16T14:45:48.480Z",
+ "exportedAt": "2026-10-17T02:16:43.251Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.ts
index 3338c0641d..03d43ad019 100644
--- a/packages/jobs/src/inngest/functions/integrations/index.ts
+++ b/packages/jobs/src/inngest/functions/integrations/index.ts
@@ -15,6 +15,7 @@ export { mountSweepFunction } from "./mount-sweep";
export { oeeSweepFunction } from "./oee-sweep";
export { oeeSyncFunction } from "./oee-sync";
export { onshapeBackfillFunction } from "./onshape-backfill";
+export { onshapePanelSyncFunction } from "./onshape-panel-sync";
export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";
export { paperlessPartsFunction } from "./paperless-parts";
export { rampSweepFunction } from "./ramp-sweep";
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts
new file mode 100644
index 0000000000..d5bb9365fc
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";
+import { z } from "zod";
+import { inngest } from "../../client";
+import {
+ syncOnshapeDrawingAssetsToItem,
+ syncOnshapeElementAssetsToItem
+} from "./onshape-sync-element";
+
+/**
+ * Exports a pushed element's model, or a release drawing's PDF, onto the item
+ * the push route already linked. Every run spends live Onshape calls, so
+ * retries stay at 1 and concurrency at 1 per item.
+ */
+const OnshapePanelSyncPayloadSchema = z.object({
+ companyId: z.string(),
+ userId: z.string(),
+ itemId: z.string(),
+ documentId: z.string(),
+ wvm: z.enum(["w", "v"]),
+ wvmId: z.string(),
+ elementId: z.string(),
+ elementKind: z.enum(["partstudio", "assembly", "drawing"]),
+ partId: z.string().optional(),
+ configuration: z.string().optional(),
+ assetBaseName: z.string().optional(),
+ microversionId: z.string().optional()
+});
+
+export const onshapePanelSyncFunction = inngest.createFunction(
+ {
+ id: "onshape-panel-sync",
+ retries: 1,
+ concurrency: { key: "event.data.itemId", limit: 1 }
+ },
+ { event: "carbon/onshape-panel-sync" },
+ async ({ event, step }) => {
+ const payload = OnshapePanelSyncPayloadSchema.parse(event.data);
+ const carbon = getCarbonServiceRole();
+ // Destructured so the narrowing below survives into the step closures.
+ const { elementKind } = payload;
+
+ if (elementKind === "drawing") {
+ // Release pushes only; no model, so no optimize or thumbnail.
+ return step.run("sync-drawing-assets", () =>
+ syncOnshapeDrawingAssetsToItem(carbon, {
+ companyId: payload.companyId,
+ userId: payload.userId,
+ // The panel pushes on its own connection.
+ integrationId: ONSHAPE_V2_INTEGRATION_ID,
+ itemId: payload.itemId,
+ sourceDocument: "Part",
+ documentId: payload.documentId,
+ versionId: payload.wvmId,
+ sourceWvm: payload.wvm,
+ drawingElementId: payload.elementId,
+ assetBaseName: payload.assetBaseName
+ })
+ );
+ }
+
+ const result = await step.run("sync-element-assets", () =>
+ syncOnshapeElementAssetsToItem(carbon, {
+ companyId: payload.companyId,
+ userId: payload.userId,
+ integrationId: ONSHAPE_V2_INTEGRATION_ID,
+ itemId: payload.itemId,
+ sourceDocument: "Part",
+ documentId: payload.documentId,
+ versionId: payload.wvmId,
+ sourceWvm: payload.wvm,
+ partId: payload.partId,
+ configuration: payload.configuration,
+ sourceMicroversionId: payload.microversionId,
+ modelElementId: payload.elementId,
+ modelElementKind: elementKind,
+ assetBaseName: payload.assetBaseName
+ })
+ );
+
+ if (result.modelUploadId) {
+ await step.sendEvent("model-optimize", {
+ name: "carbon/model-optimize" as const,
+ data: {
+ modelUploadId: result.modelUploadId,
+ companyId: payload.companyId,
+ userId: payload.userId
+ }
+ });
+ }
+
+ if (result.modelUploadId && !result.thumbnailAttached) {
+ await step.sendEvent("model-thumbnail", {
+ name: "carbon/model-thumbnail" as const,
+ data: { companyId: payload.companyId, modelId: result.modelUploadId }
+ });
+ }
+
+ return result;
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
index 31fd02db7d..29bd73873b 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
@@ -149,4 +149,32 @@ describe("released model exports", () => {
expect(ids[0]).toBe(ids[1]);
expect(new Set(ids).size).toBe(3);
});
+
+ it("gives a workspace export a new generation when the part changes", async () => {
+ const workspace = {
+ ...input,
+ sourceWvm: "w" as const,
+ versionId: "workspace-1"
+ };
+ for (const variation of [
+ { ...workspace, sourceMicroversionId: "mv-1" },
+ { ...workspace, sourceMicroversionId: "mv-1" },
+ { ...workspace, sourceMicroversionId: "mv-2" }
+ ]) {
+ await syncOnshapeElementAssetsToItem(carbon, variation);
+ }
+ const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
+ expect(ids[0]).toBe(ids[1]);
+ expect(ids[2]).not.toBe(ids[0]);
+ });
+
+ it("gives a workspace export with no microversion no fixed generation", async () => {
+ await syncOnshapeElementAssetsToItem(carbon, {
+ ...input,
+ sourceWvm: "w",
+ versionId: "workspace-1"
+ });
+ const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
+ expect(ids).toEqual([undefined]);
+ });
});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
index c46165c365..7e0366c837 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
@@ -9,6 +9,7 @@ import { join } from "node:path";
import type { Database } from "@carbon/database";
import type { OnshapeClient, OnshapeTranslation } from "@carbon/ee/onshape";
import { getOnshapeClient } from "@carbon/ee/onshape";
+import type { OnshapeOAuthIntegrationId } from "@carbon/ee/onshape/integration-id";
import { getFileSizeLimit } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import {
@@ -18,16 +19,15 @@ import {
type OnshapeModelFile
} from "./onshape-attach";
-// Export→download→attach for ONE released Onshape element. Wires the OnshapeClient
-// export methods (@carbon/ee) to the Carbon-side attach helper. Flow: create
-// translation -> poll to DONE -> download from resultDocumentId/
-// resultExternalDataIds -> attach. Poll-with-backoff (real completions take
-// seconds); no translation.complete webhook needed.
+// Export→download→attach for ONE Onshape element, released or in a workspace.
+// Wires the OnshapeClient export methods (@carbon/ee) to the Carbon-side attach
+// helper. Flow: create translation -> poll to DONE -> download from
+// resultDocumentId/resultExternalDataIds -> attach. Poll-with-backoff (real
+// completions take seconds); no translation.complete webhook needed.
//
-// The caller (release-sync / backfill job) is responsible for turning a release
-// event into these inputs: resolve itemId by part number (readableIdWithRevision,
-// LINK-ONLY skip if none), and the documentId/versionId/elementId of the released
-// geometry, including the released partId and configuration. Individual-part
+// Callers (the release-sync and backfill jobs, and onshape-panel-sync) resolve
+// itemId and the documentId/version-or-workspace/elementId of the geometry,
+// including its partId and configuration. Individual-part
// thumbnails come from that selected model after optimization; an element
// thumbnail represents the entire Part Studio and must never be attached to it.
@@ -37,10 +37,15 @@ type DocumentSourceType = Database["public"]["Enums"]["documentSourceType"];
export interface SyncOnshapeElementInput {
companyId: string;
userId: string; // Onshape integration installer (auth + audit)
+ // Omitted: the company's active sync connection.
+ integrationId?: OnshapeOAuthIntegrationId;
itemId: string; // resolved Carbon item (caller guarantees it exists)
sourceDocument: DocumentSourceType; // e.g. "Part"
documentId: string;
- versionId: string; // the released version
+ versionId: string; // released version, or workspace id when sourceWvm is "w"
+ sourceWvm?: "w" | "v"; // path segment for export/thumbnail calls; default "v"
+ // Workspace ids are mutable, so a Part Studio model id also hashes this.
+ sourceMicroversionId?: string;
modelElementId: string; // released Part Studio OR Assembly element to export
modelElementKind: "partstudio" | "assembly"; // from the revision's elementType (0/1)
partId?: string | null; // REQUIRED for individual Part Studio releases
@@ -142,7 +147,12 @@ async function exportRawGltfModel(
input.documentId,
input.versionId,
input.modelElementId,
- { formatName: "GLTF", storeInDocument: false, configuration }
+ {
+ formatName: "GLTF",
+ storeInDocument: false,
+ configuration,
+ wvm: input.sourceWvm ?? "v"
+ }
)
: await client.createPartStudioTranslation(
input.documentId,
@@ -152,7 +162,8 @@ async function exportRawGltfModel(
formatName: "GLTF",
storeInDocument: false,
configuration,
- partIds: input.partId!
+ partIds: input.partId!,
+ wvm: input.sourceWvm ?? "v"
}
);
const gltfDone = await waitForTranslation(client, gltfTranslation.id);
@@ -182,9 +193,12 @@ async function exportRawGltfModel(
// Immutable generation: old optimizer/thumbnail/compact jobs can only
// finish against their old model ID. Replays of this exact released source
// share one ID; a different part/configuration cannot reuse its artifacts.
- // Keep whole-assembly attachment behavior unchanged.
+ // Keep whole-assembly attachment behavior unchanged. A workspace id is
+ // mutable: without a microversion there is no fixed source to name, so
+ // the model refreshes in place instead of reusing old geometry.
sourceId:
- input.modelElementKind === "partstudio"
+ input.modelElementKind === "partstudio" &&
+ (input.sourceWvm !== "w" || input.sourceMicroversionId)
? `onshape-${createHash("sha256")
.update(
JSON.stringify([
@@ -195,7 +209,8 @@ async function exportRawGltfModel(
input.versionId,
input.modelElementId,
input.partId,
- configuration ?? ""
+ configuration ?? "",
+ ...(input.sourceWvm === "w" ? [input.sourceMicroversionId] : [])
])
)
.digest("hex")
@@ -208,7 +223,12 @@ export async function syncOnshapeElementAssetsToItem(
carbon: CarbonClient,
input: SyncOnshapeElementInput
): Promise<AttachOnshapeAssetsResult & { thumbnailAttached: boolean }> {
- const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);
+ const onshape = await getOnshapeClient(
+ carbon,
+ input.companyId,
+ input.userId,
+ input.integrationId
+ );
if (onshape.error || !onshape.client) {
throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);
}
@@ -232,7 +252,11 @@ export async function syncOnshapeElementAssetsToItem(
input.documentId,
input.versionId,
drawingElementId,
- { formatName: "PDF", storeInDocument: false }
+ {
+ formatName: "PDF",
+ storeInDocument: false,
+ wvm: input.sourceWvm ?? "v"
+ }
);
const pdfDone = await waitForTranslation(client, pdfTranslation.id);
const pdfBytes = await downloadTranslationBytes(
@@ -268,7 +292,9 @@ export async function syncOnshapeElementAssetsToItem(
const thumbnail = await client.getElementThumbnail(
input.documentId,
input.versionId,
- input.modelElementId
+ input.modelElementId,
+ "300x300",
+ input.sourceWvm ?? "v"
);
await attachModelThumbnail(carbon, {
companyId: input.companyId,
@@ -293,12 +319,14 @@ export async function syncOnshapeElementAssetsToItem(
export interface SyncOnshapeDrawingInput {
companyId: string;
userId: string; // Onshape integration installer (auth + audit)
+ integrationId?: OnshapeOAuthIntegrationId;
itemId: string; // resolved Carbon item (the model this drawing documents)
sourceDocument: DocumentSourceType; // e.g. "Part"
documentId: string;
versionId: string; // the released version
drawingElementId: string; // the released DRAWING element to export as PDF
assetBaseName?: string; // filename base (e.g. the model's readableIdWithRevision)
+ sourceWvm?: "w" | "v"; // path segment for the drawing translation; default "v"
}
// Export ONE released Onshape DRAWING element as a PDF and attach it as a document
@@ -311,7 +339,12 @@ export async function syncOnshapeDrawingAssetsToItem(
carbon: CarbonClient,
input: SyncOnshapeDrawingInput
): Promise<AttachOnshapeAssetsResult> {
- const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);
+ const onshape = await getOnshapeClient(
+ carbon,
+ input.companyId,
+ input.userId,
+ input.integrationId
+ );
if (onshape.error || !onshape.client) {
throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);
}
@@ -321,7 +354,7 @@ export async function syncOnshapeDrawingAssetsToItem(
input.documentId,
input.versionId,
input.drawingElementId,
- { formatName: "PDF", storeInDocument: false }
+ { formatName: "PDF", storeInDocument: false, wvm: input.sourceWvm ?? "v" }
);
const pdfDone = await waitForTranslation(client, pdfTranslation.id);
const pdfBytes = await downloadTranslationBytes(
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index debfbcdd9e..1d69e935be 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -48,6 +48,7 @@ import {
oeeSweepFunction,
oeeSyncFunction,
onshapeBackfillFunction,
+ onshapePanelSyncFunction,
onshapeRevisionSyncFunction,
paperlessPartsFunction,
rampSweepFunction,
@@ -193,6 +194,7 @@ export const functions = [
mountPublishFunction,
mountSweepFunction,
onshapeBackfillFunction,
+ onshapePanelSyncFunction,
onshapeRevisionSyncFunction,
rampSyncFunction,
rampSweepFunction,
diff --git a/packages/kv/src/index.ts b/packages/kv/src/index.ts
index d1e65e9950..7d0811e986 100644
--- a/packages/kv/src/index.ts
+++ b/packages/kv/src/index.ts
@@ -4,6 +4,8 @@
import redis from "./client";
+export type { LeaseAcquisition } from "./lease";
+export { acquireLease, releaseLease, renewLease, withLease } from "./lease";
export type {
AccountLockoutOptions,
LockDurationOptions,
diff --git a/packages/kv/src/lease.test.ts b/packages/kv/src/lease.test.ts
new file mode 100644
index 0000000000..910d4b7622
--- /dev/null
+++ b/packages/kv/src/lease.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type Redis from "ioredis";
+import RedisMock from "ioredis-mock";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { acquireLease, releaseLease, renewLease, withLease } from "./lease";
+import { withResilience } from "./resilient";
+
+// Real scripts against ioredis-mock behind the app's fail-soft proxy.
+// `unreachable()` is a client whose every command rejects.
+const current = vi.hoisted(() => ({ client: null as unknown as Redis }));
+
+vi.mock("./client", () => ({
+ get default() {
+ return current.client;
+ }
+}));
+
+function unreachable(): Redis {
+ const reject = () => Promise.reject(new Error("ECONNREFUSED"));
+ return { on: () => undefined, eval: reject } as unknown as Redis;
+}
+
+// Real clock: renewing every sixth of the lease tolerates a loaded CI runner.
+const KEY = "lease:test";
+const LEASE_MS = 300;
+const RENEW_MS = 50;
+const PAST_LEASE_MS = LEASE_MS + 100;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function acquiredOwner() {
+ const result = await acquireLease(KEY, LEASE_MS);
+ if (result.status !== "acquired") throw new Error("expected to acquire");
+ return result.owner;
+}
+
+describe("lease", () => {
+ beforeEach(async () => {
+ const mock = new RedisMock();
+ await mock.flushall();
+ current.client = withResilience(mock as unknown as Redis);
+ });
+
+ it("lets exactly one caller hold it", async () => {
+ await acquiredOwner();
+ expect(await acquireLease(KEY, LEASE_MS)).toEqual({ status: "held" });
+ });
+
+ it("reports an unreachable Redis as unavailable, not as held", async () => {
+ current.client = withResilience(unreachable());
+ expect(await acquireLease(KEY, LEASE_MS)).toEqual({
+ status: "unavailable"
+ });
+ });
+
+ it("frees itself when the lease runs out", async () => {
+ await acquiredOwner();
+ await sleep(PAST_LEASE_MS);
+ expect((await acquireLease(KEY, LEASE_MS)).status).toBe("acquired");
+ });
+
+ it("never lets a holder whose lease lapsed release or extend a newer holder's lease", async () => {
+ const stale = await acquiredOwner();
+ await sleep(PAST_LEASE_MS);
+ const newer = await acquiredOwner();
+
+ await releaseLease(KEY, stale);
+ expect(await renewLease(KEY, stale, LEASE_MS)).toBe(false);
+ expect((await acquireLease(KEY, LEASE_MS)).status).toBe("held");
+
+ await releaseLease(KEY, newer);
+ expect((await acquireLease(KEY, LEASE_MS)).status).toBe("acquired");
+ });
+
+ it("stays held while the work outlasts several leases, then releases", async () => {
+ const owner = await acquiredOwner();
+ let duringWork = "unset";
+
+ await withLease(
+ KEY,
+ owner,
+ { leaseMs: LEASE_MS, renewMs: RENEW_MS },
+ async () => {
+ await sleep(LEASE_MS * 3);
+ duringWork = (await acquireLease(KEY, LEASE_MS)).status;
+ }
+ );
+
+ expect(duringWork).toBe("held");
+ expect((await acquireLease(KEY, LEASE_MS)).status).toBe("acquired");
+ });
+
+ it("releases when the work throws", async () => {
+ const owner = await acquiredOwner();
+ await expect(
+ withLease(
+ KEY,
+ owner,
+ { leaseMs: LEASE_MS, renewMs: RENEW_MS },
+ async () => {
+ throw new Error("work failed");
+ }
+ )
+ ).rejects.toThrow("work failed");
+ expect((await acquireLease(KEY, LEASE_MS)).status).toBe("acquired");
+ });
+});
diff --git a/packages/kv/src/lease.ts b/packages/kv/src/lease.ts
new file mode 100644
index 0000000000..fab516dd10
--- /dev/null
+++ b/packages/kv/src/lease.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { randomBytes } from "node:crypto";
+import redis from "./client";
+
+/**
+ * Owner-bound Redis lease: a dead holder stops renewing and the key lapses;
+ * renew and release check the owner first. Acquire answers 1 or 0, so `null`
+ * from the fail-soft client means Redis is unavailable, never held.
+ */
+export type LeaseAcquisition =
+ | { status: "acquired"; owner: string }
+ | { status: "held" }
+ | { status: "unavailable" };
+
+const ACQUIRE = `if redis.call("set", KEYS[1], ARGV[1], "PX", ARGV[2], "NX") then return 1 else return 0 end`;
+const RENEW_IF_OWNER = `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pexpire", KEYS[1], ARGV[2]) else return 0 end`;
+const RELEASE_IF_OWNER = `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`;
+
+export async function acquireLease(
+ key: string,
+ leaseMs: number
+): Promise<LeaseAcquisition> {
+ const owner = randomBytes(16).toString("base64url");
+ const result = await redis.eval(ACQUIRE, 1, key, owner, String(leaseMs));
+ if (result === 1) return { status: "acquired", owner };
+ if (result === 0) return { status: "held" };
+ return { status: "unavailable" };
+}
+
+/** False when the lease is no longer this owner's. */
+export async function renewLease(
+ key: string,
+ owner: string,
+ leaseMs: number
+): Promise<boolean> {
+ const result = await redis.eval(
+ RENEW_IF_OWNER,
+ 1,
+ key,
+ owner,
+ String(leaseMs)
+ );
+ return result === 1;
+}
+
+export async function releaseLease(key: string, owner: string): Promise<void> {
+ await redis.eval(RELEASE_IF_OWNER, 1, key, owner);
+}
+
+/** Renewal failures are ignored: the owner check makes a lapsed lease safe. */
+export async function withLease<T>(
+ key: string,
+ owner: string,
+ { leaseMs, renewMs }: { leaseMs: number; renewMs: number },
+ work: () => Promise<T>
+): Promise<T> {
+ const renewal = setInterval(() => {
+ renewLease(key, owner, leaseMs).catch(() => undefined);
+ }, renewMs);
+ try {
+ return await work();
+ } finally {
+ clearInterval(renewal);
+ await releaseLease(key, owner).catch(() => undefined);
+ }
+}
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 114bdd7c13..e071a33575 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -666,6 +666,26 @@ export type Events = {
};
};
+ // Panel push: export one element's assets onto the item the push linked.
+ "carbon/onshape-panel-sync": {
+ data: {
+ companyId: string;
+ userId: string;
+ itemId: string;
+ documentId: string;
+ wvm: "w" | "v";
+ wvmId: string;
+ elementId: string;
+ elementKind: "partstudio" | "assembly" | "drawing";
+ partId?: string;
+ /** Non-default configuration to export; absent = default. */
+ configuration?: string;
+ assetBaseName?: string;
+ /** Workspace pushes: the part microversion the review saw. */
+ microversionId?: string;
+ };
+ };
+
// Onshape released-asset backfill / reconcile
"carbon/onshape-backfill": {
data: {
diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.ts
index 0cf61b63eb..ba6e229e42 100644
--- a/packages/lib/src/trigger.ts
+++ b/packages/lib/src/trigger.ts
@@ -31,6 +31,7 @@ const taskToEvent = {
onboard: "carbon/onboard",
"mount-publish": "carbon/mount-publish",
"onshape-backfill": "carbon/onshape-backfill",
+ "onshape-panel-sync": "carbon/onshape-panel-sync",
"onshape-revision-sync": "carbon/onshape-revision-sync",
"paperless-parts": "carbon/paperless-parts",
"post-transactions": "carbon/post-transaction",
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index d61f8e5bbb..4323bc5721 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Änderungsbeschreibung"
msgid "Description of Issue"
msgstr "Problembeschreibung"
+msgid "Detach"
+msgstr "Trennen"
+
+msgid "Detach from Onshape?"
+msgstr "Von Onshape trennen?"
+
msgid "Detail"
msgstr "Detail"
@@ -8301,6 +8307,10 @@ msgstr "Jeder Zeitraum ist ein Monat zum Monatssatz."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Jede physische Einheit erhält ihre eigene verfolgte Einheit und eine eindeutige Nummer – eine verfolgte Einheit, ein Stück."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Der Verkäufer (oder Ersteller) jeder Mietvereinbarung oder eines Vertrags erhält eine tägliche Zusammenfassung seiner Rechnungen."
@@ -12246,6 +12256,9 @@ msgstr "Letzter Push {when} fehlgeschlagen: {0}"
msgid "Last push {when}:"
msgstr "Letzte Übertragung {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Zuletzt übertragen: {lastPushed}."
+
msgid "Last Quarter"
msgstr "Letztes Quartal"
@@ -12613,6 +12626,9 @@ msgstr "Verknüpfen Sie diesen Carbon-Kunden mit einem davon, oder erstellen Sie
msgid "Link to sales order line"
msgstr "Mit Kundenauftragsposition verknüpfen"
+msgid "Linked"
+msgstr "Verknüpft"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "In Änderungsmitteilungen {ids} offen. Geben Sie sie frei, um neue Versi
msgid "Open in MES"
msgstr "Im MES öffnen"
+msgid "Open in Onshape"
+msgstr "In Onshape öffnen"
+
msgid "Open Issues"
msgstr "Offene Probleme"
@@ -17416,6 +17435,15 @@ msgstr "Den Buchungssatz ohne die Dimension verbuchen"
msgid "Push to accounting"
msgstr "Zur Buchhaltung senden"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Legen Sie diese Gebühr auf einer separaten Rechnung ab, die vor der Buchung überprüft wird. Andernfalls wird sie auf der nächsten Rechnung der Vereinbarung eingefügt."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index eafa9b2832..ab7e7dc02e 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Description of Change"
msgid "Description of Issue"
msgstr "Description of Issue"
+msgid "Detach"
+msgstr "Detach"
+
+msgid "Detach from Onshape?"
+msgstr "Detach from Onshape?"
+
msgid "Detail"
msgstr "Detail"
@@ -8301,6 +8307,10 @@ msgstr "Each period is one month, for the month rate."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr "Each push replaces: {0}. Other edits stay."
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
@@ -12246,6 +12256,9 @@ msgstr "Last push {when} failed: {0}"
msgid "Last push {when}:"
msgstr "Last push {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Last pushed {lastPushed}."
+
msgid "Last Quarter"
msgstr "Last Quarter"
@@ -12613,6 +12626,9 @@ msgstr "Link this Carbon customer to one of them, or create a separate Stripe cu
msgid "Link to sales order line"
msgstr "Link to sales order line"
+msgid "Linked"
+msgstr "Linked"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Open in change notices {ids}. Release them to create new versions or rev
msgid "Open in MES"
msgstr "Open in MES"
+msgid "Open in Onshape"
+msgstr "Open in Onshape"
+
msgid "Open Issues"
msgstr "Open Issues"
@@ -17416,6 +17435,15 @@ msgstr "Push the journal without the dimension"
msgid "Push to accounting"
msgstr "Push to accounting"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr "Pushes don't change this item's fields, so edits made here stay."
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 665988b145..0269c25dfd 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Descripción del Cambio"
msgid "Description of Issue"
msgstr "Descripción del Problema"
+msgid "Detach"
+msgstr "Desvincular"
+
+msgid "Detach from Onshape?"
+msgstr "¿Desvincularse de Onshape?"
+
msgid "Detail"
msgstr "Detalle"
@@ -8301,6 +8307,10 @@ msgstr "Cada período es un mes, para la tarifa mensual."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Cada unidad física obtiene su propia entidad rastreada y número único — una entidad, una unidad."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "El vendedor de cada acuerdo de alquiler o contrato (o su creador) recibe un resumen diario de sus facturas."
@@ -12246,6 +12256,9 @@ msgstr "El último envío {when} falló: {0}"
msgid "Last push {when}:"
msgstr "Último envío {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Último envío {lastPushed}."
+
msgid "Last Quarter"
msgstr "Trimestre Anterior"
@@ -12613,6 +12626,9 @@ msgstr "Vincule este cliente de Carbon a uno de ellos o cree un cliente de Strip
msgid "Link to sales order line"
msgstr "Vínculo a línea de pedido de venta"
+msgid "Linked"
+msgstr "Vinculado"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Abierto en avisos de cambio {ids}. Libérelos para crear nuevas versione
msgid "Open in MES"
msgstr "Abrir en MES"
+msgid "Open in Onshape"
+msgstr "Abrir en Onshape"
+
msgid "Open Issues"
msgstr "Problemas Abiertos"
@@ -17416,6 +17435,15 @@ msgstr "Enviar el asiento sin la dimensión"
msgid "Push to accounting"
msgstr "Enviar a contabilidad"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Coloca este cargo en su propia factura, retenida para revisión antes de que se contabilice. De lo contrario, va en la siguiente factura del acuerdo."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 71293be0a0..58a2015987 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Description du changement"
msgid "Description of Issue"
msgstr "Description du problème"
+msgid "Detach"
+msgstr "Détacher"
+
+msgid "Detach from Onshape?"
+msgstr "Détacher d'Onshape ?"
+
msgid "Detail"
msgstr "Détail"
@@ -8301,6 +8307,10 @@ msgstr "Chaque période dure un mois, pour le tarif mensuel."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Chaque unité physique obtient sa propre entité suivie et un numéro unique — une entité, une unité."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Le commercial de chaque accord de location ou contrat (ou son créateur) reçoit un résumé quotidien de ses factures."
@@ -12246,6 +12256,9 @@ msgstr "Le dernier envoi {when} a échoué : {0}"
msgid "Last push {when}:"
msgstr "Dernier envoi {when} :"
+msgid "Last pushed {lastPushed}."
+msgstr "Dernière mise à jour le {lastPushed}."
+
msgid "Last Quarter"
msgstr "Dernier trimestre"
@@ -12613,6 +12626,9 @@ msgstr "Liez ce client Carbon à l'un d'entre eux, ou créez un client Stripe di
msgid "Link to sales order line"
msgstr "Lier à la ligne de commande client"
+msgid "Linked"
+msgstr "Lié"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Ouverts dans les avis de modification {ids}. Lancez-les pour créer de n
msgid "Open in MES"
msgstr "Ouvrir dans MES"
+msgid "Open in Onshape"
+msgstr "Ouvrir dans Onshape"
+
msgid "Open Issues"
msgstr "Problèmes ouverts"
@@ -17416,6 +17435,15 @@ msgstr "Envoyer l'écriture sans l'axe analytique"
msgid "Push to accounting"
msgstr "Envoyer vers la comptabilité"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Mettre cette charge sur sa propre facture, en attente de Revue avant d'être comptabilisée. Sinon, elle va sur la prochaine facture de l'accord."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index d02b3c0232..b7cbe1f6ce 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -7685,6 +7685,12 @@ msgstr "परिवर्तन का विवरण"
msgid "Description of Issue"
msgstr "समस्या का विवरण"
+msgid "Detach"
+msgstr "अलग करें"
+
+msgid "Detach from Onshape?"
+msgstr "Onshape से अलग करें?"
+
msgid "Detail"
msgstr "विवरण"
@@ -8301,6 +8307,10 @@ msgstr "प्रत्येक अवधि एक महीना है, म
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "प्रत्येक भौतिक इकाई को अपनी खुद की ट्रैक की गई इकाई और अद्वितीय संख्या मिलती है — एक इकाई, एक इकाई।"
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "प्रत्येक किराये की समझौते या अनुबंध के विक्रय प्रतिनिधि (या इसके निर्माता) को इसके चालानों का दैनिक सारांश मिलता है।"
@@ -12246,6 +12256,9 @@ msgstr "अंतिम पुश ({when}) विफल हुआ: {0}"
msgid "Last push {when}:"
msgstr "अंतिम पुश {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "अंतिम बार {lastPushed} को पुश किया गया।"
+
msgid "Last Quarter"
msgstr "पिछली तिमाही"
@@ -12613,6 +12626,9 @@ msgstr "इस Carbon ग्राहक को इनमें से किस
msgid "Link to sales order line"
msgstr "विक्रय आदेश पंक्ति से जोड़ें"
+msgid "Linked"
+msgstr "जुड़ा हुआ"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "परिवर्तन सूचनाओं {ids} में खुल
msgid "Open in MES"
msgstr "MES में खोलें"
+msgid "Open in Onshape"
+msgstr "Onshape में खोलें"
+
msgid "Open Issues"
msgstr "खुले मुद्दे"
@@ -17416,6 +17435,15 @@ msgstr "आयाम के बिना जर्नल पुश करें"
msgid "Push to accounting"
msgstr "लेखांकन को धकेलें"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "इस शुल्क को अपने चालान पर रखें, जिसे पोस्ट होने से पहले समीक्षा के लिए रोका जाता है। अन्यथा यह समझौते के अगले चालान पर जाता है।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 70bd144e23..3fbed6555e 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Descrizione della Modifica"
msgid "Description of Issue"
msgstr "Descrizione del Problema"
+msgid "Detach"
+msgstr "Scollega"
+
+msgid "Detach from Onshape?"
+msgstr "Scollega da Onshape?"
+
msgid "Detail"
msgstr "Dettagli"
@@ -8301,6 +8307,10 @@ msgstr "Ogni periodo è un mese, per la tariffa mensile."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Ogni unità fisica ottiene la propria entità tracciata e numero univoco — un'entità, un'unità."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Il venditore di ogni accordo di noleggio o contratto (o il suo creatore) riceve un riepilogo giornaliero delle sue fatture."
@@ -12246,6 +12256,9 @@ msgstr "Ultimo invio {when} non riuscito: {0}"
msgid "Last push {when}:"
msgstr "Ultimo push {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Ultimo invio {lastPushed}."
+
msgid "Last Quarter"
msgstr "Ultimo Trimestre"
@@ -12613,6 +12626,9 @@ msgstr "Collega questo cliente Carbon a uno di loro, oppure crea un cliente Stri
msgid "Link to sales order line"
msgstr "Collega alla riga dell'ordine di vendita"
+msgid "Linked"
+msgstr "Collegato"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Apri negli avvisi di modifica {ids}. Rilasciali per creare nuove version
msgid "Open in MES"
msgstr "Apri in MES"
+msgid "Open in Onshape"
+msgstr "Apri in Onshape"
+
msgid "Open Issues"
msgstr "Problemi Aperti"
@@ -17416,6 +17435,15 @@ msgstr "Registra la prima nota senza la dimensione"
msgid "Push to accounting"
msgstr "Invia alla contabilità"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Inserisci questo addebito su una propria fattura, in sospeso in attesa di revisione prima che sia registrata. Altrimenti verrà inclusa sulla prossima fattura dell'accordo."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index ba4fb5a848..1e9469f03e 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -7685,6 +7685,12 @@ msgstr "変更の説明"
msgid "Description of Issue"
msgstr "問題の説明"
+msgid "Detach"
+msgstr "リンク解除"
+
+msgid "Detach from Onshape?"
+msgstr "Onshapeからリンク解除しますか?"
+
msgid "Detail"
msgstr "詳細"
@@ -8301,6 +8307,10 @@ msgstr "各期間は1ヶ月で、月額レートが適用されます。"
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "各物理的な個が独自の追跡対象と一意番号を取得します。1 追跡対象 = 1 個。"
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "各レンタル契約または契約の営業担当者(またはその作成者)は、毎日その請求書のサマリーを受け取ります。"
@@ -12246,6 +12256,9 @@ msgstr "前回の{when}の送信は失敗しました: {0}"
msgid "Last push {when}:"
msgstr "最後のプッシュ {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "最終プッシュ: {lastPushed}"
+
msgid "Last Quarter"
msgstr "前四半期"
@@ -12613,6 +12626,9 @@ msgstr "このCarbonの得意先をいずれかにリンクするか、別のStr
msgid "Link to sales order line"
msgstr "受注明細へのリンク"
+msgid "Linked"
+msgstr "リンク済み"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "変更通知{ids}で開いています。新しいバージョンまた
msgid "Open in MES"
msgstr "MESで開く"
+msgid "Open in Onshape"
+msgstr "Onshapeで開く"
+
msgid "Open Issues"
msgstr "未解決の問題"
@@ -17416,6 +17435,15 @@ msgstr "ディメンションなしで仕訳を転記する"
msgid "Push to accounting"
msgstr "会計にプッシュ"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "この請求項目を独自の請求書に配置し、転記前にレビューで保留します。そうでなければ、契約の次の請求書に記載されます。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 0436e6057c..78dacc09d5 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -7685,6 +7685,12 @@ msgstr "변경 설명"
msgid "Description of Issue"
msgstr "이슈 설명"
+msgid "Detach"
+msgstr "분리"
+
+msgid "Detach from Onshape?"
+msgstr "Onshape에서 분리하시겠습니까?"
+
msgid "Detail"
msgstr "상세"
@@ -8301,6 +8307,10 @@ msgstr "각 기간은 1개월이며, 월별 요금으로 청구됩니다."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "각 물리적 개는 자신의 추적 대상과 고유 번호를 받습니다 — 하나의 추적 대상, 하나의 개."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "각 임차료 계약 또는 계약의 영업 담당자(또는 작성자)는 매일 해당 송장 요약을 받습니다."
@@ -12246,6 +12256,9 @@ msgstr "마지막 전송 {when} 실패: {0}"
msgid "Last push {when}:"
msgstr "마지막 푸시 {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "마지막 푸시: {lastPushed}."
+
msgid "Last Quarter"
msgstr "지난 분기"
@@ -12613,6 +12626,9 @@ msgstr "이 Carbon 고객을 그 중 하나에 연결하거나 별도의 Stripe
msgid "Link to sales order line"
msgstr "수주 라인으로 링크"
+msgid "Linked"
+msgstr "연결됨"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "변경 통지 {ids}에서 열기. 새로운 버전 또는 리비전을
msgid "Open in MES"
msgstr "MES에서 열기"
+msgid "Open in Onshape"
+msgstr "Onshape에서 열기"
+
msgid "Open Issues"
msgstr "미결 이슈"
@@ -17416,6 +17435,15 @@ msgstr "차원 없이 전표를 전기하세요"
msgid "Push to accounting"
msgstr "회계로 푸시"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "이 비용을 검토 후 전기할 별도의 송장에 보관합니다. 그렇지 않으면 계약의 다음 송장에 포함됩니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index b487812b57..e63d6319cf 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Opis Zmiany"
msgid "Description of Issue"
msgstr "Opis problemu"
+msgid "Detach"
+msgstr "Odłącz"
+
+msgid "Detach from Onshape?"
+msgstr "Odłączyć od Onshape?"
+
msgid "Detail"
msgstr "Szczegóły"
@@ -8301,6 +8307,10 @@ msgstr "Każdy okres to jeden miesiąc, za stawką miesięczną."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Każda jednostka fizyczna otrzymuje swoją własną jednostkę śledzenia i unikalny numer — jedna jednostka, jedna jednostka."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Każdy sprzedawca umowy najmu lub umowy (lub jej twórca) otrzymuje codzienne podsumowanie swoich faktur."
@@ -12246,6 +12256,9 @@ msgstr "Ostatnie wysłanie {when} nie powiodło się: {0}"
msgid "Last push {when}:"
msgstr "Ostatni push {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Ostatnio wysłano {lastPushed}."
+
msgid "Last Quarter"
msgstr "Ostatni kwartał"
@@ -12613,6 +12626,9 @@ msgstr "Połącz tego klienta Carbon z jednym z nich, lub utwórz osobnego klien
msgid "Link to sales order line"
msgstr "Łącze do pozycji zamówienia sprzedaży"
+msgid "Linked"
+msgstr "Powiązane"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Otwarte w zawiadomieniach o zmianie {ids}. Zwolnij je aby utworzyć nowe
msgid "Open in MES"
msgstr "Otwórz w MES"
+msgid "Open in Onshape"
+msgstr "Otwórz w Onshape"
+
msgid "Open Issues"
msgstr "Otwarte problemy"
@@ -17416,6 +17435,15 @@ msgstr "Wyślij dowód księgowy bez wymiaru"
msgid "Push to accounting"
msgstr "Wyślij do systemu księgowego"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Umieść tę opłatę na osobnej fakturze, zatrzymanej do przeglądu zanim zostanie zaksięgowana. W przeciwnym razie przejdzie na następną fakturę umowy."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 690b2a93bc..ba8f1c4f86 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Descrição da Alteração"
msgid "Description of Issue"
msgstr "Descrição do Problema"
+msgid "Detach"
+msgstr "Desconectar"
+
+msgid "Detach from Onshape?"
+msgstr "Desconectar de Onshape?"
+
msgid "Detail"
msgstr "Detalhe"
@@ -8301,6 +8307,10 @@ msgstr "Cada período dura um mês, com taxa mensal."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Cada unidade física obtém sua própria entidade rastreada e número único — uma entidade, uma unidade."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "O vendedor (ou criador) de cada contrato de aluguel ou contrato recebe um resumo diário de suas faturas."
@@ -12246,6 +12256,9 @@ msgstr "Último envio {when} falhou: {0}"
msgid "Last push {when}:"
msgstr "Último envio {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Último envio em {lastPushed}."
+
msgid "Last Quarter"
msgstr "Último Trimestre"
@@ -12613,6 +12626,9 @@ msgstr "Vincule este cliente Carbon a um deles ou crie um cliente Stripe separad
msgid "Link to sales order line"
msgstr "Vincular à linha do pedido de venda"
+msgid "Linked"
+msgstr "Vinculado"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Aberto em avisos de alteração {ids}. Libere-os para criar novas versõ
msgid "Open in MES"
msgstr "Abrir no MES"
+msgid "Open in Onshape"
+msgstr "Abrir no Onshape"
+
msgid "Open Issues"
msgstr "Problemas Abertos"
@@ -17416,6 +17435,15 @@ msgstr "Enviar o diário sem a dimensão"
msgid "Push to accounting"
msgstr "Enviar para contabilidade"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Coloque este encargo em sua própria fatura, retida para revisão antes de ser contabilizada. Caso contrário, será incluída na próxima fatura do contrato."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index a62dcfc61d..86705d71d3 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Описание изменения"
msgid "Description of Issue"
msgstr "Описание проблемы"
+msgid "Detach"
+msgstr "Отключить"
+
+msgid "Detach from Onshape?"
+msgstr "Отключить от Onshape?"
+
msgid "Detail"
msgstr "Подробности"
@@ -8301,6 +8307,10 @@ msgstr "Каждый период — один месяц, по месячной
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Каждая физическая единица получает свой отслеживаемый объект и уникальный номер — один объект, одна единица."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Менеджер по продажам каждого договора аренды или контракта (или его создатель) получает ежедневное резюме своих счетов-фактур."
@@ -12246,6 +12256,9 @@ msgstr "Последняя попытка отправки {when} не удал
msgid "Last push {when}:"
msgstr "Последняя отправка {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Последний раз передано {lastPushed}."
+
msgid "Last Quarter"
msgstr "Последний квартал"
@@ -12613,6 +12626,9 @@ msgstr "Свяжите этого покупателя Carbon с одним из
msgid "Link to sales order line"
msgstr "Ссылка на строку заказа покупателя"
+msgid "Linked"
+msgstr "Связано"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Открыть в Извещениях об изменении {ids}. З
msgid "Open in MES"
msgstr "Открыть в MES"
+msgid "Open in Onshape"
+msgstr "Открыть в Onshape"
+
msgid "Open Issues"
msgstr "Открытые проблемы"
@@ -17416,6 +17435,15 @@ msgstr "Провести операцию без измерения"
msgid "Push to accounting"
msgstr "Отправить в бухгалтерию"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Поместить это начисление на отдельный счет-фактуру, находящуюся на рассмотрение перед проведением. В противном случае оно переходит на следующий счет-фактуру по соглашению."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 4e61b645c2..06c3c16ac5 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -7685,6 +7685,12 @@ msgstr "Değişiklimin Açıklaması"
msgid "Description of Issue"
msgstr "Sorun Açıklaması"
+msgid "Detach"
+msgstr "Ayır"
+
+msgid "Detach from Onshape?"
+msgstr "Onshape'tan Ayır?"
+
msgid "Detail"
msgstr "Detay"
@@ -8301,6 +8307,10 @@ msgstr "Her dönem bir aydır, aylık oran için."
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "Her fiziksel birim kendi izlenen varlığını ve benzersiz numarasını alır — bir varlık, bir birim."
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "Her kiralama anlaşmasının veya sözleşmenin satış temsilcisi (veya yaratıcısı) faturalarının günlük bir özetini alır."
@@ -12246,6 +12256,9 @@ msgstr "Son itme {when} başarısız oldu: {0}"
msgid "Last push {when}:"
msgstr "Son gönderim {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "Son gönderim: {lastPushed}."
+
msgid "Last Quarter"
msgstr "Son Çeyrek"
@@ -12613,6 +12626,9 @@ msgstr "Bu Carbon müşterisini bunlardan birine bağlayın veya ayrı bir Strip
msgid "Link to sales order line"
msgstr "Satış siparişi satırına bağla"
+msgid "Linked"
+msgstr "Bağlantılı"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "Değişiklik bildirimleri {ids} içinde aç. Yeni sürümler veya revizy
msgid "Open in MES"
msgstr "MES'te Aç"
+msgid "Open in Onshape"
+msgstr "Onshape'da Aç"
+
msgid "Open Issues"
msgstr "Açık Sorunlar"
@@ -17416,6 +17435,15 @@ msgstr "Muhasebe fişini boyut olmadan gönder"
msgid "Push to accounting"
msgstr "Muhasebede gönder"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "Bu masrafı, muhasebeleştirilmeden önce inceleme için kendi faturasında tutun. Aksi takdirde, sözleşmenin sonraki faturasına eklenir."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index a7fe72ec00..8a373ff3cb 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -7685,6 +7685,12 @@ msgstr "变更说明"
msgid "Description of Issue"
msgstr "问题描述"
+msgid "Detach"
+msgstr "分离"
+
+msgid "Detach from Onshape?"
+msgstr "从 Onshape 分离?"
+
msgid "Detail"
msgstr "详情"
@@ -8301,6 +8307,10 @@ msgstr "每个周期为一个月,按月费率计算。"
msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."
msgstr "每个物理件获得其自己的追踪实体和唯一编号——一个实体,一个件。"
+#. placeholder {0}: replaced.join(", ")
+msgid "Each push replaces: {0}. Other edits stay."
+msgstr ""
+
msgid "Each rental agreement's or contract's salesperson (or its creator) gets a daily summary of its invoices."
msgstr "每个租赁协议或合约的销售人员(或其创建者)每日获得其发票摘要。"
@@ -12246,6 +12256,9 @@ msgstr "上次推送 {when} 失败:{0}"
msgid "Last push {when}:"
msgstr "最后一次推送 {when}:"
+msgid "Last pushed {lastPushed}."
+msgstr "最后推送:{lastPushed}。"
+
msgid "Last Quarter"
msgstr "上一季度"
@@ -12613,6 +12626,9 @@ msgstr "将此 Carbon 客户链接到其中一个,或创建单独的 Stripe
msgid "Link to sales order line"
msgstr "关联销售订单行"
+msgid "Linked"
+msgstr "已链接"
+
#. placeholder {0}: r.linkedSum
#. placeholder {1}: r.quantity
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
@@ -15517,6 +15533,9 @@ msgstr "打开于变更通知 {ids}。下达它们来创建新版本或修订版
msgid "Open in MES"
msgstr "在 MES 中打开"
+msgid "Open in Onshape"
+msgstr "在 Onshape 中打开"
+
msgid "Open Issues"
msgstr "未结领料"
@@ -17416,6 +17435,15 @@ msgstr "发布不包含维度的凭证"
msgid "Push to accounting"
msgstr "推送到会计系统"
+msgid "Pushes don't change this item's fields, so edits made here stay."
+msgstr ""
+
+msgid "Pushes from Onshape stop updating this item. Pushing this part from Onshape again links it back."
+msgstr ""
+
+msgid "Pushes replace only the fields that Onshape's Fields page sets to Update on every push."
+msgstr ""
+
msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
msgstr "将此费用单独放在发票上,在过账之前保留以待评审。否则,它将放在协议的下一张发票上。"
diff --git a/sst.config.ts b/sst.config.ts
index 49b56bfd66..c01759fcde 100644
--- a/sst.config.ts
+++ b/sst.config.ts
@@ -86,6 +86,9 @@ export default $config({
ONSHAPE_CLIENT_ID: process.env.ONSHAPE_CLIENT_ID,
ONSHAPE_CLIENT_SECRET: process.env.ONSHAPE_CLIENT_SECRET,
ONSHAPE_OAUTH_REDIRECT_URL: process.env.ONSHAPE_OAUTH_REDIRECT_URL,
+ ONSHAPE_V2_CLIENT_ID: process.env.ONSHAPE_V2_CLIENT_ID,
+ ONSHAPE_V2_CLIENT_SECRET: process.env.ONSHAPE_V2_CLIENT_SECRET,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL: process.env.ONSHAPE_V2_OAUTH_REDIRECT_URL,
POSTHOG_API_HOST: process.env.POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY: process.env.POSTHOG_PROJECT_PUBLIC_KEY,
QUICKBOOKS_CLIENT_ID: process.env.QUICKBOOKS_CLIENT_ID,
@@ -195,6 +198,7 @@ export default $config({
ONSHAPE_CLIENT_ID: process.env.ONSHAPE_CLIENT_ID,
ONSHAPE_CLIENT_SECRET: process.env.ONSHAPE_CLIENT_SECRET,
ONSHAPE_OAUTH_REDIRECT_URL: process.env.ONSHAPE_OAUTH_REDIRECT_URL,
+ ONSHAPE_V2_OAUTH_REDIRECT_URL: process.env.ONSHAPE_V2_OAUTH_REDIRECT_URL,
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
POSTHOG_API_HOST: process.env.POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY: process.env.POSTHOG_PROJECT_PUBLIC_KEY,