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(quality): inspection plans from STEP PMI, inspected against the model (#2056)

Brad Barbinb425f932deb6
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 433268bb07..f854958267 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4170,6 +4170,17 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Applies to:** `crates/occt-bridge/src/*.cc` (any function that opens a BinXCAF document), `apps/assembler/src/actions/optimize.rs` (`run_ingest`).
+
+## A new table handler's generated migration fails locally with "must be owner"
+
+**Context:** A new statement handler (`queue_pmi_inspection_plans`) was added to `event-system/handlers/` and `attachments.ts`. `pnpm db:migrate` synced it, then `authz migration` wrote the generated migration that ships it (2026-10-27).
+
+**Problem:** The next `pnpm db:migrate` failed on that migration with `must be owner of function queue_pmi_inspection_plans`. The sync had created the function as `supabase_admin`. Every older handler is owned by `postgres`, the role the migration runs its `CREATE OR REPLACE` as. Production never syncs, so only a local database that synced first is affected.
+
+**Rule:** If the generated migration of a new managed function fails locally with "must be owner", run `ALTER FUNCTION public.<name>() OWNER TO postgres;` as `supabase_admin`, then run `pnpm db:migrate` again. Do not edit the generated migration.
+
+**Applies to:** `packages/database/src/event-system/handlers/*.sql`, `packages/database/src/event-system/functions/*.sql`, `pnpm --filter @carbon/database authz migration`.
+
## A form validator is not an API contract
**Context:** `production_createJobOperation` answered a bare 500 "Failed to insert job operation" to an API caller (2026-10-27).
diff --git a/.ai/plans/2026-10-27-pmi-inspection-plans.md b/.ai/plans/2026-10-27-pmi-inspection-plans.md
new file mode 100644
index 0000000000..ad8eb8b4cd
--- /dev/null
+++ b/.ai/plans/2026-10-27-pmi-inspection-plans.md
@@ -0,0 +1,83 @@
+# Plan: Inspection plans from STEP PMI
+
+Spec: `.ai/specs/2026-10-27-pmi-inspection-plans.md`
+Run record: `.ai/runs/2026-10-27-pmi-inspection-plans.md`
+
+## Tasks
+
+### 1. Migration and types
+
+- [x] Run `pnpm db:migrate:new pmi-inspection-plans`.
+- [x] In the new file, add `inspectionDocument."modelUploadId"` (FK `modelUpload`, ON DELETE SET NULL), `inspectionFeature."pmiItemId"`, and the partial unique index `inspectionDocument_part_model_key`.
+- [x] In the same file, drop and create `inspectionDocuments` again (body of `20260526153412_inspection-documents-view.sql`).
+- [x] Add `packages/database/src/event-system/handlers/queue_pmi_inspection_plans.sql` (copy `queue_model_pipeline.sql`). On INSERT or UPDATE of `item`, for each row whose `modelUploadId` changed to a model with `pmiPath` set, send `carbon/pmi-inspection-plan` with `{ companyId, modelUploadId, itemId }`. Skip under `app.sync_in_progress`.
+- [x] Add `queue_pmi_inspection_plans` to `item.statement` in `attachments.ts`.
+- [x] Run `pnpm db:migrate`. Run `pnpm --filter @carbon/database authz sync` if migrate does not apply handlers. Ship the handler with `pnpm --filter @carbon/database authz migration pmi-inspection-plans-handler`.
+- [x] Run `pnpm run generate:types`.
+
+Verify: `psql` shows the two columns, the index and `trg_event_statement_queue_pmi_inspection_plans_*` on `item`.
+
+### 2. Mapping (`@carbon/viewer/pmi`)
+
+- [x] Add `pmiInspectionCharacteristics(doc: PmiDocument): PmiCharacteristic[]` to `packages/viewer/src/pmi.ts` (mapping table in the spec).
+- [x] Add `"./pmi": "./src/pmi.ts"` to `packages/viewer/package.json` exports.
+- [x] Add tests in `packages/viewer/src/pmi.test.ts`: ± dimension, limit dimension, fit-only dimension, presentation dimension skipped, angle unit, inch conversion, tolerance with value, tolerance without value, datum and note skipped, labels in order.
+
+Verify: `pnpm --filter @carbon/viewer test` passes.
+
+### 3. Building block (`@carbon/database/quality`)
+
+- [x] Add `createPmiInspectionPlan(db, { companyId, itemId, modelUploadId, characteristics })` to `packages/database/src/quality.ts`. It runs in the caller's transaction. It resolves the drawing number (`readableIdWithRevision`, ` (n)` suffix), inserts the plan with `ON CONFLICT DO NOTHING` on the partial index, and inserts the features when the plan row is new. It returns the plan id or null.
+
+Verify: `pnpm exec turbo run typecheck --filter=@carbon/database`.
+
+### 4. Job
+
+- [x] Add `packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.ts`: event `carbon/pmi-inspection-plan`, concurrency key `companyId-modelUploadId` limit 1, retries 2. One step, `create-plans`: read the model and the items with no plan for it, download and map `pmi.json`, then create each plan in its own transaction through `getJobDatabaseClient`. One step keeps the characteristics out of the step output.
+- [x] Register the function in `tasks/index.ts` and the inngest index. Add the event schema to `packages/lib/src/events.ts` (and `trigger.ts` when events are typed there).
+- [x] In `model-optimize.ts`, after `persist`, `step.sendEvent("pmi-inspection-plan", …)` when `outputs.pmi` is set.
+
+Verify: `pnpm exec turbo run typecheck --filter=@carbon/jobs`.
+
+### 5. Viewer: controlled PMI selection
+
+- [x] Add `selectedPmiItemId?: string | null` and `onPmiItemSelect?: (id: string | null) => void` to `ModelPreview`. A change of `selectedPmiItemId` selects the item and sends a focus request. A user pick calls `onPmiItemSelect`.
+
+Verify: `pnpm --filter @carbon/viewer typecheck`.
+
+### 6. ERP
+
+- [x] `quality.service.ts`: `getInspectionDocument` and `mapInspectionDocument` return `model: { modelUploadId, modelPath } | null` (embed `modelUpload(modelPath)`). `getInspectionSamplingPlans` and `getInspectionFeatures` select `pmiItemId`.
+- [x] Add `ModelUploadPreview` to `@carbon/viewer` (`./model-upload-preview`): props `modelUploadId`, `modelPath`, `companyId`, `pmiLinks`, `selectedLinkId`, `onLinkSelect`. Superseded the first build's per-app `InspectionModelPane` copies (nuclear self-review).
+- [x] `InspectionView.tsx`: prop `model`; the drawing pane shows the model pane when `model` is set.
+- [x] `x+/inspection+/$id.tsx`: pass `model`.
+- [x] Editor route `x+/inspection-document+/$id.tsx` passes `model`. `InspectionDocumentEditor.tsx`: with `model`, show the model pane in the top pane, hide the PDF actions and the Balloon button, add a Show action per row with a `pmiItemId`.
+- [x] `InspectionDocumentTable.tsx`: no PDF link for a model plan (check what it shows).
+
+Verify: `pnpm exec turbo run typecheck --filter=erp`.
+
+### 7. MES
+
+- [x] `services/quality.service.ts`: select `pmiItemId` on features, and `modelUploadId, modelUpload(modelPath)` in `getInspectionDocumentWithBalloons`; return `model`.
+- [x] Use `ModelUploadPreview` from `@carbon/viewer` (no app copy).
+- [x] `InspectionView.tsx` and `x+/inspection.$operationId.tsx`: pass and use `model`.
+
+Verify: `pnpm exec turbo run typecheck --filter=mes`.
+
+### 8. Docs and gates
+
+- [x] Update `.claude/rules/inspection-system.md`, `apps/erp/app/modules/quality/AGENTS.md`, `packages/viewer/AGENTS.md` (PMI section).
+- [x] Run `pnpm --filter @carbon/checks license-headers` for new files.
+- [x] Run Biome on changed files, the scoped typechecks, and the viewer and database tests.
+- [x] Run `/translate` for new UI strings when the catalogs need it. Not needed: the one new string, `Show`, is already in the catalogs.
+- [x] Item delete (`deleteItemsWithPriceBreaks`, `items.service.ts`) deletes the item's PMI plans that no inspection used.
+
+### 9. Nuclear self-review fixes
+
+- [x] `modelPreviewUrls` in `@carbon/viewer`, used by `ModelUploadPreview`, ERP `CadModel` and the MES model tab.
+- [x] `ModelPreview`: clear `pmiSelectedRef` with the selection on a new PMI document.
+- [x] `deleteUnusedPmiInspectionPlans` building block; `items.service.ts` calls it.
+- [x] Tests: `packages/database/src/pmi-inspection-plan.test.ts` (DB), `supabase/tests/pmi-inspection-plans.test.sql` (trigger), `packages/jobs/.../pmi-inspection-plan.test.ts` (mapping graded by `valuateMeasurement`).
+- [x] Editor: zoom controls not rendered for a model plan; conformance baseline line re-keyed; `model` prop required; `pmiLinks` memoized.
+- [x] `crbn`: one `assemblerMissingPrerequisite`; `dirname`.
+- [x] Docs: jobs and dev AGENTS.md, authz-manifest handler counts, user docs `inspections.mdx`.
diff --git a/.ai/runs/2026-10-27-pmi-inspection-plans.md b/.ai/runs/2026-10-27-pmi-inspection-plans.md
new file mode 100644
index 0000000000..f784b850de
--- /dev/null
+++ b/.ai/runs/2026-10-27-pmi-inspection-plans.md
@@ -0,0 +1,26 @@
+# Feature run: Inspection plans from STEP PMI
+
+- Date: 2026-10-27
+- Mode: fully-autonomous
+- Request: "when a step file is uploaded that has MBD PMI -- we are now handling it in the UI in the viewer component. but it would be really cool if the PMI created an inspection plan. and if that inspection plan was used, it brought in the model instead of a pdf" — then: "the plan should be made automatically if there are PMI. one plan with just a model. skip them. both erp and mes"
+- Phase plan: research [skip — `.ai/research/step-pmi-viewer.md` covers PMI; codebase mapped by two explore agents] · spec [run] · plan [run] · execute [run] · test [skip unless cheap — needs a STEP AP242 file with PMI and a running stack] · self-review [run]
+
+## Decisions
+- Spec gate: no open questions; the user answered the four questions. — 2026-10-27
+- `pageNumber` stays NOT NULL; a model feature gets 1. — The save RPC defaults it to 1, so no RPC change. — 2026-10-27
+
+- No local stack existed: started this worktree's own services-only stack (`crbn up --no-apps`) to apply migrations and generate types. — 2026-10-27
+- Item delete removes the item's PMI plans no inspection used, so an automatic plan never trips `partId` RESTRICT. — 2026-10-27
+- Not committed: the user did not ask for a commit. — 2026-10-27
+- Browser test skipped: needs a STEP AP242 file with PMI and the assembler running. — 2026-10-27
+
+## Phase log
+- spec: `.ai/specs/2026-10-27-pmi-inspection-plans.md`. STE-80 pass done.
+- plan: `.ai/plans/2026-10-27-pmi-inspection-plans.md`. STE-80 pass done.
+- execute: all tasks done, uncommitted. Gates: viewer pmi tests 36/36; DB check of the building block, duplicate guard, handler and delete cleanup (rolled back); typecheck erp, mes, jobs, viewer, database, lib; Biome; `@carbon/checks` 406/406; `db:check:datasets` 5/5; `db:check:backups` restorable; authz migration + event-system tests 13/13.
+
+- self-review: 2 bugs found and fixed — one-sided deviations (⌀10 −0.013/−0.028) gave wrong limits; the model's selection could drift from the host's. Viewer tests 38/38; typechecks and conformance green again.
+- nuclear self-review: fixes applied (see plan task 9). Viewer 242/242, database 49/49 (DB tests ran against the local stack), jobs mapping×grading 4/4, dev 9/9, checks 406/406, trigger SQL test passes, docs typecheck green. Not done: the editor refactor (left as a decision), splitting the `crbn` changes into their own PR (nothing committed yet).
+
+## Outcome
+- Built and verified locally; uncommitted.
diff --git a/.ai/specs/2026-10-27-pmi-inspection-plans.md b/.ai/specs/2026-10-27-pmi-inspection-plans.md
new file mode 100644
index 0000000000..ca5e74bc30
--- /dev/null
+++ b/.ai/specs/2026-10-27-pmi-inspection-plans.md
@@ -0,0 +1,182 @@
+# Inspection plans from STEP PMI
+
+> Status: approved (decisions by the user, 2026-10-27)
+> Author: Claude (autonomous `/feature` run for Brad)
+> Date: 2026-10-27
+
+## TLDR
+
+A STEP AP242 model can carry PMI: dimensions, geometric tolerances, datums and notes. Since `2026-10-26-step-pmi-viewer.md`, the optimize ingest writes them to `pmi.json` (`modelUpload.pmiPath`) and the viewer draws them.
+
+This change makes an inspection plan from that PMI automatically. Each dimension and each geometric tolerance becomes one characteristic. The plan holds the model and no PDF. When an inspector records measurements against the plan (ERP or MES), the drawing pane shows the 3D model with its PMI, not a PDF. A pick in the measurement grid selects the PMI item on the model, and a pick on the model selects the row.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant O as model-optimize job
+ participant I as item (statement handler)
+ participant J as pmi-inspection-plan job
+ participant DB as Postgres
+ participant V as Inspection screen (ERP / MES)
+ O->>DB: persist pmiPath
+ O->>J: carbon/pmi-inspection-plan {modelUploadId}
+ I->>J: carbon/pmi-inspection-plan {modelUploadId, itemId} (model linked later)
+ J->>DB: read items that use the model
+ J->>J: read pmi.json, map items to characteristics
+ J->>DB: insert plan + features (one transaction, skip if the plan exists)
+ V->>DB: plan with modelUploadId, features with pmiItemId
+ V->>V: model pane + grid, selection both ways
+```
+
+## Problem Statement
+
+A quality engineer who gets an MBD model must type each characteristic into an inspection plan by hand. To do that, they must first export or draw a PDF, because a plan needs a PDF to show anything. The model already holds every nominal, tolerance and datum reference in machine-readable form. The viewer shows them, but nothing uses them.
+
+## Proposed Solution
+
+### When a plan is made
+
+One Inngest function, `pmi-inspection-plan` (event `carbon/pmi-inspection-plan`), makes the plans. Two places send the event:
+
+| Sender | When | Data |
+|---|---|---|
+| `model-optimize`, after the `persist` step | The run wrote a `pmi.json` | `{ companyId, modelUploadId }` |
+| Statement handler `queue_pmi_inspection_plans` on `item` | An INSERT or UPDATE sets `item.modelUploadId` to a model whose `pmiPath` is set | `{ companyId, modelUploadId, itemId }` |
+
+The second sender covers a model that is linked to an item after the optimize ran: a new revision, a quote line converted to a part, an existing model attached to a part.
+
+The function:
+
+1. Reads the model row. If `pmiPath` is null, stop.
+2. Reads the items whose `modelUploadId` is the model (only `itemId` when the event names one).
+3. Drops each item that already has a plan for this model.
+4. Downloads `pmi.json` and maps it to characteristics (`pmiInspectionCharacteristics`).
+5. If no characteristic results, stop.
+6. For each remaining item, inserts one plan and its features in one Kysely transaction.
+
+A partial unique index on `inspectionDocument ("companyId", "partId", "modelUploadId") WHERE "modelUploadId" IS NOT NULL` makes a duplicate impossible. The insert uses `ON CONFLICT DO NOTHING`.
+
+### PMI item to characteristic
+
+| PMI item | Characteristic |
+|---|---|
+| Dimension with a value and a `±` deviation | `nominalValue` = value, `tolerancePlus` = upper, `toleranceMinus` = abs(lower) |
+| Dimension whose deviations share a sign (`−0.013/−0.028`, `+0.05/+0.02`) | re-centred: `nominalValue` = the band's centre, plus and minus = half the band. The grid judges a reading by magnitudes, so the drawing nominal would pass parts outside the band |
+| Dimension with limits only (`upperBound`, `lowerBound`) | `nominalValue` = midpoint, plus and minus = half the range |
+| Dimension with a value and no numeric tolerance (fit class only, min/max qualifier, basic) | `nominalValue` = null: the grid records Pass or Fail |
+| Dimension of type `commonLabel` or `presentation`, or with no value | skipped |
+| Geometric tolerance with a value | `nominalValue` = `0`, `tolerancePlus` = zone value, `toleranceMinus` = `0` |
+| Geometric tolerance with no value | `nominalValue` = null: Pass or Fail |
+| Datum | skipped |
+| Note | skipped |
+
+Other fields:
+
+- `type` = `Measurement` for every row.
+- `label` = `1`, `2`, `3` … in the order of `pmi.json` (dimensions, then tolerances, as the file lists them).
+- `description` = the PMI title and text from `formatPmiItem`, for example `Diameter ⌀10.00 ±0.05`.
+- `unit` = `mm` or `in` from `sourceUnit` (mm when unknown); `deg` for an angle. Lengths convert from the file's mm to inches for an inch model.
+- `pageNumber` = `1`. A model plan has one "page".
+- `pmiItemId` = the PMI item id (`d1`, `t3`).
+
+### The plan row
+
+| Column | Value |
+|---|---|
+| `partId` | the item |
+| `modelUploadId` | the model |
+| `drawingNumber` | the item's `readableIdWithRevision`, with ` (1)`, ` (2)` … when taken (same rule as `resolveInspectionDocumentDrawingNumber`) |
+| `storagePath`, `fileName`, `pageCount` | null |
+| `createdBy` | `system` |
+
+### Using the plan
+
+The plan is used like any plan: assign it on the item's Quality tab for receipts, or pick it on an Inspection operation.
+
+- ERP `/x/inspection/{id}` and MES `/x/inspection/{operationId}`: when the plan has a model, the drawing pane shows `ModelUploadPreview` in place of `InspectionDrawingPane`. The active feature selects its `pmiItemId` on the model. The camera turns to it and its faces highlight. A pick on a PMI item on the model sets the active feature.
+- Editor `/x/inspection-document/{id}`: when the plan has a model, the top pane shows the model, not the PDF area. The PDF actions (Add Selector, zoom box, Replace PDF, Download PDF, Balloon) are hidden. A row's actions column shows a **Show** button that selects its PMI item on the model. Add Characteristic, edit, delete and sampling work as for a PDF plan.
+
+### Design Decisions
+
+| Decision | Choice | Why |
+|---|---|---|
+| Automatic or a button | Automatic (user) | The user asked for it. |
+| PDF and model on one plan | Model only (user) | One source per plan keeps the panes simple. |
+| Datums and notes | Skipped (user) | A datum has nothing to measure. A note has no value. |
+| Screens | ERP and MES (user) | Both run inspections. |
+| `pageNumber` on a model feature | `1`, column stays NOT NULL | The save RPC already defaults it to 1. The label trigger stays correct: labels are unique in the plan. No RPC change. |
+| A plan per item or per model | Per item and model | `inspectionDocument.partId` is NOT NULL. Each revision is its own item. |
+| A re-optimize of the same model | Leaves the plan alone | The engineer may have edited it. PMI ids are stable for the same file. |
+| A new model on the item | Makes a new plan; the old plan stays | A plan may have measurements. Assignments keep pointing at the old plan until a person changes them. |
+| Model deleted | `modelUploadId` ON DELETE SET NULL | The plan then has no pane, as a plan with no PDF has today. |
+| Where the mapping lives | `@carbon/viewer/pmi` (pure, tested) | It reads the PMI types and `formatPmiItem`. `@carbon/jobs` already depends on `@carbon/viewer`. |
+| Where the insert lives | `createPmiInspectionPlan` in `@carbon/database/quality` | The Kysely building block takes `db`. The job calls it in a transaction. |
+| Unit text | `mm`, `in`, `deg` | `inspectionFeature.unit` is free text. The grid shows a text that matches no unit code as it is. |
+| Backfill of models optimized with PMI before this change | None | PMI shipped on 2026-10-26. A Reoptimize of such a model sends the event. |
+| Auto-assign the plan for receipts | No | A person decides which plan gates a receipt. |
+| Item delete | Deletes the item's PMI plans that no inspection used (`deleteUnusedPmiInspectionPlans`) | `inspectionDocument.partId` is ON DELETE RESTRICT. A plan nobody made by hand must not block the delete. A used plan still refuses it. The delete runs as the system, so `parts_delete` alone can remove an unused PMI plan. |
+| Model deleted after the plan is made | The plan keeps its features and loses its model (SET NULL) | It then behaves as a plan made by hand, and blocks a part delete like one. Recognising it would need a column that marks a plan as made from PMI. |
+
+## Data Model Changes
+
+One migration:
+
+```sql
+ALTER TABLE "inspectionDocument"
+ ADD COLUMN "modelUploadId" TEXT REFERENCES "modelUpload"("id") ON DELETE SET NULL;
+ALTER TABLE "inspectionFeature" ADD COLUMN "pmiItemId" TEXT;
+CREATE UNIQUE INDEX "inspectionDocument_part_model_key"
+ ON "inspectionDocument" ("companyId", "partId", "modelUploadId")
+ WHERE "modelUploadId" IS NOT NULL;
+```
+
+The `inspectionDocuments` view selects `d.*`, which Postgres expands when it creates the view. The migration drops and creates the view again, so the view gets `modelUploadId`.
+
+Event system: a new statement handler `queue_pmi_inspection_plans` (`packages/database/src/event-system/handlers/`), attached to `item` in `attachments.ts`, shipped with `pnpm --filter @carbon/database authz migration`.
+
+## API / Service Changes
+
+- `@carbon/viewer/pmi` (new package export): `pmiInspectionCharacteristics(doc): PmiCharacteristic[]`.
+- `@carbon/database/quality`: `createPmiInspectionPlan(db, { companyId, itemId, modelUploadId, characteristics })`.
+- `@carbon/jobs`: `pmiInspectionPlanFunction`; `model-optimize` sends the event.
+- `@carbon/viewer` `ModelPreview`: new optional props `selectedPmiItemId` and `onPmiItemSelect` (controlled selection).
+- ERP and MES inspection loaders return `model: { modelUploadId, modelPath } | null` and `pmiItemId` on each feature.
+
+## Closest Sibling
+
+`InspectionDrawingPane` (ERP and MES copies) is the sibling of the model pane, `ModelUploadPreview` (`@carbon/viewer`): the same place in `InspectionView`, the same active-feature selection both ways. Unlike the drawing pane it is one shared component, not an app copy.
+
+## UI Changes
+
+No new route. The drawing pane slot shows a model. The editor's top pane shows a model. The plan list shows no PDF for a model plan.
+
+## Acceptance Criteria
+
+- [ ] An optimize that writes `pmi.json` makes one plan per item that uses the model, with one characteristic per dimension and geometric tolerance.
+- [ ] A second optimize of the same model makes no second plan.
+- [ ] Linking an item to a model that has PMI makes a plan for that item.
+- [ ] A model with PMI but no dimension or tolerance makes no plan.
+- [ ] The ERP and MES inspection screens show the model for a model plan. A row pick selects the PMI item. A pick on the model selects the row.
+- [ ] The editor shows the model for a model plan, and edits save.
+- [ ] `pmiInspectionCharacteristics` has unit tests for each row of the mapping table.
+- [ ] Deleting an item removes its PMI plans that no inspection used.
+
+## Risks
+
+| Risk | Effect | Mitigation |
+|---|---|---|
+| PMI ids change when the extractor changes its order | A re-optimize after an extractor change points features at other items | The plan is never rewritten, and ids are per model. Note it in the inspection rule. |
+| Many items share one model | One plan each | Correct: each revision inspects to its own plan. |
+| `pmi.json` up to 16 MB | Memory in the job | One download per run, parsed once. |
+
+## Open Questions
+
+None. The user resolved the four questions on 2026-10-27.
+
+## Changelog
+
+- 2026-10-27: first version.
+- 2026-10-27: added the item-delete rule, found during the build.
+- 2026-10-27: self-review: one-sided deviations are re-centred; the model pane reports a pick that selects no characteristic.
+- 2026-10-27: nuclear self-review: the model pane is `ModelUploadPreview` in `@carbon/viewer` (shared by ERP and MES, with `modelPreviewUrls` also used by `CadModel` and the MES model tab), not an app copy; the item-delete cleanup is the building block `deleteUnusedPmiInspectionPlans`; tests pin the building blocks, the trigger, and the mapping against `valuateMeasurement`. Recreating the `inspectionDocuments` view also adds the `sampling*` columns.
diff --git a/.claude/rules/authz-manifest.md b/.claude/rules/authz-manifest.md
index c297719d1f..ae2059b805 100644
--- a/.claude/rules/authz-manifest.md
+++ b/.claude/rules/authz-manifest.md
@@ -25,7 +25,7 @@ owns that table and its RLS switch, so sync and the generated migration never ru
`ENABLE ROW LEVEL SECURITY` on it — sync fails instead if the switch is off. To add another
external table, extend `ExternalTable` in `rules.ts` and `MANIFEST_SCHEMAS` in the check.
-The same machinery owns the event system's 45 functions, its 65 table handlers and the event triggers — see
+The same machinery owns the event system's 45 functions, its 71 table handlers and the event triggers — see
[Event-system functions](#event-system-functions) below.
| File | What it is |
@@ -107,8 +107,9 @@ RLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries i
`DROP FUNCTION` (sync refuses a file that would create an overload); the new definition
goes in the file.
- **Table handlers are managed too**: `../event-system/handlers/<name>.sql` holds every
- function a table attaches — the 64 interceptors (`sync_*`, `prevent_*`, `set_shelf_life_*`,
- `storage_unit_*`) and the statement handler `apply_item_stock_quantities`. Same format,
+ function a table attaches — the 67 interceptors (`sync_*`, `prevent_*`, `set_shelf_life_*`,
+ `storage_unit_*`) and the 4 statement handlers (`apply_item_stock_quantities`,
+ `queue_kanban_level_checks`, `queue_model_pipeline`, `queue_pmi_inspection_plans`). Same format,
same sync, same shipping; checked from `20261004194527` (`ATTACHMENTS_SINCE`). A new
interceptor is a new file there, never a function in a migration.
- **Not managed**: `util.send_inngest_event` and `public.set_inngest_event_url`
diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.md
index 49ec51ddd0..763cf5a0ed 100644
--- a/.claude/rules/inspection-system.md
+++ b/.claude/rules/inspection-system.md
@@ -146,6 +146,56 @@ Execution-layer tables (`20260722040401_inbound-inspection-execution.sql`):
RLS on all tables: standard SELECT/INSERT/UPDATE/DELETE gated by `quality_view/create/update/delete`.
+## Plans made from a model's PMI (`20261027122437_pmi-inspection-plans.sql`)
+
+Spec: `.ai/specs/2026-10-27-pmi-inspection-plans.md`. A STEP AP242 model's PMI
+(`modelUpload.pmiPath`, see `packages/viewer/AGENTS.md`) becomes an inspection
+plan automatically. The plan holds the model (`inspectionDocument.modelUploadId`,
+ON DELETE SET NULL) and no PDF; each feature names its PMI item
+(`inspectionFeature.pmiItemId`, `d1`/`t3`) and has `pageNumber = 1`.
+
+- **Made by** `pmi-inspection-plan` (`packages/jobs/.../tasks/pmi-inspection-plan.ts`),
+ event `carbon/pmi-inspection-plan`. Senders: `model-optimize` after a run that
+ wrote `pmi.json` (every item on the model), and the `queue_pmi_inspection_plans`
+ statement handler on `item` when an INSERT/UPDATE points an item at a model that
+ already has `pmiPath` (that item only; skipped under `app.sync_in_progress`).
+- **Mapping** is `pmiInspectionCharacteristics` (`@carbon/viewer/pmi`, tested):
+ a ± dimension → nominal/tol± (re-centred on its band when both deviations
+ share a sign, since the verdict reads Tol± as magnitudes); a limit dimension → midpoint ± half range; a
+ dimension with no numeric limit (fit class, min/max) or a tolerance with no
+ zone → nominal null (Pass/Fail); a geometric tolerance → nominal `0`, Tol+ =
+ zone, Tol− `0`. Datums, notes, labels and valueless dimensions are left out.
+ Units are the file's own (`mm`/`in`), `deg` for angles.
+- **Once per item and model.** `createPmiInspectionPlan` (`@carbon/database/quality`)
+ inserts with `ON CONFLICT DO NOTHING` on the partial unique index
+ `inspectionDocument_part_model_key`. A re-optimise never rewrites an edited
+ plan; a new model on the item makes a new plan and leaves the old one (and its
+ assignments) alone. No plan is made when no characteristic results.
+- **Item delete** (`deleteItemsWithPriceBreaks`) first calls
+ `deleteUnusedPmiInspectionPlans` (`@carbon/database/quality`), which deletes
+ the items' PMI plans no `inspection` used, so an automatic plan never trips
+ `partId`'s RESTRICT; a used one still refuses the delete. Pinned, with
+ `createPmiInspectionPlan`, by `packages/database/src/pmi-inspection-plan.test.ts`;
+ the trigger by `supabase/tests/pmi-inspection-plans.test.sql`; the mapping
+ against `valuateMeasurement` by `packages/jobs/.../pmi-inspection-plan.test.ts`.
+- **Screens.** `InspectionView` (ERP and MES) shows `ModelUploadPreview`
+ (`@carbon/viewer/model-upload-preview`, shared — not an app copy) in the
+ drawing pane's place when the loader returns `model`. Its `pmiLinks` (feature
+ id → `pmiItemId`) tie the active feature to its PMI item both ways; a pick on
+ a datum or note clears the active feature. The editor shows the model in its
+ top pane, does not render the PDF tools or the Balloon action, and gives each
+ PMI row a Show action.
+- **Deleting the model** sets `modelUploadId` null (ON DELETE SET NULL): the
+ plan keeps its features and shows no drawing pane, and the item-delete
+ cleanup no longer recognises it as a PMI plan, so it blocks a part delete
+ like a hand-made plan. `deleteUnusedPmiInspectionPlans` runs as the system
+ inside the item delete, so `parts_delete` alone can remove an unused PMI plan.
+- Recreating the `inspectionDocuments` view also added the six `sampling*`
+ columns added after it was first created (`d.*` is fixed at creation), so the
+ plan list now reads the document's sampling default.
+- PMI ids are per-kind counters in file order, stable for one file. An extractor
+ change that reorders items would point an old plan's features at other items.
+
## Gauges (`20260929203517_inspection-gauges.sql`)
- **Plan side** — `inspectionFeature.gaugeTypeId` (nullable FK → `gaugeType`,
diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.md
index d18b2e853a..ec7ad6766b 100644
--- a/apps/assembler/AGENTS.md
+++ b/apps/assembler/AGENTS.md
@@ -53,7 +53,8 @@ Dependency flow: `apps/assembler → planner → converter → occt-bridge`; `pl
## Native deps
-**Dev (macOS):** `brew install fcl opencascade` (pulls libccd, eigen, octomap).
+**Dev (macOS):** `brew install fcl` (pulls libccd, eigen, octomap). OCCT is not
+Homebrew's: build the patched static one with `scripts/build-occt.sh` (see Run).
Each bridge's `build.rs` resolves the lib prefix from `<PKG>_PREFIX` env, else a
fixed per-target default (macOS-arm `/opt/homebrew/opt/<pkg>`, Linux `/usr`) — no
`brew` shell-out, so the build is reproducible.
@@ -99,6 +100,17 @@ cargo test -p collision -p converter -p planner --tests
REDIS_URL=redis://localhost:6379 ASSEMBLER_DEV_MODE=true cargo run -p assembler # listens on 0.0.0.0:8000 (PORT to override)
```
+Under `crbn up`, the assembler needs Rust (rustup; `crbn` also finds
+`~/.cargo/bin/cargo` when the shell has not sourced `~/.cargo/env`), and both
+slow builds are shared by every worktree on the machine.
+OCCT is built once into `~/.cache/carbon-occt/8.0.0-p1`
+(`brew install cmake ninja`, then `scripts/build-occt.sh`). FCL comes from
+`brew install fcl`. `crbn up` refuses the assembler, naming the install step,
+until Rust, FCL and OCCT are all present. Cargo builds into
+`~/.cache/carbon-cargo-target` (`assemblerCargoTargetDir`,
+`packages/dev/src/services/apps.ts`), so a new worktree compiles only what its
+branch changed. A `CARGO_TARGET_DIR` you set yourself wins.
+
Env: `REDIS_URL` (required — the job store; boot fails without it),
`ASSEMBLER_SERVICE_API_KEY` (bearer auth), `ASSEMBLER_DEV_MODE=true` (allow
unauth + http + skip TLS verify, local only), `PORT` (8000). Every other limit is
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index a060f16133..0716248d4f 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -27,6 +27,7 @@ import {
} from "@carbon/react";
import { getFileSizeLimit, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { ModelPreview } from "@carbon/viewer/model-preview";
+import { modelPreviewUrls } from "@carbon/viewer/model-upload-preview";
import { OptimizeProgress } from "@carbon/viewer/optimize-progress";
import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -37,7 +38,7 @@ import { useModelUpload, useUser } from "~/hooks";
import type { ModelUpload } from "~/types";
import type { ViewDirection } from "~/utils/model-thumbnail";
import { regenerateModelThumbnail } from "~/utils/model-thumbnail";
-import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
+import { path } from "~/utils/path";
import type { InterruptedUpload } from "~/utils/resumable-upload";
import { InterruptedUploadNotice, UploadProgress } from "./UploadProgress";
@@ -277,41 +278,10 @@ const CadModel = ({
optimizing={backgroundOptimizing}
optimizeFailed={optimizeFailed}
sourceMissing={artifacts?.sourceAvailable === false}
- optimizedUrl={
- artifacts?.optimizedModelPath
- ? // ?v= busts the immutable preview cache on the STABLE
- // optimized.glb path when a re-optimise lands.
- `${getPrivateUrl(artifacts.optimizedModelPath)}${
- artifacts.optimizedAt
- ? `?v=${encodeURIComponent(artifacts.optimizedAt)}`
- : ""
- }`
- : null
- }
- glbUrl={
- artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
- }
- pmiUrl={
- // Unique per optimise run, so no cache-buster is needed.
- artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null
- }
- lodUrl={
- artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
- }
- rawUrl={
- artifacts?.rawPath &&
- (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES
- ? getRawModelUrl(artifacts.rawBucket, artifacts.rawPath)
- : null
- }
+ {...modelPreviewUrls(artifacts)}
rawFile={
file && file.size <= MODEL_RAW_KEEP_MAX_BYTES ? file : null
}
- thumbnailUrl={
- artifacts?.thumbnailPath
- ? getPrivateUrl(artifacts.thumbnailPath)
- : null
- }
mode={mode}
className={viewerClassName}
onRetry={modelPath && canRetry ? onRetry : undefined}
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index c6f69e8b56..709e7d457b 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -26,6 +26,7 @@ import {
withTransaction
} from "@carbon/database/client";
import { toJson } from "@carbon/database/json";
+import { deleteUnusedPmiInspectionPlans } from "@carbon/database/quality";
import { insertRows, many, maybeSingle } from "@carbon/database/rows";
import {
hasPendingApproval,
@@ -685,6 +686,9 @@ async function deleteItemsWithPriceBreaks(
)
.execute();
+ // Plans made from the items' model PMI must not block the delete.
+ await deleteUnusedPmiInspectionPlans(trx, { companyId, itemIds });
+
await trx
.deleteFrom("item")
.where("id", "in", itemIds)
diff --git a/apps/erp/app/modules/quality/AGENTS.md b/apps/erp/app/modules/quality/AGENTS.md
index 5b37cd223f..ababbac6b5 100644
--- a/apps/erp/app/modules/quality/AGENTS.md
+++ b/apps/erp/app/modules/quality/AGENTS.md
@@ -6,7 +6,7 @@ Non-conformances (issues/NCRs), corrective/preventive actions (CAPAs), gauge man
- **Issue (NCR)** — non-conformance record. Statuses: Registered → In Progress → Closed. `isIssueLocked(status)` returns true for Closed. Has 12 association types (items, customers, suppliers, job operations, PO/SO lines, shipment/receipt lines, tracked entities, inspections, RMA lines, supplier return lines).
- **Issue Workflow** — configurable multi-step workflow with action tasks (`nonConformanceActionTask`) and approval tasks (`nonConformanceApprovalTask`). Required actions have `systemType` (Containment, Corrective, Preventive, Verification, Communication) — system actions are protected by trigger.
-- **Inspection Document** — PDF-based drawing with balloon annotations linking to inspection features (dimensions with nominal/tolerance values, optional per-feature sampling rules). Used for FAI, in-process inspection, and — via the item's Receipt-usage assignment — inbound inspection. MUST use `saveInspectionDocumentAtomic` RPC for atomic saves.
+- **Inspection Document** — PDF-based drawing with balloon annotations linking to inspection features (dimensions with nominal/tolerance values, optional per-feature sampling rules). Used for FAI, in-process inspection, and — via the item's Receipt-usage assignment — inbound inspection. MUST use `saveInspectionDocumentAtomic` RPC for atomic saves. A plan can also be made from a STEP model's PMI (`modelUploadId` set, no PDF; features carry `pmiItemId`) by the `pmi-inspection-plan` job — see `.claude/rules/inspection-system.md`.
- **Inspection** — source-document-generic inspection (`sourceDocument`: Receipt or Job Operation; filterable in the list). Receipt-sourced lots are created on receipt posting for items that have a Receipt-usage inspection-document assignment (`itemInspectionDocumentAssignment`); Job Operation lots are created lazily by the MES inspection view (`/x/inspection/{jobOperationId}` in apps/mes) for operations with `operationType = 'Inspection'`, keyed to the operation's `inspectionDocumentId` FK. Uses AQL-based sampling plans (ANSI Z1.4 / ISO 2859-1), resolved **per feature**: feature rule → the inspection document's default rule → All (the per-item sampling plan tier was removed 2026-07-26; sampling is authored entirely in the document editor). Executed full-screen at `/x/inspection/{id}` (list at `/x/quality/inspections`; the document *editor* moved to `/x/inspection-document/{id}`): document-driven lots record measurements in a features × samples grid beside the ballooned drawing (sample status is derived, no override); lots without a document keep manual per-sample Pass/Fail. Tracked entities post as `On Hold` until released by measurement/sample results or disposition. All three terminal statuses (Passed/Failed/Partial) are hard-terminal (2026-07-27): the engine refuses sample/measurement writes on closed lots, and a sample whose verdict already drove a linked `productionQuantity` posting (MES job-op completion) is locked until the ERP deletes that row. **Job Operation lots are verdict-only in the ERP** — their physical outcome (complete / scrap / rework allocation) is orchestrated by the MES disposition route, which closes the lot one-shot (`dispositionInspection` `requireOpen`); receipt lots keep re-disposition (write-off retry) semantics. See `.claude/rules/inspection-system.md`.
- **Gauge** — measurement instrument with calibration tracking. Statuses: Active/Inactive. Roles: Master/Standard.
- **Disposition** — per-item outcome on an NCR. Values include Pending, Return to Supplier, Rework, Scrap, Use As Is (subset active in UI).
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 4289bcf7c9..63820ccab2 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -2318,7 +2318,7 @@ export async function getInspectionSamplingPlans(
return client
.from("inspectionSamplingPlan")
.select(
- "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit, gaugeTypeId, gaugeType(name))"
+ "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit, gaugeTypeId, pmiItemId, gaugeType(name))"
)
.eq("inspectionId", inspectionId)
.eq("companyId", companyId);
@@ -2469,6 +2469,17 @@ function mapInspectionDocument(row: Record<string, unknown>) {
annotations: [],
features: []
},
+ // A plan made from a model's PMI holds the model instead of a PDF.
+ // `modelPath` comes from the `modelUpload(modelPath)` embed when the read
+ // asked for it.
+ model: row.modelUploadId
+ ? {
+ modelUploadId: String(row.modelUploadId),
+ modelPath:
+ ((row.modelUpload as { modelPath?: string | null } | null)
+ ?.modelPath as string | null) ?? null
+ }
+ : null,
// The document's default sampling rule (feature rule -> document default
// -> All). NUMERIC columns arrive as strings from PostgREST — coerce.
sampling: {
@@ -2541,7 +2552,7 @@ export async function getInspectionDocument(
) {
const result = await client
.from("inspectionDocument")
- .select("*")
+ .select("*, modelUpload(modelPath)")
.eq("id", id)
.eq("companyId", companyId)
.single();
@@ -2789,6 +2800,7 @@ function mapInspectionFeature(row: Record<string, unknown>) {
(row.samplingInspectionLevel as string | null) ?? null,
samplingSeverity: (row.samplingSeverity as string | null) ?? null,
gaugeTypeId: (row.gaugeTypeId as string | null) ?? null,
+ pmiItemId: (row.pmiItemId as string | null) ?? null,
balloonId:
typeof balloonIdRaw === "string"
? balloonIdRaw
diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx
index 0b8a87fe6f..9aac6675c8 100644
--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx
+++ b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx
@@ -44,12 +44,14 @@ import {
BALLOON_W_NORM,
clippedBalloonToAnchorLine
} from "@carbon/utils";
+import { ModelUploadPreview } from "@carbon/viewer/model-upload-preview";
import type { ColumnDef } from "@tanstack/react-table";
import {
LuChevronDown,
LuChevronLeft,
LuChevronRight,
LuChevronUp,
+ LuCrosshair,
LuEllipsisVertical,
LuExternalLink,
LuFileDown,
@@ -158,6 +160,9 @@ type InspectionDocumentEditorProps = {
// rule) and the company's sampling standard for previews.
sampling: SamplingRule | null;
samplingStandard: SamplingStandard;
+ // A plan made from a model's PMI holds the model instead of a PDF: the top
+ // pane shows the model and the PDF tools are hidden.
+ model: { modelUploadId: string; modelPath: string | null } | null;
};
type PdfMetrics = {
@@ -340,6 +345,8 @@ type FeatureRow = {
samplingSeverity: SamplingRule["samplingSeverity"];
/** Optional gauge type the feature must be measured with. */
gaugeTypeId: string | null;
+ /** The PMI item a model plan's feature was made from (read-only). */
+ pmiItemId: string | null;
featureDirty?: boolean;
geometryDirty?: boolean;
};
@@ -588,6 +595,7 @@ function mapFeatureRowFromRecords(
samplingSeverity:
(feature.samplingSeverity as SamplingRule["samplingSeverity"]) ?? null,
gaugeTypeId: (feature.gaugeTypeId as string | null) ?? null,
+ pmiItemId: (feature.pmiItemId as string | null) ?? null,
featureDirty: false,
geometryDirty: false
};
@@ -643,13 +651,16 @@ export default function InspectionDocumentEditor({
unitOfMeasures,
gaugeTypes,
sampling,
- samplingStandard
+ samplingStandard,
+ model
}: InspectionDocumentEditorProps) {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
const [items] = useItems();
const deleteDisclosure = useDisclosure();
+ // A model plan: the characteristic whose PMI item the model shows.
+ const [modelFeatureId, setModelFeatureId] = useState<string | null>(null);
const part = partId ? items.find((i) => i.id === partId) : undefined;
const itemMasterLink =
@@ -698,6 +709,15 @@ export default function InspectionDocumentEditor({
const [featureRows, setFeatureRows] = useState<FeatureRow[]>(() =>
buildFeatureRowsFromLoader(initialFeatures, balloons)
);
+ // A model plan: each characteristic's PMI item, for the model pane.
+ const pmiLinks = useMemo(
+ () =>
+ featureRows.map((row) => ({
+ id: row.featureId,
+ pmiItemId: row.pmiItemId
+ })),
+ [featureRows]
+ );
const [placing, setPlacing] = useState(false);
const [placingAnnotation, setPlacingAnnotation] = useState(false);
const [zoomBoxMode, setZoomBoxMode] = useState(false);
@@ -1288,7 +1308,8 @@ export default function InspectionDocumentEditor({
samplingAql: null,
samplingInspectionLevel: null,
samplingSeverity: null,
- gaugeTypeId: null
+ gaugeTypeId: null,
+ pmiItemId: null
}
];
});
@@ -2465,7 +2486,8 @@ export default function InspectionDocumentEditor({
samplingAql: null,
samplingInspectionLevel: null,
samplingSeverity: null,
- gaugeTypeId: null
+ gaugeTypeId: null,
+ pmiItemId: null
}
];
});
@@ -2701,7 +2723,25 @@ export default function InspectionDocumentEditor({
size: 148,
cell: ({ row }) => (
<HStack spacing={1} className="items-center">
- {!row.original.balloonId && (
+ {model && row.original.pmiItemId && (
+ <Button
+ type="button"
+ variant={
+ modelFeatureId === row.original.featureId
+ ? "primary"
+ : "outline"
+ }
+ size="sm"
+ leftIcon={<LuCrosshair className="h-3.5 w-3.5" />}
+ onClick={(e) => {
+ e.stopPropagation();
+ setModelFeatureId(row.original.featureId);
+ }}
+ >
+ {t`Show`}
+ </Button>
+ )}
+ {!model && !row.original.balloonId && (
<Button
type="button"
variant="outline"
@@ -2754,6 +2794,8 @@ export default function InspectionDocumentEditor({
handlePlaceFeatureOnDrawing,
handleUnballoon,
isOverlayReady,
+ model,
+ modelFeatureId,
uomCodeToName,
gaugeTypeIdToName,
t
@@ -2953,24 +2995,26 @@ export default function InspectionDocumentEditor({
) : hasSaved ? (
<span className="text-xs text-muted-foreground">{t`Saved`}</span>
) : null}
- <Button
- variant={placing ? "primary" : "secondary"}
- leftIcon={<LuRectangleHorizontal />}
- onClick={() => {
- setPlacing((v) => {
- const next = !v;
- if (next) {
- setPlacingAnnotation(false);
- setZoomBoxMode(false);
- setPlacingFeatureId(null);
- }
- return next;
- });
- }}
- isDisabled={!isOverlayReady}
- >
- {placing ? t`Drag to place on drawing` : t`Add Selector`}
- </Button>
+ {!model && (
+ <Button
+ variant={placing ? "primary" : "secondary"}
+ leftIcon={<LuRectangleHorizontal />}
+ onClick={() => {
+ setPlacing((v) => {
+ const next = !v;
+ if (next) {
+ setPlacingAnnotation(false);
+ setZoomBoxMode(false);
+ setPlacingFeatureId(null);
+ }
+ return next;
+ });
+ }}
+ isDisabled={!isOverlayReady}
+ >
+ {placing ? t`Drag to place on drawing` : t`Add Selector`}
+ </Button>
+ )}
<Button
type="button"
variant="secondary"
@@ -2979,69 +3023,74 @@ export default function InspectionDocumentEditor({
>
{samplingRuleSummary(docSampling) ?? t`Sampling`}
</Button>
- <HStack
- spacing={0}
- className="ml-1 rounded-md border bg-background px-1 py-1"
- >
- <IconButton
- type="button"
- variant={zoomBoxMode ? "active" : "ghost"}
- size="sm"
- aria-label={zoomBoxMode ? t`Drag to zoom` : t`Zoom Box`}
- icon={<LuScan />}
- isDisabled={!isOverlayReady}
- onClick={() =>
- setZoomBoxMode((v) => {
- const next = !v;
- if (next) {
- setPlacing(false);
- setPlacingAnnotation(false);
- }
- return next;
- })
- }
- />
- <span className="mx-0.5 h-4 w-px bg-border" aria-hidden="true" />
- <IconButton
- type="button"
- variant="ghost"
- size="sm"
- aria-label={t`Zoom out`}
- icon={<LuMinus />}
- onClick={() =>
- setZoomScale((z) => Math.max(0.5, Number((z - 0.1).toFixed(2))))
- }
- />
- <span className="min-w-14 select-none text-center text-sm font-medium">
- {Math.round(zoomScale * 100)}%
- </span>
- <IconButton
- type="button"
- variant="ghost"
- size="sm"
- aria-label={t`Zoom in`}
- icon={<LuPlus />}
- onClick={() =>
- setZoomScale((z) => Math.min(3, Number((z + 0.1).toFixed(2))))
- }
- />
- <span className="mx-0.5 h-4 w-px bg-border" aria-hidden="true" />
- <IconButton
- type="button"
- variant="ghost"
- size="sm"
- aria-label={t`Reset view`}
- icon={<LuMaximize />}
- onClick={() => {
- setZoomScale(1);
- requestAnimationFrame(() => {
- if (!containerRef.current) return;
- containerRef.current.scrollLeft = 0;
- containerRef.current.scrollTop = 0;
- });
- }}
- />
- </HStack>
+ {/* A model plan has no drawing to zoom. */}
+ {!model && (
+ <HStack
+ spacing={0}
+ className="ml-1 rounded-md border bg-background px-1 py-1"
+ >
+ <IconButton
+ type="button"
+ variant={zoomBoxMode ? "active" : "ghost"}
+ size="sm"
+ aria-label={zoomBoxMode ? t`Drag to zoom` : t`Zoom Box`}
+ icon={<LuScan />}
+ isDisabled={!isOverlayReady}
+ onClick={() =>
+ setZoomBoxMode((v) => {
+ const next = !v;
+ if (next) {
+ setPlacing(false);
+ setPlacingAnnotation(false);
+ }
+ return next;
+ })
+ }
+ />
+ <span className="mx-0.5 h-4 w-px bg-border" aria-hidden="true" />
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t`Zoom out`}
+ icon={<LuMinus />}
+ onClick={() =>
+ setZoomScale((z) =>
+ Math.max(0.5, Number((z - 0.1).toFixed(2)))
+ )
+ }
+ />
+ <span className="min-w-14 select-none text-center text-sm font-medium">
+ {Math.round(zoomScale * 100)}%
+ </span>
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t`Zoom in`}
+ icon={<LuPlus />}
+ onClick={() =>
+ setZoomScale((z) => Math.min(3, Number((z + 0.1).toFixed(2))))
+ }
+ />
+ <span className="mx-0.5 h-4 w-px bg-border" aria-hidden="true" />
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t`Reset view`}
+ icon={<LuMaximize />}
+ onClick={() => {
+ setZoomScale(1);
+ requestAnimationFrame(() => {
+ if (!containerRef.current) return;
+ containerRef.current.scrollLeft = 0;
+ containerRef.current.scrollTop = 0;
+ });
+ }}
+ />
+ </HStack>
+ )}
</HStack>
</div>
@@ -3479,6 +3528,18 @@ export default function InspectionDocumentEditor({
</div>
)}
</div>
+ ) : model ? (
+ <div className="h-full w-full">
+ <ModelUploadPreview
+ modelUploadId={model.modelUploadId}
+ modelPath={model.modelPath}
+ companyId={companyId}
+ pmiLinks={pmiLinks}
+ selectedLinkId={modelFeatureId}
+ onLinkSelect={setModelFeatureId}
+ className="h-full rounded-none"
+ />
+ </div>
) : (
<button
type="button"
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
index d75b40ef16..2c6dbe05cd 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
@@ -59,7 +59,7 @@ import {
RecordPhoneChrome
} from "~/components/Layout/RecordHeader";
import { Confirm } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import type {
InspectionGauge,
InspectionIssue,
@@ -80,6 +80,9 @@ import RejectLotModal from "./RejectLotModal";
import ScanInspectionSample from "./ScanInspectionSample";
const InspectionDrawingPane = lazy(() => import("./InspectionDrawingPane"));
+const ModelUploadPreview = lazy(
+ () => import("@carbon/viewer/model-upload-preview")
+);
// Vertical-stack sizing, mirrored from InspectionDocumentEditor: the PDF pane
// keeps a pinned height while the features grid is expanded; a draggable
@@ -130,6 +133,8 @@ export type InspectionViewProps = {
}[];
documentName: string | null;
pdfUrl: string | null;
+ /** A plan made from a model's PMI: the drawing pane shows the model. */
+ model: { modelUploadId: string; modelPath: string | null } | null;
lotEntities: InspectionTrackedEntity[];
issueTypes: IssueTypeListItem[];
/** The issues linked to this lot (a rejected lot's NCR, or a manual link). */
@@ -159,6 +164,7 @@ const InspectionView = ({
balloons,
documentName,
pdfUrl,
+ model,
lotEntities,
issueTypes,
issues,
@@ -167,6 +173,9 @@ const InspectionView = ({
}: InspectionViewProps) => {
const { t } = useLingui();
const permissions = usePermissions();
+ const {
+ company: { id: companyId }
+ } = useUser();
const canUpdate = permissions.can("update", "quality");
const [items] = useItems();
@@ -185,7 +194,7 @@ const InspectionView = ({
// the lot has an assigned PDF; per-feature feature rows show when the
// document resolved features, otherwise the grid collapses to one pass/fail
// "Overall result" row.
- const showDrawing = pdfUrl != null;
+ const showDrawing = pdfUrl != null || model != null;
const hasFeatures = liveFeatures.length > 0;
const scannerDisclosure = useDisclosure();
@@ -464,6 +473,14 @@ const InspectionView = ({
const newIssueHref = `/x/issue/new?itemId=${encodeURIComponent(inspection.itemId)}&trackedEntityIds=${encodeURIComponent(failedTrackedEntityIds.join(","))}${inspection.supplierId ? `&supplierId=${encodeURIComponent(inspection.supplierId)}` : ""}`;
+ const pmiLinks = useMemo(
+ () =>
+ liveFeatures.map((f) => ({
+ id: f.inspectionFeatureId,
+ pmiItemId: f.inspectionFeature!.pmiItemId ?? null
+ })),
+ [liveFeatures]
+ );
const drawingBalloons = useMemo<DrawingBalloon[]>(() => {
const labelByFeatureId = new Map(
liveFeatures.map((f) => [
@@ -677,12 +694,24 @@ const InspectionView = ({
</div>
}
>
- <InspectionDrawingPane
- pdfUrl={pdfUrl!}
- balloons={drawingBalloons}
- activeFeatureId={activeFeatureId}
- onBalloonClick={setActiveFeatureId}
- />
+ {model ? (
+ <ModelUploadPreview
+ modelUploadId={model.modelUploadId}
+ modelPath={model.modelPath}
+ companyId={companyId}
+ pmiLinks={pmiLinks}
+ selectedLinkId={activeFeatureId}
+ onLinkSelect={setActiveFeatureId}
+ className="h-full rounded-none"
+ />
+ ) : (
+ <InspectionDrawingPane
+ pdfUrl={pdfUrl!}
+ balloons={drawingBalloons}
+ activeFeatureId={activeFeatureId}
+ onBalloonClick={setActiveFeatureId}
+ />
+ )}
</Suspense>
)}
</ClientOnly>
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 493eaa0bfa..b39119aba0 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1088,15 +1088,15 @@
{"name":"quality_getGaugeTypes","classification":"READ","schema":"cd40ae40fad5","response":"31ad065cdc4a","permission":"quality:view","paginates":true},
{"name":"quality_getGaugeTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},
{"name":"quality_getInspection","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"quality:view","paginates":false},
- {"name":"quality_getInspectionDocument","classification":"READ","schema":"7f8214d1083f","response":"a82889f583de","permission":"quality:view","paginates":false},
- {"name":"quality_getInspectionDocuments","classification":"READ","schema":"cd40ae40fad5","response":"daa253e3c540","permission":"quality:view","paginates":true},
+ {"name":"quality_getInspectionDocument","classification":"READ","schema":"7f8214d1083f","response":"b0b23204d0fd","permission":"quality:view","paginates":false},
+ {"name":"quality_getInspectionDocuments","classification":"READ","schema":"cd40ae40fad5","response":"8cd7a5845f74","permission":"quality:view","paginates":true},
{"name":"quality_getInspectionDocumentsForItem","classification":"READ","schema":"30ab89ff5be9","response":"cfa5f1f7b8aa","permission":"quality:view","paginates":false},
- {"name":"quality_getInspectionFeatures","classification":"READ","schema":"b6a25994639a","response":"1e8d8f002f21","permission":"quality:view","paginates":false},
+ {"name":"quality_getInspectionFeatures","classification":"READ","schema":"b6a25994639a","response":"ce9a6356909a","permission":"quality:view","paginates":false},
{"name":"quality_getInspectionGauges","classification":"READ","schema":"162c842697ab","response":"68597e017f0d","permission":"quality:view","paginates":false},
{"name":"quality_getInspectionMeasurements","classification":"READ","schema":"162c842697ab","response":"c743640a210d","permission":"quality:view","paginates":false},
{"name":"quality_getInspectionPlan","classification":"READ","schema":"b6a25994639a","response":"83a9b3640e41","permission":"quality:view","paginates":false},
{"name":"quality_getInspections","classification":"READ","schema":"c51c4913cfa1","response":"8c1809e97180","permission":"quality:view","paginates":true},
- {"name":"quality_getInspectionSamplingPlans","classification":"READ","schema":"162c842697ab","response":"fccb92d930f6","permission":"quality:view","paginates":false},
+ {"name":"quality_getInspectionSamplingPlans","classification":"READ","schema":"162c842697ab","response":"7bdcf800065e","permission":"quality:view","paginates":false},
{"name":"quality_getInspectionTrackedEntities","classification":"READ","schema":"76ee331dd860","response":"ec54684c77fb","permission":"quality:view","paginates":false},
{"name":"quality_getIssue","classification":"READ","schema":"9a315debddd5","response":"a1e666efa89c","permission":"quality:view","paginates":false},
{"name":"quality_getIssueActionTasks","classification":"READ","schema":"3c597e8cd46b","response":"7a21aafdb718","permission":"quality:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/inspection+/$id.tsx b/apps/erp/app/routes/x+/inspection+/$id.tsx
index 76a8e4d59e..936aeeb957 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.tsx
@@ -142,6 +142,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const doc = document.data as {
name?: string | null;
content?: { pdfUrl?: string | null };
+ model?: { modelUploadId: string; modelPath: string | null } | null;
} | null;
return data({
@@ -170,6 +171,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})),
documentName: doc?.name ?? null,
pdfUrl: doc?.content?.pdfUrl ?? null,
+ model: doc?.model ?? null,
lotEntities: (lotEntities.data ?? []) as InspectionTrackedEntity[],
issueTypes: (issueTypes.data ?? []) as IssueTypeListItem[],
issues: (issues.data ?? [])
@@ -201,6 +203,7 @@ export default function InspectionExecutionRoute() {
balloons={loaderData.balloons}
documentName={loaderData.documentName}
pdfUrl={loaderData.pdfUrl}
+ model={loaderData.model}
lotEntities={loaderData.lotEntities as InspectionTrackedEntity[]}
issueTypes={loaderData.issueTypes as IssueTypeListItem[]}
issues={loaderData.issues}
diff --git a/apps/erp/app/routes/x+/inspection-document+/$id.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.tsx
index f857e274bb..c927bd711d 100644
--- a/apps/erp/app/routes/x+/inspection-document+/$id.tsx
+++ b/apps/erp/app/routes/x+/inspection-document+/$id.tsx
@@ -154,6 +154,7 @@ export default function BalloonDetailRoute() {
gaugeTypes={gaugeTypes}
sampling={(diagram.sampling as SamplingRule | null) ?? null}
samplingStandard={samplingStandard}
+ model={diagram.model}
/>
</Suspense>
)}
diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsx
index ae8caa80fa..e1f1848142 100644
--- a/apps/mes/app/components/Inspection/InspectionView.tsx
+++ b/apps/mes/app/components/Inspection/InspectionView.tsx
@@ -81,6 +81,9 @@ import InspectionMeasurementMatrix from "./InspectionMeasurementMatrix";
import ScanInspectionSample from "./ScanInspectionSample";
const InspectionDrawingPane = lazy(() => import("./InspectionDrawingPane"));
+const ModelUploadPreview = lazy(
+ () => import("@carbon/viewer/model-upload-preview")
+);
// Vertical-stack sizing, mirrored from the ERP quality InspectionView: the PDF
// pane keeps a pinned height while the features table is expanded; a draggable
@@ -139,6 +142,8 @@ type InspectionViewProps = {
balloons: DrawingBalloonRow[];
documentName: string | null;
pdfUrl: string | null;
+ /** A plan made from a model's PMI: the drawing pane shows the model. */
+ model: { modelUploadId: string; modelPath: string | null } | null;
issueTypes: IssueTypeListItem[];
trackedEntities: TrackedEntity[];
requiresSerialTracking: boolean;
@@ -171,6 +176,7 @@ export function InspectionView({
balloons,
documentName,
pdfUrl,
+ model,
issueTypes,
trackedEntities,
requiresSerialTracking,
@@ -198,7 +204,7 @@ export function InspectionView({
[features]
);
const hasFeatures = liveFeatures.length > 0;
- const showDrawing = pdfUrl != null;
+ const showDrawing = pdfUrl != null || model != null;
const scannerDisclosure = useDisclosure();
const rejectDisclosure = useDisclosure();
@@ -554,6 +560,14 @@ export function InspectionView({
.filter(Boolean) as FailedFeatureSummary[];
}, [hasFeatures, liveFeatures, effectiveMeasurements]);
+ const pmiLinks = useMemo(
+ () =>
+ liveFeatures.map((f) => ({
+ id: f.inspectionFeatureId,
+ pmiItemId: f.inspectionFeature!.pmiItemId ?? null
+ })),
+ [liveFeatures]
+ );
const drawingBalloons = useMemo(() => {
const labelByFeatureId = new Map(
liveFeatures.map((f) => [
@@ -841,12 +855,24 @@ export function InspectionView({
</div>
}
>
- <InspectionDrawingPane
- pdfUrl={pdfUrl!}
- balloons={drawingBalloons}
- activeFeatureId={activeFeatureId}
- onBalloonClick={setActiveFeatureId}
- />
+ {model ? (
+ <ModelUploadPreview
+ modelUploadId={model.modelUploadId}
+ modelPath={model.modelPath}
+ companyId={user.company.id}
+ pmiLinks={pmiLinks}
+ selectedLinkId={activeFeatureId}
+ onLinkSelect={setActiveFeatureId}
+ className="h-full rounded-none"
+ />
+ ) : (
+ <InspectionDrawingPane
+ pdfUrl={pdfUrl!}
+ balloons={drawingBalloons}
+ activeFeatureId={activeFeatureId}
+ onBalloonClick={setActiveFeatureId}
+ />
+ )}
</Suspense>
)}
</ClientOnly>
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index aa8440ab9c..fe54ac79bc 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -72,10 +72,10 @@ import {
convertDateStringToIsoString,
formatDate,
formatDurationMilliseconds,
- MODEL_RAW_KEEP_MAX_BYTES,
round
} from "@carbon/utils";
import { ModelPreview } from "@carbon/viewer/model-preview";
+import { modelPreviewUrls } from "@carbon/viewer/model-upload-preview";
import { OptimizeProgress } from "@carbon/viewer/optimize-progress";
import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
@@ -144,7 +144,7 @@ import type {
import { useItems } from "~/stores";
import { makeDurations } from "~/utils/durations";
import { useOrigin } from "~/utils/origin";
-import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
+import { path } from "~/utils/path";
import ItemThumbnail from "../ItemThumbnail";
import { MesAppBar } from "../MesAppBar";
import { BatchCompleteModal } from "./components/BatchCompleteModal";
@@ -2251,38 +2251,7 @@ export const JobOperation = ({
optimizing={backgroundOptimizing}
optimizeFailed={optimizeFailed}
sourceMissing={artifacts?.sourceAvailable === false}
- optimizedUrl={
- artifacts?.optimizedModelPath
- ? // ?v= busts the immutable preview cache on the STABLE
- // optimized.glb path when a re-optimise lands.
- `${getPrivateUrl(artifacts.optimizedModelPath)}${
- artifacts.optimizedAt
- ? `?v=${encodeURIComponent(artifacts.optimizedAt)}`
- : ""
- }`
- : null
- }
- glbUrl={
- artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
- }
- pmiUrl={
- // Unique per optimise run, so no cache-buster is needed.
- artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null
- }
- lodUrl={
- artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
- }
- rawUrl={
- artifacts?.rawPath &&
- (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES
- ? getRawModelUrl(artifacts.rawBucket, artifacts.rawPath)
- : null
- }
- thumbnailUrl={
- artifacts?.thumbnailPath
- ? getPrivateUrl(artifacts.thumbnailPath)
- : null
- }
+ {...modelPreviewUrls(artifacts)}
mode={mode}
className="rounded-none"
onRetry={canRetry ? onModelRetry : undefined}
diff --git a/apps/mes/app/routes/x+/inspection.$operationId.tsx b/apps/mes/app/routes/x+/inspection.$operationId.tsx
index aad69bab6e..24650c1f96 100644
--- a/apps/mes/app/routes/x+/inspection.$operationId.tsx
+++ b/apps/mes/app/routes/x+/inspection.$operationId.tsx
@@ -254,7 +254,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobId: job.data.id ?? null,
balloons: document?.data?.balloons ?? [],
documentName: document?.data?.name ?? null,
- pdfUrl: document?.data?.pdfUrl ?? null
+ pdfUrl: document?.data?.pdfUrl ?? null,
+ model: document?.data?.model ?? null
};
}
diff --git a/apps/mes/app/services/quality.service.ts b/apps/mes/app/services/quality.service.ts
index 5a5b375e49..7a42245fcd 100644
--- a/apps/mes/app/services/quality.service.ts
+++ b/apps/mes/app/services/quality.service.ts
@@ -32,7 +32,7 @@ export async function getInspectionSamplingPlans(
return client
.from("inspectionSamplingPlan")
.select(
- "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit, gaugeTypeId, gaugeType(name))"
+ "*, inspectionFeature(id, label, description, pageNumber, type, nominalValue, tolerancePlus, toleranceMinus, unit, gaugeTypeId, pmiItemId, gaugeType(name))"
)
.eq("inspectionId", inspectionId)
.eq("companyId", companyId);
@@ -96,8 +96,8 @@ export async function getIssueTypesList(
.order("name");
}
-// The drawing pane needs the document's display name, its PDF preview URL, and
-// the balloon coordinates. This is a simplified read of what the ERP
+// The drawing pane needs the document's display name, its PDF preview URL (or
+// the model of a plan made from PMI), and the balloon coordinates. This is a simplified read of what the ERP
// quality module assembles via mapInspectionDocument/mapBalloon.
export async function getInspectionDocumentWithBalloons(
client: SupabaseClient<Database>,
@@ -106,7 +106,9 @@ export async function getInspectionDocumentWithBalloons(
const [document, balloons] = await Promise.all([
client
.from("inspectionDocument")
- .select("id, drawingNumber, fileName, storagePath")
+ .select(
+ "id, drawingNumber, fileName, storagePath, modelUploadId, modelUpload(modelPath)"
+ )
.eq("id", inspectionDocumentId)
.single(),
client
@@ -133,7 +135,14 @@ export async function getInspectionDocumentWithBalloons(
? storagePath
: `/file/preview/private/${storagePath}`
: null,
- balloons: balloons.data ?? []
+ balloons: balloons.data ?? [],
+ // A plan made from a model's PMI holds the model instead of a PDF.
+ model: document.data?.modelUploadId
+ ? {
+ modelUploadId: document.data.modelUploadId,
+ modelPath: document.data.modelUpload?.modelPath ?? null
+ }
+ : null
},
error: null
};
diff --git a/docs/content/docs/reference/inspections.mdx b/docs/content/docs/reference/inspections.mdx
index 44bcad410d..d758bc770e 100644
--- a/docs/content/docs/reference/inspections.mdx
+++ b/docs/content/docs/reference/inspections.mdx
@@ -107,6 +107,18 @@ Balloons anchor to a region of a specific PDF page (normalized 0–1 coordinates
Inspection plans live under **Quality → Inspection → Inspection Plans**. The editor has no Save button: each change saves itself a moment after you stop editing, and the toolbar shows **Saving…**, **Saved**, or **Could not save**.
+### Plans from a model's PMI
+
+A STEP AP242 model can carry its own dimensions and geometric tolerances (PMI, the model-based definition). When you upload such a model to a part, Carbon reads the PMI and makes an inspection plan for that part on its own. The plan holds the 3D model instead of a PDF:
+
+- Each dimension and each geometric tolerance becomes one characteristic, numbered in the model's order. Datums and notes are left out, because they have nothing to measure.
+- A ± dimension keeps its nominal and tolerances. A limit dimension, or one whose tolerances are both above or both below the nominal, is centred on its band, so a reading passes exactly between the drawing's limits.
+- A geometric tolerance is measured as a deviation: nominal 0, with the tolerance zone as the upper limit.
+- A dimension with no numeric tolerance (a fit class only, a min or max) is recorded Pass or Fail.
+- Lengths are in the model's own unit (mm or in); angles are in degrees.
+
+The plan is made once for each part and model. Uploading the same model again does not change it, so your edits are kept; a new model on the part makes a new plan. Assign it to receipts or an inspection operation like any other plan. While you record measurements, the model takes the drawing's place: picking a characteristic highlights its annotation on the model and turns the view to it, and picking an annotation on the model picks its characteristic.
+
### Gauges
A characteristic can name the [gauge](/docs/reference/calibration) type it must be measured with, in the plan editor's **Gauge Type** column. Leave it empty to allow any gauge.
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index ea3cff5905..a194cebdea 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -402,10 +402,10 @@
"no-raw-rounding::apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
"no-raw-rounding::apps/erp/app/modules/quality/samplingStandards.ts::const n = Math.max(1, Math.min(safeLot, Math.ceil((safeLot * pct) / 100)));",
"no-raw-rounding::apps/erp/app/modules/quality/samplingStandards.ts::const safeLot = Math.max(1, Math.floor(lotSize));",
+ "no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::Math.max(0.5, Number((z - 0.1).toFixed(2)))",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::Math.min(26, Math.round(radius * 1.15))",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::Math.min(3, Number((zoomScale * Math.min(fitX, fitY)).toFixed(2)))",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::aria-valuenow={Math.round(pdfPaneHeightPx)}",
- "no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::setZoomScale((z) => Math.max(0.5, Number((z - 0.1).toFixed(2))))",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::setZoomScale((z) => Math.min(3, Number((z + 0.1).toFixed(2))))",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx::{Math.round(zoomScale * 100)}%",
"no-raw-rounding::apps/erp/app/modules/quality/ui/InspectionDocument/drawingRaster.ts::Math.max(1, Math.floor(renderedPageWidthPx * VISION_RENDER_SCALE)),",
diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.ts
index e5aeba0f44..d6f0e0005d 100644
--- a/packages/database/src/event-system/attachments.ts
+++ b/packages/database/src/event-system/attachments.ts
@@ -124,7 +124,11 @@ export const attachments = {
"sync_propagate_item_readable_id_to_tracked_entity"
],
events: true,
- statement: ["broadcast_table_changes", "log_table_changes"]
+ statement: [
+ "broadcast_table_changes",
+ "log_table_changes",
+ "queue_pmi_inspection_plans"
+ ]
},
itemCost: { events: true },
itemLedger: {
diff --git a/packages/database/src/event-system/handlers/queue_pmi_inspection_plans.sql b/packages/database/src/event-system/handlers/queue_pmi_inspection_plans.sql
new file mode 100644
index 0000000000..189a4534b5
--- /dev/null
+++ b/packages/database/src/event-system/handlers/queue_pmi_inspection_plans.sql
@@ -0,0 +1,57 @@
+CREATE OR REPLACE FUNCTION public.queue_pmi_inspection_plans()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ link RECORD;
+BEGIN
+ -- A seed, a restore or a sync loads items in bulk; their plans come with them.
+ IF TG_OP = 'DELETE' OR current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- An item that starts using a model whose PMI was already read gets an
+ -- inspection plan made from that PMI (a new revision, a converted quote
+ -- line, an existing model attached to a part). A model whose PMI is read
+ -- later is covered by model-optimize, which sends the same event.
+ IF TG_OP = 'INSERT' THEN
+ FOR link IN
+ SELECT n."id" AS "itemId", n."companyId", n."modelUploadId"
+ FROM batched_new n
+ JOIN "modelUpload" m ON m."id" = n."modelUploadId"
+ WHERE m."pmiPath" IS NOT NULL
+ LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/pmi-inspection-plan',
+ jsonb_build_object(
+ 'companyId', link."companyId",
+ 'modelUploadId', link."modelUploadId",
+ 'itemId', link."itemId"
+ )
+ );
+ END LOOP;
+ ELSE
+ FOR link IN
+ SELECT n."id" AS "itemId", n."companyId", n."modelUploadId"
+ FROM batched_new n
+ JOIN batched_old o ON o."id" = n."id"
+ JOIN "modelUpload" m ON m."id" = n."modelUploadId"
+ WHERE n."modelUploadId" IS DISTINCT FROM o."modelUploadId"
+ AND m."pmiPath" IS NOT NULL
+ LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/pmi-inspection-plan',
+ jsonb_build_object(
+ 'companyId', link."companyId",
+ 'modelUploadId', link."modelUploadId",
+ 'itemId', link."itemId"
+ )
+ );
+ END LOOP;
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
diff --git a/packages/database/src/pmi-inspection-plan.test.ts b/packages/database/src/pmi-inspection-plan.test.ts
new file mode 100644
index 0000000000..45091becbd
--- /dev/null
+++ b/packages/database/src/pmi-inspection-plan.test.ts
@@ -0,0 +1,221 @@
+// 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 { randomUUID } from "node:crypto";
+import type { DatabaseConnection } from "kysely";
+import { CompiledQuery, Kysely, PostgresDialect, PostgresDriver } from "kysely";
+import { Client } from "pg";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import type { KyselyDatabase } from "./client.ts";
+import {
+ createPmiInspectionPlan,
+ deleteUnusedPmiInspectionPlans,
+ type PmiPlanCharacteristic
+} from "./quality.ts";
+
+// Runs against the local database, like inspection-gauge.test.ts:
+// SUPABASE_DB_URL=… pnpm --filter @carbon/database test -- pmi-inspection-plan
+//
+// Each test runs inside one transaction that is always rolled back. Fixtures
+// are inserted with `session_replication_role = replica` (FKs and triggers
+// off); the partial unique index `inspectionDocument_part_model_key` still
+// holds, which is what makes a second plan for one item and model a no-op.
+const url = process.env.SUPABASE_DB_URL;
+
+class SavepointDriver extends PostgresDriver {
+ override async beginTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(CompiledQuery.raw("SAVEPOINT engine"));
+ }
+ override async commitTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(
+ CompiledQuery.raw("RELEASE SAVEPOINT engine")
+ );
+ }
+ override async rollbackTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(
+ CompiledQuery.raw("ROLLBACK TO SAVEPOINT engine")
+ );
+ }
+}
+
+describe.skipIf(!url)(
+ "PMI inspection plans against a migrated database",
+ () => {
+ const client = new Client({ connectionString: url });
+ const config = {
+ pool: {
+ connect: async () =>
+ Object.assign(client, { release: () => undefined }),
+ end: async () => undefined
+ }
+ };
+ const dialect = new PostgresDialect(config);
+ const db = new Kysely<KyselyDatabase>({
+ dialect: {
+ createAdapter: () => dialect.createAdapter(),
+ createDriver: () => new SavepointDriver(config),
+ createIntrospector: (k) => dialect.createIntrospector(k),
+ createQueryCompiler: () => dialect.createQueryCompiler()
+ }
+ });
+
+ const run = randomUUID().slice(0, 8);
+ const id = (name: string) => `t-${run}-${name}`;
+ const companyId = id("company");
+ const model = id("model");
+
+ const characteristics: PmiPlanCharacteristic[] = [
+ {
+ pmiItemId: "d1",
+ label: "1",
+ description: "Diameter ⌀10 ±0.05",
+ nominalValue: "10",
+ tolerancePlus: "0.05",
+ toleranceMinus: "0.05",
+ unit: "mm"
+ },
+ {
+ pmiItemId: "t1",
+ label: "2",
+ description: "Flatness ⏥ | 0.02",
+ nominalValue: "0",
+ tolerancePlus: "0.02",
+ toleranceMinus: "0",
+ unit: "mm"
+ }
+ ];
+
+ async function begin() {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL session_replication_role = replica");
+ }
+
+ async function insertItem(itemId: string, readableId: string) {
+ await client.query(
+ `INSERT INTO "item" ("id", "companyId", "readableId", "name", "type", "itemTrackingType", "createdBy")
+ VALUES ($1, $2, $3, 'Bracket', 'Part', 'Inventory', 'system')`,
+ [itemId, companyId, readableId]
+ );
+ }
+
+ const createPlan = (itemId: string) =>
+ db.transaction().execute((trx) =>
+ createPmiInspectionPlan(trx, {
+ companyId,
+ itemId,
+ modelUploadId: model,
+ characteristics,
+ createdBy: "system"
+ })
+ );
+
+ beforeAll(async () => {
+ await client.connect();
+ });
+
+ afterEach(async () => {
+ await client.query("ROLLBACK");
+ });
+
+ afterAll(async () => {
+ await client.end();
+ });
+
+ it("makes one plan per item and model, with a feature per characteristic", async () => {
+ await begin();
+ await insertItem(id("item"), id("BRK"));
+
+ const planId = await createPlan(id("item"));
+ expect(planId).not.toBeNull();
+ // A second event for the same item and model (a re-optimise) makes none.
+ expect(await createPlan(id("item"))).toBeNull();
+
+ const plans = await client.query(
+ `SELECT "drawingNumber", "storagePath" FROM "inspectionDocument"
+ WHERE "companyId" = $1 AND "partId" = $2 AND "modelUploadId" = $3`,
+ [companyId, id("item"), model]
+ );
+ expect(plans.rows).toEqual([
+ { drawingNumber: id("BRK"), storagePath: null }
+ ]);
+
+ const features = await client.query(
+ `SELECT "label", "pmiItemId", "pageNumber", "type", "nominalValue"
+ FROM "inspectionFeature" WHERE "inspectionDocumentId" = $1 ORDER BY "label"`,
+ [planId]
+ );
+ expect(features.rows).toEqual([
+ {
+ label: "1",
+ pmiItemId: "d1",
+ pageNumber: 1,
+ type: "Measurement",
+ nominalValue: "10"
+ },
+ {
+ label: "2",
+ pmiItemId: "t1",
+ pageNumber: 1,
+ type: "Measurement",
+ nominalValue: "0"
+ }
+ ]);
+ });
+
+ it("suffixes a drawing number another plan already holds", async () => {
+ await begin();
+ await insertItem(id("item"), id("BRK"));
+ await client.query(
+ `INSERT INTO "inspectionDocument" ("id", "companyId", "partId", "drawingNumber", "createdBy")
+ VALUES ($1, $2, $3, $4, 'system')`,
+ [id("pdf-plan"), companyId, id("item"), id("BRK")]
+ );
+
+ const planId = await createPlan(id("item"));
+ const plan = await client.query(
+ `SELECT "drawingNumber" FROM "inspectionDocument" WHERE "id" = $1`,
+ [planId]
+ );
+ expect(plan.rows[0].drawingNumber).toBe(`${id("BRK")} (1)`);
+ });
+
+ it("deletes the items' unused PMI plans before an item delete, and keeps the rest", async () => {
+ await begin();
+ await insertItem(id("item"), id("BRK"));
+ const unused = await createPlan(id("item"));
+ await insertItem(id("item-used"), id("BRK-USED"));
+ const used = await createPlan(id("item-used"));
+ await client.query(
+ `INSERT INTO "inspection" ("id", "companyId", "inspectionId", "itemId", "lotSize",
+ "samplingStandard", "samplingPlanType", "sampleSize", "acceptanceNumber",
+ "rejectionNumber", "sourceDocument", "sourceDocumentId", "inspectionDocumentId", "createdBy")
+ VALUES ($1, $2, $1, $3, 1, 'ANSI_Z1_4', 'All', 1, 0, 1, 'Receipt', $4, $5, 'system')`,
+ [id("lot"), companyId, id("item-used"), id("receipt"), used]
+ );
+ // A plan made by hand (no model) is never touched.
+ await client.query(
+ `INSERT INTO "inspectionDocument" ("id", "companyId", "partId", "drawingNumber", "createdBy")
+ VALUES ($1, $2, $3, 'Manual', 'system')`,
+ [id("manual"), companyId, id("item")]
+ );
+
+ const deleted = await db.transaction().execute((trx) =>
+ deleteUnusedPmiInspectionPlans(trx, {
+ companyId,
+ itemIds: [id("item"), id("item-used")]
+ })
+ );
+ expect(deleted).toBe(1);
+
+ const left = await client.query(
+ `SELECT "id" FROM "inspectionDocument" WHERE "companyId" = $1 ORDER BY "id"`,
+ [companyId]
+ );
+ expect(left.rows.map((row) => row.id).sort()).toEqual(
+ [used, id("manual")].sort()
+ );
+ expect(left.rows.map((row) => row.id)).not.toContain(unused);
+ });
+ }
+);
diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.ts
index 860bcd6928..7deaf1c58f 100644
--- a/packages/database/src/quality.ts
+++ b/packages/database/src/quality.ts
@@ -1552,3 +1552,151 @@ export async function lockIssueDispositions(
if (!issue) throw new Error("Issue not found");
return { status: issue.status };
}
+
+/** One characteristic of a plan made from a model's PMI (`pmiInspectionCharacteristics`). */
+export type PmiPlanCharacteristic = {
+ pmiItemId: string;
+ label: string;
+ description: string;
+ nominalValue: string | null;
+ tolerancePlus: string | null;
+ toleranceMinus: string | null;
+ unit: string;
+};
+
+/**
+ * Makes the inspection plan for an item from its model's PMI: a plan that
+ * holds the model and no PDF, with one Measurement feature per
+ * characteristic. Runs in the caller's transaction. Returns the new plan's
+ * id, or null when the item already has a plan for this model — the partial
+ * unique index `inspectionDocument_part_model_key` decides, so two runs for
+ * one model never make two plans and an edited plan is never rewritten.
+ *
+ * The drawing number follows the editor's rule for a plan created without
+ * one: the item's `readableIdWithRevision`, with ` (1)`, ` (2)` … when taken.
+ */
+export async function createPmiInspectionPlan(
+ trx: Transaction<KyselyDatabase>,
+ args: {
+ companyId: string;
+ itemId: string;
+ modelUploadId: string;
+ characteristics: readonly PmiPlanCharacteristic[];
+ createdBy: string;
+ }
+): Promise<string | null> {
+ const { companyId, itemId, modelUploadId, characteristics, createdBy } = args;
+
+ const item = await trx
+ .selectFrom("item")
+ .select(["readableIdWithRevision"])
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!item) return null;
+
+ const base = item.readableIdWithRevision?.trim() || null;
+ let drawingNumber = base;
+ if (base) {
+ const taken = new Set(
+ (
+ await trx
+ .selectFrom("inspectionDocument")
+ .select(["drawingNumber"])
+ .where("companyId", "=", companyId)
+ .where((eb) =>
+ eb.or([
+ eb("drawingNumber", "=", base),
+ eb("drawingNumber", "like", `${base} (%)`)
+ ])
+ )
+ .execute()
+ ).map((row) => row.drawingNumber)
+ );
+ let suffix = 0;
+ while (drawingNumber && taken.has(drawingNumber)) {
+ suffix += 1;
+ drawingNumber = `${base} (${suffix})`;
+ }
+ }
+
+ const plan = await trx
+ .insertInto("inspectionDocument")
+ .values({
+ companyId,
+ partId: itemId,
+ modelUploadId,
+ drawingNumber,
+ createdBy
+ })
+ .onConflict((oc) =>
+ oc
+ .columns(["companyId", "partId", "modelUploadId"])
+ .where("modelUploadId", "is not", null)
+ .doNothing()
+ )
+ .returning(["id"])
+ .executeTakeFirst();
+ if (!plan) return null;
+
+ if (characteristics.length > 0) {
+ await trx
+ .insertInto("inspectionFeature")
+ .values(
+ characteristics.map((c) => ({
+ companyId,
+ inspectionDocumentId: plan.id,
+ // A model plan has one "page": the save RPC defaults to 1 as well,
+ // and the label trigger keeps labels unique across the plan.
+ pageNumber: 1,
+ label: c.label,
+ description: c.description,
+ nominalValue: c.nominalValue,
+ tolerancePlus: c.tolerancePlus,
+ toleranceMinus: c.toleranceMinus,
+ unit: c.unit,
+ type: "Measurement" as const,
+ pmiItemId: c.pmiItemId,
+ createdBy
+ }))
+ )
+ .execute();
+ }
+
+ return plan.id;
+}
+
+/**
+ * Deletes the plans made from the items' model PMI that no inspection used,
+ * in the caller's transaction, ahead of an item delete. A plan made for the
+ * item, not by a person, must not block the delete through
+ * `inspectionDocument.partId`'s RESTRICT. A used one is inspection history and
+ * still refuses it, as a plan made by hand does. Returns how many it deleted.
+ */
+export async function deleteUnusedPmiInspectionPlans(
+ trx: Transaction<KyselyDatabase>,
+ args: { companyId: string; itemIds: readonly string[] }
+): Promise<number> {
+ if (args.itemIds.length === 0) return 0;
+ const result = await trx
+ .deleteFrom("inspectionDocument")
+ .where("companyId", "=", args.companyId)
+ .where("partId", "in", [...args.itemIds])
+ .where("modelUploadId", "is not", null)
+ .where((eb) =>
+ eb.not(
+ eb.exists(
+ eb
+ .selectFrom("inspection")
+ .select("inspection.id")
+ .whereRef(
+ "inspection.inspectionDocumentId",
+ "=",
+ "inspectionDocument.id"
+ )
+ )
+ )
+ )
+ .executeTakeFirst();
+ return Number(result.numDeletedRows);
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0e437ea639..19d42842af 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -61098,6 +61098,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionFeature.gaugeTypeId"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.pmiItemId"
+ },
{
$ref: "#/parameters/select"
},
@@ -61223,6 +61226,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionFeature.gaugeTypeId"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.pmiItemId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -61302,6 +61308,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionFeature.gaugeTypeId"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionFeature.pmiItemId"
+ },
{
$ref: "#/parameters/body.inspectionFeature"
},
@@ -62814,6 +62823,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.modelUploadId"
+ },
{
$ref: "#/parameters/select"
},
@@ -62936,6 +62948,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.modelUploadId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -63012,6 +63027,9 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocument.samplingSeverity"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocument.modelUploadId"
+ },
{
$ref: "#/parameters/body.inspectionDocument"
},
@@ -93750,6 +93768,27 @@ export default {
{
$ref: "#/parameters/rowFilter.inspectionDocuments.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingPlanType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingSampleSize"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingPercentage"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingAql"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingInspectionLevel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.samplingSeverity"
+ },
+ {
+ $ref: "#/parameters/rowFilter.inspectionDocuments.modelUploadId"
+ },
{
$ref: "#/parameters/rowFilter.inspectionDocuments.partReadableId"
},
@@ -147301,6 +147340,10 @@ export default {
"Note:\nThis is a Foreign Key to `gaugeType.id`.<fk table='gaugeType' column='id'/>",
format: "text",
type: "string"
+ },
+ pmiItemId: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -147961,6 +148004,12 @@ export default {
enum: ["Normal", "Tightened", "Reduced"],
format: 'public."inspectionSeverity"',
type: "string"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -162998,6 +163047,39 @@ export default {
format: "timestamp with time zone",
type: "string"
},
+ samplingPlanType: {
+ enum: ["All", "First", "Percentage", "AQL"],
+ format: 'public."samplingPlanType"',
+ type: "string"
+ },
+ samplingSampleSize: {
+ format: "integer",
+ type: "integer"
+ },
+ samplingPercentage: {
+ format: "numeric",
+ type: "number"
+ },
+ samplingAql: {
+ format: "numeric",
+ type: "number"
+ },
+ samplingInspectionLevel: {
+ enum: ["I", "II", "III", "S1", "S2", "S3", "S4"],
+ format: 'public."inspectionLevel"',
+ type: "string"
+ },
+ samplingSeverity: {
+ enum: ["Normal", "Tightened", "Reduced"],
+ format: 'public."inspectionSeverity"',
+ type: "string"
+ },
+ modelUploadId: {
+ description:
+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",
+ format: "text",
+ type: "string"
+ },
partReadableId: {
format: "text",
type: "string"
@@ -200796,6 +200878,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.inspectionFeature.pmiItemId": {
+ name: "pmiItemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.itarCertification": {
name: "itarCertification",
description: "itarCertification",
@@ -201528,6 +201616,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.inspectionDocument.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.supplierQuote": {
name: "supplierQuote",
description: "supplierQuote",
@@ -218322,6 +218416,48 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.inspectionDocuments.samplingPlanType": {
+ name: "samplingPlanType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.samplingSampleSize": {
+ name: "samplingSampleSize",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.samplingPercentage": {
+ name: "samplingPercentage",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.samplingAql": {
+ name: "samplingAql",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.samplingInspectionLevel": {
+ name: "samplingInspectionLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.samplingSeverity": {
+ name: "samplingSeverity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.inspectionDocuments.modelUploadId": {
+ name: "modelUploadId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.inspectionDocuments.partReadableId": {
name: "partReadableId",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 3688e81eee..be1f2e5246 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -21986,6 +21986,7 @@ export type Database = {
drawingNumber: string | null
fileName: string | null
id: string
+ modelUploadId: string | null
pageCount: number | null
partId: string
samplingAql: number | null
@@ -22015,6 +22016,7 @@ export type Database = {
drawingNumber?: string | null
fileName?: string | null
id?: string
+ modelUploadId?: string | null
pageCount?: number | null
partId: string
samplingAql?: number | null
@@ -22044,6 +22046,7 @@ export type Database = {
drawingNumber?: string | null
fileName?: string | null
id?: string
+ modelUploadId?: string | null
pageCount?: number | null
partId?: string
samplingAql?: number | null
@@ -22128,6 +22131,27 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
{
foreignKeyName: "inspectionDocument_partId_fkey"
columns: ["partId"]
@@ -22254,6 +22278,7 @@ export type Database = {
label: string
nominalValue: string | null
pageNumber: number
+ pmiItemId: string | null
samplingAql: number | null
samplingInspectionLevel:
| Database["public"]["Enums"]["inspectionLevel"]
@@ -22284,6 +22309,7 @@ export type Database = {
label: string
nominalValue?: string | null
pageNumber: number
+ pmiItemId?: string | null
samplingAql?: number | null
samplingInspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
@@ -22314,6 +22340,7 @@ export type Database = {
label?: string
nominalValue?: string | null
pageNumber?: number
+ pmiItemId?: string | null
samplingAql?: number | null
samplingInspectionLevel?:
| Database["public"]["Enums"]["inspectionLevel"]
@@ -77168,9 +77195,22 @@ export type Database = {
drawingNumber: string | null
fileName: string | null
id: string | null
+ modelUploadId: string | null
pageCount: number | null
partId: string | null
partReadableId: string | null
+ samplingAql: number | null
+ samplingInspectionLevel:
+ | Database["public"]["Enums"]["inspectionLevel"]
+ | null
+ samplingPercentage: number | null
+ samplingPlanType:
+ | Database["public"]["Enums"]["samplingPlanType"]
+ | null
+ samplingSampleSize: number | null
+ samplingSeverity:
+ | Database["public"]["Enums"]["inspectionSeverity"]
+ | null
storagePath: string | null
updatedAt: string | null
updatedBy: string | null
@@ -77241,6 +77281,27 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "inspectionDocument_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
{
foreignKeyName: "inspectionDocument_partId_fkey"
columns: ["partId"]
diff --git a/packages/database/supabase/migrations/20261027122437_pmi-inspection-plans.sql b/packages/database/supabase/migrations/20261027122437_pmi-inspection-plans.sql
new file mode 100644
index 0000000000..0dffa3e64d
--- /dev/null
+++ b/packages/database/supabase/migrations/20261027122437_pmi-inspection-plans.sql
@@ -0,0 +1,32 @@
+-- Inspection plans made from a STEP model's PMI (spec
+-- .ai/specs/2026-10-27-pmi-inspection-plans.md). A model plan holds the model
+-- it was made from and no PDF; each of its features names the PMI item
+-- (`pmi.json` id, e.g. `d1`, `t3`) it was made from, so the inspection screens
+-- can select that item on the model.
+
+ALTER TABLE "inspectionDocument"
+ ADD COLUMN IF NOT EXISTS "modelUploadId" TEXT
+ REFERENCES "modelUpload"("id") ON DELETE SET NULL;
+
+ALTER TABLE "inspectionFeature"
+ ADD COLUMN IF NOT EXISTS "pmiItemId" TEXT;
+
+-- One plan per item and model: the pmi-inspection-plan job inserts with
+-- ON CONFLICT DO NOTHING, so a re-optimise or a second event never duplicates.
+CREATE UNIQUE INDEX IF NOT EXISTS "inspectionDocument_part_model_key"
+ ON "inspectionDocument" ("companyId", "partId", "modelUploadId")
+ WHERE "modelUploadId" IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS "inspectionDocument_modelUploadId_idx"
+ ON "inspectionDocument" ("modelUploadId")
+ WHERE "modelUploadId" IS NOT NULL;
+
+-- `d.*` was expanded when the view was created, so it must be created again
+-- to carry the new column.
+DROP VIEW IF EXISTS "inspectionDocuments";
+CREATE VIEW "inspectionDocuments" WITH (SECURITY_INVOKER=true) AS
+ SELECT
+ d.*,
+ i."readableIdWithRevision" AS "partReadableId"
+ FROM "inspectionDocument" d
+ LEFT JOIN "item" i ON i."id" = d."partId";
diff --git a/packages/database/supabase/migrations/20261027122638_pmi-inspection-plans-handler.sql b/packages/database/supabase/migrations/20261027122638_pmi-inspection-plans-handler.sql
new file mode 100644
index 0000000000..bd30ea3043
--- /dev/null
+++ b/packages/database/supabase/migrations/20261027122638_pmi-inspection-plans-handler.sql
@@ -0,0 +1,66 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.queue_pmi_inspection_plans()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ link RECORD;
+BEGIN
+ -- A seed, a restore or a sync loads items in bulk; their plans come with them.
+ IF TG_OP = 'DELETE' OR current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- An item that starts using a model whose PMI was already read gets an
+ -- inspection plan made from that PMI (a new revision, a converted quote
+ -- line, an existing model attached to a part). A model whose PMI is read
+ -- later is covered by model-optimize, which sends the same event.
+ IF TG_OP = 'INSERT' THEN
+ FOR link IN
+ SELECT n."id" AS "itemId", n."companyId", n."modelUploadId"
+ FROM batched_new n
+ JOIN "modelUpload" m ON m."id" = n."modelUploadId"
+ WHERE m."pmiPath" IS NOT NULL
+ LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/pmi-inspection-plan',
+ jsonb_build_object(
+ 'companyId', link."companyId",
+ 'modelUploadId', link."modelUploadId",
+ 'itemId', link."itemId"
+ )
+ );
+ END LOOP;
+ ELSE
+ FOR link IN
+ SELECT n."id" AS "itemId", n."companyId", n."modelUploadId"
+ FROM batched_new n
+ JOIN batched_old o ON o."id" = n."id"
+ JOIN "modelUpload" m ON m."id" = n."modelUploadId"
+ WHERE n."modelUploadId" IS DISTINCT FROM o."modelUploadId"
+ AND m."pmiPath" IS NOT NULL
+ LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/pmi-inspection-plan',
+ jsonb_build_object(
+ 'companyId', link."companyId",
+ 'modelUploadId', link."modelUploadId",
+ 'itemId', link."itemId"
+ )
+ );
+ END LOOP;
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
+
+-- event triggers (packages/database/src/event-system/attachments.ts)
+SET lock_timeout = '5s';
+SELECT set_event_triggers('item', ARRAY[]::text[], ARRAY['sync_create_item_related_records', 'sync_create_make_method_related_records', 'sync_propagate_item_readable_id_to_tracked_entity']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes', 'queue_pmi_inspection_plans']::text[]);
+RESET lock_timeout;
diff --git a/packages/database/supabase/tests/pmi-inspection-plans.test.sql b/packages/database/supabase/tests/pmi-inspection-plans.test.sql
new file mode 100644
index 0000000000..66bb9dc6c9
--- /dev/null
+++ b/packages/database/supabase/tests/pmi-inspection-plans.test.sql
@@ -0,0 +1,96 @@
+-- The statement handler `queue_pmi_inspection_plans` on `item`
+-- (packages/database/src/event-system/handlers/queue_pmi_inspection_plans.sql):
+-- an item that starts using a model whose PMI was already read asks for an
+-- inspection plan made from it (`carbon/pmi-inspection-plan`).
+-- Run from the repository root against an existing local database that has at
+-- least one company with a user and the Vault secret `inngest_event_url`
+-- (`crbn up` sets it):
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/pmi-inspection-plans.test.sql
+-- A sent event is a row in `net.http_request_queue`. pg_net reads that table
+-- only after a commit, and everything here is rolled back, so nothing is sent.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '30s';
+
+CREATE FUNCTION pg_temp.expect(label text, actual anyelement, expected anyelement)
+RETURNS void LANGUAGE plpgsql AS $fn$
+BEGIN
+ IF actual IS DISTINCT FROM expected THEN
+ RAISE EXCEPTION '%: expected %, got %', label, expected, actual;
+ END IF;
+END;
+$fn$;
+
+-- One model of the test company, loaded the way a sync loads it so the model
+-- pipeline's own handler stays quiet.
+CREATE FUNCTION pg_temp.model(pmi boolean) RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE new_id text;
+BEGIN
+ PERFORM set_config('app.sync_in_progress', 'true', true);
+ INSERT INTO "modelUpload" ("companyId", "createdBy", "modelPath", "pmiPath")
+ SELECT uc."companyId", uc."userId", uc."companyId" || '/models/test.step',
+ CASE WHEN pmi THEN uc."companyId" || '/models/test/pmi.json' END
+ FROM "userToCompany" uc ORDER BY uc."companyId", uc."userId" LIMIT 1
+ RETURNING id INTO new_id;
+ PERFORM set_config('app.sync_in_progress', 'false', true);
+ RETURN new_id;
+END;
+$fn$;
+
+-- One part of the test company, on `model_id` (null for none).
+CREATE FUNCTION pg_temp.item(model_id text, sync boolean DEFAULT false)
+RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE new_id text;
+BEGIN
+ PERFORM set_config('app.sync_in_progress', sync::text, true);
+ INSERT INTO "item" ("companyId", "createdBy", "readableId", "name", "type", "itemTrackingType", "modelUploadId")
+ SELECT uc."companyId", uc."userId", 'PMI-TEST-' || gen_random_uuid(), 'PMI test', 'Part', 'Inventory', model_id
+ FROM "userToCompany" uc ORDER BY uc."companyId", uc."userId" LIMIT 1
+ RETURNING id INTO new_id;
+ PERFORM set_config('app.sync_in_progress', 'false', true);
+ RETURN new_id;
+END;
+$fn$;
+
+-- The `carbon/pmi-inspection-plan` events queued for one item.
+CREATE FUNCTION pg_temp.sent(item_id text) RETURNS bigint LANGUAGE sql AS $fn$
+ SELECT count(*) FROM net.http_request_queue
+ WHERE convert_from(body, 'UTF8')::jsonb ->> 'name' = 'carbon/pmi-inspection-plan'
+ AND convert_from(body, 'UTF8')::jsonb -> 'data' ->> 'itemId' = item_id;
+$fn$;
+
+DO $test$
+DECLARE
+ with_pmi text; without_pmi text;
+ created text; plain text; synced text; linked text; moved text;
+BEGIN
+ with_pmi := pg_temp.model(true);
+ without_pmi := pg_temp.model(false);
+
+ -- INSERT: a new item (a revision, a converted line) already on a PMI model.
+ created := pg_temp.item(with_pmi);
+ PERFORM pg_temp.expect('insert: on a model with PMI', pg_temp.sent(created), 1::bigint);
+
+ plain := pg_temp.item(without_pmi);
+ PERFORM pg_temp.expect('insert: on a model without PMI', pg_temp.sent(plain), 0::bigint);
+
+ synced := pg_temp.item(with_pmi, sync => true);
+ PERFORM pg_temp.expect('insert: a synced row', pg_temp.sent(synced), 0::bigint);
+
+ -- UPDATE: only a change of model asks, and only for a model with PMI.
+ linked := pg_temp.item(NULL);
+ UPDATE "item" SET "modelUploadId" = with_pmi WHERE id = linked;
+ PERFORM pg_temp.expect('update: linked to a PMI model', pg_temp.sent(linked), 1::bigint);
+
+ UPDATE "item" SET "name" = 'Renamed' WHERE id = linked;
+ PERFORM pg_temp.expect('update: model unchanged', pg_temp.sent(linked), 1::bigint);
+
+ moved := pg_temp.item(with_pmi);
+ UPDATE "item" SET "modelUploadId" = without_pmi WHERE id = moved;
+ PERFORM pg_temp.expect('update: moved to a model without PMI', pg_temp.sent(moved), 1::bigint);
+
+ RAISE NOTICE 'pmi-inspection-plans: all checks passed';
+END;
+$test$;
+
+ROLLBACK;
diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.md
index bfbadd3a79..04303d1478 100644
--- a/packages/dev/AGENTS.md
+++ b/packages/dev/AGENTS.md
@@ -39,7 +39,7 @@ pnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, u
- **Provision** (`commands/init.ts`): `crbn init` provisions an already-created worktree (canonical slug + env sync + skills) to match a `crbn checkout`; shared by `new`, the bash `checkout` post-create hook, and Conductor's `setup` (`.conductor/settings.toml`). It does NOT boot the stack — `crbn up` still mints ports/`.env.local`.
- **Worktree** (`worktree.ts`): `resolveSlug()`, `canonicalSlug()` (branch-derived `<repoBase>-<branch>`), `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`
- **Services**: `compose.ts` (Docker), `migrations.ts` (Postgres/Supabase), `portless.ts` (`.dev` URLs), `apps.ts` (dev servers)
-- **Aux spawners** (`services/apps.ts`): `spawnAssembler` (cargo) and `spawnEmailPreview` (`@carbon/documents` `email:previews` on `PORT_EMAIL` — the react-email server over `src/email/previews`, one fixture per email) — opt-in picker apps with their own spawners, not react-router dev servers
+- **Aux spawners** (`services/apps.ts`): `spawnAssembler` (cargo; `crbn up` first refuses the assembler with an install hint while `assemblerMissingPrerequisite` names Rust, FCL or the OCCT build as missing, and builds into the shared `~/.cache/carbon-cargo-target`, `assemblerCargoTargetDir`) and `spawnEmailPreview` (`@carbon/documents` `email:previews` on `PORT_EMAIL` — the react-email server over `src/email/previews`, one fixture per email) — opt-in picker apps with their own spawners, not react-router dev servers
- **Vite helpers** (`vite.js`, exported as `@carbon/dev/vite`, typed by `vite.d.ts`): `carbon({ command, mode, locales, clientOnly, splitServer, precompress })` is each app's one plugin call, listed after `tailwindcss()` and `reactRouter()` (which stay in the app). It always adds stack activity and Lingui's macro transform (with `linguiWithoutIdQuery`, which works around Lingui 6.9.0 parsing React Router's `?query`-suffixed route ids as plain JS), and on request react-aria's locale trimming (`locales`), `clientOnlyAlias` stubs (`clientOnly`), `splitServerByPackage` (`splitServer`: one server chunk per package, so Vercel's file trace stays fast; only modules loaded at startup are grouped) and `precompressedAssets` (`precompress`). Packages are imported only when their plugin runs; hooks use native filters. `applyDotenvToProcessEnv` stays a separate call. Lingui, `@lingui/conf` and the react-aria plugin are peer dependencies the apps provide
- **Spinners come from `ui.ts`, not `@clack/prompts`**: `tasks`, `spinner` and `progress` there print one line per step when stdout is not a terminal (an agent, a pipe, a log file) instead of every animation frame. Importing them from clack directly brings the frame noise back.
- **No command allow-list in `bin/crbn`**: the bash router runs from the main checkout while the TypeScript CLI runs from the current worktree, so the router passes anything it doesn't own (`checkout`, help, version) straight through. Register a subcommand in `src/main.ts` only.
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index f08c0e9e2e..6310707078 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -14,8 +14,7 @@ import { currentBranch } from "../git.js";
import { onShutdown, tryConnect } from "../helpers.js";
import { pickApps, pickBorrowSlug } from "../prompts.js";
import {
- assemblerDepsBuilt,
- assertAssemblerDepsBuilt,
+ assemblerMissingPrerequisite,
installDeps,
installSkills,
spawnApps,
@@ -190,18 +189,21 @@ export async function up(opts: UpOpts = {}) {
// the assembler still fails fast below.
APP_CHOICES.map((c) => c.value).filter((v) => {
if (v !== "assembler") return true;
- if (assemblerDepsBuilt()) return true;
+ if (assemblerMissingPrerequisite() === null) return true;
log.warn(
- "assembler skipped from --all: its OCCT build isn't present " +
- "(apps/assembler/scripts/build-occt.sh)"
+ "assembler skipped from --all: Rust, FCL or its OCCT build isn't " +
+ "present (pick the assembler on its own to see what to install)"
);
return false;
})
: await pickApps()
: [];
// Fail before booting anything heavy (docker, migrations) if the assembler is
- // selected without its one-time OCCT build.
- if (selectedApps.includes("assembler")) assertAssemblerDepsBuilt();
+ // selected without Rust, FCL or its one-time OCCT build.
+ if (selectedApps.includes("assembler")) {
+ const missing = assemblerMissingPrerequisite();
+ if (missing) throw new Error(missing);
+ }
const size: StackSize = {
minimal,
full: !minimal && opts.full === true,
diff --git a/packages/dev/src/services/apps.test.ts b/packages/dev/src/services/apps.test.ts
index f57c13cdd3..297b7fe671 100644
--- a/packages/dev/src/services/apps.test.ts
+++ b/packages/dev/src/services/apps.test.ts
@@ -15,6 +15,8 @@ import { join } from "pathe";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PortMap } from "../worktree.js";
import {
+ assemblerCargoTargetDir,
+ cargoBinary,
spawnApps,
spawnEmailPreview,
stopAuxApps,
@@ -229,3 +231,33 @@ describe("aux app lifecycle", () => {
await expect(exited).resolves.toBeUndefined();
}, 20_000);
});
+
+describe("assemblerCargoTargetDir", () => {
+ it("shares one build directory across worktrees by default", () => {
+ expect(assemblerCargoTargetDir({})).toMatch(
+ /\.cache\/carbon-cargo-target$/
+ );
+ });
+
+ it("keeps a CARGO_TARGET_DIR the developer set", () => {
+ expect(assemblerCargoTargetDir({ CARGO_TARGET_DIR: "/tmp/mine" })).toBe(
+ "/tmp/mine"
+ );
+ });
+});
+
+describe("cargoBinary", () => {
+ it("finds cargo in rustup's home when PATH lacks it", () => {
+ const home = mkdtempSync(join(tmpdir(), "cargo-home-"));
+ mkdirSync(join(home, "bin"));
+ writeFileSync(join(home, "bin", "cargo"), "");
+ expect(cargoBinary({ PATH: "", CARGO_HOME: home })).toBe(
+ join(home, "bin", "cargo")
+ );
+ });
+
+ it("is null when Rust is not installed", () => {
+ const home = mkdtempSync(join(tmpdir(), "cargo-home-"));
+ expect(cargoBinary({ PATH: "", CARGO_HOME: home })).toBeNull();
+ });
+});
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index 4f5eafea89..2f87b923de 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -4,9 +4,10 @@
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
+import { delimiter } from "node:path";
import { parse } from "dotenv";
import { type ExecaChildProcess, execa } from "execa";
-import { join } from "pathe";
+import { dirname, join } from "pathe";
import pc from "picocolors";
import { isAtLeastAsNew, onShutdown, readLines } from "../helpers.js";
import { type PortMap, sameWorktreePath } from "../worktree.js";
@@ -235,33 +236,99 @@ export function spawnApps(opts: {
const ASSEMBLER_PREFIX = pc.yellow(pc.bold("asm | "));
+/** Where the one-time OCCT build lives: per machine, shared by every worktree. */
+function occtPrefix(): string {
+ return (
+ process.env.OCCT_PREFIX ||
+ join(homedir(), ".cache", "carbon-occt", "8.0.0-p1")
+ );
+}
+
/**
- * Fail fast (before spawning) when the assembler is selected but its one-time
- * native OCCT dependency isn't built. `cargo run --release` would otherwise
- * either fail deep in a cc/link error or trigger a ~30-min build — neither is
- * what a plain `crbn up` should do. We never auto-build it: the user runs the
- * OCCT script once, then the assembler is available.
+ * The cargo the assembler runs with: the first on PATH, else rustup's default
+ * home — a shell started before Rust was installed has not sourced
+ * `~/.cargo/env` yet, and that must not read as "Rust is missing".
*/
-/** Non-throwing check: is the assembler's one-time native OCCT build present? */
-export function assemblerDepsBuilt(): boolean {
+export function cargoBinary(
+ env: NodeJS.ProcessEnv = process.env
+): string | null {
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
+ if (dir && existsSync(join(dir, "cargo"))) return join(dir, "cargo");
+ }
+ const fallback = join(
+ env.CARGO_HOME || join(homedir(), ".cargo"),
+ "bin",
+ "cargo"
+ );
+ return existsSync(fallback) ? fallback : null;
+}
+
+/**
+ * The FCL headers the `collision` crate compiles against, at the prefix its
+ * build.rs resolves (`FCL_PREFIX`, else Homebrew's `opt` layout on macOS, else
+ * `/usr`). Missing, the assembler build fails minutes in on a C++ include.
+ */
+function fclInstalled(env: NodeJS.ProcessEnv = process.env): boolean {
const prefix =
- process.env.OCCT_PREFIX ||
- join(homedir(), ".cache", "carbon-occt", "8.0.0-p1");
- return existsSync(prefix);
+ env.FCL_PREFIX ||
+ (process.platform === "darwin"
+ ? process.arch === "arm64"
+ ? "/opt/homebrew/opt/fcl"
+ : "/usr/local/opt/fcl"
+ : "/usr");
+ return existsSync(join(prefix, "include", "fcl"));
}
-export function assertAssemblerDepsBuilt(): void {
- if (!assemblerDepsBuilt()) {
- const prefix =
- process.env.OCCT_PREFIX ||
- join(homedir(), ".cache", "carbon-occt", "8.0.0-p1");
- throw new Error(
- `Assembler selected, but its OCCT dependency isn't built.\n` +
- ` expected: ${prefix}\n` +
- ` build it once (~15-30 min): apps/assembler/scripts/build-occt.sh\n` +
- ` then re-run, or run without the assembler app.`
- );
+/**
+ * What the assembler still needs on this machine, as the message that says how
+ * to install it, or null when Rust, FCL and the OCCT build are all present.
+ * `crbn up` checks it before booting anything, because `cargo run --release`
+ * would otherwise fail minutes in on a missing tool, header or library. It
+ * never installs or builds them itself.
+ */
+export function assemblerMissingPrerequisite(): string | null {
+ const instead = " then re-run, or run without the assembler app.";
+ if (cargoBinary() === null) {
+ return [
+ "Assembler selected, but Rust (cargo) isn't installed.",
+ " install it once per machine:",
+ " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh",
+ instead
+ ].join("\n");
+ }
+ if (!fclInstalled()) {
+ return [
+ "Assembler selected, but the FCL collision library isn't installed.",
+ " install it once per machine (pulls libccd, eigen, octomap):",
+ " brew install fcl # Linux: libfcl-dev, or set FCL_PREFIX",
+ instead
+ ].join("\n");
}
+ if (!existsSync(occtPrefix())) {
+ return [
+ "Assembler selected, but its OCCT dependency isn't built.",
+ ` expected: ${occtPrefix()}`,
+ " build it once per machine (~15-30 min, every worktree shares it):",
+ " brew install cmake ninja # once; the script needs cmake",
+ " apps/assembler/scripts/build-occt.sh",
+ instead
+ ].join("\n");
+ }
+ return null;
+}
+
+/**
+ * Cargo's build directory for the assembler. Every worktree builds the same
+ * crates, so one shared directory turns each new worktree's first
+ * `cargo run --release` (minutes, several GB) into an incremental build of
+ * what its branch changed. Cargo locks the directory, so two worktrees
+ * building at once wait for each other rather than corrupt it. A
+ * `CARGO_TARGET_DIR` the developer set (shell or `.env*`) wins.
+ */
+export function assemblerCargoTargetDir(env: NodeJS.ProcessEnv): string {
+ return (
+ env.CARGO_TARGET_DIR || join(homedir(), ".cache", "carbon-cargo-target")
+ );
}
const auxChildren = new Set<ExecaChildProcess>();
@@ -301,9 +368,11 @@ export function spawnAssembler(opts: {
// `cargo run --release` compiles-if-stale then runs, so a Rust change is
// picked up on the next `crbn up` (the CLI does not watch/rebuild otherwise).
- // First build is slow (OCCT/FCL); incremental is quick. Run from the workspace
- // root so cargo resolves the `assembler` package.
- const file = "cargo";
+ // First build is slow (OCCT/FCL); incremental is quick, and the build
+ // directory is shared across worktrees (`assemblerCargoTargetDir`). Run from
+ // the workspace root so cargo resolves the `assembler` package.
+ const cargo = cargoBinary();
+ const file = cargo ?? "cargo";
const args = ["run", "--release", "-p", "assembler"];
const cwd = root;
// Merge the worktree .env* stack so the assembler shares the same REDIS_URL as
@@ -313,7 +382,12 @@ export function spawnAssembler(opts: {
// portless's self-signed CA needs no extra trust wiring. Passing
// REDIS_URL points the service at the stateless Redis-backed job +
// result store; unset (no worktree REDIS_URL) => in-memory, single-process.
+ // Put cargo's own directory first on PATH, so rustc and the rustup proxies
+ // resolve even when cargo was found only in ~/.cargo/bin.
+ const pathEnv = appEnv.PATH ?? process.env.PATH ?? "";
const extraEnv: NodeJS.ProcessEnv = {
+ ...(cargo ? { PATH: `${dirname(cargo)}${delimiter}${pathEnv}` } : {}),
+ CARGO_TARGET_DIR: assemblerCargoTargetDir({ ...process.env, ...appEnv }),
PORT: String(port),
ASSEMBLER_SERVICE_API_KEY: "dev-local-key",
ASSEMBLER_DEV_MODE: "true",
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index d18f2cdccb..21b8c585a1 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -74,7 +74,8 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic |
| `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers |
| `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls `postingOrThrow("kanban-replenish", …)` in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |
-| `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, the thumbnail, and for a STEP with PMI the `pmi-{run}.json` the viewer draws (`modelUpload.pmiPath`, null when the model has none; the previous run's file is removed). Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |
+| `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, the thumbnail, and for a STEP with PMI the `pmi-{run}.json` the viewer draws (`modelUpload.pmiPath`, null when the model has none; the previous run's file is removed), and then sends `carbon/pmi-inspection-plan` when it wrote one. Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |
+| `pmi-inspection-plan` | `carbon/pmi-inspection-plan` `{ companyId, modelUploadId, itemId? }` (sent by `model-optimize` once a run wrote `pmi.json`, every item on the model; and by the `queue_pmi_inspection_plans` statement handler on `item` when an item starts using a model that already has PMI, that item only) | Makes an inspection plan from the model's PMI for each item with no plan for that model (`tasks/pmi-inspection-plan.ts`): `pmiInspectionCharacteristics` (`@carbon/viewer/pmi`) maps dimensions and geometric tolerances to characteristics, `createPmiInspectionPlan` (`@carbon/database/quality`) inserts the plan and its features in one transaction per item. Once per item and model (partial unique index `inspectionDocument_part_model_key`), never rewritten. Concurrency 1 per company and model. See `.claude/rules/inspection-system.md` |
| `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |
| `table-export` | `carbon/table-export` (`api+/table.export.ts`) | Background CSV export of a registered ERP list past 1,000 rows. One run per company. Steps of at most 10,000 rows write part files to `temp-staging`; `compose` streams them into `{companyId}/exports/{userId}/{exportId}.csv`. Stops at 100,000 rows or 200 MB. Step bodies in `src/table-jobs/export-run.ts` |
| `table-bulk-action` | `carbon/table-bulk-action` (`startBackgroundBulkAction`, ERP `utils/table-jobs.server.ts`) | A bulk action on every matching row of a registered list, or on selected rows too many for one request (`ids` in the event). One run per company, `retries: 0`. Collect steps store the ids (10,000 rows per step) in `temp-staging`; a selected-rows run stores its ids in one step instead. Apply steps run the action on one slice each, 100 ids per call, passing each call's `carry` to the next. Step bodies in `src/table-jobs/bulk-run.ts` |
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index 627616a6dd..50ddecc5b2 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -23,6 +23,7 @@ export { modelCompactFunction } from "./model-compact";
export { modelOptimizeFunction } from "./model-optimize";
export { modelThumbnailFunction } from "./model-thumbnail";
export { onboardFunction } from "./onboard";
+export { pmiInspectionPlanFunction } from "./pmi-inspection-plan";
export { postTransactionFunction } from "./post-transaction";
export { printJobFunction } from "./print-job";
export { printJobDeliverFunction } from "./print-job-deliver";
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index 5dfa9fb5f1..3826f1e0da 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -268,6 +268,15 @@ export const modelOptimizeFunction = inngest.createFunction(
}
});
+ if (outputs.pmi) {
+ // The model carries PMI: every item on it gets an inspection plan made
+ // from it (once per item and model — a re-optimise makes none).
+ await step.sendEvent("pmi-inspection-plan", {
+ name: "carbon/pmi-inspection-plan",
+ data: { companyId, modelUploadId }
+ });
+ }
+
if (compact) {
// The preview now exists, which is what lets an oversized raw be pruned.
const settled = {
diff --git a/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.test.ts b/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.test.ts
new file mode 100644
index 0000000000..9078c29883
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.test.ts
@@ -0,0 +1,104 @@
+// 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 { valuateMeasurement } from "@carbon/database/quality";
+import {
+ type PmiDimension,
+ type PmiDocument,
+ type PmiItem,
+ pmiInspectionCharacteristics
+} from "@carbon/viewer/pmi";
+import { describe, expect, it } from "vitest";
+
+// The characteristics a PMI plan holds are graded by `valuateMeasurement`,
+// which reads Tol+ and Tol− as magnitudes around the nominal. These cases pin
+// that the mapping and the grading agree at the drawing's own limits — the
+// pair lives in two packages, so neither package's tests can see a drift.
+
+function dimension(id: string, overrides: Partial<PmiDimension>): PmiItem {
+ return {
+ id,
+ kind: "dimension",
+ name: null,
+ dimension: {
+ type: "diameter",
+ value: 10,
+ upper: null,
+ lower: null,
+ upperBound: null,
+ lowerBound: null,
+ fitClass: null,
+ qualifier: null,
+ decimals: null,
+ modifiers: [],
+ descriptions: [],
+ ...overrides
+ },
+ tolerance: null,
+ datum: null,
+ lines: [],
+ mesh: null,
+ plane: null,
+ textPosition: null,
+ faces: [],
+ edges: []
+ };
+}
+
+function grade(item: PmiItem, readings: number[]) {
+ const doc: PmiDocument = {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ items: [item],
+ faces: [],
+ edges: [],
+ views: []
+ };
+ const [feature] = pmiInspectionCharacteristics(doc);
+ if (!feature) throw new Error("no characteristic");
+ return readings.map((value) =>
+ valuateMeasurement({ ...feature, type: "Measurement" }, value)
+ );
+}
+
+describe("PMI characteristics graded by valuateMeasurement", () => {
+ it("passes a ± dimension inside its limits only", () => {
+ expect(
+ grade(
+ dimension("d1", { upper: 0.05, lower: -0.02 }),
+ [9.979, 9.98, 10.05, 10.051]
+ )
+ ).toEqual(["Failed", "Passed", "Passed", "Failed"]);
+ });
+
+ it("passes a shaft fit wholly below the nominal only inside its band", () => {
+ // ⌀10 −0.013/−0.028: 9.972 to 9.987. The nominal itself is oversize.
+ expect(
+ grade(
+ dimension("d1", { upper: -0.013, lower: -0.028 }),
+ [9.971, 9.972, 9.987, 9.988, 10]
+ )
+ ).toEqual(["Failed", "Passed", "Passed", "Failed", "Failed"]);
+ });
+
+ it("passes a press fit wholly above the nominal only inside its band", () => {
+ // ⌀10 +0.05/+0.02: 10.02 to 10.05.
+ expect(
+ grade(
+ dimension("d1", { upper: 0.05, lower: 0.02 }),
+ [10, 10.02, 10.05, 10.051]
+ )
+ ).toEqual(["Failed", "Passed", "Passed", "Failed"]);
+ });
+
+ it("passes a limit dimension between its limits", () => {
+ expect(
+ grade(
+ dimension("d1", { value: 35, upperBound: 35.2, lowerBound: 34.8 }),
+ [34.79, 34.8, 35.2, 35.21]
+ )
+ ).toEqual(["Failed", "Passed", "Passed", "Failed"]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.ts b/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.ts
new file mode 100644
index 0000000000..3a0d2bb9be
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/pmi-inspection-plan.ts
@@ -0,0 +1,127 @@
+// 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 { createPmiInspectionPlan } from "@carbon/database/quality";
+import { storage } from "@carbon/files";
+import {
+ parsePmiDocument,
+ pmiInspectionCharacteristics
+} from "@carbon/viewer/pmi";
+import { getJobDatabaseClient } from "../../../db";
+import { inngest } from "../../client";
+
+/**
+ * Makes an inspection plan from a model's PMI for every item that uses the
+ * model and has no plan for it yet (spec
+ * `.ai/specs/2026-10-27-pmi-inspection-plans.md`). Each dimension and
+ * geometric tolerance becomes one characteristic; the plan holds the model and
+ * no PDF, so the inspection screens show the model.
+ *
+ * Sent by `model-optimize` once a run has written `pmi.json` (every item on
+ * the model), and by the `queue_pmi_inspection_plans` handler when an item
+ * starts using a model whose PMI was already read (that item only). A plan is
+ * made once per item and model and never rewritten: the partial unique index
+ * `inspectionDocument_part_model_key` turns a second insert into a no-op.
+ */
+export const pmiInspectionPlanFunction = inngest.createFunction(
+ {
+ id: "pmi-inspection-plan",
+ retries: 2,
+ concurrency: {
+ key: "event.data.companyId + '-' + event.data.modelUploadId",
+ limit: 1
+ }
+ },
+ { event: "carbon/pmi-inspection-plan" },
+ async ({ event, step, logger }) => {
+ const { companyId, modelUploadId, itemId } = event.data;
+
+ return step.run("create-plans", async () => {
+ const db = getJobDatabaseClient();
+
+ const model = await db
+ .selectFrom("modelUpload")
+ .select(["pmiPath"])
+ .where("id", "=", modelUploadId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!model?.pmiPath) return { created: 0, reason: "no-pmi" as const };
+
+ let items = db
+ .selectFrom("item")
+ .select(["id"])
+ .where("companyId", "=", companyId)
+ .where("modelUploadId", "=", modelUploadId)
+ .where((eb) =>
+ eb.not(
+ eb.exists(
+ eb
+ .selectFrom("inspectionDocument")
+ .select("inspectionDocument.id")
+ .whereRef("inspectionDocument.partId", "=", "item.id")
+ .where("inspectionDocument.companyId", "=", companyId)
+ .where("inspectionDocument.modelUploadId", "=", modelUploadId)
+ )
+ )
+ );
+ if (itemId) items = items.where("id", "=", itemId);
+ const itemIds = (await items.execute()).map((row) => row.id);
+ if (itemIds.length === 0) {
+ return { created: 0, reason: "no-items" as const };
+ }
+
+ const download = await storage(getCarbonServiceRole())
+ .company(companyId)
+ .download(model.pmiPath);
+ if (!download.data) {
+ throw new Error(
+ `Failed to download pmi.json for model ${modelUploadId}: ${download.error.message}`
+ );
+ }
+ const pmi = parsePmiDocument(JSON.parse(await download.data.text()));
+ if (!pmi) {
+ logger.warn("pmi.json did not parse; no inspection plan made", {
+ companyId,
+ modelUploadId,
+ pmiPath: model.pmiPath
+ });
+ return { created: 0, reason: "unreadable-pmi" as const };
+ }
+
+ const characteristics = pmiInspectionCharacteristics(pmi);
+ if (characteristics.length === 0) {
+ // Datums and notes only: nothing to measure, so no plan.
+ logger.info("PMI has no dimension or tolerance; no inspection plan", {
+ companyId,
+ modelUploadId
+ });
+ return { created: 0, reason: "no-characteristics" as const };
+ }
+
+ let created = 0;
+ for (const id of itemIds) {
+ const planId = await db.transaction().execute((trx) =>
+ createPmiInspectionPlan(trx, {
+ companyId,
+ itemId: id,
+ modelUploadId,
+ characteristics,
+ createdBy: "system"
+ })
+ );
+ if (planId) {
+ created += 1;
+ logger.info("inspection plan made from PMI", {
+ modelUploadId,
+ itemId: id,
+ planId,
+ characteristics: characteristics.length
+ });
+ }
+ }
+ return { created, reason: "ok" as const };
+ });
+ }
+);
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 981e24d88b..559923ab3f 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -128,6 +128,7 @@ import {
modelOptimizeFunction,
modelThumbnailFunction,
onboardFunction,
+ pmiInspectionPlanFunction,
postTransactionFunction,
printJobDeliverFunction,
printJobFunction,
@@ -181,6 +182,7 @@ export const functions = [
modelCompactFunction,
modelOptimizeFunction,
modelThumbnailFunction,
+ pmiInspectionPlanFunction,
updatePermissionsFunction,
recalculateFunction,
userAdminFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index dcc3acdd7d..4f3422300d 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -177,6 +177,18 @@ export type Events = {
};
};
+ // Make an inspection plan from a model's PMI (`pmi-inspection-plan`). Sent
+ // by model-optimize when a run wrote `pmi.json` (every item on the model),
+ // and by the `queue_pmi_inspection_plans` handler on `item` when an item
+ // starts using a model that has PMI (that item only).
+ "carbon/pmi-inspection-plan": {
+ data: {
+ companyId: string;
+ modelUploadId: string;
+ itemId?: string;
+ };
+ };
+
// Compact the retained raw (STEP → BinXCAF `.xbf.zst`, mesh → `.{ext}.zst`)
// so it never lingers as the fat upload. A successful optimise compacts
// inline; this fires when model-optimize skips (already optimised, a format
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
index fcdf53feec..e6247eb263 100644
--- a/packages/viewer/AGENTS.md
+++ b/packages/viewer/AGENTS.md
@@ -11,7 +11,7 @@
- **Sub-assemblies** (`subassembly.ts`) — a header step (`isSubAssembly`) groups the steps whose `parentStepId` points at it; those steps sit directly before it in play order and are BUILT ON THEIR OWN: while one is active the player isolates its sub-assembly's parts (focus-style, ancestors kept, not cleared by playback, framed on their own bounds). A header's `usedInStepId` names the later step that carries the finished unit in. A header whose `motion` is not `none` has a path of its own: the unit plays it (`buildStepClip`'s `units`, one after another in sub-assembly order) before the step's own parts move — a step with no animation of its own fades its parts in only after those units seat (`fadeProgress`). One `stepClipTiming` per step feeds the timeline segment, the clip and the fade delay; while picking components it gives the units and the glide no time. `buildCarryPlans` is THE per-step answer to which units fly (`pathUnits`), which glide, what the step's own insertion moves (`ownMovingPartIds`) and whether the step is an unused header joining on its own path (`joinsOnOwnPath`: that path is the header's motion, so it has no insertion of its own); `carriesUnits` says whether a step brings any unit in. The clip, the fade, the path editor and the framing all read it. Each header's unit parts come from `buildSubAssemblyPlan` (`unitPartIds`). A unit whose header has no path of its own (`motion` `none`) glides from beside the build (`CARRY_IN_GLIDE_SECONDS` / `buildStepClip`'s `glide.nodeIds`), then rides the using step's insertion. A header nothing uses is where its unit joins the main build; a USED header plays nothing (0-length segment, skipped by prev/next). A step whose own insertion moves nothing (`stepClipTiming`'s `ownParts: false`, e.g. a header joining on its own path) gets a slot of just its units and the hold — the fixed `none` slot is for process-only steps and own parts that fade in. No nesting — a step USES a finished sub-assembly instead, so chains of any length work. `arrivalIndexByNode(steps, world)` is THE answer to "when does this part appear in the build on screen" and drives visibility; `validateSubAssemblies` is THE structural rule the ERP service and editor share. `scopeStepIds` limits the timeline to an opened sub-assembly.
- **Motion** — discriminated union `linear | L | helix | path | waypoints | none`. `waypoints` is editor-authored: poses relative to the seated pose, turning about the moving set's seated bounds center, then shifting (`waypointMatrix`), so one motion fits a part, a rigid group or a sub-assembly. The player takes that center from graph.json's seated bounds for the clip (`buildStepClip`'s required `pivot`), the path editor and the framed start pose alike — the live nodes are mid-animation when framing runs. `resampleEased` keeps every input keyframe (at its eased time) besides its evenly spaced samples, so easing never cuts a turning leg's 15° samples short. The path editor saves `linear`/`L` until a waypoint is turned (`editorWaypointsToMotion`); it has a Move / Rotate tool (`pathToolLabels` on the player, host-translated — no labels, no switch): Rotate shows drei `TransformControls` rings on the selected waypoint and stops the spheres dragging, because the rings' invisible free-rotation grip sits over the sphere. Insertion motion; the player derives removal (reverse) and start poses. `flagged`/`blockedBy` steps use `none` and fade in (no collision-free path exists — a synthesized path would clip through geometry).
- **Artifact tiers** — a model renders from best-available: LOD GLB → optimised GLB → lossless GLB → raw WASM (in-browser occt-import-js) fallback.
-- **pmi.json** (`PmiDocument`, `pmi.ts`) — a STEP AP242 model's PMI (dimensions, geometric tolerances, datums, graphic-only notes, saved views), written by the optimize ingest (`crates/converter/src/pmi.rs` is the other half of the contract). World mm in the optimised GLB's frame; each referenced face ships its own triangles, so the highlight never depends on the GLB's mesh layout. `ModelPreview` takes `pmiUrl`, draws it through `PmiLayer` inside `ModelCanvas`, and lists it in the PMI panel; `formatPmiItem` builds every label (mm/in, the file's decimals only in its own unit). Only over a server GLB — never the raw tier.
+- **pmi.json** (`PmiDocument`, `pmi.ts`) — a STEP AP242 model's PMI (dimensions, geometric tolerances, datums, graphic-only notes, saved views), written by the optimize ingest (`crates/converter/src/pmi.rs` is the other half of the contract). World mm in the optimised GLB's frame; each referenced face ships its own triangles, so the highlight never depends on the GLB's mesh layout. `ModelPreview` takes `pmiUrl`, draws it through `PmiLayer` inside `ModelCanvas`, and lists it in the PMI panel; `formatPmiItem` builds every label (mm/in, the file's decimals only in its own unit). Only over a server GLB — never the raw tier. `selectedPmiItemId` / `onPmiItemSelect` make the selection controlled. `pmiInspectionCharacteristics` (`@carbon/viewer/pmi`, pure) maps a document to the inspection characteristics the `pmi-inspection-plan` job writes: one per dimension and geometric tolerance, datums and notes left out.
## Always
@@ -49,6 +49,8 @@ pnpm --filter @carbon/viewer typecheck # tsc --noEmit
| `.` | `AssemblyPlayer` (+ `AssemblyPlayerHandle`/`Props`), `AssemblyViewer`, `ModelCanvas`, all plan/motion/graph/camera/describe/visibility helpers and types |
| `./steps` | Three-free plan→steps logic for server code: `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`, the sub-assembly structure helpers, and the step flags `isSavedView` / `hasCustomMotion` / `isPlanFlagged` (also on `.`) |
| `./canvas` | `ModelCanvas` — standalone static GLB viewer (orbit + view, no steps) |
+| `./pmi` | `pmi.ts` alone (types, parsing, labels, `pmiInspectionCharacteristics`) — no React, so `@carbon/jobs` reads it |
+| `./model-upload-preview` | `ModelUploadPreview` — a read-only preview of a stored model (`useOptimizedModel` + `ModelPreview`); `pmiLinks` / `selectedLinkId` / `onLinkSelect` tie host records (inspection characteristics) to PMI items both ways. `modelPreviewUrls(artifacts)` is the one place artifact paths become `ModelPreview` URLs, also used by ERP `CadModel` and the MES model tab |
| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view; `pmiUrl` adds the PMI layer and panel |
| `./optimize-progress` | `OptimizeProgress` — optimise-status chip |
| `./use-optimized-model` | `useOptimizedModel` — TanStack Query polling of the model optimise lifecycle (shared by ERP `CadModel` + MES model tab) |
diff --git a/packages/viewer/package.json b/packages/viewer/package.json
index b9efadb620..0aecde7acc 100644
--- a/packages/viewer/package.json
+++ b/packages/viewer/package.json
@@ -29,7 +29,9 @@
"./steps": "./src/steps.ts",
"./canvas": "./src/ModelCanvas.tsx",
"./model-preview": "./src/ModelPreview.tsx",
+ "./model-upload-preview": "./src/ModelUploadPreview.tsx",
"./optimize-progress": "./src/OptimizeProgress.tsx",
+ "./pmi": "./src/pmi.ts",
"./use-optimized-model": "./src/useOptimizedModel.ts"
},
"peerDependencies": {
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
index ea24ec6097..8d103834e2 100644
--- a/packages/viewer/src/ModelPreview.tsx
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -73,6 +73,13 @@ export type ModelPreviewProps = {
/** The model's `pmi.json` (PMI read from its STEP AP242 source). When it
* holds items, a PMI panel lists them and the server model draws them. */
pmiUrl?: string | null;
+ /** Controls which PMI item is selected (an inspection screen's active
+ * characteristic). A change selects the item and turns the camera to it.
+ * Leave undefined to let the PMI panel own the selection. */
+ selectedPmiItemId?: string | null;
+ /** Called when the user picks a PMI item in the panel or on the model
+ * (null when the pick clears the selection). */
+ onPmiItemSelect?: (id: string | null) => void;
/** Static poster image (thumbnail PNG) shown before any 3D loads. */
thumbnailUrl?: string | null;
/** The raw uploaded file's auth-proxied URL — the WASM fallback tier renders
@@ -127,6 +134,8 @@ export function ModelPreview({
optimizedUrl = null,
glbUrl = null,
pmiUrl = null,
+ selectedPmiItemId,
+ onPmiItemSelect,
thumbnailUrl = null,
rawUrl = null,
optimizing = false,
@@ -181,9 +190,15 @@ export function ModelPreview({
null
);
const focusSeqRef = useRef(0);
- // A new document starts with nothing picked.
+ // The selection as last set here, so a host echoing a pick back does not
+ // turn the camera a second time.
+ const pmiSelectedRef = useRef<string | null>(null);
+ pmiSelectedRef.current = pmiSelectedId;
+ // A new document starts with nothing picked. The ref is cleared with it, so
+ // a controlled selection (below) is applied again to the new document.
// biome-ignore lint/correctness/useExhaustiveDependencies: resets on a new document without reading it
useEffect(() => {
+ pmiSelectedRef.current = null;
setPmiViewId(null);
setPmiSelectedId(null);
setFocusRequest(null);
@@ -192,28 +207,58 @@ export function ModelPreview({
() => (pmi ? visibleItemIds(pmi, pmiViewId) : undefined),
[pmi, pmiViewId]
);
+ const focusPmiItem = useCallback((id: string) => {
+ pmiSelectedRef.current = id;
+ setPmiSelectedId(id);
+ setPmiVisible(true);
+ focusSeqRef.current += 1;
+ setFocusRequest({ kind: "item", id, seq: focusSeqRef.current });
+ }, []);
// Picking the selected item again clears it; picking another turns to it.
const selectPmiItem = useCallback(
(id: string) => {
if (pmiSelectedId === id) {
setPmiSelectedId(null);
+ onPmiItemSelect?.(null);
return;
}
- setPmiSelectedId(id);
- setPmiVisible(true);
- focusSeqRef.current += 1;
- setFocusRequest({ kind: "item", id, seq: focusSeqRef.current });
+ focusPmiItem(id);
+ onPmiItemSelect?.(id);
},
- [pmiSelectedId]
+ [pmiSelectedId, focusPmiItem, onPmiItemSelect]
);
- const selectPmiView = useCallback((viewId: string | null) => {
- setPmiViewId(viewId);
- setPmiSelectedId(null);
- if (viewId) {
- focusSeqRef.current += 1;
- setFocusRequest({ kind: "view", id: viewId, seq: focusSeqRef.current });
+ // A controlled selection follows the host, also once the document arrives
+ // (a new document resets the selection above).
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reacts to the host's id and a new document only
+ useEffect(() => {
+ if (selectedPmiItemId === undefined || !pmi) return;
+ if (selectedPmiItemId === null) {
+ setPmiSelectedId(null);
+ return;
}
- }, []);
+ if (
+ selectedPmiItemId !== pmiSelectedRef.current &&
+ pmi.items.some((item) => item.id === selectedPmiItemId)
+ ) {
+ focusPmiItem(selectedPmiItemId);
+ }
+ }, [selectedPmiItemId, pmi]);
+ const selectPmiView = useCallback(
+ (viewId: string | null) => {
+ setPmiViewId(viewId);
+ setPmiSelectedId(null);
+ onPmiItemSelect?.(null);
+ if (viewId) {
+ focusSeqRef.current += 1;
+ setFocusRequest({
+ kind: "view",
+ id: viewId,
+ seq: focusSeqRef.current
+ });
+ }
+ },
+ [onPmiItemSelect]
+ );
const interactiveUrl = optimizedUrl ?? glbUrl;
// The instant 3D layer: the LOD if it's distinct from the interactive model
diff --git a/packages/viewer/src/ModelUploadPreview.tsx b/packages/viewer/src/ModelUploadPreview.tsx
new file mode 100644
index 0000000000..966339b090
--- /dev/null
+++ b/packages/viewer/src/ModelUploadPreview.tsx
@@ -0,0 +1,120 @@
+// 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 { getPrivateUrl, getRawModelUrl } from "@carbon/files/media";
+import { useMode } from "@carbon/react";
+import { MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
+import { useCallback, useMemo } from "react";
+import { ModelPreview } from "./ModelPreview";
+import { type ModelArtifacts, useOptimizedModel } from "./useOptimizedModel";
+
+/**
+ * The `ModelPreview` URLs for a model's artifacts — the one place a stored
+ * artifact path becomes a URL, shared by every host that mounts a preview.
+ */
+export function modelPreviewUrls(artifacts: ModelArtifacts | null | undefined) {
+ return {
+ optimizedUrl: artifacts?.optimizedModelPath
+ ? // ?v= busts the immutable preview cache on the STABLE optimized.glb
+ // path when a re-optimise lands.
+ `${getPrivateUrl(artifacts.optimizedModelPath)}${
+ artifacts.optimizedAt
+ ? `?v=${encodeURIComponent(artifacts.optimizedAt)}`
+ : ""
+ }`
+ : null,
+ glbUrl: artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null,
+ // Unique per optimise run, so no cache-buster is needed.
+ pmiUrl: artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null,
+ lodUrl: artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null,
+ rawUrl:
+ artifacts?.rawPath && (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES
+ ? getRawModelUrl(artifacts.rawBucket, artifacts.rawPath)
+ : null,
+ thumbnailUrl: artifacts?.thumbnailPath
+ ? getPrivateUrl(artifacts.thumbnailPath)
+ : null
+ };
+}
+
+/** A host record made from one PMI item (an inspection characteristic). */
+export type PmiLink = { id: string; pmiItemId: string | null };
+
+type ModelUploadPreviewProps = {
+ modelUploadId: string;
+ modelPath: string | null;
+ companyId: string;
+ /**
+ * Ties the host's records to PMI items: the selected record selects its
+ * item on the model (highlighted, camera turned to it), and a pick on the
+ * model selects the record made from that item — null for an item no
+ * record names, or a cleared pick.
+ */
+ pmiLinks?: readonly PmiLink[];
+ selectedLinkId?: string | null;
+ onLinkSelect?: (id: string | null) => void;
+ className?: string;
+};
+
+/**
+ * A read-only preview of a stored model: resolves its artifacts and renders
+ * `ModelPreview` with them. Hosts that also upload, delete or recapture the
+ * thumbnail (`CadModel`, the MES model tab) mount `ModelPreview` themselves
+ * with `modelPreviewUrls`. Import lazily (ClientOnly) — the viewer is three.js.
+ */
+export function ModelUploadPreview({
+ modelUploadId,
+ modelPath,
+ companyId,
+ pmiLinks,
+ selectedLinkId,
+ onLinkSelect,
+ className
+}: ModelUploadPreviewProps) {
+ const mode = useMode();
+ const selectedPmiItemId = useMemo(
+ () =>
+ pmiLinks
+ ? (pmiLinks.find((link) => link.id === selectedLinkId)?.pmiItemId ??
+ null)
+ : undefined,
+ [pmiLinks, selectedLinkId]
+ );
+ const onPmiItemSelect = useCallback(
+ (pmiItemId: string | null) => {
+ const link = pmiItemId
+ ? pmiLinks?.find((l) => l.pmiItemId === pmiItemId)
+ : undefined;
+ onLinkSelect?.(link?.id ?? null);
+ },
+ [pmiLinks, onLinkSelect]
+ );
+ const {
+ artifacts,
+ awaitingModel,
+ backgroundOptimizing,
+ optimizeFailed,
+ canRetry,
+ retry,
+ retryLabel
+ } = useOptimizedModel({ modelPath, modelUploadId, companyId });
+
+ return (
+ <ModelPreview
+ {...modelPreviewUrls(artifacts)}
+ awaitingModel={awaitingModel}
+ optimizing={backgroundOptimizing}
+ optimizeFailed={optimizeFailed}
+ sourceMissing={artifacts?.sourceAvailable === false}
+ selectedPmiItemId={selectedPmiItemId}
+ onPmiItemSelect={pmiLinks ? onPmiItemSelect : undefined}
+ mode={mode}
+ className={className}
+ onRetry={canRetry ? retry : undefined}
+ retryLabel={retryLabel}
+ />
+ );
+}
+
+export default ModelUploadPreview;
diff --git a/packages/viewer/src/pmi.test.ts b/packages/viewer/src/pmi.test.ts
index 188d48bfaa..9f951ee29f 100644
--- a/packages/viewer/src/pmi.test.ts
+++ b/packages/viewer/src/pmi.test.ts
@@ -11,6 +11,7 @@ import {
type PmiItem,
type PmiTolerance,
parsePmiDocument,
+ pmiInspectionCharacteristics,
pmiItemBounds,
pmiViewBounds,
visibleItemIds
@@ -442,3 +443,149 @@ describe("bounds", () => {
});
});
});
+
+describe("pmiInspectionCharacteristics", () => {
+ const characteristics = (items: PmiItem[], sourceUnit: "mm" | "in" = "mm") =>
+ pmiInspectionCharacteristics(doc({ items, sourceUnit }));
+
+ it("takes a ± dimension's nominal and deviations", () => {
+ const [row] = characteristics([
+ dimension({ type: "diameter", value: 10, upper: 0.05, lower: -0.02 })
+ ]);
+ expect(row).toMatchObject({
+ pmiItemId: "d1",
+ label: "1",
+ nominalValue: "10",
+ tolerancePlus: "0.05",
+ toleranceMinus: "0.02",
+ unit: "mm"
+ });
+ expect(row?.description).toContain("Diameter");
+ expect(row?.description).toContain("⌀10");
+ });
+
+ it("re-centres a deviation that lies wholly below the nominal", () => {
+ const [row] = characteristics([
+ dimension({ type: "diameter", value: 10, upper: -0.013, lower: -0.028 })
+ ]);
+ // The band is 9.972–9.987: centre 9.9795, half width 0.0075.
+ expect(row).toMatchObject({
+ nominalValue: "9.9795",
+ tolerancePlus: "0.0075",
+ toleranceMinus: "0.0075"
+ });
+ });
+
+ it("re-centres a deviation that lies wholly above the nominal", () => {
+ const [row] = characteristics([
+ dimension({ value: 10, upper: 0.05, lower: 0.02 })
+ ]);
+ expect(row).toMatchObject({
+ nominalValue: "10.035",
+ tolerancePlus: "0.015",
+ toleranceMinus: "0.015"
+ });
+ });
+
+ it("centres a limit dimension between its limits", () => {
+ const [row] = characteristics([
+ dimension({ value: 10.05, upperBound: 10.1, lowerBound: 10 })
+ ]);
+ expect(row).toMatchObject({
+ nominalValue: "10.05",
+ tolerancePlus: "0.05",
+ toleranceMinus: "0.05"
+ });
+ });
+
+ it("records a dimension with no numeric limits as Pass or Fail", () => {
+ const [row] = characteristics([
+ dimension({
+ type: "diameter",
+ value: 8,
+ fitClass: { hole: true, formVariance: "H", grade: "IT7" }
+ })
+ ]);
+ expect(row).toMatchObject({
+ nominalValue: null,
+ tolerancePlus: null,
+ toleranceMinus: null
+ });
+ });
+
+ it("leaves out labels, dimensions with no value, datums and notes", () => {
+ const rows = characteristics([
+ dimension({ type: "presentation" }),
+ dimension({ value: null, upper: 0.1, lower: -0.1 }),
+ item({
+ id: "a1",
+ kind: "datum",
+ datum: { name: "A", modifiers: [], target: null }
+ }),
+ item({ id: "n1", kind: "note" })
+ ]);
+ expect(rows).toEqual([]);
+ });
+
+ it("keeps an angle in degrees in an inch model", () => {
+ const [row] = characteristics(
+ [dimension({ type: "angular", value: 45, upper: 0.5, lower: -0.5 })],
+ "in"
+ );
+ expect(row).toMatchObject({
+ nominalValue: "45",
+ tolerancePlus: "0.5",
+ unit: "deg"
+ });
+ });
+
+ it("converts lengths to inches for an inch model", () => {
+ const [row] = characteristics(
+ [dimension({ value: 25.4, upper: 0.127, lower: -0.127 })],
+ "in"
+ );
+ expect(row).toMatchObject({
+ nominalValue: "1",
+ tolerancePlus: "0.005",
+ toleranceMinus: "0.005",
+ unit: "in"
+ });
+ });
+
+ it("measures a geometric tolerance as a deviation within its zone", () => {
+ const [row] = characteristics([
+ tolerance({ type: "flatness", value: 0.02 })
+ ]);
+ expect(row).toMatchObject({
+ pmiItemId: "t1",
+ nominalValue: "0",
+ tolerancePlus: "0.02",
+ toleranceMinus: "0",
+ unit: "mm"
+ });
+ expect(row?.description).toBe("Flatness ⏥ | 0.02");
+ });
+
+ it("records a geometric tolerance with no zone as Pass or Fail", () => {
+ const [row] = characteristics([tolerance({ value: null })]);
+ expect(row?.nominalValue).toBeNull();
+ });
+
+ it("numbers characteristics in file order, skipping what it leaves out", () => {
+ const rows = characteristics([
+ { ...dimension({ value: 5, upper: 0.1, lower: -0.1 }), id: "d1" },
+ item({
+ id: "a1",
+ kind: "datum",
+ datum: { name: "A", modifiers: [], target: null }
+ }),
+ { ...tolerance({ value: 0.1 }), id: "t1" },
+ { ...dimension({ value: 7, upper: 0.1, lower: -0.1 }), id: "d2" }
+ ]);
+ expect(rows.map((r) => [r.label, r.pmiItemId])).toEqual([
+ ["1", "d1"],
+ ["2", "t1"],
+ ["3", "d2"]
+ ]);
+ });
+});
diff --git a/packages/viewer/src/pmi.ts b/packages/viewer/src/pmi.ts
index 901f8b86a5..150c9becf5 100644
--- a/packages/viewer/src/pmi.ts
+++ b/packages/viewer/src/pmi.ts
@@ -2,6 +2,7 @@
// 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 { round } from "@carbon/utils";
import type { Vec3 } from "./types";
/**
@@ -750,3 +751,146 @@ export function pmiViewBounds(
}
return builder.result();
}
+
+// ---------------------------------------------------------------------------
+// Inspection characteristics
+// ---------------------------------------------------------------------------
+
+/**
+ * One inspection characteristic made from a PMI item: the shape the
+ * `pmi-inspection-plan` job writes into `inspectionFeature`. Values are text,
+ * as the feature columns are; a null nominal is a Pass/Fail characteristic.
+ */
+export type PmiCharacteristic = {
+ /** The PMI item it was made from (`d1`, `t3`). */
+ pmiItemId: string;
+ /** Characteristic number: `1`, `2`, … in `pmi.json` order. */
+ label: string;
+ /** What the drawing would print, e.g. `Diameter ⌀10 ±0.05`. */
+ description: string;
+ nominalValue: string | null;
+ tolerancePlus: string | null;
+ toleranceMinus: string | null;
+ /** `mm` or `in` (the file's own unit), or `deg` for an angle. */
+ unit: string;
+};
+
+/**
+ * The characteristics an inspection plan made from this PMI holds: one per
+ * dimension and geometric tolerance. Datums and notes have nothing to
+ * measure, and a dimension with no value (a label, a presentation-only
+ * dimension) has nothing to compare against — all are left out.
+ *
+ * Lengths are in the file's own unit (mm when unknown), so an inch drawing
+ * inspects in inches. A geometric tolerance is a zone: the reading is the
+ * measured deviation, nominal 0 and the zone as its upper limit. A dimension
+ * whose only tolerance is a fit class, a min/max qualifier or none at all
+ * keeps its nominal off, so the grid records Pass or Fail.
+ */
+export function pmiInspectionCharacteristics(
+ doc: PmiDocument
+): PmiCharacteristic[] {
+ const lengthUnit: PmiDisplayUnit = doc.sourceUnit ?? "mm";
+ const toLength = (mm: number) => (lengthUnit === "mm" ? mm : mm / MM_PER_IN);
+ const text = (value: number) => String(round(value));
+
+ const characteristics: PmiCharacteristic[] = [];
+ for (const item of doc.items) {
+ const spec =
+ item.kind === "dimension" && item.dimension
+ ? dimensionSpec(item.dimension, toLength, text)
+ : item.kind === "tolerance" && item.tolerance
+ ? toleranceSpec(item.tolerance, toLength, text)
+ : null;
+ if (!spec) continue;
+
+ // A tolerance's label already opens with its symbol (`⌖ | 0.75 | A`).
+ const { title, label } = formatPmiItem(item, lengthUnit, doc.sourceUnit);
+ characteristics.push({
+ pmiItemId: item.id,
+ label: String(characteristics.length + 1),
+ description: label === title ? title : `${title} ${label}`,
+ nominalValue: spec.nominal,
+ tolerancePlus: spec.plus,
+ toleranceMinus: spec.minus,
+ unit: spec.angular ? "deg" : lengthUnit
+ });
+ }
+ return characteristics;
+}
+
+type CharacteristicSpec = {
+ nominal: string | null;
+ plus: string | null;
+ minus: string | null;
+ angular: boolean;
+};
+
+function dimensionSpec(
+ dimension: PmiDimension,
+ toLength: (mm: number) => number,
+ text: (value: number) => string
+): CharacteristicSpec | null {
+ if (dimension.type === "commonLabel" || dimension.type === "presentation") {
+ return null;
+ }
+ const angular = isAngular(dimension.type);
+ const convert = (value: number) => (angular ? value : toLength(value));
+
+ if (dimension.upper !== null || dimension.lower !== null) {
+ if (dimension.value === null) return null;
+ const value = convert(dimension.value);
+ const upper = convert(dimension.upper ?? 0);
+ const lower = convert(dimension.lower ?? 0);
+ // A reading passes inside [nominal − Tol−, nominal + Tol+], both taken
+ // as magnitudes. That holds the drawing's limits only while the nominal
+ // lies between them; a one-sided fit (⌀10 −0.013/−0.028, a press fit
+ // +0.05/+0.02) is re-centred on its band instead.
+ if (lower <= 0 && upper >= 0) {
+ return {
+ nominal: text(value),
+ plus: text(upper),
+ minus: text(-lower),
+ angular
+ };
+ }
+ const half = Math.abs(upper - lower) / 2;
+ return {
+ nominal: text(value + (upper + lower) / 2),
+ plus: text(half),
+ minus: text(half),
+ angular
+ };
+ }
+ if (dimension.upperBound !== null && dimension.lowerBound !== null) {
+ const upper = convert(dimension.upperBound);
+ const lower = convert(dimension.lowerBound);
+ const half = Math.abs(upper - lower) / 2;
+ return {
+ nominal: text((upper + lower) / 2),
+ plus: text(half),
+ minus: text(half),
+ angular
+ };
+ }
+ if (dimension.value === null) return null;
+ // No numeric limits (a fit class, a min/max qualifier, a basic dimension):
+ // nothing to compare a reading against, so it is recorded Pass or Fail.
+ return { nominal: null, plus: null, minus: null, angular };
+}
+
+function toleranceSpec(
+ tolerance: PmiTolerance,
+ toLength: (mm: number) => number,
+ text: (value: number) => string
+): CharacteristicSpec {
+ if (tolerance.value === null) {
+ return { nominal: null, plus: null, minus: null, angular: false };
+ }
+ return {
+ nominal: "0",
+ plus: text(toLength(tolerance.value)),
+ minus: "0",
+ angular: false
+ };
+}